@clinebot/core 0.0.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.
Files changed (200) hide show
  1. package/README.md +88 -0
  2. package/dist/account/cline-account-service.d.ts +34 -0
  3. package/dist/account/index.d.ts +3 -0
  4. package/dist/account/rpc.d.ts +38 -0
  5. package/dist/account/types.d.ts +74 -0
  6. package/dist/agents/agent-config-loader.d.ts +18 -0
  7. package/dist/agents/agent-config-parser.d.ts +25 -0
  8. package/dist/agents/hooks-config-loader.d.ts +23 -0
  9. package/dist/agents/index.d.ts +11 -0
  10. package/dist/agents/plugin-config-loader.d.ts +22 -0
  11. package/dist/agents/plugin-loader.d.ts +9 -0
  12. package/dist/agents/plugin-sandbox.d.ts +12 -0
  13. package/dist/agents/unified-config-file-watcher.d.ts +77 -0
  14. package/dist/agents/user-instruction-config-loader.d.ts +63 -0
  15. package/dist/auth/client.d.ts +11 -0
  16. package/dist/auth/cline.d.ts +41 -0
  17. package/dist/auth/codex.d.ts +39 -0
  18. package/dist/auth/oca.d.ts +22 -0
  19. package/dist/auth/server.d.ts +22 -0
  20. package/dist/auth/types.d.ts +72 -0
  21. package/dist/auth/utils.d.ts +32 -0
  22. package/dist/chat/chat-schema.d.ts +145 -0
  23. package/dist/default-tools/constants.d.ts +23 -0
  24. package/dist/default-tools/definitions.d.ts +96 -0
  25. package/dist/default-tools/executors/apply-patch-parser.d.ts +68 -0
  26. package/dist/default-tools/executors/apply-patch.d.ts +26 -0
  27. package/dist/default-tools/executors/bash.d.ts +49 -0
  28. package/dist/default-tools/executors/editor.d.ts +31 -0
  29. package/dist/default-tools/executors/file-read.d.ts +40 -0
  30. package/dist/default-tools/executors/index.d.ts +44 -0
  31. package/dist/default-tools/executors/search.d.ts +50 -0
  32. package/dist/default-tools/executors/web-fetch.d.ts +58 -0
  33. package/dist/default-tools/index.d.ts +57 -0
  34. package/dist/default-tools/presets.d.ts +124 -0
  35. package/dist/default-tools/schemas.d.ts +121 -0
  36. package/dist/default-tools/types.d.ts +237 -0
  37. package/dist/index.d.ts +23 -0
  38. package/dist/index.js +220 -0
  39. package/dist/input/file-indexer.d.ts +5 -0
  40. package/dist/input/index.d.ts +4 -0
  41. package/dist/input/mention-enricher.d.ts +12 -0
  42. package/dist/mcp/config-loader.d.ts +15 -0
  43. package/dist/mcp/index.d.ts +4 -0
  44. package/dist/mcp/manager.d.ts +24 -0
  45. package/dist/mcp/types.d.ts +66 -0
  46. package/dist/runtime/hook-file-hooks.d.ts +18 -0
  47. package/dist/runtime/rules.d.ts +5 -0
  48. package/dist/runtime/runtime-builder.d.ts +5 -0
  49. package/dist/runtime/sandbox/subprocess-sandbox.d.ts +19 -0
  50. package/dist/runtime/session-runtime.d.ts +36 -0
  51. package/dist/runtime/tool-approval.d.ts +9 -0
  52. package/dist/runtime/workflows.d.ts +13 -0
  53. package/dist/server/index.d.ts +47 -0
  54. package/dist/server/index.js +641 -0
  55. package/dist/session/default-session-manager.d.ts +77 -0
  56. package/dist/session/rpc-session-service.d.ts +12 -0
  57. package/dist/session/runtime-oauth-token-manager.d.ts +28 -0
  58. package/dist/session/session-artifacts.d.ts +19 -0
  59. package/dist/session/session-graph.d.ts +15 -0
  60. package/dist/session/session-host.d.ts +21 -0
  61. package/dist/session/session-manager.d.ts +50 -0
  62. package/dist/session/session-manifest.d.ts +30 -0
  63. package/dist/session/session-service.d.ts +113 -0
  64. package/dist/session/sqlite-rpc-session-backend.d.ts +30 -0
  65. package/dist/session/unified-session-persistence-service.d.ts +93 -0
  66. package/dist/session/workspace-manager.d.ts +28 -0
  67. package/dist/session/workspace-manifest.d.ts +25 -0
  68. package/dist/storage/provider-settings-legacy-migration.d.ts +13 -0
  69. package/dist/storage/provider-settings-manager.d.ts +20 -0
  70. package/dist/storage/sqlite-session-store.d.ts +29 -0
  71. package/dist/storage/sqlite-team-store.d.ts +31 -0
  72. package/dist/storage/team-store.d.ts +2 -0
  73. package/dist/team/index.d.ts +1 -0
  74. package/dist/team/projections.d.ts +8 -0
  75. package/dist/types/common.d.ts +10 -0
  76. package/dist/types/config.d.ts +37 -0
  77. package/dist/types/events.d.ts +54 -0
  78. package/dist/types/provider-settings.d.ts +20 -0
  79. package/dist/types/sessions.d.ts +9 -0
  80. package/dist/types/storage.d.ts +37 -0
  81. package/dist/types/workspace.d.ts +7 -0
  82. package/dist/types.d.ts +26 -0
  83. package/package.json +63 -0
  84. package/src/account/cline-account-service.test.ts +101 -0
  85. package/src/account/cline-account-service.ts +267 -0
  86. package/src/account/index.ts +20 -0
  87. package/src/account/rpc.test.ts +62 -0
  88. package/src/account/rpc.ts +172 -0
  89. package/src/account/types.ts +80 -0
  90. package/src/agents/agent-config-loader.test.ts +234 -0
  91. package/src/agents/agent-config-loader.ts +107 -0
  92. package/src/agents/agent-config-parser.ts +191 -0
  93. package/src/agents/hooks-config-loader.ts +97 -0
  94. package/src/agents/index.ts +84 -0
  95. package/src/agents/plugin-config-loader.test.ts +91 -0
  96. package/src/agents/plugin-config-loader.ts +160 -0
  97. package/src/agents/plugin-loader.test.ts +102 -0
  98. package/src/agents/plugin-loader.ts +105 -0
  99. package/src/agents/plugin-sandbox.test.ts +120 -0
  100. package/src/agents/plugin-sandbox.ts +471 -0
  101. package/src/agents/unified-config-file-watcher.test.ts +196 -0
  102. package/src/agents/unified-config-file-watcher.ts +483 -0
  103. package/src/agents/user-instruction-config-loader.test.ts +158 -0
  104. package/src/agents/user-instruction-config-loader.ts +438 -0
  105. package/src/auth/client.test.ts +40 -0
  106. package/src/auth/client.ts +25 -0
  107. package/src/auth/cline.test.ts +130 -0
  108. package/src/auth/cline.ts +414 -0
  109. package/src/auth/codex.test.ts +170 -0
  110. package/src/auth/codex.ts +466 -0
  111. package/src/auth/oca.test.ts +215 -0
  112. package/src/auth/oca.ts +546 -0
  113. package/src/auth/server.ts +216 -0
  114. package/src/auth/types.ts +78 -0
  115. package/src/auth/utils.test.ts +128 -0
  116. package/src/auth/utils.ts +247 -0
  117. package/src/chat/chat-schema.ts +82 -0
  118. package/src/default-tools/constants.ts +35 -0
  119. package/src/default-tools/definitions.test.ts +233 -0
  120. package/src/default-tools/definitions.ts +632 -0
  121. package/src/default-tools/executors/apply-patch-parser.ts +520 -0
  122. package/src/default-tools/executors/apply-patch.ts +359 -0
  123. package/src/default-tools/executors/bash.ts +205 -0
  124. package/src/default-tools/executors/editor.ts +231 -0
  125. package/src/default-tools/executors/file-read.test.ts +25 -0
  126. package/src/default-tools/executors/file-read.ts +94 -0
  127. package/src/default-tools/executors/index.ts +75 -0
  128. package/src/default-tools/executors/search.ts +278 -0
  129. package/src/default-tools/executors/web-fetch.ts +259 -0
  130. package/src/default-tools/index.ts +161 -0
  131. package/src/default-tools/presets.test.ts +63 -0
  132. package/src/default-tools/presets.ts +168 -0
  133. package/src/default-tools/schemas.ts +228 -0
  134. package/src/default-tools/types.ts +324 -0
  135. package/src/index.ts +119 -0
  136. package/src/input/file-indexer.d.ts +11 -0
  137. package/src/input/file-indexer.test.ts +87 -0
  138. package/src/input/file-indexer.ts +280 -0
  139. package/src/input/index.ts +7 -0
  140. package/src/input/mention-enricher.test.ts +82 -0
  141. package/src/input/mention-enricher.ts +119 -0
  142. package/src/mcp/config-loader.test.ts +238 -0
  143. package/src/mcp/config-loader.ts +219 -0
  144. package/src/mcp/index.ts +26 -0
  145. package/src/mcp/manager.test.ts +106 -0
  146. package/src/mcp/manager.ts +262 -0
  147. package/src/mcp/types.ts +88 -0
  148. package/src/runtime/hook-file-hooks.test.ts +106 -0
  149. package/src/runtime/hook-file-hooks.ts +736 -0
  150. package/src/runtime/index.ts +27 -0
  151. package/src/runtime/rules.ts +34 -0
  152. package/src/runtime/runtime-builder.team-persistence.test.ts +203 -0
  153. package/src/runtime/runtime-builder.test.ts +215 -0
  154. package/src/runtime/runtime-builder.ts +515 -0
  155. package/src/runtime/runtime-parity.test.ts +132 -0
  156. package/src/runtime/sandbox/subprocess-sandbox.ts +207 -0
  157. package/src/runtime/session-runtime.ts +44 -0
  158. package/src/runtime/tool-approval.ts +104 -0
  159. package/src/runtime/workflows.test.ts +119 -0
  160. package/src/runtime/workflows.ts +54 -0
  161. package/src/server/index.ts +282 -0
  162. package/src/session/default-session-manager.e2e.test.ts +354 -0
  163. package/src/session/default-session-manager.test.ts +816 -0
  164. package/src/session/default-session-manager.ts +1286 -0
  165. package/src/session/index.ts +37 -0
  166. package/src/session/rpc-session-service.ts +189 -0
  167. package/src/session/runtime-oauth-token-manager.test.ts +137 -0
  168. package/src/session/runtime-oauth-token-manager.ts +265 -0
  169. package/src/session/session-artifacts.ts +106 -0
  170. package/src/session/session-graph.ts +90 -0
  171. package/src/session/session-host.ts +190 -0
  172. package/src/session/session-manager.ts +56 -0
  173. package/src/session/session-manifest.ts +29 -0
  174. package/src/session/session-service.team-persistence.test.ts +48 -0
  175. package/src/session/session-service.ts +610 -0
  176. package/src/session/sqlite-rpc-session-backend.ts +303 -0
  177. package/src/session/unified-session-persistence-service.ts +781 -0
  178. package/src/session/workspace-manager.ts +98 -0
  179. package/src/session/workspace-manifest.ts +100 -0
  180. package/src/storage/artifact-store.ts +1 -0
  181. package/src/storage/index.ts +11 -0
  182. package/src/storage/provider-settings-legacy-migration.test.ts +175 -0
  183. package/src/storage/provider-settings-legacy-migration.ts +637 -0
  184. package/src/storage/provider-settings-manager.test.ts +111 -0
  185. package/src/storage/provider-settings-manager.ts +129 -0
  186. package/src/storage/session-store.ts +1 -0
  187. package/src/storage/sqlite-session-store.ts +270 -0
  188. package/src/storage/sqlite-team-store.ts +443 -0
  189. package/src/storage/team-store.ts +5 -0
  190. package/src/team/index.ts +4 -0
  191. package/src/team/projections.ts +285 -0
  192. package/src/types/common.ts +14 -0
  193. package/src/types/config.ts +64 -0
  194. package/src/types/events.ts +46 -0
  195. package/src/types/index.ts +24 -0
  196. package/src/types/provider-settings.ts +43 -0
  197. package/src/types/sessions.ts +16 -0
  198. package/src/types/storage.ts +64 -0
  199. package/src/types/workspace.ts +7 -0
  200. package/src/types.ts +127 -0
