@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.
- package/README.md +88 -0
- package/dist/account/cline-account-service.d.ts +34 -0
- package/dist/account/index.d.ts +3 -0
- package/dist/account/rpc.d.ts +38 -0
- package/dist/account/types.d.ts +74 -0
- package/dist/agents/agent-config-loader.d.ts +18 -0
- package/dist/agents/agent-config-parser.d.ts +25 -0
- package/dist/agents/hooks-config-loader.d.ts +23 -0
- package/dist/agents/index.d.ts +11 -0
- package/dist/agents/plugin-config-loader.d.ts +22 -0
- package/dist/agents/plugin-loader.d.ts +9 -0
- package/dist/agents/plugin-sandbox.d.ts +12 -0
- package/dist/agents/unified-config-file-watcher.d.ts +77 -0
- package/dist/agents/user-instruction-config-loader.d.ts +63 -0
- package/dist/auth/client.d.ts +11 -0
- package/dist/auth/cline.d.ts +41 -0
- package/dist/auth/codex.d.ts +39 -0
- package/dist/auth/oca.d.ts +22 -0
- package/dist/auth/server.d.ts +22 -0
- package/dist/auth/types.d.ts +72 -0
- package/dist/auth/utils.d.ts +32 -0
- package/dist/chat/chat-schema.d.ts +145 -0
- package/dist/default-tools/constants.d.ts +23 -0
- package/dist/default-tools/definitions.d.ts +96 -0
- package/dist/default-tools/executors/apply-patch-parser.d.ts +68 -0
- package/dist/default-tools/executors/apply-patch.d.ts +26 -0
- package/dist/default-tools/executors/bash.d.ts +49 -0
- package/dist/default-tools/executors/editor.d.ts +31 -0
- package/dist/default-tools/executors/file-read.d.ts +40 -0
- package/dist/default-tools/executors/index.d.ts +44 -0
- package/dist/default-tools/executors/search.d.ts +50 -0
- package/dist/default-tools/executors/web-fetch.d.ts +58 -0
- package/dist/default-tools/index.d.ts +57 -0
- package/dist/default-tools/presets.d.ts +124 -0
- package/dist/default-tools/schemas.d.ts +121 -0
- package/dist/default-tools/types.d.ts +237 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +220 -0
- package/dist/input/file-indexer.d.ts +5 -0
- package/dist/input/index.d.ts +4 -0
- package/dist/input/mention-enricher.d.ts +12 -0
- package/dist/mcp/config-loader.d.ts +15 -0
- package/dist/mcp/index.d.ts +4 -0
- package/dist/mcp/manager.d.ts +24 -0
- package/dist/mcp/types.d.ts +66 -0
- package/dist/runtime/hook-file-hooks.d.ts +18 -0
- package/dist/runtime/rules.d.ts +5 -0
- package/dist/runtime/runtime-builder.d.ts +5 -0
- package/dist/runtime/sandbox/subprocess-sandbox.d.ts +19 -0
- package/dist/runtime/session-runtime.d.ts +36 -0
- package/dist/runtime/tool-approval.d.ts +9 -0
- package/dist/runtime/workflows.d.ts +13 -0
- package/dist/server/index.d.ts +47 -0
- package/dist/server/index.js +641 -0
- package/dist/session/default-session-manager.d.ts +77 -0
- package/dist/session/rpc-session-service.d.ts +12 -0
- package/dist/session/runtime-oauth-token-manager.d.ts +28 -0
- package/dist/session/session-artifacts.d.ts +19 -0
- package/dist/session/session-graph.d.ts +15 -0
- package/dist/session/session-host.d.ts +21 -0
- package/dist/session/session-manager.d.ts +50 -0
- package/dist/session/session-manifest.d.ts +30 -0
- package/dist/session/session-service.d.ts +113 -0
- package/dist/session/sqlite-rpc-session-backend.d.ts +30 -0
- package/dist/session/unified-session-persistence-service.d.ts +93 -0
- package/dist/session/workspace-manager.d.ts +28 -0
- package/dist/session/workspace-manifest.d.ts +25 -0
- package/dist/storage/provider-settings-legacy-migration.d.ts +13 -0
- package/dist/storage/provider-settings-manager.d.ts +20 -0
- package/dist/storage/sqlite-session-store.d.ts +29 -0
- package/dist/storage/sqlite-team-store.d.ts +31 -0
- package/dist/storage/team-store.d.ts +2 -0
- package/dist/team/index.d.ts +1 -0
- package/dist/team/projections.d.ts +8 -0
- package/dist/types/common.d.ts +10 -0
- package/dist/types/config.d.ts +37 -0
- package/dist/types/events.d.ts +54 -0
- package/dist/types/provider-settings.d.ts +20 -0
- package/dist/types/sessions.d.ts +9 -0
- package/dist/types/storage.d.ts +37 -0
- package/dist/types/workspace.d.ts +7 -0
- package/dist/types.d.ts +26 -0
- package/package.json +63 -0
- package/src/account/cline-account-service.test.ts +101 -0
- package/src/account/cline-account-service.ts +267 -0
- package/src/account/index.ts +20 -0
- package/src/account/rpc.test.ts +62 -0
- package/src/account/rpc.ts +172 -0
- package/src/account/types.ts +80 -0
- package/src/agents/agent-config-loader.test.ts +234 -0
- package/src/agents/agent-config-loader.ts +107 -0
- package/src/agents/agent-config-parser.ts +191 -0
- package/src/agents/hooks-config-loader.ts +97 -0
- package/src/agents/index.ts +84 -0
- package/src/agents/plugin-config-loader.test.ts +91 -0
- package/src/agents/plugin-config-loader.ts +160 -0
- package/src/agents/plugin-loader.test.ts +102 -0
- package/src/agents/plugin-loader.ts +105 -0
- package/src/agents/plugin-sandbox.test.ts +120 -0
- package/src/agents/plugin-sandbox.ts +471 -0
- package/src/agents/unified-config-file-watcher.test.ts +196 -0
- package/src/agents/unified-config-file-watcher.ts +483 -0
- package/src/agents/user-instruction-config-loader.test.ts +158 -0
- package/src/agents/user-instruction-config-loader.ts +438 -0
- package/src/auth/client.test.ts +40 -0
- package/src/auth/client.ts +25 -0
- package/src/auth/cline.test.ts +130 -0
- package/src/auth/cline.ts +414 -0
- package/src/auth/codex.test.ts +170 -0
- package/src/auth/codex.ts +466 -0
- package/src/auth/oca.test.ts +215 -0
- package/src/auth/oca.ts +546 -0
- package/src/auth/server.ts +216 -0
- package/src/auth/types.ts +78 -0
- package/src/auth/utils.test.ts +128 -0
- package/src/auth/utils.ts +247 -0
- package/src/chat/chat-schema.ts +82 -0
- package/src/default-tools/constants.ts +35 -0
- package/src/default-tools/definitions.test.ts +233 -0
- package/src/default-tools/definitions.ts +632 -0
- package/src/default-tools/executors/apply-patch-parser.ts +520 -0
- package/src/default-tools/executors/apply-patch.ts +359 -0
- package/src/default-tools/executors/bash.ts +205 -0
- package/src/default-tools/executors/editor.ts +231 -0
- package/src/default-tools/executors/file-read.test.ts +25 -0
- package/src/default-tools/executors/file-read.ts +94 -0
- package/src/default-tools/executors/index.ts +75 -0
- package/src/default-tools/executors/search.ts +278 -0
- package/src/default-tools/executors/web-fetch.ts +259 -0
- package/src/default-tools/index.ts +161 -0
- package/src/default-tools/presets.test.ts +63 -0
- package/src/default-tools/presets.ts +168 -0
- package/src/default-tools/schemas.ts +228 -0
- package/src/default-tools/types.ts +324 -0
- package/src/index.ts +119 -0
- package/src/input/file-indexer.d.ts +11 -0
- package/src/input/file-indexer.test.ts +87 -0
- package/src/input/file-indexer.ts +280 -0
- package/src/input/index.ts +7 -0
- package/src/input/mention-enricher.test.ts +82 -0
- package/src/input/mention-enricher.ts +119 -0
- package/src/mcp/config-loader.test.ts +238 -0
- package/src/mcp/config-loader.ts +219 -0
- package/src/mcp/index.ts +26 -0
- package/src/mcp/manager.test.ts +106 -0
- package/src/mcp/manager.ts +262 -0
- package/src/mcp/types.ts +88 -0
- package/src/runtime/hook-file-hooks.test.ts +106 -0
- package/src/runtime/hook-file-hooks.ts +736 -0
- package/src/runtime/index.ts +27 -0
- package/src/runtime/rules.ts +34 -0
- package/src/runtime/runtime-builder.team-persistence.test.ts +203 -0
- package/src/runtime/runtime-builder.test.ts +215 -0
- package/src/runtime/runtime-builder.ts +515 -0
- package/src/runtime/runtime-parity.test.ts +132 -0
- package/src/runtime/sandbox/subprocess-sandbox.ts +207 -0
- package/src/runtime/session-runtime.ts +44 -0
- package/src/runtime/tool-approval.ts +104 -0
- package/src/runtime/workflows.test.ts +119 -0
- package/src/runtime/workflows.ts +54 -0
- package/src/server/index.ts +282 -0
- package/src/session/default-session-manager.e2e.test.ts +354 -0
- package/src/session/default-session-manager.test.ts +816 -0
- package/src/session/default-session-manager.ts +1286 -0
- package/src/session/index.ts +37 -0
- package/src/session/rpc-session-service.ts +189 -0
- package/src/session/runtime-oauth-token-manager.test.ts +137 -0
- package/src/session/runtime-oauth-token-manager.ts +265 -0
- package/src/session/session-artifacts.ts +106 -0
- package/src/session/session-graph.ts +90 -0
- package/src/session/session-host.ts +190 -0
- package/src/session/session-manager.ts +56 -0
- package/src/session/session-manifest.ts +29 -0
- package/src/session/session-service.team-persistence.test.ts +48 -0
- package/src/session/session-service.ts +610 -0
- package/src/session/sqlite-rpc-session-backend.ts +303 -0
- package/src/session/unified-session-persistence-service.ts +781 -0
- package/src/session/workspace-manager.ts +98 -0
- package/src/session/workspace-manifest.ts +100 -0
- package/src/storage/artifact-store.ts +1 -0
- package/src/storage/index.ts +11 -0
- package/src/storage/provider-settings-legacy-migration.test.ts +175 -0
- package/src/storage/provider-settings-legacy-migration.ts +637 -0
- package/src/storage/provider-settings-manager.test.ts +111 -0
- package/src/storage/provider-settings-manager.ts +129 -0
- package/src/storage/session-store.ts +1 -0
- package/src/storage/sqlite-session-store.ts +270 -0
- package/src/storage/sqlite-team-store.ts +443 -0
- package/src/storage/team-store.ts +5 -0
- package/src/team/index.ts +4 -0
- package/src/team/projections.ts +285 -0
- package/src/types/common.ts +14 -0
- package/src/types/config.ts +64 -0
- package/src/types/events.ts +46 -0
- package/src/types/index.ts +24 -0
- package/src/types/provider-settings.ts +43 -0
- package/src/types/sessions.ts +16 -0
- package/src/types/storage.ts +64 -0
- package/src/types/workspace.ts +7 -0
- package/src/types.ts +127 -0
|
@@ -0,0 +1,414 @@
|
|
|
1
|
+
import { startLocalOAuthServer } from "./server.js";
|
|
2
|
+
import type {
|
|
3
|
+
OAuthCredentials,
|
|
4
|
+
OAuthLoginCallbacks,
|
|
5
|
+
OAuthProviderInterface,
|
|
6
|
+
} from "./types.js";
|
|
7
|
+
import {
|
|
8
|
+
isCredentialLikelyExpired,
|
|
9
|
+
parseAuthorizationInput,
|
|
10
|
+
parseOAuthError,
|
|
11
|
+
resolveAuthorizationCodeInput,
|
|
12
|
+
resolveUrl,
|
|
13
|
+
} from "./utils.js";
|
|
14
|
+
|
|
15
|
+
const DEFAULT_AUTH_ENDPOINTS = {
|
|
16
|
+
authorize: "/api/v1/auth/authorize",
|
|
17
|
+
token: "/api/v1/auth/token",
|
|
18
|
+
refresh: "/api/v1/auth/refresh",
|
|
19
|
+
} as const;
|
|
20
|
+
|
|
21
|
+
const DEFAULT_CALLBACK_PATH = "/auth";
|
|
22
|
+
const DEFAULT_CALLBACK_PORTS = Array.from(
|
|
23
|
+
{ length: 11 },
|
|
24
|
+
(_, index) => 48801 + index,
|
|
25
|
+
);
|
|
26
|
+
const DEFAULT_REFRESH_BUFFER_MS = 5 * 60 * 1000;
|
|
27
|
+
const DEFAULT_RETRYABLE_TOKEN_GRACE_MS = 30 * 1000;
|
|
28
|
+
const DEFAULT_HTTP_TIMEOUT_MS = 30 * 1000;
|
|
29
|
+
|
|
30
|
+
export type ClineTokenResolution = {
|
|
31
|
+
forceRefresh?: boolean;
|
|
32
|
+
refreshBufferMs?: number;
|
|
33
|
+
retryableTokenGraceMs?: number;
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
interface ClineAuthApiUser {
|
|
37
|
+
subject: string | null;
|
|
38
|
+
email: string;
|
|
39
|
+
name: string;
|
|
40
|
+
clineUserId: string | null;
|
|
41
|
+
accounts: string[] | null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface ClineAuthResponseData {
|
|
45
|
+
accessToken: string;
|
|
46
|
+
refreshToken?: string;
|
|
47
|
+
tokenType: string;
|
|
48
|
+
expiresAt: string;
|
|
49
|
+
userInfo: ClineAuthApiUser;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
type ClineTokenResponse = {
|
|
53
|
+
success: boolean;
|
|
54
|
+
data: ClineAuthResponseData;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
type HeaderMap = Record<string, string>;
|
|
58
|
+
type HeaderInput = HeaderMap | (() => Promise<HeaderMap> | HeaderMap);
|
|
59
|
+
|
|
60
|
+
export interface ClineOAuthProviderOptions {
|
|
61
|
+
apiBaseUrl: string;
|
|
62
|
+
headers?: HeaderInput;
|
|
63
|
+
callbackPath?: string;
|
|
64
|
+
callbackPorts?: number[];
|
|
65
|
+
requestTimeoutMs?: number;
|
|
66
|
+
/**
|
|
67
|
+
* Optional identity provider name for token exchange.
|
|
68
|
+
*/
|
|
69
|
+
provider?: string;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface ClineOAuthCredentials extends OAuthCredentials {
|
|
73
|
+
metadata?: {
|
|
74
|
+
provider?: string;
|
|
75
|
+
tokenType?: string;
|
|
76
|
+
userInfo?: ClineAuthApiUser;
|
|
77
|
+
[key: string]: unknown;
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
class ClineOAuthTokenError extends Error {
|
|
82
|
+
public readonly status?: number;
|
|
83
|
+
public readonly errorCode?: string;
|
|
84
|
+
|
|
85
|
+
constructor(message: string, opts?: { status?: number; errorCode?: string }) {
|
|
86
|
+
super(message);
|
|
87
|
+
this.name = "ClineOAuthTokenError";
|
|
88
|
+
this.status = opts?.status;
|
|
89
|
+
this.errorCode = opts?.errorCode;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
public isLikelyInvalidGrant(): boolean {
|
|
93
|
+
if (
|
|
94
|
+
this.errorCode &&
|
|
95
|
+
/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode)
|
|
96
|
+
) {
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
if (this.status === 400 || this.status === 401 || this.status === 403) {
|
|
100
|
+
return /invalid|expired|revoked|unauthorized/i.test(this.message);
|
|
101
|
+
}
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function createState(): string {
|
|
107
|
+
const cryptoApi = globalThis.crypto;
|
|
108
|
+
if (!cryptoApi) {
|
|
109
|
+
return Math.random().toString(16).slice(2);
|
|
110
|
+
}
|
|
111
|
+
const bytes = new Uint8Array(16);
|
|
112
|
+
cryptoApi.getRandomValues(bytes);
|
|
113
|
+
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join(
|
|
114
|
+
"",
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function toEpochMs(isoDateTime: string): number {
|
|
119
|
+
const epoch = Date.parse(isoDateTime);
|
|
120
|
+
if (Number.isNaN(epoch)) {
|
|
121
|
+
throw new Error(`Invalid expiresAt value: ${isoDateTime}`);
|
|
122
|
+
}
|
|
123
|
+
return epoch;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function toClineCredentials(
|
|
127
|
+
responseData: ClineAuthResponseData,
|
|
128
|
+
provider: string | undefined,
|
|
129
|
+
fallback: Partial<ClineOAuthCredentials> = {},
|
|
130
|
+
): ClineOAuthCredentials {
|
|
131
|
+
const accountId = responseData.userInfo.clineUserId ?? fallback.accountId;
|
|
132
|
+
const refreshToken = responseData.refreshToken ?? fallback.refresh;
|
|
133
|
+
|
|
134
|
+
if (!refreshToken) {
|
|
135
|
+
throw new Error("Token response did not include a refresh token");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
return {
|
|
139
|
+
access: responseData.accessToken,
|
|
140
|
+
refresh: refreshToken,
|
|
141
|
+
expires: toEpochMs(responseData.expiresAt),
|
|
142
|
+
accountId: accountId ?? undefined,
|
|
143
|
+
email: responseData.userInfo.email || fallback.email,
|
|
144
|
+
metadata: {
|
|
145
|
+
provider,
|
|
146
|
+
tokenType: responseData.tokenType,
|
|
147
|
+
userInfo: responseData.userInfo,
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function resolveHeaders(input?: HeaderInput): Promise<HeaderMap> {
|
|
153
|
+
if (!input) {
|
|
154
|
+
return {};
|
|
155
|
+
}
|
|
156
|
+
return typeof input === "function" ? await input() : input;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function requestAuthorizationUrl(
|
|
160
|
+
options: ClineOAuthProviderOptions,
|
|
161
|
+
params: {
|
|
162
|
+
callbackUrl: string;
|
|
163
|
+
state: string;
|
|
164
|
+
},
|
|
165
|
+
): Promise<string> {
|
|
166
|
+
const authUrl = new URL(
|
|
167
|
+
resolveUrl(options.apiBaseUrl, DEFAULT_AUTH_ENDPOINTS.authorize),
|
|
168
|
+
);
|
|
169
|
+
authUrl.searchParams.set("client_type", "extension");
|
|
170
|
+
authUrl.searchParams.set("callback_url", params.callbackUrl);
|
|
171
|
+
authUrl.searchParams.set("redirect_uri", params.callbackUrl);
|
|
172
|
+
authUrl.searchParams.set("state", params.state);
|
|
173
|
+
|
|
174
|
+
const response = await fetch(authUrl.toString(), {
|
|
175
|
+
method: "GET",
|
|
176
|
+
redirect: "manual",
|
|
177
|
+
headers: await resolveHeaders(options.headers),
|
|
178
|
+
signal: AbortSignal.timeout(
|
|
179
|
+
options.requestTimeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,
|
|
180
|
+
),
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
if (response.status >= 300 && response.status < 400) {
|
|
184
|
+
const redirectUrl = response.headers.get("location");
|
|
185
|
+
if (redirectUrl) {
|
|
186
|
+
return redirectUrl;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
if (!response.ok) {
|
|
191
|
+
const text = await response.text().catch(() => "");
|
|
192
|
+
throw new Error(
|
|
193
|
+
`Authentication request failed: ${response.status} ${text}`,
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const body = (await response.json()) as { redirect_url?: string };
|
|
198
|
+
if (typeof body.redirect_url === "string" && body.redirect_url.length > 0) {
|
|
199
|
+
return body.redirect_url;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
throw new Error("Authentication request did not return a redirect URL");
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
async function exchangeAuthorizationCode(
|
|
206
|
+
code: string,
|
|
207
|
+
callbackUrl: string,
|
|
208
|
+
options: ClineOAuthProviderOptions,
|
|
209
|
+
provider?: string,
|
|
210
|
+
): Promise<ClineOAuthCredentials> {
|
|
211
|
+
const body = {
|
|
212
|
+
grant_type: "authorization_code",
|
|
213
|
+
code,
|
|
214
|
+
client_type: "extension",
|
|
215
|
+
redirect_uri: callbackUrl,
|
|
216
|
+
provider: provider ?? options.provider,
|
|
217
|
+
};
|
|
218
|
+
|
|
219
|
+
const response = await fetch(
|
|
220
|
+
resolveUrl(options.apiBaseUrl, DEFAULT_AUTH_ENDPOINTS.token),
|
|
221
|
+
{
|
|
222
|
+
method: "POST",
|
|
223
|
+
headers: {
|
|
224
|
+
"Content-Type": "application/json",
|
|
225
|
+
...(await resolveHeaders(options.headers)),
|
|
226
|
+
},
|
|
227
|
+
body: JSON.stringify(body),
|
|
228
|
+
signal: AbortSignal.timeout(
|
|
229
|
+
options.requestTimeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,
|
|
230
|
+
),
|
|
231
|
+
},
|
|
232
|
+
);
|
|
233
|
+
|
|
234
|
+
if (!response.ok) {
|
|
235
|
+
const text = await response.text().catch(() => "");
|
|
236
|
+
const details = parseOAuthError(text);
|
|
237
|
+
throw new ClineOAuthTokenError(
|
|
238
|
+
`Token exchange failed: ${response.status}${details.message ? ` - ${details.message}` : ""}`,
|
|
239
|
+
{ status: response.status, errorCode: details.code },
|
|
240
|
+
);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const json = (await response.json()) as ClineTokenResponse;
|
|
244
|
+
if (!json.success || !json.data?.accessToken) {
|
|
245
|
+
throw new Error("Invalid token exchange response");
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return toClineCredentials(json.data, provider ?? options.provider);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export async function loginClineOAuth(
|
|
252
|
+
options: ClineOAuthProviderOptions & {
|
|
253
|
+
callbacks: OAuthLoginCallbacks;
|
|
254
|
+
},
|
|
255
|
+
): Promise<ClineOAuthCredentials> {
|
|
256
|
+
const callbackPorts = options.callbackPorts?.length
|
|
257
|
+
? options.callbackPorts
|
|
258
|
+
: DEFAULT_CALLBACK_PORTS;
|
|
259
|
+
const callbackPath = options.callbackPath ?? DEFAULT_CALLBACK_PATH;
|
|
260
|
+
const state = createState();
|
|
261
|
+
|
|
262
|
+
const localServer = await startLocalOAuthServer({
|
|
263
|
+
ports: callbackPorts,
|
|
264
|
+
callbackPath,
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
const callbackUrl =
|
|
268
|
+
localServer.callbackUrl ||
|
|
269
|
+
`http://127.0.0.1:${callbackPorts[0] ?? DEFAULT_CALLBACK_PORTS[0]}${callbackPath}`;
|
|
270
|
+
|
|
271
|
+
const authUrl = await requestAuthorizationUrl(options, {
|
|
272
|
+
callbackUrl,
|
|
273
|
+
state,
|
|
274
|
+
});
|
|
275
|
+
options.callbacks.onAuth({
|
|
276
|
+
url: authUrl,
|
|
277
|
+
instructions: "Continue the authentication process in your browser.",
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
try {
|
|
281
|
+
let code: string | undefined;
|
|
282
|
+
let provider = options.provider;
|
|
283
|
+
|
|
284
|
+
const authResult = await resolveAuthorizationCodeInput({
|
|
285
|
+
waitForCallback: localServer.waitForCallback,
|
|
286
|
+
cancelWait: localServer.cancelWait,
|
|
287
|
+
onManualCodeInput: options.callbacks.onManualCodeInput,
|
|
288
|
+
parseOptions: { includeProvider: true },
|
|
289
|
+
});
|
|
290
|
+
if (authResult.error) {
|
|
291
|
+
throw new Error(`OAuth error: ${authResult.error}`);
|
|
292
|
+
}
|
|
293
|
+
if (authResult.state && authResult.state !== state) {
|
|
294
|
+
throw new Error("State mismatch");
|
|
295
|
+
}
|
|
296
|
+
code = authResult.code;
|
|
297
|
+
provider = authResult.provider ?? provider;
|
|
298
|
+
|
|
299
|
+
if (!code) {
|
|
300
|
+
const input = await options.callbacks.onPrompt({
|
|
301
|
+
message: "Paste the authorization code (or full redirect URL):",
|
|
302
|
+
});
|
|
303
|
+
const parsed = parseAuthorizationInput(input, { includeProvider: true });
|
|
304
|
+
if (parsed.state && parsed.state !== state) {
|
|
305
|
+
throw new Error("State mismatch");
|
|
306
|
+
}
|
|
307
|
+
code = parsed.code;
|
|
308
|
+
provider = parsed.provider ?? provider;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
if (!code) {
|
|
312
|
+
throw new Error("Missing authorization code");
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
return exchangeAuthorizationCode(code, callbackUrl, options, provider);
|
|
316
|
+
} finally {
|
|
317
|
+
localServer.close();
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
export async function refreshClineToken(
|
|
322
|
+
current: ClineOAuthCredentials,
|
|
323
|
+
options: ClineOAuthProviderOptions,
|
|
324
|
+
): Promise<ClineOAuthCredentials> {
|
|
325
|
+
const response = await fetch(
|
|
326
|
+
resolveUrl(options.apiBaseUrl, DEFAULT_AUTH_ENDPOINTS.refresh),
|
|
327
|
+
{
|
|
328
|
+
method: "POST",
|
|
329
|
+
headers: {
|
|
330
|
+
"Content-Type": "application/json",
|
|
331
|
+
...(await resolveHeaders(options.headers)),
|
|
332
|
+
},
|
|
333
|
+
body: JSON.stringify({
|
|
334
|
+
refreshToken: current.refresh,
|
|
335
|
+
grantType: "refresh_token",
|
|
336
|
+
}),
|
|
337
|
+
signal: AbortSignal.timeout(
|
|
338
|
+
options.requestTimeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,
|
|
339
|
+
),
|
|
340
|
+
},
|
|
341
|
+
);
|
|
342
|
+
|
|
343
|
+
if (!response.ok) {
|
|
344
|
+
const text = await response.text().catch(() => "");
|
|
345
|
+
const details = parseOAuthError(text);
|
|
346
|
+
throw new ClineOAuthTokenError(
|
|
347
|
+
`Token refresh failed: ${response.status}${details.message ? ` - ${details.message}` : ""}`,
|
|
348
|
+
{ status: response.status, errorCode: details.code },
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
const json = (await response.json()) as ClineTokenResponse;
|
|
353
|
+
if (!json.success || !json.data?.accessToken) {
|
|
354
|
+
throw new Error("Invalid token refresh response");
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const provider =
|
|
358
|
+
(current.metadata?.provider as string | undefined) ?? options.provider;
|
|
359
|
+
return toClineCredentials(json.data, provider, current);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
export async function getValidClineCredentials(
|
|
363
|
+
currentCredentials: ClineOAuthCredentials | null,
|
|
364
|
+
providerOptions: ClineOAuthProviderOptions,
|
|
365
|
+
options?: ClineTokenResolution,
|
|
366
|
+
): Promise<ClineOAuthCredentials | null> {
|
|
367
|
+
if (!currentCredentials) {
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
const refreshBufferMs = options?.refreshBufferMs ?? DEFAULT_REFRESH_BUFFER_MS;
|
|
372
|
+
const retryableTokenGraceMs =
|
|
373
|
+
options?.retryableTokenGraceMs ?? DEFAULT_RETRYABLE_TOKEN_GRACE_MS;
|
|
374
|
+
const forceRefresh = options?.forceRefresh === true;
|
|
375
|
+
|
|
376
|
+
if (
|
|
377
|
+
!forceRefresh &&
|
|
378
|
+
!isCredentialLikelyExpired(currentCredentials, refreshBufferMs)
|
|
379
|
+
) {
|
|
380
|
+
return currentCredentials;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
try {
|
|
384
|
+
return await refreshClineToken(currentCredentials, providerOptions);
|
|
385
|
+
} catch (error) {
|
|
386
|
+
if (error instanceof ClineOAuthTokenError && error.isLikelyInvalidGrant()) {
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
if (currentCredentials.expires - Date.now() > retryableTokenGraceMs) {
|
|
390
|
+
// Keep current token on transient refresh failures while still valid.
|
|
391
|
+
return currentCredentials;
|
|
392
|
+
}
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export function createClineOAuthProvider(
|
|
398
|
+
options: ClineOAuthProviderOptions,
|
|
399
|
+
): OAuthProviderInterface {
|
|
400
|
+
return {
|
|
401
|
+
id: "cline",
|
|
402
|
+
name: "Cline Account",
|
|
403
|
+
usesCallbackServer: true,
|
|
404
|
+
async login(callbacks) {
|
|
405
|
+
return loginClineOAuth({ ...options, callbacks });
|
|
406
|
+
},
|
|
407
|
+
async refreshToken(credentials) {
|
|
408
|
+
return refreshClineToken(credentials as ClineOAuthCredentials, options);
|
|
409
|
+
},
|
|
410
|
+
getApiKey(credentials) {
|
|
411
|
+
return `workos:${credentials.access}`;
|
|
412
|
+
},
|
|
413
|
+
};
|
|
414
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import {
|
|
3
|
+
getValidOpenAICodexCredentials,
|
|
4
|
+
normalizeOpenAICodexCredentials,
|
|
5
|
+
refreshOpenAICodexToken,
|
|
6
|
+
} from "./codex.js";
|
|
7
|
+
import type { OAuthCredentials } from "./types.js";
|
|
8
|
+
|
|
9
|
+
function toBase64Url(value: string): string {
|
|
10
|
+
return Buffer.from(value, "utf8").toString("base64url");
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function createJwt(payload: Record<string, unknown>): string {
|
|
14
|
+
return `${toBase64Url(JSON.stringify({ alg: "none", typ: "JWT" }))}.${toBase64Url(JSON.stringify(payload))}.sig`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function createCredentials(
|
|
18
|
+
overrides: Partial<OAuthCredentials> = {},
|
|
19
|
+
): OAuthCredentials {
|
|
20
|
+
return {
|
|
21
|
+
access: "access-old",
|
|
22
|
+
refresh: "refresh-old",
|
|
23
|
+
expires: 0,
|
|
24
|
+
accountId: "acct-old",
|
|
25
|
+
email: "old@example.com",
|
|
26
|
+
metadata: { provider: "openai-codex" },
|
|
27
|
+
...overrides,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
describe("auth/codex token lifecycle", () => {
|
|
32
|
+
afterEach(() => {
|
|
33
|
+
vi.unstubAllGlobals();
|
|
34
|
+
vi.restoreAllMocks();
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("returns current credentials when not expired", async () => {
|
|
38
|
+
const nowSpy = vi.spyOn(Date, "now").mockReturnValue(10_000);
|
|
39
|
+
const current = createCredentials({ expires: 400_000 });
|
|
40
|
+
const fetchMock = vi.fn();
|
|
41
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
42
|
+
|
|
43
|
+
const result = await getValidOpenAICodexCredentials(current);
|
|
44
|
+
expect(result).toBe(current);
|
|
45
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
46
|
+
nowSpy.mockRestore();
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
it("refreshes expired credentials and preserves provider metadata", async () => {
|
|
50
|
+
const nowSpy = vi.spyOn(Date, "now").mockReturnValue(100_000);
|
|
51
|
+
const idToken = createJwt({
|
|
52
|
+
"https://api.openai.com/auth": { chatgpt_account_id: "acct-new" },
|
|
53
|
+
email: "new@example.com",
|
|
54
|
+
});
|
|
55
|
+
const accessToken = createJwt({
|
|
56
|
+
"https://api.openai.com/auth": { chatgpt_account_id: "acct-new" },
|
|
57
|
+
});
|
|
58
|
+
vi.stubGlobal(
|
|
59
|
+
"fetch",
|
|
60
|
+
vi.fn(
|
|
61
|
+
async () =>
|
|
62
|
+
new Response(
|
|
63
|
+
JSON.stringify({
|
|
64
|
+
access_token: accessToken,
|
|
65
|
+
refresh_token: "refresh-new",
|
|
66
|
+
expires_in: 3600,
|
|
67
|
+
email: "new@example.com",
|
|
68
|
+
id_token: idToken,
|
|
69
|
+
}),
|
|
70
|
+
{ status: 200, headers: { "Content-Type": "application/json" } },
|
|
71
|
+
),
|
|
72
|
+
),
|
|
73
|
+
);
|
|
74
|
+
|
|
75
|
+
const current = createCredentials({ expires: 110_000 });
|
|
76
|
+
const result = await getValidOpenAICodexCredentials(current);
|
|
77
|
+
expect(result).toMatchObject({
|
|
78
|
+
access: accessToken,
|
|
79
|
+
refresh: "refresh-new",
|
|
80
|
+
accountId: "acct-new",
|
|
81
|
+
email: "new@example.com",
|
|
82
|
+
metadata: { provider: "openai-codex" },
|
|
83
|
+
});
|
|
84
|
+
nowSpy.mockRestore();
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
it("returns null on invalid_grant refresh errors", async () => {
|
|
88
|
+
const nowSpy = vi.spyOn(Date, "now").mockReturnValue(100_000);
|
|
89
|
+
vi.stubGlobal(
|
|
90
|
+
"fetch",
|
|
91
|
+
vi.fn(
|
|
92
|
+
async () =>
|
|
93
|
+
new Response(
|
|
94
|
+
JSON.stringify({
|
|
95
|
+
error: "invalid_grant",
|
|
96
|
+
error_description: "token revoked",
|
|
97
|
+
}),
|
|
98
|
+
{
|
|
99
|
+
status: 400,
|
|
100
|
+
headers: { "Content-Type": "application/json" },
|
|
101
|
+
},
|
|
102
|
+
),
|
|
103
|
+
),
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
const result = await getValidOpenAICodexCredentials(
|
|
107
|
+
createCredentials({ expires: 120_000 }),
|
|
108
|
+
);
|
|
109
|
+
expect(result).toBeNull();
|
|
110
|
+
nowSpy.mockRestore();
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it("keeps current credentials on non-invalid transient refresh failures when still valid", async () => {
|
|
114
|
+
const nowSpy = vi.spyOn(Date, "now").mockReturnValue(100_000);
|
|
115
|
+
vi.stubGlobal(
|
|
116
|
+
"fetch",
|
|
117
|
+
vi.fn(
|
|
118
|
+
async () =>
|
|
119
|
+
new Response(
|
|
120
|
+
JSON.stringify({
|
|
121
|
+
error: "server_error",
|
|
122
|
+
error_description: "try again",
|
|
123
|
+
}),
|
|
124
|
+
{
|
|
125
|
+
status: 500,
|
|
126
|
+
headers: { "Content-Type": "application/json" },
|
|
127
|
+
},
|
|
128
|
+
),
|
|
129
|
+
),
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
const current = createCredentials({ expires: 150_000 });
|
|
133
|
+
const result = await getValidOpenAICodexCredentials(current, {
|
|
134
|
+
refreshBufferMs: 60_000,
|
|
135
|
+
retryableTokenGraceMs: 30_000,
|
|
136
|
+
});
|
|
137
|
+
expect(result).toBe(current);
|
|
138
|
+
nowSpy.mockRestore();
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
it("normalizes credentials by deriving accountId from access token", () => {
|
|
142
|
+
const accessToken = createJwt({
|
|
143
|
+
"https://api.openai.com/auth": { chatgpt_account_id: "acct-derived" },
|
|
144
|
+
});
|
|
145
|
+
const normalized = normalizeOpenAICodexCredentials({
|
|
146
|
+
access: accessToken,
|
|
147
|
+
refresh: "refresh",
|
|
148
|
+
expires: 1,
|
|
149
|
+
});
|
|
150
|
+
expect(normalized.accountId).toBe("acct-derived");
|
|
151
|
+
expect(normalized.metadata).toMatchObject({ provider: "openai-codex" });
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it("refreshOpenAICodexToken throws when response is structurally invalid", async () => {
|
|
155
|
+
vi.stubGlobal(
|
|
156
|
+
"fetch",
|
|
157
|
+
vi.fn(
|
|
158
|
+
async () =>
|
|
159
|
+
new Response(JSON.stringify({ access_token: "only-access" }), {
|
|
160
|
+
status: 200,
|
|
161
|
+
headers: { "Content-Type": "application/json" },
|
|
162
|
+
}),
|
|
163
|
+
),
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
await expect(refreshOpenAICodexToken("refresh")).rejects.toThrow(
|
|
167
|
+
"Failed to refresh OpenAI Codex token",
|
|
168
|
+
);
|
|
169
|
+
});
|
|
170
|
+
});
|