@elyracode/ai 0.9.44 → 0.9.46
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/image-models.generated.d.ts +30 -0
- package/dist/image-models.generated.d.ts.map +1 -1
- package/dist/image-models.generated.js +30 -0
- package/dist/image-models.generated.js.map +1 -1
- package/dist/models.generated.d.ts +541 -175
- package/dist/models.generated.d.ts.map +1 -1
- package/dist/models.generated.js +677 -270
- package/dist/models.generated.js.map +1 -1
- package/dist/utils/oauth/index.d.ts +2 -0
- package/dist/utils/oauth/index.d.ts.map +1 -1
- package/dist/utils/oauth/index.js +3 -0
- package/dist/utils/oauth/index.js.map +1 -1
- package/dist/utils/oauth/loopback.d.ts +86 -0
- package/dist/utils/oauth/loopback.d.ts.map +1 -0
- package/dist/utils/oauth/loopback.js +223 -0
- package/dist/utils/oauth/loopback.js.map +1 -0
- package/package.json +1 -1
|
@@ -8,7 +8,9 @@
|
|
|
8
8
|
*/
|
|
9
9
|
export { anthropicOAuthProvider, loginAnthropic, refreshAnthropicToken } from "./anthropic.js";
|
|
10
10
|
export { getGitHubCopilotBaseUrl, githubCopilotOAuthProvider, loginGitHubCopilot, normalizeDomain, refreshGitHubCopilotToken, } from "./github-copilot.js";
|
|
11
|
+
export { type AuthorizeWithPkceOptions, authorizeWithPkce, isOAuthTokenSetExpired, type OAuthCallbackResult, type OAuthCallbackServer, type OAuthCallbackServerOptions, type OAuthTokenSet, type RefreshOAuthTokenOptions, refreshOAuthTokenSet, startOAuthCallbackServer, } from "./loopback.js";
|
|
11
12
|
export { loginOpenAICodex, openaiCodexOAuthProvider, refreshOpenAICodexToken } from "./openai-codex.js";
|
|
13
|
+
export { generatePKCE } from "./pkce.js";
|
|
12
14
|
export * from "./types.js";
|
|
13
15
|
import type { OAuthCredentials, OAuthProviderId, OAuthProviderInfo, OAuthProviderInterface } from "./types.js";
|
|
14
16
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/utils/oauth/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAE/F,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,kBAAkB,EAClB,eAAe,EACf,yBAAyB,GACzB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/utils/oauth/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAE/F,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,kBAAkB,EAClB,eAAe,EACf,yBAAyB,GACzB,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EACN,KAAK,wBAAwB,EAC7B,iBAAiB,EACjB,sBAAsB,EACtB,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,0BAA0B,EAC/B,KAAK,aAAa,EAClB,KAAK,wBAAwB,EAC7B,oBAAoB,EACpB,wBAAwB,GACxB,MAAM,eAAe,CAAC;AAEvB,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AACxG,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,cAAc,YAAY,CAAC;AAS3B,OAAO,KAAK,EAAE,gBAAgB,EAAE,eAAe,EAAE,iBAAiB,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAY/G;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,EAAE,EAAE,eAAe,GAAG,sBAAsB,GAAG,SAAS,CAExF;AAED;;GAEG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,sBAAsB,GAAG,IAAI,CAE5E;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAOxD;AAED;;GAEG;AACH,wBAAgB,mBAAmB,IAAI,IAAI,CAK1C;AAED;;GAEG;AACH,wBAAgB,iBAAiB,IAAI,sBAAsB,EAAE,CAE5D;AAED;;GAEG;AACH,wBAAgB,wBAAwB,IAAI,iBAAiB,EAAE,CAM9D;AAMD;;;GAGG;AACH,wBAAsB,iBAAiB,CACtC,UAAU,EAAE,eAAe,EAC3B,WAAW,EAAE,gBAAgB,GAC3B,OAAO,CAAC,gBAAgB,CAAC,CAM3B;AAED;;;;;;GAMG;AACH,wBAAsB,cAAc,CACnC,UAAU,EAAE,eAAe,EAC3B,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,GAC3C,OAAO,CAAC;IAAE,cAAc,EAAE,gBAAgB,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAAC,CAsBtE"}
|
|
@@ -10,8 +10,11 @@
|
|
|
10
10
|
export { anthropicOAuthProvider, loginAnthropic, refreshAnthropicToken } from "./anthropic.js";
|
|
11
11
|
// GitHub Copilot
|
|
12
12
|
export { getGitHubCopilotBaseUrl, githubCopilotOAuthProvider, loginGitHubCopilot, normalizeDomain, refreshGitHubCopilotToken, } from "./github-copilot.js";
|
|
13
|
+
// Generic authorization-code + PKCE flow over a loopback redirect (for extensions and new integrations)
|
|
14
|
+
export { authorizeWithPkce, isOAuthTokenSetExpired, refreshOAuthTokenSet, startOAuthCallbackServer, } from "./loopback.js";
|
|
13
15
|
// OpenAI Codex (ChatGPT OAuth)
|
|
14
16
|
export { loginOpenAICodex, openaiCodexOAuthProvider, refreshOpenAICodexToken } from "./openai-codex.js";
|
|
17
|
+
export { generatePKCE } from "./pkce.js";
|
|
15
18
|
export * from "./types.js";
|
|
16
19
|
// ============================================================================
|
|
17
20
|
// Provider Registry
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/oauth/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,YAAY;AACZ,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAC/F,iBAAiB;AACjB,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,kBAAkB,EAClB,eAAe,EACf,yBAAyB,GACzB,MAAM,qBAAqB,CAAC;AAC7B,+BAA+B;AAC/B,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/utils/oauth/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,YAAY;AACZ,OAAO,EAAE,sBAAsB,EAAE,cAAc,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAC/F,iBAAiB;AACjB,OAAO,EACN,uBAAuB,EACvB,0BAA0B,EAC1B,kBAAkB,EAClB,eAAe,EACf,yBAAyB,GACzB,MAAM,qBAAqB,CAAC;AAC7B,wGAAwG;AACxG,OAAO,EAEN,iBAAiB,EACjB,sBAAsB,EAMtB,oBAAoB,EACpB,wBAAwB,GACxB,MAAM,eAAe,CAAC;AACvB,+BAA+B;AAC/B,OAAO,EAAE,gBAAgB,EAAE,wBAAwB,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AACxG,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AACzC,cAAc,YAAY,CAAC;AAE3B,+EAA+E;AAC/E,oBAAoB;AACpB,+EAA+E;AAE/E,OAAO,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AACxD,OAAO,EAAE,0BAA0B,EAAE,MAAM,qBAAqB,CAAC;AACjE,OAAO,EAAE,wBAAwB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I,KAAK,CAAC,qCAAqC,UAAU,EAAE,CAAC,CAAC;QACpE,CAAC;IACF,CAAC;IAED,MAAM,MAAM,GAAG,QAAQ,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACzC,OAAO,EAAE,cAAc,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AAC1C,CAAC","sourcesContent":["/**\n * OAuth credential management for AI providers.\n *\n * This module handles login, token refresh, and credential storage\n * for OAuth-based providers:\n * - Anthropic (Claude Pro/Max)\n * - GitHub Copilot\n */\n\n// Anthropic\nexport { anthropicOAuthProvider, loginAnthropic, refreshAnthropicToken } from \"./anthropic.js\";\n// GitHub Copilot\nexport {\n\tgetGitHubCopilotBaseUrl,\n\tgithubCopilotOAuthProvider,\n\tloginGitHubCopilot,\n\tnormalizeDomain,\n\trefreshGitHubCopilotToken,\n} from \"./github-copilot.js\";\n// Generic authorization-code + PKCE flow over a loopback redirect (for extensions and new integrations)\nexport {\n\ttype AuthorizeWithPkceOptions,\n\tauthorizeWithPkce,\n\tisOAuthTokenSetExpired,\n\ttype OAuthCallbackResult,\n\ttype OAuthCallbackServer,\n\ttype OAuthCallbackServerOptions,\n\ttype OAuthTokenSet,\n\ttype RefreshOAuthTokenOptions,\n\trefreshOAuthTokenSet,\n\tstartOAuthCallbackServer,\n} from \"./loopback.js\";\n// OpenAI Codex (ChatGPT OAuth)\nexport { loginOpenAICodex, openaiCodexOAuthProvider, refreshOpenAICodexToken } from \"./openai-codex.js\";\nexport { generatePKCE } from \"./pkce.js\";\nexport * from \"./types.js\";\n\n// ============================================================================\n// Provider Registry\n// ============================================================================\n\nimport { anthropicOAuthProvider } from \"./anthropic.js\";\nimport { githubCopilotOAuthProvider } from \"./github-copilot.js\";\nimport { openaiCodexOAuthProvider } from \"./openai-codex.js\";\nimport type { OAuthCredentials, OAuthProviderId, OAuthProviderInfo, OAuthProviderInterface } from \"./types.js\";\n\nconst BUILT_IN_OAUTH_PROVIDERS: OAuthProviderInterface[] = [\n\tanthropicOAuthProvider,\n\tgithubCopilotOAuthProvider,\n\topenaiCodexOAuthProvider,\n];\n\nconst oauthProviderRegistry = new Map<string, OAuthProviderInterface>(\n\tBUILT_IN_OAUTH_PROVIDERS.map((provider) => [provider.id, provider]),\n);\n\n/**\n * Get an OAuth provider by ID\n */\nexport function getOAuthProvider(id: OAuthProviderId): OAuthProviderInterface | undefined {\n\treturn oauthProviderRegistry.get(id);\n}\n\n/**\n * Register a custom OAuth provider\n */\nexport function registerOAuthProvider(provider: OAuthProviderInterface): void {\n\toauthProviderRegistry.set(provider.id, provider);\n}\n\n/**\n * Unregister an OAuth provider.\n *\n * If the provider is built-in, restores the built-in implementation.\n * Custom providers are removed completely.\n */\nexport function unregisterOAuthProvider(id: string): void {\n\tconst builtInProvider = BUILT_IN_OAUTH_PROVIDERS.find((provider) => provider.id === id);\n\tif (builtInProvider) {\n\t\toauthProviderRegistry.set(id, builtInProvider);\n\t\treturn;\n\t}\n\toauthProviderRegistry.delete(id);\n}\n\n/**\n * Reset OAuth providers to built-ins.\n */\nexport function resetOAuthProviders(): void {\n\toauthProviderRegistry.clear();\n\tfor (const provider of BUILT_IN_OAUTH_PROVIDERS) {\n\t\toauthProviderRegistry.set(provider.id, provider);\n\t}\n}\n\n/**\n * Get all registered OAuth providers\n */\nexport function getOAuthProviders(): OAuthProviderInterface[] {\n\treturn Array.from(oauthProviderRegistry.values());\n}\n\n/**\n * @deprecated Use getOAuthProviders() which returns OAuthProviderInterface[]\n */\nexport function getOAuthProviderInfoList(): OAuthProviderInfo[] {\n\treturn getOAuthProviders().map((p) => ({\n\t\tid: p.id,\n\t\tname: p.name,\n\t\tavailable: true,\n\t}));\n}\n\n// ============================================================================\n// High-level API (uses provider registry)\n// ============================================================================\n\n/**\n * Refresh token for any OAuth provider.\n * @deprecated Use getOAuthProvider(id).refreshToken() instead\n */\nexport async function refreshOAuthToken(\n\tproviderId: OAuthProviderId,\n\tcredentials: OAuthCredentials,\n): Promise<OAuthCredentials> {\n\tconst provider = getOAuthProvider(providerId);\n\tif (!provider) {\n\t\tthrow new Error(`Unknown OAuth provider: ${providerId}`);\n\t}\n\treturn provider.refreshToken(credentials);\n}\n\n/**\n * Get API key for a provider from OAuth credentials.\n * Automatically refreshes expired tokens.\n *\n * @returns API key string and updated credentials, or null if no credentials\n * @throws Error if refresh fails\n */\nexport async function getOAuthApiKey(\n\tproviderId: OAuthProviderId,\n\tcredentials: Record<string, OAuthCredentials>,\n): Promise<{ newCredentials: OAuthCredentials; apiKey: string } | null> {\n\tconst provider = getOAuthProvider(providerId);\n\tif (!provider) {\n\t\tthrow new Error(`Unknown OAuth provider: ${providerId}`);\n\t}\n\n\tlet creds = credentials[providerId];\n\tif (!creds) {\n\t\treturn null;\n\t}\n\n\t// Refresh if expired\n\tif (Date.now() >= creds.expires) {\n\t\ttry {\n\t\t\tcreds = await provider.refreshToken(creds);\n\t\t} catch (_error) {\n\t\t\tthrow new Error(`Failed to refresh OAuth token for ${providerId}`);\n\t\t}\n\t}\n\n\tconst apiKey = provider.getApiKey(creds);\n\treturn { newCredentials: creds, apiKey };\n}\n"]}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic OAuth 2.x authorization-code flow for native apps (RFC 8252):
|
|
3
|
+
* a loopback redirect server, PKCE (RFC 7636), token exchange, and refresh.
|
|
4
|
+
*
|
|
5
|
+
* Provider-specific flows (anthropic.ts, openai-codex.ts) predate this module and
|
|
6
|
+
* keep their fixed ports. New integrations, including extensions, should use these
|
|
7
|
+
* helpers instead of starting their own servers.
|
|
8
|
+
*
|
|
9
|
+
* Node.js only (uses node:http).
|
|
10
|
+
*/
|
|
11
|
+
export interface OAuthCallbackResult {
|
|
12
|
+
code: string;
|
|
13
|
+
state: string | undefined;
|
|
14
|
+
/** All query parameters of the redirect, for providers that return extra values. */
|
|
15
|
+
params: Record<string, string>;
|
|
16
|
+
}
|
|
17
|
+
export interface OAuthCallbackServer {
|
|
18
|
+
/** The redirect URI to register/send, e.g. `http://127.0.0.1:53124/callback`. */
|
|
19
|
+
readonly redirectUri: string;
|
|
20
|
+
readonly port: number;
|
|
21
|
+
/**
|
|
22
|
+
* Resolves with the first valid redirect. Rejects when the authorization server
|
|
23
|
+
* returns an error, when `signal` aborts, or when the server is closed first.
|
|
24
|
+
*/
|
|
25
|
+
waitForCallback(signal?: AbortSignal): Promise<OAuthCallbackResult>;
|
|
26
|
+
close(): void;
|
|
27
|
+
}
|
|
28
|
+
export interface OAuthCallbackServerOptions {
|
|
29
|
+
/** Interface to bind. Default `127.0.0.1` (loopback only). */
|
|
30
|
+
host?: string;
|
|
31
|
+
/** Port to bind. Default 0 (an ephemeral port chosen by the OS). */
|
|
32
|
+
port?: number;
|
|
33
|
+
/** Redirect path. Default `/callback`. */
|
|
34
|
+
path?: string;
|
|
35
|
+
/** When set, redirects with a different `state` are rejected (CSRF protection). */
|
|
36
|
+
expectedState?: string;
|
|
37
|
+
/** Shown on the browser page, e.g. "GitHub MCP". */
|
|
38
|
+
serviceName?: string;
|
|
39
|
+
}
|
|
40
|
+
/** Start a loopback HTTP server that receives one OAuth authorization-code redirect. */
|
|
41
|
+
export declare function startOAuthCallbackServer(options?: OAuthCallbackServerOptions): Promise<OAuthCallbackServer>;
|
|
42
|
+
/** Tokens returned by an OAuth token endpoint, normalized. */
|
|
43
|
+
export interface OAuthTokenSet {
|
|
44
|
+
accessToken: string;
|
|
45
|
+
refreshToken?: string;
|
|
46
|
+
/** Absolute expiry in ms since epoch, when the server sent `expires_in`. */
|
|
47
|
+
expiresAt?: number;
|
|
48
|
+
tokenType?: string;
|
|
49
|
+
scope?: string;
|
|
50
|
+
idToken?: string;
|
|
51
|
+
}
|
|
52
|
+
export interface AuthorizeWithPkceOptions {
|
|
53
|
+
authorizationEndpoint: string;
|
|
54
|
+
tokenEndpoint: string;
|
|
55
|
+
clientId: string;
|
|
56
|
+
/** For confidential clients only. Sent with HTTP Basic auth. */
|
|
57
|
+
clientSecret?: string;
|
|
58
|
+
scopes?: string[];
|
|
59
|
+
/** Extra authorization request parameters, e.g. `{ resource: "https://mcp.example.com" }` (RFC 8707). */
|
|
60
|
+
extraAuthorizeParams?: Record<string, string>;
|
|
61
|
+
/** Extra token request parameters. */
|
|
62
|
+
extraTokenParams?: Record<string, string>;
|
|
63
|
+
/** Fixed callback port, for providers that require a pre-registered redirect URI. Default: ephemeral. */
|
|
64
|
+
callbackPort?: number;
|
|
65
|
+
callbackPath?: string;
|
|
66
|
+
serviceName?: string;
|
|
67
|
+
/** Called with the URL the user must open. Open a browser and/or show it. */
|
|
68
|
+
onAuthUrl: (url: string, redirectUri: string) => void;
|
|
69
|
+
signal?: AbortSignal;
|
|
70
|
+
}
|
|
71
|
+
/** Run a full authorization-code + PKCE flow through a loopback redirect. */
|
|
72
|
+
export declare function authorizeWithPkce(options: AuthorizeWithPkceOptions): Promise<OAuthTokenSet>;
|
|
73
|
+
export interface RefreshOAuthTokenOptions {
|
|
74
|
+
tokenEndpoint: string;
|
|
75
|
+
clientId: string;
|
|
76
|
+
clientSecret?: string;
|
|
77
|
+
refreshToken: string;
|
|
78
|
+
scopes?: string[];
|
|
79
|
+
extraParams?: Record<string, string>;
|
|
80
|
+
signal?: AbortSignal;
|
|
81
|
+
}
|
|
82
|
+
/** Exchange a refresh token for a new token set. */
|
|
83
|
+
export declare function refreshOAuthTokenSet(options: RefreshOAuthTokenOptions): Promise<OAuthTokenSet>;
|
|
84
|
+
/** True when the token set expires within `skewMs` (default 60 s). Token sets without expiry never expire. */
|
|
85
|
+
export declare function isOAuthTokenSetExpired(tokens: OAuthTokenSet, skewMs?: number): boolean;
|
|
86
|
+
//# sourceMappingURL=loopback.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loopback.d.ts","sourceRoot":"","sources":["../../../src/utils/oauth/loopback.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAOH,MAAM,WAAW,mBAAmB;IACnC,IAAI,EAAE,MAAM,CAAC;IACb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AAM,EAAE,CAAC;IAClB,yGAAyG;IACzG,oBAAoB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9C,sCAAsC;IACtC,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC1C,yGAAyG;IACzG,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,6EAA6E;IAC7E,SAAS,EAAE,CAAC,GAAG,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,KAAK,IAAI,CAAC;IACtD,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,6EAA6E;AAC7E,wBAAsB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,OAAO,CAAC,aAAa,CAAC,CA+CjG;AAED,MAAM,WAAW,wBAAwB;IACxC,aAAa,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACrC,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,oDAAoD;AACpD,wBAAsB,oBAAoB,CAAC,OAAO,EAAE,wBAAwB,GAAG,OAAO,CAAC,aAAa,CAAC,CAiBpG;AAED,8GAA8G;AAC9G,wBAAgB,sBAAsB,CAAC,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,GAAG,OAAO,CAEtF"}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Generic OAuth 2.x authorization-code flow for native apps (RFC 8252):
|
|
3
|
+
* a loopback redirect server, PKCE (RFC 7636), token exchange, and refresh.
|
|
4
|
+
*
|
|
5
|
+
* Provider-specific flows (anthropic.ts, openai-codex.ts) predate this module and
|
|
6
|
+
* keep their fixed ports. New integrations, including extensions, should use these
|
|
7
|
+
* helpers instead of starting their own servers.
|
|
8
|
+
*
|
|
9
|
+
* Node.js only (uses node:http).
|
|
10
|
+
*/
|
|
11
|
+
import { createServer } from "node:http";
|
|
12
|
+
import { oauthErrorHtml, oauthSuccessHtml } from "./oauth-page.js";
|
|
13
|
+
import { generatePKCE } from "./pkce.js";
|
|
14
|
+
/** Start a loopback HTTP server that receives one OAuth authorization-code redirect. */
|
|
15
|
+
export async function startOAuthCallbackServer(options = {}) {
|
|
16
|
+
const host = options.host ?? "127.0.0.1";
|
|
17
|
+
const path = options.path ?? "/callback";
|
|
18
|
+
const service = options.serviceName ?? "Authentication";
|
|
19
|
+
let settled = false;
|
|
20
|
+
let resolveResult = () => { };
|
|
21
|
+
let rejectResult = () => { };
|
|
22
|
+
const result = new Promise((resolve, reject) => {
|
|
23
|
+
resolveResult = resolve;
|
|
24
|
+
rejectResult = reject;
|
|
25
|
+
});
|
|
26
|
+
// Avoid unhandled rejections when nobody is waiting yet.
|
|
27
|
+
result.catch(() => { });
|
|
28
|
+
const settle = (outcome) => {
|
|
29
|
+
if (settled)
|
|
30
|
+
return;
|
|
31
|
+
settled = true;
|
|
32
|
+
if ("ok" in outcome)
|
|
33
|
+
resolveResult(outcome.ok);
|
|
34
|
+
else
|
|
35
|
+
rejectResult(outcome.error);
|
|
36
|
+
};
|
|
37
|
+
const server = createServer((req, res) => {
|
|
38
|
+
try {
|
|
39
|
+
const url = new URL(req.url || "", "http://localhost");
|
|
40
|
+
if (url.pathname !== path) {
|
|
41
|
+
res.writeHead(404, { "Content-Type": "text/html; charset=utf-8" });
|
|
42
|
+
res.end(oauthErrorHtml("Callback route not found."));
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const params = Object.fromEntries(url.searchParams.entries());
|
|
46
|
+
const error = params.error;
|
|
47
|
+
if (error) {
|
|
48
|
+
const description = params.error_description;
|
|
49
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
50
|
+
res.end(oauthErrorHtml(`${service} did not complete.`, description ? `${error}: ${description}` : error));
|
|
51
|
+
settle({ error: new Error(`Authorization failed: ${description ? `${error}: ${description}` : error}`) });
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
const code = params.code;
|
|
55
|
+
if (!code) {
|
|
56
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
57
|
+
res.end(oauthErrorHtml("Missing code parameter."));
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (options.expectedState !== undefined && params.state !== options.expectedState) {
|
|
61
|
+
res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
|
|
62
|
+
res.end(oauthErrorHtml("State mismatch."));
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
66
|
+
res.end(oauthSuccessHtml(`${service} completed. You can close this window.`));
|
|
67
|
+
settle({ ok: { code, state: params.state, params } });
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
|
|
71
|
+
res.end("Internal error");
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
await new Promise((resolve, reject) => {
|
|
75
|
+
server.once("error", reject);
|
|
76
|
+
server.listen(options.port ?? 0, host, () => {
|
|
77
|
+
server.off("error", reject);
|
|
78
|
+
resolve();
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
const port = server.address().port;
|
|
82
|
+
const urlHost = host.includes(":") ? `[${host}]` : host;
|
|
83
|
+
const close = () => {
|
|
84
|
+
settle({ error: new Error("OAuth callback server closed before a redirect arrived") });
|
|
85
|
+
server.close();
|
|
86
|
+
server.closeAllConnections?.();
|
|
87
|
+
};
|
|
88
|
+
return {
|
|
89
|
+
redirectUri: `http://${urlHost}:${port}${path}`,
|
|
90
|
+
port,
|
|
91
|
+
waitForCallback(signal) {
|
|
92
|
+
if (signal) {
|
|
93
|
+
if (signal.aborted) {
|
|
94
|
+
settle({ error: new Error("Authorization cancelled") });
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
signal.addEventListener("abort", () => settle({ error: new Error("Authorization cancelled") }), {
|
|
98
|
+
once: true,
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return result;
|
|
103
|
+
},
|
|
104
|
+
close,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
function parseTokenResponse(body, previousRefreshToken) {
|
|
108
|
+
if (typeof body !== "object" || body === null) {
|
|
109
|
+
throw new Error("Token endpoint returned a non-object response");
|
|
110
|
+
}
|
|
111
|
+
const data = body;
|
|
112
|
+
if (typeof data.error === "string") {
|
|
113
|
+
const description = typeof data.error_description === "string" ? `: ${data.error_description}` : "";
|
|
114
|
+
throw new Error(`Token endpoint error ${data.error}${description}`);
|
|
115
|
+
}
|
|
116
|
+
if (typeof data.access_token !== "string" || data.access_token.length === 0) {
|
|
117
|
+
throw new Error("Token endpoint response has no access_token");
|
|
118
|
+
}
|
|
119
|
+
const expiresIn = typeof data.expires_in === "number" ? data.expires_in : Number(data.expires_in);
|
|
120
|
+
return {
|
|
121
|
+
accessToken: data.access_token,
|
|
122
|
+
// Servers may omit refresh_token on refresh; keep the old one (RFC 6749 section 6).
|
|
123
|
+
refreshToken: typeof data.refresh_token === "string" ? data.refresh_token : previousRefreshToken,
|
|
124
|
+
expiresAt: Number.isFinite(expiresIn) && expiresIn > 0 ? Date.now() + expiresIn * 1000 : undefined,
|
|
125
|
+
tokenType: typeof data.token_type === "string" ? data.token_type : undefined,
|
|
126
|
+
scope: typeof data.scope === "string" ? data.scope : undefined,
|
|
127
|
+
idToken: typeof data.id_token === "string" ? data.id_token : undefined,
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
async function postTokenRequest(tokenEndpoint, params, clientSecret, clientId, signal) {
|
|
131
|
+
const headers = {
|
|
132
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
133
|
+
Accept: "application/json",
|
|
134
|
+
};
|
|
135
|
+
const body = new URLSearchParams(params);
|
|
136
|
+
if (clientSecret !== undefined) {
|
|
137
|
+
// client_secret_basic (RFC 6749 section 2.3.1)
|
|
138
|
+
const encode = (value) => encodeURIComponent(value).replace(/%20/g, "+");
|
|
139
|
+
headers.Authorization = `Basic ${btoa(`${encode(clientId)}:${encode(clientSecret)}`)}`;
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
body.set("client_id", clientId);
|
|
143
|
+
}
|
|
144
|
+
const response = await fetch(tokenEndpoint, {
|
|
145
|
+
method: "POST",
|
|
146
|
+
headers,
|
|
147
|
+
body,
|
|
148
|
+
signal: signal ?? AbortSignal.timeout(30_000),
|
|
149
|
+
});
|
|
150
|
+
const text = await response.text();
|
|
151
|
+
let parsed;
|
|
152
|
+
try {
|
|
153
|
+
parsed = JSON.parse(text);
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
parsed = Object.fromEntries(new URLSearchParams(text).entries());
|
|
157
|
+
}
|
|
158
|
+
if (!response.ok) {
|
|
159
|
+
const data = (parsed ?? {});
|
|
160
|
+
const detail = typeof data.error === "string" ? `${data.error} ${data.error_description ?? ""}`.trim() : text;
|
|
161
|
+
throw new Error(`Token request failed (${response.status}): ${detail}`);
|
|
162
|
+
}
|
|
163
|
+
return parsed;
|
|
164
|
+
}
|
|
165
|
+
/** Run a full authorization-code + PKCE flow through a loopback redirect. */
|
|
166
|
+
export async function authorizeWithPkce(options) {
|
|
167
|
+
const { verifier, challenge } = await generatePKCE();
|
|
168
|
+
const stateBytes = new Uint8Array(16);
|
|
169
|
+
crypto.getRandomValues(stateBytes);
|
|
170
|
+
const state = Array.from(stateBytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
171
|
+
const server = await startOAuthCallbackServer({
|
|
172
|
+
port: options.callbackPort,
|
|
173
|
+
path: options.callbackPath,
|
|
174
|
+
expectedState: state,
|
|
175
|
+
serviceName: options.serviceName,
|
|
176
|
+
});
|
|
177
|
+
try {
|
|
178
|
+
const authUrl = new URL(options.authorizationEndpoint);
|
|
179
|
+
authUrl.searchParams.set("response_type", "code");
|
|
180
|
+
authUrl.searchParams.set("client_id", options.clientId);
|
|
181
|
+
authUrl.searchParams.set("redirect_uri", server.redirectUri);
|
|
182
|
+
authUrl.searchParams.set("code_challenge", challenge);
|
|
183
|
+
authUrl.searchParams.set("code_challenge_method", "S256");
|
|
184
|
+
authUrl.searchParams.set("state", state);
|
|
185
|
+
if (options.scopes && options.scopes.length > 0) {
|
|
186
|
+
authUrl.searchParams.set("scope", options.scopes.join(" "));
|
|
187
|
+
}
|
|
188
|
+
for (const [key, value] of Object.entries(options.extraAuthorizeParams ?? {})) {
|
|
189
|
+
authUrl.searchParams.set(key, value);
|
|
190
|
+
}
|
|
191
|
+
options.onAuthUrl(authUrl.toString(), server.redirectUri);
|
|
192
|
+
const { code } = await server.waitForCallback(options.signal);
|
|
193
|
+
const body = await postTokenRequest(options.tokenEndpoint, {
|
|
194
|
+
grant_type: "authorization_code",
|
|
195
|
+
code,
|
|
196
|
+
redirect_uri: server.redirectUri,
|
|
197
|
+
code_verifier: verifier,
|
|
198
|
+
...options.extraTokenParams,
|
|
199
|
+
}, options.clientSecret, options.clientId, options.signal);
|
|
200
|
+
return parseTokenResponse(body);
|
|
201
|
+
}
|
|
202
|
+
finally {
|
|
203
|
+
server.close();
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
/** Exchange a refresh token for a new token set. */
|
|
207
|
+
export async function refreshOAuthTokenSet(options) {
|
|
208
|
+
const params = {
|
|
209
|
+
grant_type: "refresh_token",
|
|
210
|
+
refresh_token: options.refreshToken,
|
|
211
|
+
...options.extraParams,
|
|
212
|
+
};
|
|
213
|
+
if (options.scopes && options.scopes.length > 0) {
|
|
214
|
+
params.scope = options.scopes.join(" ");
|
|
215
|
+
}
|
|
216
|
+
const body = await postTokenRequest(options.tokenEndpoint, params, options.clientSecret, options.clientId, options.signal);
|
|
217
|
+
return parseTokenResponse(body, options.refreshToken);
|
|
218
|
+
}
|
|
219
|
+
/** True when the token set expires within `skewMs` (default 60 s). Token sets without expiry never expire. */
|
|
220
|
+
export function isOAuthTokenSetExpired(tokens, skewMs = 60_000) {
|
|
221
|
+
return tokens.expiresAt !== undefined && tokens.expiresAt - skewMs <= Date.now();
|
|
222
|
+
}
|
|
223
|
+
//# sourceMappingURL=loopback.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loopback.js","sourceRoot":"","sources":["../../../src/utils/oauth/loopback.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,YAAY,EAAe,MAAM,WAAW,CAAC;AAEtD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAkCzC,wFAAwF;AACxF,MAAM,CAAC,KAAK,UAAU,wBAAwB,CAAC,OAAO,GAA+B,EAAE;IACtF,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,WAAW,CAAC;IACzC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,WAAW,CAAC;IACzC,MAAM,OAAO,GAAG,OAAO,CAAC,WAAW,IAAI,gBAAgB,CAAC;IAExD,IAAI,OAAO,GAAG,KAAK,CAAC;IACpB,IAAI,aAAa,GAAyC,GAAG,EAAE,GAAE,CAAC,CAAC;IACnE,IAAI,YAAY,GAA2B,GAAG,EAAE,GAAE,CAAC,CAAC;IACpD,MAAM,MAAM,GAAG,IAAI,OAAO,CAAsB,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACnE,aAAa,GAAG,OAAO,CAAC;QACxB,YAAY,GAAG,MAAM,CAAC;IACvB,CAAC,CAAC,CAAC;IACH,yDAAyD;IACzD,MAAM,CAAC,KAA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,MAAM,UAAU,sBAAsB,CAAC,MAAqB,EAAE,MAAM,GAAG,MAAM;IAC5E,OAAO,MAAM,CAAC,SAAS,KAAK,SAAS,IAAI,MAAM,CAAC,SAAS,GAAG,MAAM,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;AAClF,CAAC","sourcesContent":["/**\n * Generic OAuth 2.x authorization-code flow for native apps (RFC 8252):\n * a loopback redirect server, PKCE (RFC 7636), token exchange, and refresh.\n *\n * Provider-specific flows (anthropic.ts, openai-codex.ts) predate this module and\n * keep their fixed ports. New integrations, including extensions, should use these\n * helpers instead of starting their own servers.\n *\n * Node.js only (uses node:http).\n */\n\nimport { createServer, type Server } from \"node:http\";\nimport type { AddressInfo } from \"node:net\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.js\";\nimport { generatePKCE } from \"./pkce.js\";\n\nexport interface OAuthCallbackResult {\n\tcode: string;\n\tstate: string | undefined;\n\t/** All query parameters of the redirect, for providers that return extra values. */\n\tparams: Record<string, string>;\n}\n\nexport interface OAuthCallbackServer {\n\t/** The redirect URI to register/send, e.g. `http://127.0.0.1:53124/callback`. */\n\treadonly redirectUri: string;\n\treadonly port: number;\n\t/**\n\t * Resolves with the first valid redirect. Rejects when the authorization server\n\t * returns an error, when `signal` aborts, or when the server is closed first.\n\t */\n\twaitForCallback(signal?: AbortSignal): Promise<OAuthCallbackResult>;\n\tclose(): void;\n}\n\nexport interface OAuthCallbackServerOptions {\n\t/** Interface to bind. Default `127.0.0.1` (loopback only). */\n\thost?: string;\n\t/** Port to bind. Default 0 (an ephemeral port chosen by the OS). */\n\tport?: number;\n\t/** Redirect path. Default `/callback`. */\n\tpath?: string;\n\t/** When set, redirects with a different `state` are rejected (CSRF protection). */\n\texpectedState?: string;\n\t/** Shown on the browser page, e.g. \"GitHub MCP\". */\n\tserviceName?: string;\n}\n\n/** Start a loopback HTTP server that receives one OAuth authorization-code redirect. */\nexport async function startOAuthCallbackServer(options: OAuthCallbackServerOptions = {}): Promise<OAuthCallbackServer> {\n\tconst host = options.host ?? \"127.0.0.1\";\n\tconst path = options.path ?? \"/callback\";\n\tconst service = options.serviceName ?? \"Authentication\";\n\n\tlet settled = false;\n\tlet resolveResult: (value: OAuthCallbackResult) => void = () => {};\n\tlet rejectResult: (error: Error) => void = () => {};\n\tconst result = new Promise<OAuthCallbackResult>((resolve, reject) => {\n\t\tresolveResult = resolve;\n\t\trejectResult = reject;\n\t});\n\t// Avoid unhandled rejections when nobody is waiting yet.\n\tresult.catch(() => {});\n\n\tconst settle = (outcome: { ok: OAuthCallbackResult } | { error: Error }) => {\n\t\tif (settled) return;\n\t\tsettled = true;\n\t\tif (\"ok\" in outcome) resolveResult(outcome.ok);\n\t\telse rejectResult(outcome.error);\n\t};\n\n\tconst server: Server = createServer((req, res) => {\n\t\ttry {\n\t\t\tconst url = new URL(req.url || \"\", \"http://localhost\");\n\t\t\tif (url.pathname !== path) {\n\t\t\t\tres.writeHead(404, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(oauthErrorHtml(\"Callback route not found.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst params = Object.fromEntries(url.searchParams.entries());\n\t\t\tconst error = params.error;\n\t\t\tif (error) {\n\t\t\t\tconst description = params.error_description;\n\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(oauthErrorHtml(`${service} did not complete.`, description ? `${error}: ${description}` : error));\n\t\t\t\tsettle({ error: new Error(`Authorization failed: ${description ? `${error}: ${description}` : error}`) });\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst code = params.code;\n\t\t\tif (!code) {\n\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(oauthErrorHtml(\"Missing code parameter.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (options.expectedState !== undefined && params.state !== options.expectedState) {\n\t\t\t\tres.writeHead(400, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\t\tres.end(oauthErrorHtml(\"State mismatch.\"));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tres.writeHead(200, { \"Content-Type\": \"text/html; charset=utf-8\" });\n\t\t\tres.end(oauthSuccessHtml(`${service} completed. You can close this window.`));\n\t\t\tsettle({ ok: { code, state: params.state, params } });\n\t\t} catch {\n\t\t\tres.writeHead(500, { \"Content-Type\": \"text/plain; charset=utf-8\" });\n\t\t\tres.end(\"Internal error\");\n\t\t}\n\t});\n\n\tawait new Promise<void>((resolve, reject) => {\n\t\tserver.once(\"error\", reject);\n\t\tserver.listen(options.port ?? 0, host, () => {\n\t\t\tserver.off(\"error\", reject);\n\t\t\tresolve();\n\t\t});\n\t});\n\n\tconst port = (server.address() as AddressInfo).port;\n\tconst urlHost = host.includes(\":\") ? `[${host}]` : host;\n\tconst close = () => {\n\t\tsettle({ error: new Error(\"OAuth callback server closed before a redirect arrived\") });\n\t\tserver.close();\n\t\tserver.closeAllConnections?.();\n\t};\n\n\treturn {\n\t\tredirectUri: `http://${urlHost}:${port}${path}`,\n\t\tport,\n\t\twaitForCallback(signal?: AbortSignal) {\n\t\t\tif (signal) {\n\t\t\t\tif (signal.aborted) {\n\t\t\t\t\tsettle({ error: new Error(\"Authorization cancelled\") });\n\t\t\t\t} else {\n\t\t\t\t\tsignal.addEventListener(\"abort\", () => settle({ error: new Error(\"Authorization cancelled\") }), {\n\t\t\t\t\t\tonce: true,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result;\n\t\t},\n\t\tclose,\n\t};\n}\n\n/** Tokens returned by an OAuth token endpoint, normalized. */\nexport interface OAuthTokenSet {\n\taccessToken: string;\n\trefreshToken?: string;\n\t/** Absolute expiry in ms since epoch, when the server sent `expires_in`. */\n\texpiresAt?: number;\n\ttokenType?: string;\n\tscope?: string;\n\tidToken?: string;\n}\n\nfunction parseTokenResponse(body: unknown, previousRefreshToken?: string): OAuthTokenSet {\n\tif (typeof body !== \"object\" || body === null) {\n\t\tthrow new Error(\"Token endpoint returned a non-object response\");\n\t}\n\tconst data = body as Record<string, unknown>;\n\tif (typeof data.error === \"string\") {\n\t\tconst description = typeof data.error_description === \"string\" ? `: ${data.error_description}` : \"\";\n\t\tthrow new Error(`Token endpoint error ${data.error}${description}`);\n\t}\n\tif (typeof data.access_token !== \"string\" || data.access_token.length === 0) {\n\t\tthrow new Error(\"Token endpoint response has no access_token\");\n\t}\n\tconst expiresIn = typeof data.expires_in === \"number\" ? data.expires_in : Number(data.expires_in);\n\treturn {\n\t\taccessToken: data.access_token,\n\t\t// Servers may omit refresh_token on refresh; keep the old one (RFC 6749 section 6).\n\t\trefreshToken: typeof data.refresh_token === \"string\" ? data.refresh_token : previousRefreshToken,\n\t\texpiresAt: Number.isFinite(expiresIn) && expiresIn > 0 ? Date.now() + expiresIn * 1000 : undefined,\n\t\ttokenType: typeof data.token_type === \"string\" ? data.token_type : undefined,\n\t\tscope: typeof data.scope === \"string\" ? data.scope : undefined,\n\t\tidToken: typeof data.id_token === \"string\" ? data.id_token : undefined,\n\t};\n}\n\nasync function postTokenRequest(\n\ttokenEndpoint: string,\n\tparams: Record<string, string>,\n\tclientSecret: string | undefined,\n\tclientId: string,\n\tsignal?: AbortSignal,\n): Promise<unknown> {\n\tconst headers: Record<string, string> = {\n\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\tAccept: \"application/json\",\n\t};\n\tconst body = new URLSearchParams(params);\n\tif (clientSecret !== undefined) {\n\t\t// client_secret_basic (RFC 6749 section 2.3.1)\n\t\tconst encode = (value: string) => encodeURIComponent(value).replace(/%20/g, \"+\");\n\t\theaders.Authorization = `Basic ${btoa(`${encode(clientId)}:${encode(clientSecret)}`)}`;\n\t} else {\n\t\tbody.set(\"client_id\", clientId);\n\t}\n\tconst response = await fetch(tokenEndpoint, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody,\n\t\tsignal: signal ?? AbortSignal.timeout(30_000),\n\t});\n\tconst text = await response.text();\n\tlet parsed: unknown;\n\ttry {\n\t\tparsed = JSON.parse(text);\n\t} catch {\n\t\tparsed = Object.fromEntries(new URLSearchParams(text).entries());\n\t}\n\tif (!response.ok) {\n\t\tconst data = (parsed ?? {}) as Record<string, unknown>;\n\t\tconst detail = typeof data.error === \"string\" ? `${data.error} ${data.error_description ?? \"\"}`.trim() : text;\n\t\tthrow new Error(`Token request failed (${response.status}): ${detail}`);\n\t}\n\treturn parsed;\n}\n\nexport interface AuthorizeWithPkceOptions {\n\tauthorizationEndpoint: string;\n\ttokenEndpoint: string;\n\tclientId: string;\n\t/** For confidential clients only. Sent with HTTP Basic auth. */\n\tclientSecret?: string;\n\tscopes?: string[];\n\t/** Extra authorization request parameters, e.g. `{ resource: \"https://mcp.example.com\" }` (RFC 8707). */\n\textraAuthorizeParams?: Record<string, string>;\n\t/** Extra token request parameters. */\n\textraTokenParams?: Record<string, string>;\n\t/** Fixed callback port, for providers that require a pre-registered redirect URI. Default: ephemeral. */\n\tcallbackPort?: number;\n\tcallbackPath?: string;\n\tserviceName?: string;\n\t/** Called with the URL the user must open. Open a browser and/or show it. */\n\tonAuthUrl: (url: string, redirectUri: string) => void;\n\tsignal?: AbortSignal;\n}\n\n/** Run a full authorization-code + PKCE flow through a loopback redirect. */\nexport async function authorizeWithPkce(options: AuthorizeWithPkceOptions): Promise<OAuthTokenSet> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst stateBytes = new Uint8Array(16);\n\tcrypto.getRandomValues(stateBytes);\n\tconst state = Array.from(stateBytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n\n\tconst server = await startOAuthCallbackServer({\n\t\tport: options.callbackPort,\n\t\tpath: options.callbackPath,\n\t\texpectedState: state,\n\t\tserviceName: options.serviceName,\n\t});\n\ttry {\n\t\tconst authUrl = new URL(options.authorizationEndpoint);\n\t\tauthUrl.searchParams.set(\"response_type\", \"code\");\n\t\tauthUrl.searchParams.set(\"client_id\", options.clientId);\n\t\tauthUrl.searchParams.set(\"redirect_uri\", server.redirectUri);\n\t\tauthUrl.searchParams.set(\"code_challenge\", challenge);\n\t\tauthUrl.searchParams.set(\"code_challenge_method\", \"S256\");\n\t\tauthUrl.searchParams.set(\"state\", state);\n\t\tif (options.scopes && options.scopes.length > 0) {\n\t\t\tauthUrl.searchParams.set(\"scope\", options.scopes.join(\" \"));\n\t\t}\n\t\tfor (const [key, value] of Object.entries(options.extraAuthorizeParams ?? {})) {\n\t\t\tauthUrl.searchParams.set(key, value);\n\t\t}\n\n\t\toptions.onAuthUrl(authUrl.toString(), server.redirectUri);\n\t\tconst { code } = await server.waitForCallback(options.signal);\n\n\t\tconst body = await postTokenRequest(\n\t\t\toptions.tokenEndpoint,\n\t\t\t{\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tcode,\n\t\t\t\tredirect_uri: server.redirectUri,\n\t\t\t\tcode_verifier: verifier,\n\t\t\t\t...options.extraTokenParams,\n\t\t\t},\n\t\t\toptions.clientSecret,\n\t\t\toptions.clientId,\n\t\t\toptions.signal,\n\t\t);\n\t\treturn parseTokenResponse(body);\n\t} finally {\n\t\tserver.close();\n\t}\n}\n\nexport interface RefreshOAuthTokenOptions {\n\ttokenEndpoint: string;\n\tclientId: string;\n\tclientSecret?: string;\n\trefreshToken: string;\n\tscopes?: string[];\n\textraParams?: Record<string, string>;\n\tsignal?: AbortSignal;\n}\n\n/** Exchange a refresh token for a new token set. */\nexport async function refreshOAuthTokenSet(options: RefreshOAuthTokenOptions): Promise<OAuthTokenSet> {\n\tconst params: Record<string, string> = {\n\t\tgrant_type: \"refresh_token\",\n\t\trefresh_token: options.refreshToken,\n\t\t...options.extraParams,\n\t};\n\tif (options.scopes && options.scopes.length > 0) {\n\t\tparams.scope = options.scopes.join(\" \");\n\t}\n\tconst body = await postTokenRequest(\n\t\toptions.tokenEndpoint,\n\t\tparams,\n\t\toptions.clientSecret,\n\t\toptions.clientId,\n\t\toptions.signal,\n\t);\n\treturn parseTokenResponse(body, options.refreshToken);\n}\n\n/** True when the token set expires within `skewMs` (default 60 s). Token sets without expiry never expire. */\nexport function isOAuthTokenSetExpired(tokens: OAuthTokenSet, skewMs = 60_000): boolean {\n\treturn tokens.expiresAt !== undefined && tokens.expiresAt - skewMs <= Date.now();\n}\n"]}
|