@@ -0,0 +1,466 @@
1
+ /**
2
+ * OpenAI Codex (ChatGPT OAuth) flow
3
+ *
4
+ * NOTE: This module uses Node.js crypto and http for the OAuth callback.
5
+ * It is only intended for CLI use, not browser environments.
6
+ */
7
+
8
+ import { nanoid } from "nanoid";
9
+ import { startLocalOAuthServer } from "./server.js";
10
+ import type {
11
+ OAuthCredentials,
12
+ OAuthLoginCallbacks,
13
+ OAuthPrompt,
14
+ OAuthProviderInterface,
15
+ } from "./types.js";
16
+ import {
17
+ decodeJwtPayload,
18
+ getProofKey,
19
+ isCredentialLikelyExpired,
20
+ parseAuthorizationInput,
21
+ parseOAuthError,
22
+ resolveAuthorizationCodeInput,
23
+ } from "./utils.js";
24
+
25
+ export const OPENAI_CODEX_OAUTH_CONFIG = {
26
+ authorizationEndpoint: "https://auth.openai.com/oauth/authorize",
27
+ tokenEndpoint: "https://auth.openai.com/oauth/token",
28
+ clientId: "app_EMoamEEZ73f0CkXaXp7hrann",
29
+ redirectUri: "http://localhost:1455/auth/callback",
30
+ scopes: "openid profile email offline_access",
31
+ callbackPort: 1455,
32
+ jwtClaimPath: "https://api.openai.com/auth",
33
+ refreshBufferMs: 5 * 60 * 1000,
34
+ retryableTokenGraceMs: 30 * 1000,
35
+ httpTimeoutMs: 30 * 1000,
36
+ } as const;
37
+
38
+ type CodexTokenSuccess = {
39
+ type: "success";
40
+ access: string;
41
+ refresh: string;
42
+ expires: number;
43
+ email?: string;
44
+ idToken?: string;
45
+ };
46
+ type CodexTokenFailure = { type: "failed" };
47
+ type CodexTokenResult = CodexTokenSuccess | CodexTokenFailure;
48
+ export type RefreshTokenResolution = {
49
+ forceRefresh?: boolean;
50
+ refreshBufferMs?: number;
51
+ retryableTokenGraceMs?: number;
52
+ };
53
+
54
+ type JwtPayload = {
55
+ [OPENAI_CODEX_OAUTH_CONFIG.jwtClaimPath]?: {
56
+ chatgpt_account_id?: string;
57
+ };
58
+ [key: string]: unknown;
59
+ };
60
+
61
+ class OpenAICodexOAuthTokenError extends Error {
62
+ public readonly status?: number;
63
+ public readonly errorCode?: string;
64
+
65
+ constructor(message: string, opts?: { status?: number; errorCode?: string }) {
66
+ super(message);
67
+ this.name = "OpenAICodexOAuthTokenError";
68
+ this.status = opts?.status;
69
+ this.errorCode = opts?.errorCode;
70
+ }
71
+
72
+ public isLikelyInvalidGrant(): boolean {
73
+ if (this.errorCode && /invalid_grant/i.test(this.errorCode)) {
74
+ return true;
75
+ }
76
+ if (this.status === 400 || this.status === 401 || this.status === 403) {
77
+ return /invalid_grant|revoked|expired|invalid refresh/i.test(
78
+ this.message,
79
+ );
80
+ }
81
+ return false;
82
+ }
83
+ }
84
+
85
+ async function exchangeAuthorizationCode(
86
+ code: string,
87
+ verifier: string,
88
+ redirectUri: string = OPENAI_CODEX_OAUTH_CONFIG.redirectUri,
89
+ ): Promise<CodexTokenResult> {
90
+ const response = await fetch(OPENAI_CODEX_OAUTH_CONFIG.tokenEndpoint, {
91
+ method: "POST",
92
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
93
+ body: new URLSearchParams({
94
+ grant_type: "authorization_code",
95
+ client_id: OPENAI_CODEX_OAUTH_CONFIG.clientId,
96
+ code,
97
+ code_verifier: verifier,
98
+ redirect_uri: redirectUri,
99
+ }),
100
+ signal: AbortSignal.timeout(OPENAI_CODEX_OAUTH_CONFIG.httpTimeoutMs),
101
+ });
102
+
103
+ if (!response.ok) {
104
+ return { type: "failed" };
105
+ }
106
+
107
+ const json = (await response.json()) as {
108
+ access_token?: string;
109
+ refresh_token?: string;
110
+ expires_in?: number;
111
+ email?: string;
112
+ id_token?: string;
113
+ };
114
+
115
+ if (
116
+ !json.access_token ||
117
+ !json.refresh_token ||
118
+ typeof json.expires_in !== "number"
119
+ ) {
120
+ return { type: "failed" };
121
+ }
122
+
123
+ return {
124
+ type: "success",
125
+ access: json.access_token,
126
+ refresh: json.refresh_token,
127
+ expires: Date.now() + json.expires_in * 1000,
128
+ email: json.email,
129
+ idToken: json.id_token,
130
+ };
131
+ }
132
+
133
+ async function refreshAccessToken(
134
+ refreshToken: string,
135
+ ): Promise<CodexTokenResult> {
136
+ try {
137
+ const response = await fetch(OPENAI_CODEX_OAUTH_CONFIG.tokenEndpoint, {
138
+ method: "POST",
139
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
140
+ body: new URLSearchParams({
141
+ grant_type: "refresh_token",
142
+ refresh_token: refreshToken,
143
+ client_id: OPENAI_CODEX_OAUTH_CONFIG.clientId,
144
+ }),
145
+ signal: AbortSignal.timeout(OPENAI_CODEX_OAUTH_CONFIG.httpTimeoutMs),
146
+ });
147
+
148
+ if (!response.ok) {
149
+ const text = await response.text().catch(() => "");
150
+ const details = parseOAuthError(text);
151
+ throw new OpenAICodexOAuthTokenError(
152
+ `Token refresh failed: ${response.status}${details.message ? ` - ${details.message}` : ""}`,
153
+ { status: response.status, errorCode: details.code },
154
+ );
155
+ }
156
+
157
+ const json = (await response.json()) as {
158
+ access_token?: string;
159
+ refresh_token?: string;
160
+ expires_in?: number;
161
+ email?: string;
162
+ id_token?: string;
163
+ };
164
+
165
+ if (
166
+ !json.access_token ||
167
+ !json.refresh_token ||
168
+ typeof json.expires_in !== "number"
169
+ ) {
170
+ return { type: "failed" };
171
+ }
172
+
173
+ return {
174
+ type: "success",
175
+ access: json.access_token,
176
+ refresh: json.refresh_token,
177
+ expires: Date.now() + json.expires_in * 1000,
178
+ email: json.email,
179
+ idToken: json.id_token,
180
+ };
181
+ } catch (error) {
182
+ if (error instanceof OpenAICodexOAuthTokenError) {
183
+ throw error;
184
+ }
185
+ return { type: "failed" };
186
+ }
187
+ }
188
+
189
+ async function createAuthorizationFlow(
190
+ originator = "pi",
191
+ ): Promise<{ verifier: string; state: string; url: string }> {
192
+ const { verifier, challenge } = await getProofKey();
193
+ const state = nanoid(32);
194
+
195
+ const url = new URL(OPENAI_CODEX_OAUTH_CONFIG.authorizationEndpoint);
196
+ url.searchParams.set("response_type", "code");
197
+ url.searchParams.set("client_id", OPENAI_CODEX_OAUTH_CONFIG.clientId);
198
+ url.searchParams.set("redirect_uri", OPENAI_CODEX_OAUTH_CONFIG.redirectUri);
199
+ url.searchParams.set("scope", OPENAI_CODEX_OAUTH_CONFIG.scopes);
200
+ url.searchParams.set("code_challenge", challenge);
201
+ url.searchParams.set("code_challenge_method", "S256");
202
+ url.searchParams.set("state", state);
203
+ url.searchParams.set("id_token_add_organizations", "true");
204
+ url.searchParams.set("codex_cli_simplified_flow", "true");
205
+ url.searchParams.set("originator", originator);
206
+
207
+ return { verifier, state, url: url.toString() };
208
+ }
209
+
210
+ function resolveCallbackServerConfig(): {
211
+ host: string;
212
+ port: number;
213
+ callbackPath: string;
214
+ redirectUri: string;
215
+ } {
216
+ try {
217
+ const redirect = new URL(OPENAI_CODEX_OAUTH_CONFIG.redirectUri);
218
+ const parsedPort =
219
+ redirect.port.length > 0
220
+ ? Number.parseInt(redirect.port, 10)
221
+ : OPENAI_CODEX_OAUTH_CONFIG.callbackPort;
222
+ return {
223
+ host: redirect.hostname || "localhost",
224
+ port: Number.isFinite(parsedPort)
225
+ ? parsedPort
226
+ : OPENAI_CODEX_OAUTH_CONFIG.callbackPort,
227
+ callbackPath: redirect.pathname || "/auth/callback",
228
+ redirectUri: redirect.toString(),
229
+ };
230
+ } catch {
231
+ return {
232
+ host: "localhost",
233
+ port: OPENAI_CODEX_OAUTH_CONFIG.callbackPort,
234
+ callbackPath: "/auth/callback",
235
+ redirectUri: OPENAI_CODEX_OAUTH_CONFIG.redirectUri,
236
+ };
237
+ }
238
+ }
239
+
240
+ function getAccountId(accessToken: string, idToken?: string): string | null {
241
+ const payload = (
242
+ idToken ? decodeJwtPayload(idToken) : decodeJwtPayload(accessToken)
243
+ ) as JwtPayload | null;
244
+ const fallback = (
245
+ payload ? payload : decodeJwtPayload(accessToken)
246
+ ) as JwtPayload | null;
247
+ const auth = fallback?.[OPENAI_CODEX_OAUTH_CONFIG.jwtClaimPath];
248
+ const accountId = auth?.chatgpt_account_id;
249
+ if (typeof accountId === "string" && accountId.length > 0) {
250
+ return accountId;
251
+ }
252
+
253
+ const organizations = fallback?.organizations;
254
+ if (Array.isArray(organizations) && organizations.length > 0) {
255
+ const first = organizations[0] as { id?: unknown } | undefined;
256
+ if (typeof first?.id === "string" && first.id.length > 0) {
257
+ return first.id;
258
+ }
259
+ }
260
+
261
+ const rootAccountId = fallback?.chatgpt_account_id;
262
+ if (typeof rootAccountId === "string" && rootAccountId.length > 0) {
263
+ return rootAccountId;
264
+ }
265
+
266
+ return null;
267
+ }
268
+
269
+ function toCodexCredentials(
270
+ result: CodexTokenSuccess,
271
+ fallback?: OAuthCredentials,
272
+ ): OAuthCredentials {
273
+ const accountId =
274
+ getAccountId(result.access, result.idToken) ?? fallback?.accountId;
275
+ if (!accountId) {
276
+ throw new Error("Failed to extract accountId from token");
277
+ }
278
+
279
+ return {
280
+ access: result.access,
281
+ refresh: result.refresh || fallback?.refresh || "",
282
+ expires: result.expires,
283
+ accountId,
284
+ email: result.email ?? fallback?.email,
285
+ metadata: {
286
+ ...(fallback?.metadata ?? {}),
287
+ provider: "openai-codex",
288
+ },
289
+ };
290
+ }
291
+
292
+ export async function loginOpenAICodex(options: {
293
+ onAuth: (info: { url: string; instructions?: string }) => void;
294
+ onPrompt: (prompt: OAuthPrompt) => Promise<string>;
295
+ onProgress?: (message: string) => void;
296
+ onManualCodeInput?: () => Promise<string>;
297
+ originator?: string;
298
+ }): Promise<OAuthCredentials> {
299
+ const callbackConfig = resolveCallbackServerConfig();
300
+ const { verifier, state, url } = await createAuthorizationFlow(
301
+ options.originator,
302
+ );
303
+ const server = await startLocalOAuthServer({
304
+ host: callbackConfig.host,
305
+ ports: [callbackConfig.port],
306
+ callbackPath: callbackConfig.callbackPath,
307
+ expectedState: state,
308
+ });
309
+
310
+ options.onAuth({
311
+ url,
312
+ instructions: "Continue the authentication process in your browser.",
313
+ });
314
+
315
+ let code: string | undefined;
316
+ try {
317
+ const authResult = await resolveAuthorizationCodeInput({
318
+ waitForCallback: server.waitForCallback,
319
+ cancelWait: server.cancelWait,
320
+ onManualCodeInput: options.onManualCodeInput,
321
+ parseOptions: { allowHashCodeState: true },
322
+ });
323
+ if (authResult.state && authResult.state !== state) {
324
+ throw new Error("State mismatch");
325
+ }
326
+ code = authResult.code;
327
+
328
+ // Fallback to onPrompt if still no code
329
+ if (!code) {
330
+ const input = await options.onPrompt({
331
+ message: "Paste the authorization code (or full redirect URL):",
332
+ });
333
+ const parsed = parseAuthorizationInput(input, {
334
+ allowHashCodeState: true,
335
+ });
336
+ if (parsed.state && parsed.state !== state) {
337
+ throw new Error("State mismatch");
338
+ }
339
+ code = parsed.code;
340
+ }
341
+
342
+ if (!code) {
343
+ throw new Error("Missing authorization code");
344
+ }
345
+
346
+ const tokenResult = await exchangeAuthorizationCode(
347
+ code,
348
+ verifier,
349
+ callbackConfig.redirectUri,
350
+ );
351
+ if (tokenResult.type !== "success") {
352
+ throw new Error("Token exchange failed");
353
+ }
354
+
355
+ return toCodexCredentials(tokenResult);
356
+ } finally {
357
+ server.close();
358
+ }
359
+ }
360
+
361
+ export async function refreshOpenAICodexToken(
362
+ refreshToken: string,
363
+ fallback?: OAuthCredentials,
364
+ ): Promise<OAuthCredentials> {
365
+ const result = await refreshAccessToken(refreshToken);
366
+ if (result.type !== "success") {
367
+ throw new Error("Failed to refresh OpenAI Codex token");
368
+ }
369
+
370
+ const normalized = toCodexCredentials(result, fallback);
371
+ if (!normalized.refresh) {
372
+ throw new Error(
373
+ "Failed to refresh OpenAI Codex token: missing refresh token",
374
+ );
375
+ }
376
+ return normalized;
377
+ }
378
+
379
+ export async function getValidOpenAICodexCredentials(
380
+ currentCredentials: OAuthCredentials | null,
381
+ options?: RefreshTokenResolution,
382
+ ): Promise<OAuthCredentials | null> {
383
+ if (!currentCredentials) {
384
+ return null;
385
+ }
386
+
387
+ const refreshBufferMs =
388
+ options?.refreshBufferMs ?? OPENAI_CODEX_OAUTH_CONFIG.refreshBufferMs;
389
+ const retryableTokenGraceMs =
390
+ options?.retryableTokenGraceMs ??
391
+ OPENAI_CODEX_OAUTH_CONFIG.retryableTokenGraceMs;
392
+ const forceRefresh = options?.forceRefresh === true;
393
+
394
+ if (
395
+ !forceRefresh &&
396
+ !isCredentialLikelyExpired(currentCredentials, refreshBufferMs)
397
+ ) {
398
+ return currentCredentials;
399
+ }
400
+
401
+ try {
402
+ const refreshed = await refreshOpenAICodexToken(
403
+ currentCredentials.refresh,
404
+ currentCredentials,
405
+ );
406
+ return refreshed;
407
+ } catch (error) {
408
+ if (
409
+ error instanceof OpenAICodexOAuthTokenError &&
410
+ error.isLikelyInvalidGrant()
411
+ ) {
412
+ return null;
413
+ }
414
+ if (currentCredentials.expires - Date.now() > retryableTokenGraceMs) {
415
+ return currentCredentials;
416
+ }
417
+ return null;
418
+ }
419
+ }
420
+
421
+ export function isOpenAICodexTokenExpired(
422
+ credentials: OAuthCredentials,
423
+ refreshBufferMs: number = OPENAI_CODEX_OAUTH_CONFIG.refreshBufferMs,
424
+ ): boolean {
425
+ return isCredentialLikelyExpired(credentials, refreshBufferMs);
426
+ }
427
+
428
+ export function normalizeOpenAICodexCredentials(
429
+ credentials: OAuthCredentials,
430
+ ): OAuthCredentials {
431
+ const accountId = credentials.accountId ?? getAccountId(credentials.access);
432
+ if (!accountId) {
433
+ throw new Error("Failed to extract accountId from token");
434
+ }
435
+ return {
436
+ ...credentials,
437
+ accountId,
438
+ metadata: {
439
+ ...(credentials.metadata ?? {}),
440
+ provider: "openai-codex",
441
+ },
442
+ };
443
+ }
444
+
445
+ export const openaiCodexOAuthProvider: OAuthProviderInterface = {
446
+ id: "openai-codex",
447
+ name: "ChatGPT Plus/Pro (ChatGPT Subscription)",
448
+ usesCallbackServer: true,
449
+
450
+ async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
451
+ return loginOpenAICodex({
452
+ onAuth: callbacks.onAuth,
453
+ onPrompt: callbacks.onPrompt,
454
+ onProgress: callbacks.onProgress,
455
+ onManualCodeInput: callbacks.onManualCodeInput,
456
+ });
457
+ },
458
+
459
+ async refreshToken(credentials: OAuthCredentials): Promise<OAuthCredentials> {
460
+ return refreshOpenAICodexToken(credentials.refresh, credentials);
461
+ },
462
+
463
+ getApiKey(credentials: OAuthCredentials): string {
464
+ return credentials.access;
465
+ },
466
+ };
@@ -0,0 +1,215 @@
1
+ import { afterEach, describe, expect, it, vi } from "vitest";
2
+ import { getValidOcaCredentials } from "./oca.js";
3
+ import type { OAuthCredentials } from "./types.js";
4
+
5
+ function toBase64Url(value: string): string {
6
+ return Buffer.from(value, "utf8").toString("base64url");
7
+ }
8
+
9
+ function createJwt(payload: Record<string, unknown>): string {
10
+ return `${toBase64Url(JSON.stringify({ alg: "none", typ: "JWT" }))}.${toBase64Url(JSON.stringify(payload))}.sig`;
11
+ }
12
+
13
+ function createCredentials(
14
+ overrides: Partial<OAuthCredentials> = {},
15
+ ): OAuthCredentials {
16
+ return {
17
+ access: "access-old",
18
+ refresh: "refresh-old",
19
+ expires: 0,
20
+ accountId: "acct-old",
21
+ email: "old@example.com",
22
+ metadata: { provider: "oca", mode: "internal" },
23
+ ...overrides,
24
+ };
25
+ }
26
+
27
+ describe("auth/oca getValidOcaCredentials", () => {
28
+ afterEach(() => {
29
+ vi.unstubAllGlobals();
30
+ vi.restoreAllMocks();
31
+ });
32
+
33
+ it("returns current credentials when token is still fresh", async () => {
34
+ const nowSpy = vi.spyOn(Date, "now").mockReturnValue(10_000);
35
+ const current = createCredentials({ expires: 400_000 });
36
+ const fetchMock = vi.fn();
37
+ vi.stubGlobal("fetch", fetchMock);
38
+
39
+ const result = await getValidOcaCredentials(current);
40
+ expect(result).toBe(current);
41
+ expect(fetchMock).not.toHaveBeenCalled();
42
+ nowSpy.mockRestore();
43
+ });
44
+
45
+ it("refreshes an expired token after discovery", async () => {
46
+ const nowSpy = vi.spyOn(Date, "now").mockReturnValue(100_000);
47
+ const idToken = createJwt({
48
+ sub: "acct-new",
49
+ email: "new@example.com",
50
+ exp: 2_000_000_000,
51
+ });
52
+
53
+ const fetchMock = vi
54
+ .fn()
55
+ .mockImplementationOnce(
56
+ async () =>
57
+ new Response(
58
+ JSON.stringify({
59
+ token_endpoint: "https://idcs.example.com/oauth2/v1/token",
60
+ }),
61
+ {
62
+ status: 200,
63
+ headers: { "Content-Type": "application/json" },
64
+ },
65
+ ),
66
+ )
67
+ .mockImplementationOnce(
68
+ async () =>
69
+ new Response(
70
+ JSON.stringify({
71
+ access_token: createJwt({
72
+ sub: "acct-new",
73
+ email: "new@example.com",
74
+ exp: 2_000_000_000,
75
+ }),
76
+ refresh_token: "refresh-new",
77
+ id_token: idToken,
78
+ }),
79
+ { status: 200, headers: { "Content-Type": "application/json" } },
80
+ ),
81
+ );
82
+
83
+ vi.stubGlobal("fetch", fetchMock);
84
+
85
+ const result = await getValidOcaCredentials(
86
+ createCredentials({ expires: 101_000 }),
87
+ undefined,
88
+ {
89
+ config: {
90
+ internal: {
91
+ clientId: "client-1",
92
+ idcsUrl: "https://idcs.example.com",
93
+ scopes: "openid offline_access",
94
+ baseUrl: "https://oca.example.com",
95
+ },
96
+ },
97
+ },
98
+ );
99
+
100
+ expect(result).toMatchObject({
101
+ access: expect.any(String),
102
+ refresh: "refresh-new",
103
+ accountId: "acct-new",
104
+ email: "new@example.com",
105
+ metadata: {
106
+ provider: "oca",
107
+ mode: "internal",
108
+ },
109
+ });
110
+ expect(fetchMock).toHaveBeenCalledTimes(2);
111
+ nowSpy.mockRestore();
112
+ });
113
+
114
+ it("returns null when refresh fails with invalid_grant", async () => {
115
+ const nowSpy = vi.spyOn(Date, "now").mockReturnValue(100_000);
116
+ const fetchMock = vi
117
+ .fn()
118
+ .mockImplementationOnce(
119
+ async () =>
120
+ new Response(
121
+ JSON.stringify({
122
+ token_endpoint: "https://idcs.invalid/oauth2/v1/token",
123
+ }),
124
+ {
125
+ status: 200,
126
+ headers: { "Content-Type": "application/json" },
127
+ },
128
+ ),
129
+ )
130
+ .mockImplementationOnce(
131
+ async () =>
132
+ new Response(
133
+ JSON.stringify({
134
+ error: "invalid_grant",
135
+ error_description: "expired refresh token",
136
+ }),
137
+ {
138
+ status: 400,
139
+ headers: { "Content-Type": "application/json" },
140
+ },
141
+ ),
142
+ );
143
+ vi.stubGlobal("fetch", fetchMock);
144
+
145
+ const result = await getValidOcaCredentials(
146
+ createCredentials({ expires: 101_000 }),
147
+ undefined,
148
+ {
149
+ config: {
150
+ internal: {
151
+ clientId: "client-2",
152
+ idcsUrl: "https://idcs.invalid",
153
+ scopes: "openid offline_access",
154
+ baseUrl: "https://oca.example.com",
155
+ },
156
+ },
157
+ },
158
+ );
159
+ expect(result).toBeNull();
160
+ nowSpy.mockRestore();
161
+ });
162
+
163
+ it("keeps current credentials on transient refresh failures when access token is still usable", async () => {
164
+ const nowSpy = vi.spyOn(Date, "now").mockReturnValue(100_000);
165
+ const fetchMock = vi
166
+ .fn()
167
+ .mockImplementationOnce(
168
+ async () =>
169
+ new Response(
170
+ JSON.stringify({
171
+ token_endpoint: "https://idcs.retry/oauth2/v1/token",
172
+ }),
173
+ {
174
+ status: 200,
175
+ headers: { "Content-Type": "application/json" },
176
+ },
177
+ ),
178
+ )
179
+ .mockImplementationOnce(
180
+ async () =>
181
+ new Response(
182
+ JSON.stringify({
183
+ error: "server_error",
184
+ error_description: "temporary issue",
185
+ }),
186
+ {
187
+ status: 500,
188
+ headers: { "Content-Type": "application/json" },
189
+ },
190
+ ),
191
+ );
192
+ vi.stubGlobal("fetch", fetchMock);
193
+
194
+ const current = createCredentials({ expires: 150_000 });
195
+ const result = await getValidOcaCredentials(
196
+ current,
197
+ {
198
+ refreshBufferMs: 60_000,
199
+ retryableTokenGraceMs: 30_000,
200
+ },
201
+ {
202
+ config: {
203
+ internal: {
204
+ clientId: "client-3",
205
+ idcsUrl: "https://idcs.retry",
206
+ scopes: "openid offline_access",
207
+ baseUrl: "https://oca.example.com",
208
+ },
209
+ },
210
+ },
211
+ );
212
+ expect(result).toBe(current);
213
+ nowSpy.mockRestore();
214
+ });
215
+ });