offrouter-core 0.2.0 → 0.2.2
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/dist/audit.d.ts +137 -0
- package/dist/audit.d.ts.map +1 -0
- package/dist/audit.js +320 -0
- package/dist/audit.js.map +1 -0
- package/dist/auth/credential-chain.d.ts +84 -0
- package/dist/auth/credential-chain.d.ts.map +1 -0
- package/dist/auth/credential-chain.js +150 -0
- package/dist/auth/credential-chain.js.map +1 -0
- package/dist/auth/index.d.ts +10 -0
- package/dist/auth/index.d.ts.map +1 -0
- package/dist/auth/index.js +7 -0
- package/dist/auth/index.js.map +1 -0
- package/dist/auth/keychain.d.ts +60 -0
- package/dist/auth/keychain.d.ts.map +1 -0
- package/dist/auth/keychain.js +104 -0
- package/dist/auth/keychain.js.map +1 -0
- package/dist/auth/oauth-pkce.d.ts +138 -0
- package/dist/auth/oauth-pkce.d.ts.map +1 -0
- package/dist/auth/oauth-pkce.js +375 -0
- package/dist/auth/oauth-pkce.js.map +1 -0
- package/dist/auth/oauth-server.d.ts +36 -0
- package/dist/auth/oauth-server.d.ts.map +1 -0
- package/dist/auth/oauth-server.js +210 -0
- package/dist/auth/oauth-server.js.map +1 -0
- package/dist/config.d.ts +76 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +355 -0
- package/dist/config.js.map +1 -0
- package/dist/delegation.d.ts +123 -0
- package/dist/delegation.d.ts.map +1 -0
- package/dist/delegation.js +455 -0
- package/dist/delegation.js.map +1 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +26 -0
- package/dist/index.js.map +1 -0
- package/dist/policy.d.ts +45 -0
- package/dist/policy.d.ts.map +1 -0
- package/dist/policy.js +318 -0
- package/dist/policy.js.map +1 -0
- package/{src/protocol.ts → dist/protocol.d.ts} +2 -2
- package/dist/protocol.d.ts.map +1 -0
- package/dist/protocol.js +6 -0
- package/dist/protocol.js.map +1 -0
- package/dist/providers/adapter.d.ts +137 -0
- package/dist/providers/adapter.d.ts.map +1 -0
- package/dist/providers/adapter.js +163 -0
- package/dist/providers/adapter.js.map +1 -0
- package/dist/providers/catalog-data.d.ts +128 -0
- package/dist/providers/catalog-data.d.ts.map +1 -0
- package/dist/providers/catalog-data.js +397 -0
- package/dist/providers/catalog-data.js.map +1 -0
- package/dist/providers/catalog.d.ts +63 -0
- package/dist/providers/catalog.d.ts.map +1 -0
- package/dist/providers/catalog.js +394 -0
- package/dist/providers/catalog.js.map +1 -0
- package/dist/providers/fake.d.ts +46 -0
- package/dist/providers/fake.d.ts.map +1 -0
- package/dist/providers/fake.js +234 -0
- package/dist/providers/fake.js.map +1 -0
- package/dist/providers/openai-compatible.d.ts +65 -0
- package/dist/providers/openai-compatible.d.ts.map +1 -0
- package/dist/providers/openai-compatible.js +434 -0
- package/dist/providers/openai-compatible.js.map +1 -0
- package/dist/proxy/responses-mapper.d.ts +366 -0
- package/dist/proxy/responses-mapper.d.ts.map +1 -0
- package/dist/proxy/responses-mapper.js +517 -0
- package/dist/proxy/responses-mapper.js.map +1 -0
- package/dist/proxy/responses-server.d.ts +29 -0
- package/dist/proxy/responses-server.d.ts.map +1 -0
- package/dist/proxy/responses-server.js +360 -0
- package/dist/proxy/responses-server.js.map +1 -0
- package/dist/router.d.ts +18 -0
- package/dist/router.d.ts.map +1 -0
- package/dist/router.js +296 -0
- package/dist/router.js.map +1 -0
- package/dist/schemas.d.ts +560 -0
- package/dist/schemas.d.ts.map +1 -0
- package/{src/schemas.ts → dist/schemas.js} +83 -103
- package/dist/schemas.js.map +1 -0
- package/dist/secrets.d.ts +112 -0
- package/dist/secrets.d.ts.map +1 -0
- package/dist/secrets.js +326 -0
- package/dist/secrets.js.map +1 -0
- package/dist/types.d.ts +117 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +6 -0
- package/dist/types.js.map +1 -0
- package/dist/usage-file.d.ts +59 -0
- package/dist/usage-file.d.ts.map +1 -0
- package/dist/usage-file.js +316 -0
- package/dist/usage-file.js.map +1 -0
- package/dist/usage.d.ts +235 -0
- package/dist/usage.d.ts.map +1 -0
- package/dist/usage.js +517 -0
- package/dist/usage.js.map +1 -0
- package/package.json +9 -4
- package/src/audit.test.ts +0 -302
- package/src/audit.ts +0 -553
- package/src/auth/credential-chain.test.ts +0 -326
- package/src/auth/credential-chain.ts +0 -235
- package/src/auth/index.ts +0 -45
- package/src/auth/keychain.test.ts +0 -265
- package/src/auth/keychain.ts +0 -168
- package/src/auth/oauth-pkce.test.ts +0 -329
- package/src/auth/oauth-pkce.ts +0 -571
- package/src/auth/oauth-server.test.ts +0 -83
- package/src/auth/oauth-server.ts +0 -296
- package/src/config.test.ts +0 -479
- package/src/config.ts +0 -505
- package/src/delegation.test.ts +0 -368
- package/src/delegation.ts +0 -605
- package/src/index.ts +0 -280
- package/src/policy.test.ts +0 -634
- package/src/policy.ts +0 -420
- package/src/providers/adapter.test.ts +0 -293
- package/src/providers/adapter.ts +0 -328
- package/src/providers/catalog-data.test.ts +0 -258
- package/src/providers/catalog-data.ts +0 -498
- package/src/providers/catalog.test.ts +0 -84
- package/src/providers/catalog.ts +0 -483
- package/src/providers/fake.ts +0 -312
- package/src/providers/openai-compatible.test.ts +0 -366
- package/src/providers/openai-compatible.ts +0 -554
- package/src/proxy/responses-mapper.test.ts +0 -290
- package/src/proxy/responses-mapper.ts +0 -736
- package/src/proxy/responses-server.test.ts +0 -322
- package/src/proxy/responses-server.ts +0 -469
- package/src/router.test.ts +0 -699
- package/src/router.ts +0 -352
- package/src/schemas.test.ts +0 -291
- package/src/secrets.test.ts +0 -271
- package/src/secrets.ts +0 -461
- package/src/types.ts +0 -173
- package/src/usage-file.test.ts +0 -243
- package/src/usage-file.ts +0 -435
- package/src/usage.test.ts +0 -335
- package/src/usage.ts +0 -859
- package/tsconfig.json +0 -9
package/src/auth/oauth-pkce.ts
DELETED
|
@@ -1,571 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OAuth PKCE flow for OffRouter.
|
|
3
|
-
*
|
|
4
|
-
* Supports Anthropic and OpenAI/Codex only (opt-in, bring-your-own-client-id).
|
|
5
|
-
* Gemini/xAI/Z.ai are API-key only and do NOT implement OAuth.
|
|
6
|
-
*
|
|
7
|
-
* Never auto-triggers OAuth. Requires explicit user configuration.
|
|
8
|
-
* Tokens are stored in the SecretStore (keychain or file fallback).
|
|
9
|
-
*/
|
|
10
|
-
import { randomBytes } from "node:crypto";
|
|
11
|
-
import type { SecretStore } from "../secrets.js";
|
|
12
|
-
import { Redacted } from "./credential-chain.js";
|
|
13
|
-
import { setOAuthTokens } from "./keychain.js";
|
|
14
|
-
import { startCallbackServer } from "./oauth-server.js";
|
|
15
|
-
|
|
16
|
-
// ---------------------------------------------------------------------------
|
|
17
|
-
// PKCE code generation
|
|
18
|
-
// ---------------------------------------------------------------------------
|
|
19
|
-
|
|
20
|
-
const VERIFIER_CHARS =
|
|
21
|
-
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
* Generate a random code verifier for PKCE (RFC 7636).
|
|
25
|
-
* Length is between 43 and 128 characters.
|
|
26
|
-
*/
|
|
27
|
-
export function generateCodeVerifier(): string {
|
|
28
|
-
const length = 64 + (randomBytes(1)[0]! % 32); // 64-95 chars
|
|
29
|
-
const bytes = randomBytes(length);
|
|
30
|
-
let verifier = "";
|
|
31
|
-
for (let i = 0; i < length; i++) {
|
|
32
|
-
verifier += VERIFIER_CHARS[bytes[i]! % VERIFIER_CHARS.length];
|
|
33
|
-
}
|
|
34
|
-
return verifier;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
/**
|
|
38
|
-
* Generate a S256 code challenge from a verifier (RFC 7636).
|
|
39
|
-
* Uses Web Crypto API (available in Node >= 22, Workers, browsers).
|
|
40
|
-
*/
|
|
41
|
-
export async function generateCodeChallenge(
|
|
42
|
-
verifier: string,
|
|
43
|
-
): Promise<string> {
|
|
44
|
-
const encoder = new TextEncoder();
|
|
45
|
-
const data = encoder.encode(verifier);
|
|
46
|
-
const digest = await crypto.subtle.digest("SHA-256", data);
|
|
47
|
-
const base64 = btoa(
|
|
48
|
-
String.fromCharCode(...new Uint8Array(digest)),
|
|
49
|
-
);
|
|
50
|
-
return base64
|
|
51
|
-
.replace(/\+/g, "-")
|
|
52
|
-
.replace(/\//g, "_")
|
|
53
|
-
.replace(/=+$/, "");
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
// ---------------------------------------------------------------------------
|
|
57
|
-
// OAuth provider configs
|
|
58
|
-
// ---------------------------------------------------------------------------
|
|
59
|
-
|
|
60
|
-
export interface OAuthProviderConfig {
|
|
61
|
-
authorizeUrl: string;
|
|
62
|
-
tokenUrl: string;
|
|
63
|
-
scopes: string[];
|
|
64
|
-
defaultClientId?: string;
|
|
65
|
-
clientIdEnvVar?: string;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* OAuth PKCE configurations for supported providers.
|
|
70
|
-
* Only Anthropic and OpenAI/Codex are supported.
|
|
71
|
-
* Gemini/xAI/Z.ai are API-key only.
|
|
72
|
-
*/
|
|
73
|
-
export const PKCE_CONFIGS: Record<string, OAuthProviderConfig> = {
|
|
74
|
-
anthropic: {
|
|
75
|
-
authorizeUrl: "https://console.anthropic.com/oauth/authorize",
|
|
76
|
-
tokenUrl: "https://console.anthropic.com/oauth/token",
|
|
77
|
-
scopes: ["api", "offline_access"],
|
|
78
|
-
clientIdEnvVar: "OFFROUTER_ANTHROPIC_CLIENT_ID",
|
|
79
|
-
// No default client id; users must bring their own.
|
|
80
|
-
},
|
|
81
|
-
openai: {
|
|
82
|
-
authorizeUrl: "https://auth.openai.com/oauth/authorize",
|
|
83
|
-
tokenUrl: "https://auth.openai.com/oauth/token",
|
|
84
|
-
scopes: ["offline_access"],
|
|
85
|
-
clientIdEnvVar: "OFFROUTER_OPENAI_CLIENT_ID",
|
|
86
|
-
// Note: reuses Codex client id; documented as fragile.
|
|
87
|
-
},
|
|
88
|
-
};
|
|
89
|
-
|
|
90
|
-
/**
|
|
91
|
-
* Returns true if the provider supports OAuth (opt-in).
|
|
92
|
-
*/
|
|
93
|
-
export function isOAuthProvider(providerId: string): boolean {
|
|
94
|
-
return providerId in PKCE_CONFIGS;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
// ---------------------------------------------------------------------------
|
|
98
|
-
// OAuth session store (in-memory, out-of-band — NOT embedded in state)
|
|
99
|
-
// ---------------------------------------------------------------------------
|
|
100
|
-
|
|
101
|
-
/** Time-to-live for a stored OAuth session (10 minutes). */
|
|
102
|
-
const SESSION_TTL_MS = 10 * 60 * 1000;
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* In-memory session data associated with a PKCE nonce.
|
|
106
|
-
* Never serialised into the caller-visible state string.
|
|
107
|
-
*/
|
|
108
|
-
export interface OAuthSession {
|
|
109
|
-
codeVerifier: string;
|
|
110
|
-
redirectUri: string;
|
|
111
|
-
createdAt: number;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** Module-level session store: nonce → session. */
|
|
115
|
-
const sessions = new Map<string, OAuthSession>();
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Retrieve and delete a session by nonce (one-shot consume).
|
|
119
|
-
* Returns null if the nonce is unknown, already consumed, or expired.
|
|
120
|
-
*/
|
|
121
|
-
export function consumeOAuthSession(nonce: string): OAuthSession | null {
|
|
122
|
-
const session = sessions.get(nonce);
|
|
123
|
-
if (!session) return null;
|
|
124
|
-
sessions.delete(nonce);
|
|
125
|
-
if (Date.now() - session.createdAt > SESSION_TTL_MS) {
|
|
126
|
-
return null; // expired
|
|
127
|
-
}
|
|
128
|
-
return session;
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* Cancel / discard a session without consuming it.
|
|
133
|
-
*/
|
|
134
|
-
export function cancelOAuthSession(nonce: string): void {
|
|
135
|
-
sessions.delete(nonce);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
// ---------------------------------------------------------------------------
|
|
139
|
-
// OAuth flow state
|
|
140
|
-
// ---------------------------------------------------------------------------
|
|
141
|
-
|
|
142
|
-
export interface OAuthFlowState {
|
|
143
|
-
provider: string;
|
|
144
|
-
nonce: string;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
export interface OAuthFlowResult {
|
|
148
|
-
authorizeUrl: string;
|
|
149
|
-
state: string;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
export interface OAuthTokenResponse {
|
|
153
|
-
accessToken: Redacted<string>;
|
|
154
|
-
refreshToken?: Redacted<string>;
|
|
155
|
-
expiresIn?: number;
|
|
156
|
-
scope?: string;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
export interface OAuthStartOptions {
|
|
160
|
-
redirectUri: string;
|
|
161
|
-
/** Override client ID (default from env or PKCE_CONFIGS). */
|
|
162
|
-
clientId?: string;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
export interface OAuthTokenOptions {
|
|
166
|
-
store: SecretStore;
|
|
167
|
-
fetch?: typeof globalThis.fetch;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
/**
|
|
171
|
-
* Create an OAuth state string that encodes provider metadata.
|
|
172
|
-
* Used to validate the callback matches the initiated flow.
|
|
173
|
-
*/
|
|
174
|
-
export function createOAuthState(provider: string): string {
|
|
175
|
-
const nonce = randomBytes(16).toString("hex");
|
|
176
|
-
return JSON.stringify({ provider, nonce });
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
/**
|
|
180
|
-
* Start an OAuth PKCE flow for the given provider.
|
|
181
|
-
* Returns the authorization URL and state for redirect.
|
|
182
|
-
* Never auto-triggers; requires explicit user configuration.
|
|
183
|
-
*/
|
|
184
|
-
export async function startOAuthFlow(
|
|
185
|
-
provider: string,
|
|
186
|
-
options: OAuthStartOptions,
|
|
187
|
-
): Promise<OAuthFlowResult> {
|
|
188
|
-
const config = PKCE_CONFIGS[provider];
|
|
189
|
-
if (!config) {
|
|
190
|
-
throw new Error(
|
|
191
|
-
`OAuth not supported for provider: ${provider}. ` +
|
|
192
|
-
`OAuth is only available for anthropic and openai providers.`,
|
|
193
|
-
);
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
const clientId =
|
|
197
|
-
options.clientId ??
|
|
198
|
-
(config.clientIdEnvVar ? process.env[config.clientIdEnvVar] : undefined);
|
|
199
|
-
|
|
200
|
-
if (!clientId) {
|
|
201
|
-
throw new Error(
|
|
202
|
-
`Client ID required for ${provider} OAuth. ` +
|
|
203
|
-
`Set the ${config.clientIdEnvVar ?? "client id"} environment variable ` +
|
|
204
|
-
`or pass it explicitly.`,
|
|
205
|
-
);
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
const codeVerifier = generateCodeVerifier();
|
|
209
|
-
const codeChallenge = await generateCodeChallenge(codeVerifier);
|
|
210
|
-
const state = createOAuthState(provider);
|
|
211
|
-
|
|
212
|
-
const params = new URLSearchParams({
|
|
213
|
-
response_type: "code",
|
|
214
|
-
client_id: clientId,
|
|
215
|
-
redirect_uri: options.redirectUri,
|
|
216
|
-
code_challenge: codeChallenge,
|
|
217
|
-
code_challenge_method: "S256",
|
|
218
|
-
state,
|
|
219
|
-
scope: config.scopes.join(" "),
|
|
220
|
-
});
|
|
221
|
-
|
|
222
|
-
const authorizeUrl = `${config.authorizeUrl}?${params.toString()}`;
|
|
223
|
-
|
|
224
|
-
// Store the verifier OOB so it never appears in the caller-visible state
|
|
225
|
-
const parsed = JSON.parse(state) as { provider: string; nonce: string };
|
|
226
|
-
sessions.set(parsed.nonce, {
|
|
227
|
-
codeVerifier,
|
|
228
|
-
redirectUri: options.redirectUri,
|
|
229
|
-
createdAt: Date.now(),
|
|
230
|
-
});
|
|
231
|
-
|
|
232
|
-
return {
|
|
233
|
-
authorizeUrl,
|
|
234
|
-
state, // clean — provider + nonce only, no secrets
|
|
235
|
-
};
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
/**
|
|
239
|
-
* Exchange an authorization code for tokens.
|
|
240
|
-
* Called after the user completes the OAuth flow in their browser.
|
|
241
|
-
*/
|
|
242
|
-
export async function exchangeCodeForTokens(
|
|
243
|
-
provider: string,
|
|
244
|
-
code: string,
|
|
245
|
-
statePayload: string,
|
|
246
|
-
options: OAuthTokenOptions,
|
|
247
|
-
): Promise<OAuthTokenResponse> {
|
|
248
|
-
const config = PKCE_CONFIGS[provider];
|
|
249
|
-
if (!config) {
|
|
250
|
-
throw new Error(`OAuth not supported for provider: ${provider}`);
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
let stateData: { provider?: string; nonce?: string };
|
|
254
|
-
try {
|
|
255
|
-
stateData = JSON.parse(statePayload) as typeof stateData;
|
|
256
|
-
} catch {
|
|
257
|
-
throw new Error("Invalid OAuth state payload");
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
if (!stateData.nonce) {
|
|
261
|
-
throw new Error("Missing nonce in OAuth state");
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
const session = consumeOAuthSession(stateData.nonce);
|
|
265
|
-
if (!session) {
|
|
266
|
-
throw new Error(
|
|
267
|
-
"OAuth session expired, already consumed, or not found. Please restart the OAuth flow.",
|
|
268
|
-
);
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
if (!session.codeVerifier) {
|
|
272
|
-
throw new Error("Missing code verifier in OAuth session");
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
const clientId =
|
|
276
|
-
config.clientIdEnvVar
|
|
277
|
-
? (process.env[config.clientIdEnvVar] ?? "")
|
|
278
|
-
: "";
|
|
279
|
-
|
|
280
|
-
const tokenParams = new URLSearchParams({
|
|
281
|
-
grant_type: "authorization_code",
|
|
282
|
-
code,
|
|
283
|
-
redirect_uri: session.redirectUri ?? "http://127.0.0.1:8765/callback",
|
|
284
|
-
client_id: clientId,
|
|
285
|
-
code_verifier: session.codeVerifier,
|
|
286
|
-
});
|
|
287
|
-
|
|
288
|
-
const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
289
|
-
const response = await fetchImpl(config.tokenUrl, {
|
|
290
|
-
method: "POST",
|
|
291
|
-
headers: {
|
|
292
|
-
"content-type": "application/x-www-form-urlencoded",
|
|
293
|
-
},
|
|
294
|
-
body: tokenParams.toString(),
|
|
295
|
-
});
|
|
296
|
-
|
|
297
|
-
if (!response.ok) {
|
|
298
|
-
const body = await response.text().catch(() => "");
|
|
299
|
-
throw new Error(
|
|
300
|
-
`Token exchange failed for ${provider}: HTTP ${response.status} ${body}`,
|
|
301
|
-
);
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
const json = (await response.json()) as {
|
|
305
|
-
access_token?: string;
|
|
306
|
-
refresh_token?: string;
|
|
307
|
-
expires_in?: number;
|
|
308
|
-
scope?: string;
|
|
309
|
-
};
|
|
310
|
-
|
|
311
|
-
if (!json.access_token) {
|
|
312
|
-
throw new Error(
|
|
313
|
-
`Token exchange for ${provider} returned no access_token`,
|
|
314
|
-
);
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
// Store tokens in secret store (structured)
|
|
318
|
-
if (options.store) {
|
|
319
|
-
const obtainedAt = Date.now();
|
|
320
|
-
await setOAuthTokens(
|
|
321
|
-
provider,
|
|
322
|
-
{
|
|
323
|
-
accessToken: json.access_token,
|
|
324
|
-
refreshToken: json.refresh_token,
|
|
325
|
-
expiresAt: json.expires_in
|
|
326
|
-
? obtainedAt + json.expires_in * 1000
|
|
327
|
-
: undefined,
|
|
328
|
-
scope: json.scope,
|
|
329
|
-
obtainedAt,
|
|
330
|
-
},
|
|
331
|
-
options.store,
|
|
332
|
-
);
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
return {
|
|
336
|
-
accessToken: new Redacted(json.access_token),
|
|
337
|
-
refreshToken: json.refresh_token
|
|
338
|
-
? new Redacted(json.refresh_token)
|
|
339
|
-
: undefined,
|
|
340
|
-
expiresIn: json.expires_in,
|
|
341
|
-
scope: json.scope,
|
|
342
|
-
};
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
// ---------------------------------------------------------------------------
|
|
346
|
-
// Login orchestration (callback server + browser + token exchange)
|
|
347
|
-
// ---------------------------------------------------------------------------
|
|
348
|
-
|
|
349
|
-
/** Default loopback ports for supported providers. */
|
|
350
|
-
const DEFAULT_CALLBACK_PORTS: Record<string, number> = {
|
|
351
|
-
anthropic: 1456,
|
|
352
|
-
openai: 1455,
|
|
353
|
-
};
|
|
354
|
-
|
|
355
|
-
/**
|
|
356
|
-
* Return the default callback port for a provider, or 0 (OS-assigned).
|
|
357
|
-
*/
|
|
358
|
-
export function defaultCallbackPort(provider: string): number {
|
|
359
|
-
return DEFAULT_CALLBACK_PORTS[provider] ?? 0;
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
/**
|
|
363
|
-
* Resolve the client id for a provider from process env (or a provided env
|
|
364
|
-
* override). Returns undefined if the env var is not set.
|
|
365
|
-
*/
|
|
366
|
-
export function resolveClientId(
|
|
367
|
-
provider: string,
|
|
368
|
-
env: NodeJS.ProcessEnv = process.env,
|
|
369
|
-
): string | undefined {
|
|
370
|
-
const config = PKCE_CONFIGS[provider];
|
|
371
|
-
if (!config?.clientIdEnvVar) return undefined;
|
|
372
|
-
return env[config.clientIdEnvVar] ?? undefined;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
export interface RunOAuthLoginOptions {
|
|
376
|
-
provider: string;
|
|
377
|
-
store: SecretStore;
|
|
378
|
-
/** Override client id (else resolved from env / PKCE_CONFIGS). */
|
|
379
|
-
clientId?: string;
|
|
380
|
-
/** Loopback port (defaults to provider default or 0). */
|
|
381
|
-
port?: number;
|
|
382
|
-
/** Wait timeout in ms (default 5 min). */
|
|
383
|
-
timeoutMs?: number;
|
|
384
|
-
/** Called with the authorize URL once built (test/display). */
|
|
385
|
-
onAuthorizeUrl?: (url: string) => void;
|
|
386
|
-
/** Best-effort browser open (non-throwing). */
|
|
387
|
-
openBrowser?: (url: string) => Promise<boolean> | boolean;
|
|
388
|
-
/** Injectable fetch (tests). */
|
|
389
|
-
fetch?: typeof globalThis.fetch;
|
|
390
|
-
/** Optional abort signal. */
|
|
391
|
-
signal?: AbortSignal;
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
export interface RunOAuthLoginResult {
|
|
395
|
-
provider: string;
|
|
396
|
-
redirectUri: string;
|
|
397
|
-
expiresAt?: number;
|
|
398
|
-
scope?: string;
|
|
399
|
-
}
|
|
400
|
-
|
|
401
|
-
/**
|
|
402
|
-
* Run the full OAuth PKCE login flow:
|
|
403
|
-
* 1. Start a local callback server on 127.0.0.1
|
|
404
|
-
* 2. Build the authorize URL with PKCE challenge + state
|
|
405
|
-
* 3. Notify caller (onAuthorizeUrl) and attempt browser open
|
|
406
|
-
* 4. Wait for the provider callback (code + state)
|
|
407
|
-
* 5. Exchange code for tokens
|
|
408
|
-
* 6. Store structured tokens in the secret store
|
|
409
|
-
* 7. Clean up the server
|
|
410
|
-
*/
|
|
411
|
-
export async function runOAuthLogin(
|
|
412
|
-
opts: RunOAuthLoginOptions,
|
|
413
|
-
): Promise<RunOAuthLoginResult> {
|
|
414
|
-
const config = PKCE_CONFIGS[opts.provider];
|
|
415
|
-
if (!config) {
|
|
416
|
-
throw new Error(
|
|
417
|
-
`OAuth not supported for provider: ${opts.provider}. ` +
|
|
418
|
-
`OAuth is only available for anthropic and openai providers.`,
|
|
419
|
-
);
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
const clientId =
|
|
423
|
-
opts.clientId ?? resolveClientId(opts.provider) ?? undefined;
|
|
424
|
-
if (!clientId) {
|
|
425
|
-
const envHint =
|
|
426
|
-
config.clientIdEnvVar
|
|
427
|
-
? `Set the ${config.clientIdEnvVar} environment variable or pass it explicitly.`
|
|
428
|
-
: "A client id is required for this provider.";
|
|
429
|
-
throw new Error(
|
|
430
|
-
`Client ID required for ${opts.provider} OAuth. ${envHint}`,
|
|
431
|
-
);
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
// 1. Start callback server
|
|
435
|
-
const port = opts.port ?? defaultCallbackPort(opts.provider);
|
|
436
|
-
const server = await startCallbackServer(port);
|
|
437
|
-
|
|
438
|
-
try {
|
|
439
|
-
const redirectUri = server.url;
|
|
440
|
-
|
|
441
|
-
// 2. Build the authorize URL with PKCE
|
|
442
|
-
const flow = await startOAuthFlow(opts.provider, {
|
|
443
|
-
redirectUri,
|
|
444
|
-
clientId,
|
|
445
|
-
});
|
|
446
|
-
|
|
447
|
-
// 3. Notify and attempt to open browser
|
|
448
|
-
opts.onAuthorizeUrl?.(flow.authorizeUrl);
|
|
449
|
-
if (opts.openBrowser) {
|
|
450
|
-
try {
|
|
451
|
-
await opts.openBrowser(flow.authorizeUrl);
|
|
452
|
-
} catch {
|
|
453
|
-
// Best-effort only.
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
|
|
457
|
-
// 4. Wait for callback (validates expected state)
|
|
458
|
-
const { code } = await server.waitForCode({
|
|
459
|
-
expectedState: flow.state,
|
|
460
|
-
timeoutMs: opts.timeoutMs,
|
|
461
|
-
signal: opts.signal,
|
|
462
|
-
});
|
|
463
|
-
|
|
464
|
-
// 5. Exchange code for tokens (also stores them)
|
|
465
|
-
const tokens = await exchangeCodeForTokens(opts.provider, code, flow.state, {
|
|
466
|
-
store: opts.store,
|
|
467
|
-
fetch: opts.fetch,
|
|
468
|
-
});
|
|
469
|
-
|
|
470
|
-
// 6. Tokens are already stored by exchangeCodeForTokens.
|
|
471
|
-
// Compute expiresAt from expiresIn for the result.
|
|
472
|
-
const expiresAt = tokens.expiresIn
|
|
473
|
-
? Date.now() + tokens.expiresIn * 1000
|
|
474
|
-
: undefined;
|
|
475
|
-
|
|
476
|
-
return {
|
|
477
|
-
provider: opts.provider,
|
|
478
|
-
redirectUri,
|
|
479
|
-
expiresAt,
|
|
480
|
-
scope: tokens.scope,
|
|
481
|
-
};
|
|
482
|
-
} finally {
|
|
483
|
-
// 7. Clean up
|
|
484
|
-
await server.close();
|
|
485
|
-
}
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
/**
|
|
489
|
-
* Refresh an OAuth token using a refresh token.
|
|
490
|
-
* Updates the stored tokens on success.
|
|
491
|
-
*/
|
|
492
|
-
export async function refreshTokens(
|
|
493
|
-
provider: string,
|
|
494
|
-
refreshToken: string,
|
|
495
|
-
store: SecretStore,
|
|
496
|
-
options?: { fetch?: typeof globalThis.fetch },
|
|
497
|
-
): Promise<OAuthTokenResponse> {
|
|
498
|
-
const config = PKCE_CONFIGS[provider];
|
|
499
|
-
if (!config) {
|
|
500
|
-
throw new Error(`OAuth not supported for provider: ${provider}`);
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
if (!store) {
|
|
504
|
-
throw new Error("SecretStore is required for token refresh");
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
const clientId =
|
|
508
|
-
config.clientIdEnvVar
|
|
509
|
-
? (process.env[config.clientIdEnvVar] ?? "")
|
|
510
|
-
: "";
|
|
511
|
-
|
|
512
|
-
const params = new URLSearchParams({
|
|
513
|
-
grant_type: "refresh_token",
|
|
514
|
-
refresh_token: refreshToken,
|
|
515
|
-
client_id: clientId,
|
|
516
|
-
});
|
|
517
|
-
|
|
518
|
-
const fetchImpl = options?.fetch ?? globalThis.fetch.bind(globalThis);
|
|
519
|
-
const response = await fetchImpl(config.tokenUrl, {
|
|
520
|
-
method: "POST",
|
|
521
|
-
headers: {
|
|
522
|
-
"content-type": "application/x-www-form-urlencoded",
|
|
523
|
-
},
|
|
524
|
-
body: params.toString(),
|
|
525
|
-
});
|
|
526
|
-
|
|
527
|
-
if (!response.ok) {
|
|
528
|
-
const body = await response.text().catch(() => "");
|
|
529
|
-
throw new Error(
|
|
530
|
-
`Token refresh failed for ${provider}: HTTP ${response.status} ${body}`,
|
|
531
|
-
);
|
|
532
|
-
}
|
|
533
|
-
|
|
534
|
-
const json = (await response.json()) as {
|
|
535
|
-
access_token?: string;
|
|
536
|
-
refresh_token?: string;
|
|
537
|
-
expires_in?: number;
|
|
538
|
-
scope?: string;
|
|
539
|
-
};
|
|
540
|
-
|
|
541
|
-
if (!json.access_token) {
|
|
542
|
-
throw new Error(
|
|
543
|
-
`Token refresh for ${provider} returned no access_token`,
|
|
544
|
-
);
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
// Update stored tokens (structured)
|
|
548
|
-
const obtainedAt = Date.now();
|
|
549
|
-
await setOAuthTokens(
|
|
550
|
-
provider,
|
|
551
|
-
{
|
|
552
|
-
accessToken: json.access_token,
|
|
553
|
-
refreshToken: json.refresh_token,
|
|
554
|
-
expiresAt: json.expires_in
|
|
555
|
-
? obtainedAt + json.expires_in * 1000
|
|
556
|
-
: undefined,
|
|
557
|
-
scope: json.scope,
|
|
558
|
-
obtainedAt,
|
|
559
|
-
},
|
|
560
|
-
store,
|
|
561
|
-
);
|
|
562
|
-
|
|
563
|
-
return {
|
|
564
|
-
accessToken: new Redacted(json.access_token),
|
|
565
|
-
refreshToken: json.refresh_token
|
|
566
|
-
? new Redacted(json.refresh_token)
|
|
567
|
-
: undefined,
|
|
568
|
-
expiresIn: json.expires_in,
|
|
569
|
-
scope: json.scope,
|
|
570
|
-
};
|
|
571
|
-
}
|
|
@@ -1,83 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tests for the local OAuth callback server.
|
|
3
|
-
* No real OAuth: we hit the callback URL directly over HTTP.
|
|
4
|
-
*/
|
|
5
|
-
import { describe, expect, it } from "vitest";
|
|
6
|
-
import { startCallbackServer } from "./oauth-server.js";
|
|
7
|
-
|
|
8
|
-
describe("startCallbackServer", () => {
|
|
9
|
-
it("binds to 127.0.0.1 and exposes a localhost redirect URL", async () => {
|
|
10
|
-
const server = await startCallbackServer(0);
|
|
11
|
-
try {
|
|
12
|
-
expect(server.url).toContain("127.0.0.1");
|
|
13
|
-
expect(server.url).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/callback$/);
|
|
14
|
-
expect(server.port).toBeGreaterThan(0);
|
|
15
|
-
} finally {
|
|
16
|
-
await server.close();
|
|
17
|
-
}
|
|
18
|
-
});
|
|
19
|
-
|
|
20
|
-
it("captures the authorization code from a matching callback", async () => {
|
|
21
|
-
const server = await startCallbackServer(0);
|
|
22
|
-
try {
|
|
23
|
-
const waitPromise = server.waitForCode({
|
|
24
|
-
expectedState: "state-abc",
|
|
25
|
-
timeoutMs: 2000,
|
|
26
|
-
});
|
|
27
|
-
const res = await fetch(`${server.url}?code=AUTHCODE123&state=state-abc`);
|
|
28
|
-
expect(res.status).toBe(200);
|
|
29
|
-
const body = await res.text();
|
|
30
|
-
expect(body).toMatch(/success|complete|authorized/i);
|
|
31
|
-
|
|
32
|
-
const result = await waitPromise;
|
|
33
|
-
expect(result.code).toBe("AUTHCODE123");
|
|
34
|
-
expect(result.state).toBe("state-abc");
|
|
35
|
-
} finally {
|
|
36
|
-
await server.close();
|
|
37
|
-
}
|
|
38
|
-
});
|
|
39
|
-
|
|
40
|
-
it("rejects a callback with a mismatched state", async () => {
|
|
41
|
-
const server = await startCallbackServer(0);
|
|
42
|
-
try {
|
|
43
|
-
const waitPromise = server.waitForCode({
|
|
44
|
-
expectedState: "expected-state",
|
|
45
|
-
timeoutMs: 2000,
|
|
46
|
-
});
|
|
47
|
-
// Attach the rejection handler before triggering the callback so the
|
|
48
|
-
// rejection is never momentarily unhandled.
|
|
49
|
-
const assertion = expect(waitPromise).rejects.toThrow(/state/i);
|
|
50
|
-
await fetch(`${server.url}?code=CODE&state=wrong-state`);
|
|
51
|
-
await assertion;
|
|
52
|
-
} finally {
|
|
53
|
-
await server.close();
|
|
54
|
-
}
|
|
55
|
-
});
|
|
56
|
-
|
|
57
|
-
it("rejects when no callback arrives before the timeout", async () => {
|
|
58
|
-
const server = await startCallbackServer(0);
|
|
59
|
-
try {
|
|
60
|
-
await expect(
|
|
61
|
-
server.waitForCode({ timeoutMs: 50 }),
|
|
62
|
-
).rejects.toThrow(/timed out|timeout/i);
|
|
63
|
-
} finally {
|
|
64
|
-
await server.close();
|
|
65
|
-
}
|
|
66
|
-
});
|
|
67
|
-
|
|
68
|
-
it("returns an error page for callbacks missing the code", async () => {
|
|
69
|
-
const server = await startCallbackServer(0);
|
|
70
|
-
try {
|
|
71
|
-
const res = await fetch(`${server.url}?state=only-state`);
|
|
72
|
-
expect(res.status).toBe(400);
|
|
73
|
-
} finally {
|
|
74
|
-
await server.close();
|
|
75
|
-
}
|
|
76
|
-
});
|
|
77
|
-
|
|
78
|
-
it("close is idempotent and releases the port", async () => {
|
|
79
|
-
const server = await startCallbackServer(0);
|
|
80
|
-
await server.close();
|
|
81
|
-
await expect(server.close()).resolves.toBeUndefined();
|
|
82
|
-
});
|
|
83
|
-
});
|