@handy_wote/pi-ai 0.81.1
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 +1623 -0
- package/dist/api/anthropic-messages.d.ts +71 -0
- package/dist/api/anthropic-messages.d.ts.map +1 -0
- package/dist/api/anthropic-messages.js +1024 -0
- package/dist/api/anthropic-messages.js.map +1 -0
- package/dist/api/anthropic-messages.lazy.d.ts +3 -0
- package/dist/api/anthropic-messages.lazy.d.ts.map +1 -0
- package/dist/api/anthropic-messages.lazy.js +3 -0
- package/dist/api/anthropic-messages.lazy.js.map +1 -0
- package/dist/api/azure-openai-responses.d.ts +15 -0
- package/dist/api/azure-openai-responses.d.ts.map +1 -0
- package/dist/api/azure-openai-responses.js +221 -0
- package/dist/api/azure-openai-responses.js.map +1 -0
- package/dist/api/azure-openai-responses.lazy.d.ts +3 -0
- package/dist/api/azure-openai-responses.lazy.d.ts.map +1 -0
- package/dist/api/azure-openai-responses.lazy.js +3 -0
- package/dist/api/azure-openai-responses.lazy.js.map +1 -0
- package/dist/api/bedrock-converse-stream.d.ts +38 -0
- package/dist/api/bedrock-converse-stream.d.ts.map +1 -0
- package/dist/api/bedrock-converse-stream.js +883 -0
- package/dist/api/bedrock-converse-stream.js.map +1 -0
- package/dist/api/bedrock-converse-stream.lazy.d.ts +9 -0
- package/dist/api/bedrock-converse-stream.lazy.d.ts.map +1 -0
- package/dist/api/bedrock-converse-stream.lazy.js +30 -0
- package/dist/api/bedrock-converse-stream.lazy.js.map +1 -0
- package/dist/api/cloudflare.d.ts +9 -0
- package/dist/api/cloudflare.d.ts.map +1 -0
- package/dist/api/cloudflare.js +9 -0
- package/dist/api/cloudflare.js.map +1 -0
- package/dist/api/github-copilot-headers.d.ts +8 -0
- package/dist/api/github-copilot-headers.d.ts.map +1 -0
- package/dist/api/github-copilot-headers.js +29 -0
- package/dist/api/github-copilot-headers.js.map +1 -0
- package/dist/api/google-generative-ai.d.ts +13 -0
- package/dist/api/google-generative-ai.d.ts.map +1 -0
- package/dist/api/google-generative-ai.js +407 -0
- package/dist/api/google-generative-ai.js.map +1 -0
- package/dist/api/google-generative-ai.lazy.d.ts +3 -0
- package/dist/api/google-generative-ai.lazy.d.ts.map +1 -0
- package/dist/api/google-generative-ai.lazy.js +3 -0
- package/dist/api/google-generative-ai.lazy.js.map +1 -0
- package/dist/api/google-shared.d.ts +70 -0
- package/dist/api/google-shared.d.ts.map +1 -0
- package/dist/api/google-shared.js +329 -0
- package/dist/api/google-shared.js.map +1 -0
- package/dist/api/google-vertex.d.ts +15 -0
- package/dist/api/google-vertex.d.ts.map +1 -0
- package/dist/api/google-vertex.js +456 -0
- package/dist/api/google-vertex.js.map +1 -0
- package/dist/api/google-vertex.lazy.d.ts +3 -0
- package/dist/api/google-vertex.lazy.d.ts.map +1 -0
- package/dist/api/google-vertex.lazy.js +3 -0
- package/dist/api/google-vertex.lazy.js.map +1 -0
- package/dist/api/lazy.d.ts +15 -0
- package/dist/api/lazy.d.ts.map +1 -0
- package/dist/api/lazy.js +58 -0
- package/dist/api/lazy.js.map +1 -0
- package/dist/api/mistral-conversations.d.ts +25 -0
- package/dist/api/mistral-conversations.d.ts.map +1 -0
- package/dist/api/mistral-conversations.js +555 -0
- package/dist/api/mistral-conversations.js.map +1 -0
- package/dist/api/mistral-conversations.lazy.d.ts +3 -0
- package/dist/api/mistral-conversations.lazy.d.ts.map +1 -0
- package/dist/api/mistral-conversations.lazy.js +3 -0
- package/dist/api/mistral-conversations.lazy.js.map +1 -0
- package/dist/api/openai-codex-responses.d.ts +31 -0
- package/dist/api/openai-codex-responses.d.ts.map +1 -0
- package/dist/api/openai-codex-responses.js +1222 -0
- package/dist/api/openai-codex-responses.js.map +1 -0
- package/dist/api/openai-codex-responses.lazy.d.ts +3 -0
- package/dist/api/openai-codex-responses.lazy.d.ts.map +1 -0
- package/dist/api/openai-codex-responses.lazy.js +3 -0
- package/dist/api/openai-codex-responses.lazy.js.map +1 -0
- package/dist/api/openai-completions.d.ts +20 -0
- package/dist/api/openai-completions.d.ts.map +1 -0
- package/dist/api/openai-completions.js +1120 -0
- package/dist/api/openai-completions.js.map +1 -0
- package/dist/api/openai-completions.lazy.d.ts +3 -0
- package/dist/api/openai-completions.lazy.d.ts.map +1 -0
- package/dist/api/openai-completions.lazy.js +3 -0
- package/dist/api/openai-completions.lazy.js.map +1 -0
- package/dist/api/openai-prompt-cache.d.ts +3 -0
- package/dist/api/openai-prompt-cache.d.ts.map +1 -0
- package/dist/api/openai-prompt-cache.js +10 -0
- package/dist/api/openai-prompt-cache.js.map +1 -0
- package/dist/api/openai-responses-shared.d.ts +20 -0
- package/dist/api/openai-responses-shared.d.ts.map +1 -0
- package/dist/api/openai-responses-shared.js +535 -0
- package/dist/api/openai-responses-shared.js.map +1 -0
- package/dist/api/openai-responses.d.ts +14 -0
- package/dist/api/openai-responses.d.ts.map +1 -0
- package/dist/api/openai-responses.js +246 -0
- package/dist/api/openai-responses.js.map +1 -0
- package/dist/api/openai-responses.lazy.d.ts +3 -0
- package/dist/api/openai-responses.lazy.d.ts.map +1 -0
- package/dist/api/openai-responses.lazy.js +3 -0
- package/dist/api/openai-responses.lazy.js.map +1 -0
- package/dist/api/openrouter-images.d.ts +3 -0
- package/dist/api/openrouter-images.d.ts.map +1 -0
- package/dist/api/openrouter-images.js +126 -0
- package/dist/api/openrouter-images.js.map +1 -0
- package/dist/api/openrouter-images.lazy.d.ts +3 -0
- package/dist/api/openrouter-images.lazy.d.ts.map +1 -0
- package/dist/api/openrouter-images.lazy.js +4 -0
- package/dist/api/openrouter-images.lazy.js.map +1 -0
- package/dist/api/pi-messages.d.ts +97 -0
- package/dist/api/pi-messages.d.ts.map +1 -0
- package/dist/api/pi-messages.js +307 -0
- package/dist/api/pi-messages.js.map +1 -0
- package/dist/api/pi-messages.lazy.d.ts +3 -0
- package/dist/api/pi-messages.lazy.d.ts.map +1 -0
- package/dist/api/pi-messages.lazy.js +3 -0
- package/dist/api/pi-messages.lazy.js.map +1 -0
- package/dist/api/simple-options.d.ts +9 -0
- package/dist/api/simple-options.d.ts.map +1 -0
- package/dist/api/simple-options.js +52 -0
- package/dist/api/simple-options.js.map +1 -0
- package/dist/api/transform-messages.d.ts +8 -0
- package/dist/api/transform-messages.d.ts.map +1 -0
- package/dist/api/transform-messages.js +187 -0
- package/dist/api/transform-messages.js.map +1 -0
- package/dist/auth/context.d.ts +7 -0
- package/dist/auth/context.d.ts.map +1 -0
- package/dist/auth/context.js +42 -0
- package/dist/auth/context.js.map +1 -0
- package/dist/auth/credential-store.d.ts +17 -0
- package/dist/auth/credential-store.d.ts.map +1 -0
- package/dist/auth/credential-store.js +40 -0
- package/dist/auth/credential-store.js.map +1 -0
- package/dist/auth/helpers.d.ts +21 -0
- package/dist/auth/helpers.d.ts.map +1 -0
- package/dist/auth/helpers.js +48 -0
- package/dist/auth/helpers.js.map +1 -0
- package/dist/auth/oauth/anthropic.d.ts +9 -0
- package/dist/auth/oauth/anthropic.d.ts.map +1 -0
- package/dist/auth/oauth/anthropic.js +302 -0
- package/dist/auth/oauth/anthropic.js.map +1 -0
- package/dist/auth/oauth/device-code.d.ts +23 -0
- package/dist/auth/oauth/device-code.d.ts.map +1 -0
- package/dist/auth/oauth/device-code.js +69 -0
- package/dist/auth/oauth/device-code.js.map +1 -0
- package/dist/auth/oauth/github-copilot.d.ts +6 -0
- package/dist/auth/oauth/github-copilot.d.ts.map +1 -0
- package/dist/auth/oauth/github-copilot.js +313 -0
- package/dist/auth/oauth/github-copilot.js.map +1 -0
- package/dist/auth/oauth/load.d.ts +23 -0
- package/dist/auth/oauth/load.d.ts.map +1 -0
- package/dist/auth/oauth/load.js +49 -0
- package/dist/auth/oauth/load.js.map +1 -0
- package/dist/auth/oauth/oauth-page.d.ts +3 -0
- package/dist/auth/oauth/oauth-page.d.ts.map +1 -0
- package/dist/auth/oauth/oauth-page.js +105 -0
- package/dist/auth/oauth/oauth-page.js.map +1 -0
- package/dist/auth/oauth/openai-codex.d.ts +9 -0
- package/dist/auth/oauth/openai-codex.d.ts.map +1 -0
- package/dist/auth/oauth/openai-codex.js +443 -0
- package/dist/auth/oauth/openai-codex.js.map +1 -0
- package/dist/auth/oauth/pkce.d.ts +13 -0
- package/dist/auth/oauth/pkce.d.ts.map +1 -0
- package/dist/auth/oauth/pkce.js +31 -0
- package/dist/auth/oauth/pkce.js.map +1 -0
- package/dist/auth/oauth/radius.d.ts +16 -0
- package/dist/auth/oauth/radius.d.ts.map +1 -0
- package/dist/auth/oauth/radius.js +321 -0
- package/dist/auth/oauth/radius.js.map +1 -0
- package/dist/auth/oauth/xai.d.ts +6 -0
- package/dist/auth/oauth/xai.d.ts.map +1 -0
- package/dist/auth/oauth/xai.js +189 -0
- package/dist/auth/oauth/xai.js.map +1 -0
- package/dist/auth/resolve.d.ts +24 -0
- package/dist/auth/resolve.d.ts.map +1 -0
- package/dist/auth/resolve.js +103 -0
- package/dist/auth/resolve.js.map +1 -0
- package/dist/auth/types.d.ts +219 -0
- package/dist/auth/types.d.ts.map +1 -0
- package/dist/auth/types.js +2 -0
- package/dist/auth/types.js.map +1 -0
- package/dist/bedrock-provider.d.ts +5 -0
- package/dist/bedrock-provider.d.ts.map +1 -0
- package/dist/bedrock-provider.js +6 -0
- package/dist/bedrock-provider.js.map +1 -0
- package/dist/bun-oauth.d.ts +3 -0
- package/dist/bun-oauth.d.ts.map +1 -0
- package/dist/bun-oauth.js +17 -0
- package/dist/bun-oauth.js.map +1 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.d.ts.map +1 -0
- package/dist/cli.js +115 -0
- package/dist/cli.js.map +1 -0
- package/dist/compat/extension-oauth-types.d.ts +39 -0
- package/dist/compat/extension-oauth-types.d.ts.map +1 -0
- package/dist/compat/extension-oauth-types.js +2 -0
- package/dist/compat/extension-oauth-types.js.map +1 -0
- package/dist/compat.d.ts +70 -0
- package/dist/compat.d.ts.map +1 -0
- package/dist/compat.js +189 -0
- package/dist/compat.js.map +1 -0
- package/dist/env-api-keys.d.ts +18 -0
- package/dist/env-api-keys.d.ts.map +1 -0
- package/dist/env-api-keys.js +148 -0
- package/dist/env-api-keys.js.map +1 -0
- package/dist/image-models.d.ts +10 -0
- package/dist/image-models.d.ts.map +1 -0
- package/dist/image-models.js +24 -0
- package/dist/image-models.js.map +1 -0
- package/dist/images-api-registry.d.ts +14 -0
- package/dist/images-api-registry.d.ts.map +1 -0
- package/dist/images-api-registry.js +22 -0
- package/dist/images-api-registry.js.map +1 -0
- package/dist/images-models.d.ts +95 -0
- package/dist/images-models.d.ts.map +1 -0
- package/dist/images-models.js +142 -0
- package/dist/images-models.js.map +1 -0
- package/dist/images.d.ts +4 -0
- package/dist/images.d.ts.map +1 -0
- package/dist/images.js +14 -0
- package/dist/images.js.map +1 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/legacy-api-aliases.d.ts +42 -0
- package/dist/legacy-api-aliases.d.ts.map +1 -0
- package/dist/legacy-api-aliases.js +49 -0
- package/dist/legacy-api-aliases.js.map +1 -0
- package/dist/models-store.d.ts +27 -0
- package/dist/models-store.d.ts.map +1 -0
- package/dist/models-store.js +14 -0
- package/dist/models-store.js.map +1 -0
- package/dist/models.d.ts +178 -0
- package/dist/models.d.ts.map +1 -0
- package/dist/models.js +432 -0
- package/dist/models.js.map +1 -0
- package/dist/oauth.d.ts +3 -0
- package/dist/oauth.d.ts.map +1 -0
- package/dist/oauth.js +2 -0
- package/dist/oauth.js.map +1 -0
- package/dist/providers/all.d.ts +6 -0
- package/dist/providers/all.d.ts.map +1 -0
- package/dist/providers/all.js +9 -0
- package/dist/providers/all.js.map +1 -0
- package/dist/providers/anthropic-compat.d.ts +10 -0
- package/dist/providers/anthropic-compat.d.ts.map +1 -0
- package/dist/providers/anthropic-compat.js +20 -0
- package/dist/providers/anthropic-compat.js.map +1 -0
- package/dist/providers/faux.d.ts +97 -0
- package/dist/providers/faux.d.ts.map +1 -0
- package/dist/providers/faux.js +395 -0
- package/dist/providers/faux.js.map +1 -0
- package/dist/providers/images/register-builtins.d.ts +4 -0
- package/dist/providers/images/register-builtins.d.ts.map +1 -0
- package/dist/providers/images/register-builtins.js +34 -0
- package/dist/providers/images/register-builtins.js.map +1 -0
- package/dist/providers/openai-compat.d.ts +10 -0
- package/dist/providers/openai-compat.d.ts.map +1 -0
- package/dist/providers/openai-compat.js +24 -0
- package/dist/providers/openai-compat.js.map +1 -0
- package/dist/providers/openrouter-images.d.ts +3 -0
- package/dist/providers/openrouter-images.d.ts.map +1 -0
- package/dist/providers/openrouter-images.js +15 -0
- package/dist/providers/openrouter-images.js.map +1 -0
- package/dist/providers/radius.d.ts +9 -0
- package/dist/providers/radius.d.ts.map +1 -0
- package/dist/providers/radius.js +70 -0
- package/dist/providers/radius.js.map +1 -0
- package/dist/session-resources.d.ts +4 -0
- package/dist/session-resources.d.ts.map +1 -0
- package/dist/session-resources.js +22 -0
- package/dist/session-resources.js.map +1 -0
- package/dist/types.d.ts +629 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/dist/utils/abort-signals.d.ts +6 -0
- package/dist/utils/abort-signals.d.ts.map +1 -0
- package/dist/utils/abort-signals.js +34 -0
- package/dist/utils/abort-signals.js.map +1 -0
- package/dist/utils/deferred-tools.d.ts +9 -0
- package/dist/utils/deferred-tools.d.ts.map +1 -0
- package/dist/utils/deferred-tools.js +36 -0
- package/dist/utils/deferred-tools.js.map +1 -0
- package/dist/utils/diagnostics.d.ts +19 -0
- package/dist/utils/diagnostics.d.ts.map +1 -0
- package/dist/utils/diagnostics.js +25 -0
- package/dist/utils/diagnostics.js.map +1 -0
- package/dist/utils/error-body.d.ts +25 -0
- package/dist/utils/error-body.d.ts.map +1 -0
- package/dist/utils/error-body.js +109 -0
- package/dist/utils/error-body.js.map +1 -0
- package/dist/utils/estimate.d.ts +17 -0
- package/dist/utils/estimate.d.ts.map +1 -0
- package/dist/utils/estimate.js +116 -0
- package/dist/utils/estimate.js.map +1 -0
- package/dist/utils/event-stream.d.ts +21 -0
- package/dist/utils/event-stream.d.ts.map +1 -0
- package/dist/utils/event-stream.js +81 -0
- package/dist/utils/event-stream.js.map +1 -0
- package/dist/utils/hash.d.ts +3 -0
- package/dist/utils/hash.d.ts.map +1 -0
- package/dist/utils/hash.js +14 -0
- package/dist/utils/hash.js.map +1 -0
- package/dist/utils/headers.d.ts +4 -0
- package/dist/utils/headers.d.ts.map +1 -0
- package/dist/utils/headers.js +18 -0
- package/dist/utils/headers.js.map +1 -0
- package/dist/utils/json-parse.d.ts +16 -0
- package/dist/utils/json-parse.d.ts.map +1 -0
- package/dist/utils/json-parse.js +113 -0
- package/dist/utils/json-parse.js.map +1 -0
- package/dist/utils/node-http-proxy.d.ts +4 -0
- package/dist/utils/node-http-proxy.d.ts.map +1 -0
- package/dist/utils/node-http-proxy.js +92 -0
- package/dist/utils/node-http-proxy.js.map +1 -0
- package/dist/utils/overflow.d.ts +59 -0
- package/dist/utils/overflow.d.ts.map +1 -0
- package/dist/utils/overflow.js +161 -0
- package/dist/utils/overflow.js.map +1 -0
- package/dist/utils/provider-env.d.ts +7 -0
- package/dist/utils/provider-env.d.ts.map +1 -0
- package/dist/utils/provider-env.js +44 -0
- package/dist/utils/provider-env.js.map +1 -0
- package/dist/utils/retry.d.ts +53 -0
- package/dist/utils/retry.d.ts.map +1 -0
- package/dist/utils/retry.js +170 -0
- package/dist/utils/retry.js.map +1 -0
- package/dist/utils/sanitize-unicode.d.ts +22 -0
- package/dist/utils/sanitize-unicode.d.ts.map +1 -0
- package/dist/utils/sanitize-unicode.js +26 -0
- package/dist/utils/sanitize-unicode.js.map +1 -0
- package/dist/utils/text.d.ts +6 -0
- package/dist/utils/text.d.ts.map +1 -0
- package/dist/utils/text.js +10 -0
- package/dist/utils/text.js.map +1 -0
- package/dist/utils/typebox-helpers.d.ts +17 -0
- package/dist/utils/typebox-helpers.d.ts.map +1 -0
- package/dist/utils/typebox-helpers.js +21 -0
- package/dist/utils/typebox-helpers.js.map +1 -0
- package/dist/utils/uuid.d.ts +3 -0
- package/dist/utils/uuid.d.ts.map +1 -0
- package/dist/utils/uuid.js +46 -0
- package/dist/utils/uuid.js.map +1 -0
- package/dist/utils/validation.d.ts +18 -0
- package/dist/utils/validation.d.ts.map +1 -0
- package/dist/utils/validation.js +269 -0
- package/dist/utils/validation.js.map +1 -0
- package/package.json +95 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"radius.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/radius.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAUH,OAAO,KAAK,EAAmB,SAAS,EAAmB,MAAM,aAAa,CAAC;AAqV/E,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,kBAAkB,GAAG,SAAS,CAkDxE","sourcesContent":["/**\n * Radius gateway OAuth flow.\n *\n * Radius is a pi-messages gateway. OAuth endpoints are discovered from the\n * gateway (`/v1/oauth`); model catalog loading is owned by the Radius provider.\n *\n * NOTE: This module uses node:http for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\n\n// NEVER convert to top-level imports - breaks browser/Vite builds\nlet _http: typeof import(\"node:http\") | null = null;\nif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\timport(\"node:http\").then((m) => {\n\t\t_http = m;\n\t});\n}\n\nimport type { AuthInteraction, OAuthAuth, OAuthCredential } from \"../types.ts\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction normalizeRadiusGatewayUrl(url: string): string {\n\treturn url;\n}\n\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst CALLBACK_HOST = \"127.0.0.1\";\nconst CALLBACK_PORT = 1456;\nconst CALLBACK_PATH = \"/oauth/callback\";\nconst REDIRECT_URI = `http://${CALLBACK_HOST}:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst TOKEN_EXPIRY_SKEW_MS = 60_000;\nconst LOGIN_METHOD_BROWSER = \"browser\";\nconst LOGIN_METHOD_DEVICE_CODE = \"device-code\";\n\ntype RadiusOAuthConfig = {\n\tissuer: string;\n\tauthorizationEndpoint: string;\n\ttokenEndpoint: string;\n\tdeviceAuthorizationEndpoint: string;\n\tdeviceAuthorizationEventsEndpoint: string;\n\tverificationEndpoint: string;\n\tclientId: string;\n\tscope: string;\n\tdeviceCodeGrantType: string;\n};\n\ntype DeviceAuthorizationResponse = {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri?: string;\n\tverification_uri_complete?: string;\n\texpires_in: number;\n\tinterval?: number;\n};\n\nasync function loadRadiusOAuthConfig(gateway: string): Promise<RadiusOAuthConfig> {\n\tconst response = await fetch(new URL(\"/v1/oauth\", gateway), {\n\t\theaders: { accept: \"application/json\" },\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Could not load Radius OAuth config from ${gateway}: ${response.status} ${await response.text()}`,\n\t\t);\n\t}\n\n\treturn (await response.json()) as RadiusOAuthConfig;\n}\n\nclass OAuthResponseError extends Error {\n\treadonly status: number;\n\treadonly oauthError?: string;\n\n\tconstructor(status: number, oauthError: string | undefined, description: string | undefined, message: string) {\n\t\tconst detail = oauthError\n\t\t\t? description\n\t\t\t\t? `${oauthError}: ${description}`\n\t\t\t\t: oauthError\n\t\t\t: description || String(status);\n\t\tsuper(`${message}: ${detail}`);\n\t\tthis.status = status;\n\t\tthis.oauthError = oauthError;\n\t}\n}\n\nasync function readOAuthResponseError(response: Response, message: string): Promise<OAuthResponseError> {\n\tconst text = await response.text().catch(() => \"\");\n\tlet oauthError: string | undefined;\n\tlet description: string | undefined;\n\n\tif (text) {\n\t\ttry {\n\t\t\tconst data = JSON.parse(text) as { error?: unknown; error_description?: unknown };\n\t\t\toauthError = typeof data.error === \"string\" ? data.error : undefined;\n\t\t\tdescription = typeof data.error_description === \"string\" ? data.error_description : undefined;\n\t\t} catch {\n\t\t\tdescription = text;\n\t\t}\n\t}\n\n\treturn new OAuthResponseError(response.status, oauthError, description, message);\n}\n\nasync function requestOAuthToken(\n\toauth: RadiusOAuthConfig,\n\tbody: URLSearchParams,\n\tsignal?: AbortSignal,\n): Promise<OAuthCredential> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(oauth.tokenEndpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody,\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth token request failed\");\n\t}\n\n\tconst data = (await response.json()) as {\n\t\taccess_token: string;\n\t\trefresh_token: string;\n\t\texpires_in: number;\n\t\tscope?: string;\n\t};\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess: data.access_token,\n\t\trefresh: data.refresh_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - TOKEN_EXPIRY_SKEW_MS,\n\t\tscope: data.scope,\n\t};\n}\n\ntype OAuthCallbackServer = {\n\twaitForCode(): Promise<string | null>;\n\tclose(): void;\n};\n\nfunction startOAuthCallbackServer(\n\texpectedState: string,\n\tsignal: AbortSignal | undefined,\n): Promise<OAuthCallbackServer> {\n\tif (!_http) {\n\t\tthrow new Error(\"Radius OAuth is only available in Node.js environments\");\n\t}\n\n\tlet settle: (code: string | null) => void = () => {};\n\tlet settled = false;\n\tconst wait = new Promise<string | null>((resolve) => {\n\t\tsettle = resolve;\n\t});\n\tconst finish = (code: string | null) => {\n\t\tif (settled) {\n\t\t\treturn;\n\t\t}\n\t\tsettled = true;\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\tsettle(code);\n\t};\n\tconst onAbort = () => finish(null);\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\tconst sendPage = (response: import(\"node:http\").ServerResponse, status: number, html: string) => {\n\t\tresponse.statusCode = status;\n\t\tresponse.setHeader(\"content-type\", \"text/html; charset=utf-8\");\n\t\tresponse.end(html);\n\t};\n\n\tconst server = _http.createServer((request, response) => {\n\t\tconst url = new URL(request.url ?? \"/\", REDIRECT_URI);\n\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\tsendPage(response, 404, oauthErrorHtml(\"Callback route not found.\"));\n\t\t\treturn;\n\t\t}\n\t\tif (url.searchParams.get(\"state\") !== expectedState) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(\"OAuth state mismatch.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tconst error = url.searchParams.get(\"error\");\n\t\tif (error) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(url.searchParams.get(\"error_description\") ?? error));\n\t\t\tfinish(null);\n\t\t\treturn;\n\t\t}\n\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tif (!code) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(\"Missing authorization code.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tsendPage(response, 200, oauthSuccessHtml(\"Signed in to Radius. You may now close this page.\"));\n\t\tfinish(code);\n\t});\n\n\treturn new Promise((resolve) => {\n\t\tserver\n\t\t\t.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\t\tresolve({\n\t\t\t\t\twaitForCode: () => wait,\n\t\t\t\t\tclose: () => {\n\t\t\t\t\t\tfinish(null);\n\t\t\t\t\t\tserver.close();\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t})\n\t\t\t.once(\"error\", () => {\n\t\t\t\tfinish(null);\n\t\t\t\tresolve({ waitForCode: async () => null, close: () => {} });\n\t\t\t});\n\t});\n}\n\nasync function loginWithBrowser(oauth: RadiusOAuthConfig, interaction: AuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = crypto.randomUUID();\n\tconst authorizeUrl = new URL(oauth.authorizationEndpoint);\n\tauthorizeUrl.search = new URLSearchParams({\n\t\tresponse_type: \"code\",\n\t\tclient_id: oauth.clientId,\n\t\tredirect_uri: REDIRECT_URI,\n\t\tscope: oauth.scope,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\thandoff: \"url\",\n\t\tstate,\n\t}).toString();\n\n\tconst callbackServer = await startOAuthCallbackServer(state, interaction.signal);\n\tinteraction.notify({ type: \"progress\", message: `Listening for OAuth callback on ${REDIRECT_URI}` });\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: authorizeUrl.toString(),\n\t\tinstructions: \"Continue in your browser.\",\n\t});\n\n\ttry {\n\t\tconst code = await callbackServer.waitForCode();\n\t\tif (!code) {\n\t\t\tif (interaction.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Login cancelled\");\n\t\t\t}\n\t\t\tthrow new Error(\"OAuth callback did not complete.\");\n\t\t}\n\t\treturn await requestOAuthToken(\n\t\t\toauth,\n\t\t\tnew URLSearchParams({\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\t\tcode,\n\t\t\t\tcode_verifier: verifier,\n\t\t\t}),\n\t\t\tinteraction.signal,\n\t\t);\n\t} finally {\n\t\tcallbackServer.close();\n\t}\n}\n\nasync function requestDeviceAuthorization(\n\toauth: RadiusOAuthConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<DeviceAuthorizationResponse> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(oauth.deviceAuthorizationEndpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody: new URLSearchParams({ client_id: oauth.clientId, scope: oauth.scope }),\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth device authorization failed\");\n\t}\n\n\tconst data = (await response.json()) as Partial<DeviceAuthorizationResponse>;\n\tif (!data.device_code || !data.user_code || !data.expires_in) {\n\t\tthrow new Error(\"Radius OAuth device authorization response is missing required fields\");\n\t}\n\n\treturn {\n\t\tdevice_code: data.device_code,\n\t\tuser_code: data.user_code,\n\t\tverification_uri: data.verification_uri,\n\t\tverification_uri_complete: data.verification_uri_complete,\n\t\texpires_in: data.expires_in,\n\t\tinterval: data.interval,\n\t};\n}\n\nasync function loginWithDeviceCode(oauth: RadiusOAuthConfig, interaction: AuthInteraction): Promise<OAuthCredential> {\n\tconst device = await requestDeviceAuthorization(oauth, interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.user_code,\n\t\tverificationUri: device.verification_uri || oauth.verificationEndpoint,\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t});\n\n\treturn pollOAuthDeviceCodeFlow<OAuthCredential>({\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t\tsignal: interaction.signal,\n\t\tpoll: async () => {\n\t\t\ttry {\n\t\t\t\tconst credentials = await requestOAuthToken(\n\t\t\t\t\toauth,\n\t\t\t\t\tnew URLSearchParams({\n\t\t\t\t\t\tgrant_type: oauth.deviceCodeGrantType,\n\t\t\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\t\t\tdevice_code: device.device_code,\n\t\t\t\t\t}),\n\t\t\t\t\tinteraction.signal,\n\t\t\t\t);\n\t\t\t\treturn { status: \"complete\", value: credentials };\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof OAuthResponseError)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tswitch (error.oauthError) {\n\t\t\t\t\tcase \"authorization_pending\":\n\t\t\t\t\t\treturn { status: \"pending\" };\n\t\t\t\t\tcase \"slow_down\":\n\t\t\t\t\t\treturn { status: \"slow_down\" };\n\t\t\t\t\tcase \"expired_token\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization expired.\" };\n\t\t\t\t\tcase \"access_denied\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization was denied.\" };\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n}\n\nexport interface RadiusOAuthOptions {\n\tname: string;\n\tgateway: string;\n}\n\nexport function createRadiusOAuth(options: RadiusOAuthOptions): OAuthAuth {\n\tconst gateway = normalizeRadiusGatewayUrl(options.gateway);\n\n\treturn {\n\t\tname: options.name,\n\n\t\tasync login(interaction): Promise<OAuthCredential> {\n\t\t\tconst oauth = await loadRadiusOAuthConfig(gateway);\n\t\t\tconst loginMethod = await interaction.prompt({\n\t\t\t\ttype: \"select\",\n\t\t\t\tmessage: `Sign in to ${options.name}:`,\n\t\t\t\toptions: [\n\t\t\t\t\t{ id: LOGIN_METHOD_BROWSER, label: \"Sign in with browser (recommended)\" },\n\t\t\t\t\t{\n\t\t\t\t\t\tid: LOGIN_METHOD_DEVICE_CODE,\n\t\t\t\t\t\tlabel: \"Sign in with device code (when signing in from another device)\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t});\n\n\t\t\tlet credential: OAuthCredential;\n\t\t\tif (loginMethod === LOGIN_METHOD_DEVICE_CODE) {\n\t\t\t\tcredential = await loginWithDeviceCode(oauth, interaction);\n\t\t\t} else if (loginMethod === LOGIN_METHOD_BROWSER) {\n\t\t\t\tcredential = await loginWithBrowser(oauth, interaction);\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Unknown ${options.name} sign-in method: ${loginMethod}`);\n\t\t\t}\n\n\t\t\treturn credential;\n\t\t},\n\n\t\tasync refresh(credential, signal): Promise<OAuthCredential> {\n\t\t\tconst oauth = await loadRadiusOAuthConfig(gateway);\n\t\t\tconst refreshed = await requestOAuthToken(\n\t\t\t\toauth,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\t\trefresh_token: credential.refresh,\n\t\t\t\t}),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\treturn refreshed;\n\t\t},\n\n\t\tasync toAuth(credential) {\n\t\t\treturn { apiKey: credential.access };\n\t\t},\n\t};\n}\n"]}
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Radius gateway OAuth flow.
|
|
3
|
+
*
|
|
4
|
+
* Radius is a pi-messages gateway. OAuth endpoints are discovered from the
|
|
5
|
+
* gateway (`/v1/oauth`); model catalog loading is owned by the Radius provider.
|
|
6
|
+
*
|
|
7
|
+
* NOTE: This module uses node:http for the OAuth callback server.
|
|
8
|
+
* It is only intended for CLI use, not browser environments.
|
|
9
|
+
*/
|
|
10
|
+
// NEVER convert to top-level imports - breaks browser/Vite builds
|
|
11
|
+
let _http = null;
|
|
12
|
+
if (typeof process !== "undefined" && (process.versions?.node || process.versions?.bun)) {
|
|
13
|
+
import("node:http").then((m) => {
|
|
14
|
+
_http = m;
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
18
|
+
function normalizeRadiusGatewayUrl(url) {
|
|
19
|
+
return url;
|
|
20
|
+
}
|
|
21
|
+
import { pollOAuthDeviceCodeFlow } from "./device-code.js";
|
|
22
|
+
import { oauthErrorHtml, oauthSuccessHtml } from "./oauth-page.js";
|
|
23
|
+
import { generatePKCE } from "./pkce.js";
|
|
24
|
+
const CALLBACK_HOST = "127.0.0.1";
|
|
25
|
+
const CALLBACK_PORT = 1456;
|
|
26
|
+
const CALLBACK_PATH = "/oauth/callback";
|
|
27
|
+
const REDIRECT_URI = `http://${CALLBACK_HOST}:${CALLBACK_PORT}${CALLBACK_PATH}`;
|
|
28
|
+
const TOKEN_EXPIRY_SKEW_MS = 60_000;
|
|
29
|
+
const LOGIN_METHOD_BROWSER = "browser";
|
|
30
|
+
const LOGIN_METHOD_DEVICE_CODE = "device-code";
|
|
31
|
+
async function loadRadiusOAuthConfig(gateway) {
|
|
32
|
+
const response = await fetch(new URL("/v1/oauth", gateway), {
|
|
33
|
+
headers: { accept: "application/json" },
|
|
34
|
+
});
|
|
35
|
+
if (!response.ok) {
|
|
36
|
+
throw new Error(`Could not load Radius OAuth config from ${gateway}: ${response.status} ${await response.text()}`);
|
|
37
|
+
}
|
|
38
|
+
return (await response.json());
|
|
39
|
+
}
|
|
40
|
+
class OAuthResponseError extends Error {
|
|
41
|
+
status;
|
|
42
|
+
oauthError;
|
|
43
|
+
constructor(status, oauthError, description, message) {
|
|
44
|
+
const detail = oauthError
|
|
45
|
+
? description
|
|
46
|
+
? `${oauthError}: ${description}`
|
|
47
|
+
: oauthError
|
|
48
|
+
: description || String(status);
|
|
49
|
+
super(`${message}: ${detail}`);
|
|
50
|
+
this.status = status;
|
|
51
|
+
this.oauthError = oauthError;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async function readOAuthResponseError(response, message) {
|
|
55
|
+
const text = await response.text().catch(() => "");
|
|
56
|
+
let oauthError;
|
|
57
|
+
let description;
|
|
58
|
+
if (text) {
|
|
59
|
+
try {
|
|
60
|
+
const data = JSON.parse(text);
|
|
61
|
+
oauthError = typeof data.error === "string" ? data.error : undefined;
|
|
62
|
+
description = typeof data.error_description === "string" ? data.error_description : undefined;
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
description = text;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return new OAuthResponseError(response.status, oauthError, description, message);
|
|
69
|
+
}
|
|
70
|
+
async function requestOAuthToken(oauth, body, signal) {
|
|
71
|
+
let response;
|
|
72
|
+
try {
|
|
73
|
+
response = await fetch(oauth.tokenEndpoint, {
|
|
74
|
+
method: "POST",
|
|
75
|
+
headers: { accept: "application/json", "content-type": "application/x-www-form-urlencoded" },
|
|
76
|
+
body,
|
|
77
|
+
signal,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
if (signal?.aborted) {
|
|
82
|
+
throw new Error("Login cancelled");
|
|
83
|
+
}
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
if (!response.ok) {
|
|
87
|
+
throw await readOAuthResponseError(response, "Radius OAuth token request failed");
|
|
88
|
+
}
|
|
89
|
+
const data = (await response.json());
|
|
90
|
+
return {
|
|
91
|
+
type: "oauth",
|
|
92
|
+
access: data.access_token,
|
|
93
|
+
refresh: data.refresh_token,
|
|
94
|
+
expires: Date.now() + data.expires_in * 1000 - TOKEN_EXPIRY_SKEW_MS,
|
|
95
|
+
scope: data.scope,
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
function startOAuthCallbackServer(expectedState, signal) {
|
|
99
|
+
if (!_http) {
|
|
100
|
+
throw new Error("Radius OAuth is only available in Node.js environments");
|
|
101
|
+
}
|
|
102
|
+
let settle = () => { };
|
|
103
|
+
let settled = false;
|
|
104
|
+
const wait = new Promise((resolve) => {
|
|
105
|
+
settle = resolve;
|
|
106
|
+
});
|
|
107
|
+
const finish = (code) => {
|
|
108
|
+
if (settled) {
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
settled = true;
|
|
112
|
+
signal?.removeEventListener("abort", onAbort);
|
|
113
|
+
settle(code);
|
|
114
|
+
};
|
|
115
|
+
const onAbort = () => finish(null);
|
|
116
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
117
|
+
const sendPage = (response, status, html) => {
|
|
118
|
+
response.statusCode = status;
|
|
119
|
+
response.setHeader("content-type", "text/html; charset=utf-8");
|
|
120
|
+
response.end(html);
|
|
121
|
+
};
|
|
122
|
+
const server = _http.createServer((request, response) => {
|
|
123
|
+
const url = new URL(request.url ?? "/", REDIRECT_URI);
|
|
124
|
+
if (url.pathname !== CALLBACK_PATH) {
|
|
125
|
+
sendPage(response, 404, oauthErrorHtml("Callback route not found."));
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
if (url.searchParams.get("state") !== expectedState) {
|
|
129
|
+
sendPage(response, 400, oauthErrorHtml("OAuth state mismatch."));
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
const error = url.searchParams.get("error");
|
|
133
|
+
if (error) {
|
|
134
|
+
sendPage(response, 400, oauthErrorHtml(url.searchParams.get("error_description") ?? error));
|
|
135
|
+
finish(null);
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
const code = url.searchParams.get("code");
|
|
139
|
+
if (!code) {
|
|
140
|
+
sendPage(response, 400, oauthErrorHtml("Missing authorization code."));
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
sendPage(response, 200, oauthSuccessHtml("Signed in to Radius. You may now close this page."));
|
|
144
|
+
finish(code);
|
|
145
|
+
});
|
|
146
|
+
return new Promise((resolve) => {
|
|
147
|
+
server
|
|
148
|
+
.listen(CALLBACK_PORT, CALLBACK_HOST, () => {
|
|
149
|
+
resolve({
|
|
150
|
+
waitForCode: () => wait,
|
|
151
|
+
close: () => {
|
|
152
|
+
finish(null);
|
|
153
|
+
server.close();
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
})
|
|
157
|
+
.once("error", () => {
|
|
158
|
+
finish(null);
|
|
159
|
+
resolve({ waitForCode: async () => null, close: () => { } });
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
async function loginWithBrowser(oauth, interaction) {
|
|
164
|
+
const { verifier, challenge } = await generatePKCE();
|
|
165
|
+
const state = crypto.randomUUID();
|
|
166
|
+
const authorizeUrl = new URL(oauth.authorizationEndpoint);
|
|
167
|
+
authorizeUrl.search = new URLSearchParams({
|
|
168
|
+
response_type: "code",
|
|
169
|
+
client_id: oauth.clientId,
|
|
170
|
+
redirect_uri: REDIRECT_URI,
|
|
171
|
+
scope: oauth.scope,
|
|
172
|
+
code_challenge: challenge,
|
|
173
|
+
code_challenge_method: "S256",
|
|
174
|
+
handoff: "url",
|
|
175
|
+
state,
|
|
176
|
+
}).toString();
|
|
177
|
+
const callbackServer = await startOAuthCallbackServer(state, interaction.signal);
|
|
178
|
+
interaction.notify({ type: "progress", message: `Listening for OAuth callback on ${REDIRECT_URI}` });
|
|
179
|
+
interaction.notify({
|
|
180
|
+
type: "auth_url",
|
|
181
|
+
url: authorizeUrl.toString(),
|
|
182
|
+
instructions: "Continue in your browser.",
|
|
183
|
+
});
|
|
184
|
+
try {
|
|
185
|
+
const code = await callbackServer.waitForCode();
|
|
186
|
+
if (!code) {
|
|
187
|
+
if (interaction.signal?.aborted) {
|
|
188
|
+
throw new Error("Login cancelled");
|
|
189
|
+
}
|
|
190
|
+
throw new Error("OAuth callback did not complete.");
|
|
191
|
+
}
|
|
192
|
+
return await requestOAuthToken(oauth, new URLSearchParams({
|
|
193
|
+
grant_type: "authorization_code",
|
|
194
|
+
client_id: oauth.clientId,
|
|
195
|
+
redirect_uri: REDIRECT_URI,
|
|
196
|
+
code,
|
|
197
|
+
code_verifier: verifier,
|
|
198
|
+
}), interaction.signal);
|
|
199
|
+
}
|
|
200
|
+
finally {
|
|
201
|
+
callbackServer.close();
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
async function requestDeviceAuthorization(oauth, signal) {
|
|
205
|
+
let response;
|
|
206
|
+
try {
|
|
207
|
+
response = await fetch(oauth.deviceAuthorizationEndpoint, {
|
|
208
|
+
method: "POST",
|
|
209
|
+
headers: { accept: "application/json", "content-type": "application/x-www-form-urlencoded" },
|
|
210
|
+
body: new URLSearchParams({ client_id: oauth.clientId, scope: oauth.scope }),
|
|
211
|
+
signal,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
if (signal?.aborted) {
|
|
216
|
+
throw new Error("Login cancelled");
|
|
217
|
+
}
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
if (!response.ok) {
|
|
221
|
+
throw await readOAuthResponseError(response, "Radius OAuth device authorization failed");
|
|
222
|
+
}
|
|
223
|
+
const data = (await response.json());
|
|
224
|
+
if (!data.device_code || !data.user_code || !data.expires_in) {
|
|
225
|
+
throw new Error("Radius OAuth device authorization response is missing required fields");
|
|
226
|
+
}
|
|
227
|
+
return {
|
|
228
|
+
device_code: data.device_code,
|
|
229
|
+
user_code: data.user_code,
|
|
230
|
+
verification_uri: data.verification_uri,
|
|
231
|
+
verification_uri_complete: data.verification_uri_complete,
|
|
232
|
+
expires_in: data.expires_in,
|
|
233
|
+
interval: data.interval,
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
async function loginWithDeviceCode(oauth, interaction) {
|
|
237
|
+
const device = await requestDeviceAuthorization(oauth, interaction.signal);
|
|
238
|
+
interaction.notify({
|
|
239
|
+
type: "device_code",
|
|
240
|
+
userCode: device.user_code,
|
|
241
|
+
verificationUri: device.verification_uri || oauth.verificationEndpoint,
|
|
242
|
+
intervalSeconds: device.interval,
|
|
243
|
+
expiresInSeconds: device.expires_in,
|
|
244
|
+
});
|
|
245
|
+
return pollOAuthDeviceCodeFlow({
|
|
246
|
+
intervalSeconds: device.interval,
|
|
247
|
+
expiresInSeconds: device.expires_in,
|
|
248
|
+
signal: interaction.signal,
|
|
249
|
+
poll: async () => {
|
|
250
|
+
try {
|
|
251
|
+
const credentials = await requestOAuthToken(oauth, new URLSearchParams({
|
|
252
|
+
grant_type: oauth.deviceCodeGrantType,
|
|
253
|
+
client_id: oauth.clientId,
|
|
254
|
+
device_code: device.device_code,
|
|
255
|
+
}), interaction.signal);
|
|
256
|
+
return { status: "complete", value: credentials };
|
|
257
|
+
}
|
|
258
|
+
catch (error) {
|
|
259
|
+
if (!(error instanceof OAuthResponseError)) {
|
|
260
|
+
throw error;
|
|
261
|
+
}
|
|
262
|
+
switch (error.oauthError) {
|
|
263
|
+
case "authorization_pending":
|
|
264
|
+
return { status: "pending" };
|
|
265
|
+
case "slow_down":
|
|
266
|
+
return { status: "slow_down" };
|
|
267
|
+
case "expired_token":
|
|
268
|
+
return { status: "failed", message: "Device authorization expired." };
|
|
269
|
+
case "access_denied":
|
|
270
|
+
return { status: "failed", message: "Device authorization was denied." };
|
|
271
|
+
default:
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
export function createRadiusOAuth(options) {
|
|
279
|
+
const gateway = normalizeRadiusGatewayUrl(options.gateway);
|
|
280
|
+
return {
|
|
281
|
+
name: options.name,
|
|
282
|
+
async login(interaction) {
|
|
283
|
+
const oauth = await loadRadiusOAuthConfig(gateway);
|
|
284
|
+
const loginMethod = await interaction.prompt({
|
|
285
|
+
type: "select",
|
|
286
|
+
message: `Sign in to ${options.name}:`,
|
|
287
|
+
options: [
|
|
288
|
+
{ id: LOGIN_METHOD_BROWSER, label: "Sign in with browser (recommended)" },
|
|
289
|
+
{
|
|
290
|
+
id: LOGIN_METHOD_DEVICE_CODE,
|
|
291
|
+
label: "Sign in with device code (when signing in from another device)",
|
|
292
|
+
},
|
|
293
|
+
],
|
|
294
|
+
});
|
|
295
|
+
let credential;
|
|
296
|
+
if (loginMethod === LOGIN_METHOD_DEVICE_CODE) {
|
|
297
|
+
credential = await loginWithDeviceCode(oauth, interaction);
|
|
298
|
+
}
|
|
299
|
+
else if (loginMethod === LOGIN_METHOD_BROWSER) {
|
|
300
|
+
credential = await loginWithBrowser(oauth, interaction);
|
|
301
|
+
}
|
|
302
|
+
else {
|
|
303
|
+
throw new Error(`Unknown ${options.name} sign-in method: ${loginMethod}`);
|
|
304
|
+
}
|
|
305
|
+
return credential;
|
|
306
|
+
},
|
|
307
|
+
async refresh(credential, signal) {
|
|
308
|
+
const oauth = await loadRadiusOAuthConfig(gateway);
|
|
309
|
+
const refreshed = await requestOAuthToken(oauth, new URLSearchParams({
|
|
310
|
+
grant_type: "refresh_token",
|
|
311
|
+
client_id: oauth.clientId,
|
|
312
|
+
refresh_token: credential.refresh,
|
|
313
|
+
}), signal);
|
|
314
|
+
return refreshed;
|
|
315
|
+
},
|
|
316
|
+
async toAuth(credential) {
|
|
317
|
+
return { apiKey: credential.access };
|
|
318
|
+
},
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
//# sourceMappingURL=radius.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"radius.js","sourceRoot":"","sources":["../../../src/auth/oauth/radius.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,kEAAkE;AAClE,IAAI,KAAK,GAAsC,IAAI,CAAC;AACpD,IAAI,OAAO,OAAO,KAAK,WAAW,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,IAAI,OAAO,CAAC,QAAQ,EAAE,GAAG,CAAC,EAAE,CAAC;IACzF,MAAM,CAAC,WAAW,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;QAC/B,KAAK,GAAG,CAAC,CAAC;IAAA,CACV,CAAC,CAAC;AACJ,CAAC;AAID,6DAA6D;AAC7D,SAAS,yBAAyB,CAAC,GAAW,EAAU;IACvD,OAAO,GAAG,CAAC;AAAA,CACX;AAED,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACnE,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,MAAM,aAAa,GAAG,IAAI,CAAC;AAC3B,MAAM,aAAa,GAAG,iBAAiB,CAAC;AACxC,MAAM,YAAY,GAAG,UAAU,a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BAAqB,CAAC,OAAO,CAAC,CAAC;YACnD,MAAM,SAAS,GAAG,MAAM,iBAAiB,CACxC,KAAK,EACL,IAAI,eAAe,CAAC;gBACnB,UAAU,EAAE,eAAe;gBAC3B,SAAS,EAAE,KAAK,CAAC,QAAQ;gBACzB,aAAa,EAAE,UAAU,CAAC,OAAO;aACjC,CAAC,EACF,MAAM,CACN,CAAC;YACF,OAAO,SAAS,CAAC;QAAA,CACjB;QAED,KAAK,CAAC,MAAM,CAAC,UAAU,EAAE;YACxB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;QAAA,CACrC;KACD,CAAC;AAAA,CACF","sourcesContent":["/**\n * Radius gateway OAuth flow.\n *\n * Radius is a pi-messages gateway. OAuth endpoints are discovered from the\n * gateway (`/v1/oauth`); model catalog loading is owned by the Radius provider.\n *\n * NOTE: This module uses node:http for the OAuth callback server.\n * It is only intended for CLI use, not browser environments.\n */\n\n// NEVER convert to top-level imports - breaks browser/Vite builds\nlet _http: typeof import(\"node:http\") | null = null;\nif (typeof process !== \"undefined\" && (process.versions?.node || process.versions?.bun)) {\n\timport(\"node:http\").then((m) => {\n\t\t_http = m;\n\t});\n}\n\nimport type { AuthInteraction, OAuthAuth, OAuthCredential } from \"../types.ts\";\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction normalizeRadiusGatewayUrl(url: string): string {\n\treturn url;\n}\n\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { oauthErrorHtml, oauthSuccessHtml } from \"./oauth-page.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\n\nconst CALLBACK_HOST = \"127.0.0.1\";\nconst CALLBACK_PORT = 1456;\nconst CALLBACK_PATH = \"/oauth/callback\";\nconst REDIRECT_URI = `http://${CALLBACK_HOST}:${CALLBACK_PORT}${CALLBACK_PATH}`;\nconst TOKEN_EXPIRY_SKEW_MS = 60_000;\nconst LOGIN_METHOD_BROWSER = \"browser\";\nconst LOGIN_METHOD_DEVICE_CODE = \"device-code\";\n\ntype RadiusOAuthConfig = {\n\tissuer: string;\n\tauthorizationEndpoint: string;\n\ttokenEndpoint: string;\n\tdeviceAuthorizationEndpoint: string;\n\tdeviceAuthorizationEventsEndpoint: string;\n\tverificationEndpoint: string;\n\tclientId: string;\n\tscope: string;\n\tdeviceCodeGrantType: string;\n};\n\ntype DeviceAuthorizationResponse = {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri?: string;\n\tverification_uri_complete?: string;\n\texpires_in: number;\n\tinterval?: number;\n};\n\nasync function loadRadiusOAuthConfig(gateway: string): Promise<RadiusOAuthConfig> {\n\tconst response = await fetch(new URL(\"/v1/oauth\", gateway), {\n\t\theaders: { accept: \"application/json\" },\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Could not load Radius OAuth config from ${gateway}: ${response.status} ${await response.text()}`,\n\t\t);\n\t}\n\n\treturn (await response.json()) as RadiusOAuthConfig;\n}\n\nclass OAuthResponseError extends Error {\n\treadonly status: number;\n\treadonly oauthError?: string;\n\n\tconstructor(status: number, oauthError: string | undefined, description: string | undefined, message: string) {\n\t\tconst detail = oauthError\n\t\t\t? description\n\t\t\t\t? `${oauthError}: ${description}`\n\t\t\t\t: oauthError\n\t\t\t: description || String(status);\n\t\tsuper(`${message}: ${detail}`);\n\t\tthis.status = status;\n\t\tthis.oauthError = oauthError;\n\t}\n}\n\nasync function readOAuthResponseError(response: Response, message: string): Promise<OAuthResponseError> {\n\tconst text = await response.text().catch(() => \"\");\n\tlet oauthError: string | undefined;\n\tlet description: string | undefined;\n\n\tif (text) {\n\t\ttry {\n\t\t\tconst data = JSON.parse(text) as { error?: unknown; error_description?: unknown };\n\t\t\toauthError = typeof data.error === \"string\" ? data.error : undefined;\n\t\t\tdescription = typeof data.error_description === \"string\" ? data.error_description : undefined;\n\t\t} catch {\n\t\t\tdescription = text;\n\t\t}\n\t}\n\n\treturn new OAuthResponseError(response.status, oauthError, description, message);\n}\n\nasync function requestOAuthToken(\n\toauth: RadiusOAuthConfig,\n\tbody: URLSearchParams,\n\tsignal?: AbortSignal,\n): Promise<OAuthCredential> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(oauth.tokenEndpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody,\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth token request failed\");\n\t}\n\n\tconst data = (await response.json()) as {\n\t\taccess_token: string;\n\t\trefresh_token: string;\n\t\texpires_in: number;\n\t\tscope?: string;\n\t};\n\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess: data.access_token,\n\t\trefresh: data.refresh_token,\n\t\texpires: Date.now() + data.expires_in * 1000 - TOKEN_EXPIRY_SKEW_MS,\n\t\tscope: data.scope,\n\t};\n}\n\ntype OAuthCallbackServer = {\n\twaitForCode(): Promise<string | null>;\n\tclose(): void;\n};\n\nfunction startOAuthCallbackServer(\n\texpectedState: string,\n\tsignal: AbortSignal | undefined,\n): Promise<OAuthCallbackServer> {\n\tif (!_http) {\n\t\tthrow new Error(\"Radius OAuth is only available in Node.js environments\");\n\t}\n\n\tlet settle: (code: string | null) => void = () => {};\n\tlet settled = false;\n\tconst wait = new Promise<string | null>((resolve) => {\n\t\tsettle = resolve;\n\t});\n\tconst finish = (code: string | null) => {\n\t\tif (settled) {\n\t\t\treturn;\n\t\t}\n\t\tsettled = true;\n\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\tsettle(code);\n\t};\n\tconst onAbort = () => finish(null);\n\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n\tconst sendPage = (response: import(\"node:http\").ServerResponse, status: number, html: string) => {\n\t\tresponse.statusCode = status;\n\t\tresponse.setHeader(\"content-type\", \"text/html; charset=utf-8\");\n\t\tresponse.end(html);\n\t};\n\n\tconst server = _http.createServer((request, response) => {\n\t\tconst url = new URL(request.url ?? \"/\", REDIRECT_URI);\n\t\tif (url.pathname !== CALLBACK_PATH) {\n\t\t\tsendPage(response, 404, oauthErrorHtml(\"Callback route not found.\"));\n\t\t\treturn;\n\t\t}\n\t\tif (url.searchParams.get(\"state\") !== expectedState) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(\"OAuth state mismatch.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tconst error = url.searchParams.get(\"error\");\n\t\tif (error) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(url.searchParams.get(\"error_description\") ?? error));\n\t\t\tfinish(null);\n\t\t\treturn;\n\t\t}\n\n\t\tconst code = url.searchParams.get(\"code\");\n\t\tif (!code) {\n\t\t\tsendPage(response, 400, oauthErrorHtml(\"Missing authorization code.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tsendPage(response, 200, oauthSuccessHtml(\"Signed in to Radius. You may now close this page.\"));\n\t\tfinish(code);\n\t});\n\n\treturn new Promise((resolve) => {\n\t\tserver\n\t\t\t.listen(CALLBACK_PORT, CALLBACK_HOST, () => {\n\t\t\t\tresolve({\n\t\t\t\t\twaitForCode: () => wait,\n\t\t\t\t\tclose: () => {\n\t\t\t\t\t\tfinish(null);\n\t\t\t\t\t\tserver.close();\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t})\n\t\t\t.once(\"error\", () => {\n\t\t\t\tfinish(null);\n\t\t\t\tresolve({ waitForCode: async () => null, close: () => {} });\n\t\t\t});\n\t});\n}\n\nasync function loginWithBrowser(oauth: RadiusOAuthConfig, interaction: AuthInteraction): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = crypto.randomUUID();\n\tconst authorizeUrl = new URL(oauth.authorizationEndpoint);\n\tauthorizeUrl.search = new URLSearchParams({\n\t\tresponse_type: \"code\",\n\t\tclient_id: oauth.clientId,\n\t\tredirect_uri: REDIRECT_URI,\n\t\tscope: oauth.scope,\n\t\tcode_challenge: challenge,\n\t\tcode_challenge_method: \"S256\",\n\t\thandoff: \"url\",\n\t\tstate,\n\t}).toString();\n\n\tconst callbackServer = await startOAuthCallbackServer(state, interaction.signal);\n\tinteraction.notify({ type: \"progress\", message: `Listening for OAuth callback on ${REDIRECT_URI}` });\n\tinteraction.notify({\n\t\ttype: \"auth_url\",\n\t\turl: authorizeUrl.toString(),\n\t\tinstructions: \"Continue in your browser.\",\n\t});\n\n\ttry {\n\t\tconst code = await callbackServer.waitForCode();\n\t\tif (!code) {\n\t\t\tif (interaction.signal?.aborted) {\n\t\t\t\tthrow new Error(\"Login cancelled\");\n\t\t\t}\n\t\t\tthrow new Error(\"OAuth callback did not complete.\");\n\t\t}\n\t\treturn await requestOAuthToken(\n\t\t\toauth,\n\t\t\tnew URLSearchParams({\n\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\t\tcode,\n\t\t\t\tcode_verifier: verifier,\n\t\t\t}),\n\t\t\tinteraction.signal,\n\t\t);\n\t} finally {\n\t\tcallbackServer.close();\n\t}\n}\n\nasync function requestDeviceAuthorization(\n\toauth: RadiusOAuthConfig,\n\tsignal: AbortSignal | undefined,\n): Promise<DeviceAuthorizationResponse> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(oauth.deviceAuthorizationEndpoint, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" },\n\t\t\tbody: new URLSearchParams({ client_id: oauth.clientId, scope: oauth.scope }),\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tif (!response.ok) {\n\t\tthrow await readOAuthResponseError(response, \"Radius OAuth device authorization failed\");\n\t}\n\n\tconst data = (await response.json()) as Partial<DeviceAuthorizationResponse>;\n\tif (!data.device_code || !data.user_code || !data.expires_in) {\n\t\tthrow new Error(\"Radius OAuth device authorization response is missing required fields\");\n\t}\n\n\treturn {\n\t\tdevice_code: data.device_code,\n\t\tuser_code: data.user_code,\n\t\tverification_uri: data.verification_uri,\n\t\tverification_uri_complete: data.verification_uri_complete,\n\t\texpires_in: data.expires_in,\n\t\tinterval: data.interval,\n\t};\n}\n\nasync function loginWithDeviceCode(oauth: RadiusOAuthConfig, interaction: AuthInteraction): Promise<OAuthCredential> {\n\tconst device = await requestDeviceAuthorization(oauth, interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.user_code,\n\t\tverificationUri: device.verification_uri || oauth.verificationEndpoint,\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t});\n\n\treturn pollOAuthDeviceCodeFlow<OAuthCredential>({\n\t\tintervalSeconds: device.interval,\n\t\texpiresInSeconds: device.expires_in,\n\t\tsignal: interaction.signal,\n\t\tpoll: async () => {\n\t\t\ttry {\n\t\t\t\tconst credentials = await requestOAuthToken(\n\t\t\t\t\toauth,\n\t\t\t\t\tnew URLSearchParams({\n\t\t\t\t\t\tgrant_type: oauth.deviceCodeGrantType,\n\t\t\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\t\t\tdevice_code: device.device_code,\n\t\t\t\t\t}),\n\t\t\t\t\tinteraction.signal,\n\t\t\t\t);\n\t\t\t\treturn { status: \"complete\", value: credentials };\n\t\t\t} catch (error) {\n\t\t\t\tif (!(error instanceof OAuthResponseError)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t\tswitch (error.oauthError) {\n\t\t\t\t\tcase \"authorization_pending\":\n\t\t\t\t\t\treturn { status: \"pending\" };\n\t\t\t\t\tcase \"slow_down\":\n\t\t\t\t\t\treturn { status: \"slow_down\" };\n\t\t\t\t\tcase \"expired_token\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization expired.\" };\n\t\t\t\t\tcase \"access_denied\":\n\t\t\t\t\t\treturn { status: \"failed\", message: \"Device authorization was denied.\" };\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t});\n}\n\nexport interface RadiusOAuthOptions {\n\tname: string;\n\tgateway: string;\n}\n\nexport function createRadiusOAuth(options: RadiusOAuthOptions): OAuthAuth {\n\tconst gateway = normalizeRadiusGatewayUrl(options.gateway);\n\n\treturn {\n\t\tname: options.name,\n\n\t\tasync login(interaction): Promise<OAuthCredential> {\n\t\t\tconst oauth = await loadRadiusOAuthConfig(gateway);\n\t\t\tconst loginMethod = await interaction.prompt({\n\t\t\t\ttype: \"select\",\n\t\t\t\tmessage: `Sign in to ${options.name}:`,\n\t\t\t\toptions: [\n\t\t\t\t\t{ id: LOGIN_METHOD_BROWSER, label: \"Sign in with browser (recommended)\" },\n\t\t\t\t\t{\n\t\t\t\t\t\tid: LOGIN_METHOD_DEVICE_CODE,\n\t\t\t\t\t\tlabel: \"Sign in with device code (when signing in from another device)\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t});\n\n\t\t\tlet credential: OAuthCredential;\n\t\t\tif (loginMethod === LOGIN_METHOD_DEVICE_CODE) {\n\t\t\t\tcredential = await loginWithDeviceCode(oauth, interaction);\n\t\t\t} else if (loginMethod === LOGIN_METHOD_BROWSER) {\n\t\t\t\tcredential = await loginWithBrowser(oauth, interaction);\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Unknown ${options.name} sign-in method: ${loginMethod}`);\n\t\t\t}\n\n\t\t\treturn credential;\n\t\t},\n\n\t\tasync refresh(credential, signal): Promise<OAuthCredential> {\n\t\t\tconst oauth = await loadRadiusOAuthConfig(gateway);\n\t\t\tconst refreshed = await requestOAuthToken(\n\t\t\t\toauth,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\t\tclient_id: oauth.clientId,\n\t\t\t\t\trefresh_token: credential.refresh,\n\t\t\t\t}),\n\t\t\t\tsignal,\n\t\t\t);\n\t\t\treturn refreshed;\n\t\t},\n\n\t\tasync toAuth(credential) {\n\t\t\treturn { apiKey: credential.access };\n\t\t},\n\t};\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"xai.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/xai.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAmB,SAAS,EAAmB,MAAM,aAAa,CAAC;AAgO/E,eAAO,MAAM,QAAQ,EAAE,SAStB,CAAC","sourcesContent":["/**\n * xAI OAuth device-code flow.\n */\n\nimport type { AuthInteraction, OAuthAuth, OAuthCredential } from \"../types.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\n\nconst XAI_CLIENT_ID = \"b1a00492-073a-47ea-816f-4c329264a828\";\nconst XAI_SCOPE = \"openid profile email offline_access grok-cli:access api:access\";\nconst XAI_DEVICE_CODE_URL = \"https://auth.x.ai/oauth2/device/code\";\nconst XAI_TOKEN_URL = \"https://auth.x.ai/oauth2/token\";\n// Refresh slightly before the reported expiry to avoid using a token that dies mid-request.\nconst REFRESH_SKEW_MS = 5 * 60 * 1000;\nconst DEFAULT_TOKEN_LIFETIME_SECONDS = 3600;\n\ntype JsonObject = Record<string, unknown>;\n\ntype OAuthHttpResponse = {\n\tok: boolean;\n\tstatus: number;\n\tbody: JsonObject;\n};\n\ntype XaiDeviceCode = {\n\tdeviceCode: string;\n\tuserCode: string;\n\tverificationUri: string;\n\tverificationUriComplete?: string;\n\tintervalSeconds?: number;\n\texpiresInSeconds: number;\n};\n\nfunction requiredString(body: JsonObject, field: string): string {\n\tconst value = body[field];\n\tif (typeof value !== \"string\" || value.length === 0) {\n\t\tthrow new Error(`Invalid xAI OAuth response field: ${field}`);\n\t}\n\treturn value;\n}\n\nfunction positiveNumber(body: JsonObject, field: string): number {\n\tconst value = body[field];\n\tif (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n\t\tthrow new Error(`Invalid xAI OAuth response field: ${field}`);\n\t}\n\treturn value;\n}\n\n// The verification URI is opened in the user's browser; force it to be an https URL\n// so a malicious response cannot make `open` launch something else.\nfunction validateVerificationUri(raw: string): string {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(raw);\n\t} catch {\n\t\tthrow new Error(\"Untrusted verification URI in xAI OAuth response\");\n\t}\n\tif (url.protocol !== \"https:\") {\n\t\tthrow new Error(\"Untrusted verification URI in xAI OAuth response\");\n\t}\n\treturn url.href;\n}\n\nasync function postForm(url: string, fields: Record<string, string>, signal?: AbortSignal): Promise<OAuthHttpResponse> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t},\n\t\t\tbody: new URLSearchParams(fields),\n\t\t\tsignal,\n\t\t});\n\t} catch (error) {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow error;\n\t}\n\n\tlet body: JsonObject;\n\ttry {\n\t\tconst parsed = (await response.json()) as unknown;\n\t\tbody = parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? (parsed as JsonObject) : {};\n\t} catch {\n\t\tif (signal?.aborted) {\n\t\t\tthrow new Error(\"Login cancelled\");\n\t\t}\n\t\tthrow new Error(`xAI OAuth returned invalid JSON (HTTP ${response.status})`);\n\t}\n\treturn {\n\t\tok: response.ok,\n\t\tstatus: response.status,\n\t\tbody,\n\t};\n}\n\nfunction requestFailure(action: string, response: OAuthHttpResponse): Error {\n\tconst error = typeof response.body.error === \"string\" ? response.body.error : undefined;\n\tconst description =\n\t\ttypeof response.body.error_description === \"string\" ? response.body.error_description : undefined;\n\tconst detail = [error, description].filter(Boolean).join(\": \");\n\treturn new Error(`xAI OAuth ${action} failed (HTTP ${response.status})${detail ? `: ${detail}` : \"\"}`);\n}\n\nfunction parseDeviceCode(body: JsonObject): XaiDeviceCode {\n\t// RFC 8628 allows interval 0 (no minimum wait); fall back to the poller's\n\t// default instead of failing on non-positive or malformed values.\n\tconst interval = body.interval;\n\tconst intervalSeconds =\n\t\ttypeof interval === \"number\" && Number.isFinite(interval) && interval > 0 ? interval : undefined;\n\tconst verificationUriComplete =\n\t\ttypeof body.verification_uri_complete === \"string\" && body.verification_uri_complete.length > 0\n\t\t\t? validateVerificationUri(body.verification_uri_complete)\n\t\t\t: undefined;\n\treturn {\n\t\tdeviceCode: requiredString(body, \"device_code\"),\n\t\tuserCode: requiredString(body, \"user_code\"),\n\t\tverificationUri: validateVerificationUri(requiredString(body, \"verification_uri\")),\n\t\tverificationUriComplete,\n\t\tintervalSeconds,\n\t\texpiresInSeconds: positiveNumber(body, \"expires_in\"),\n\t};\n}\n\nfunction credentialsFromTokenResponse(body: JsonObject, previousRefreshToken?: string): OAuthCredential {\n\tconst access = requiredString(body, \"access_token\");\n\t// xAI may omit refresh_token on refresh when the token is not rotated.\n\tconst refresh =\n\t\tbody.refresh_token === undefined && previousRefreshToken\n\t\t\t? previousRefreshToken\n\t\t\t: requiredString(body, \"refresh_token\");\n\tconst expiresInSeconds =\n\t\tbody.expires_in === undefined ? DEFAULT_TOKEN_LIFETIME_SECONDS : positiveNumber(body, \"expires_in\");\n\treturn {\n\t\ttype: \"oauth\",\n\t\taccess,\n\t\trefresh,\n\t\texpires: Date.now() + expiresInSeconds * 1000 - REFRESH_SKEW_MS,\n\t};\n}\n\nasync function requestDeviceCode(signal?: AbortSignal): Promise<XaiDeviceCode> {\n\tconst response = await postForm(\n\t\tXAI_DEVICE_CODE_URL,\n\t\t{\n\t\t\tclient_id: XAI_CLIENT_ID,\n\t\t\tscope: XAI_SCOPE,\n\t\t\treferrer: \"pi\",\n\t\t},\n\t\tsignal,\n\t);\n\tif (!response.ok) {\n\t\tthrow requestFailure(\"device authorization\", response);\n\t}\n\treturn parseDeviceCode(response.body);\n}\n\nasync function pollForTokens(device: XaiDeviceCode, signal?: AbortSignal): Promise<OAuthCredential> {\n\treturn pollOAuthDeviceCodeFlow<OAuthCredential>({\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: device.expiresInSeconds,\n\t\twaitBeforeFirstPoll: true,\n\t\tsignal,\n\t\tpoll: async () => {\n\t\t\tconst response = await postForm(\n\t\t\t\tXAI_TOKEN_URL,\n\t\t\t\t{\n\t\t\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\t\t\tclient_id: XAI_CLIENT_ID,\n\t\t\t\t\tdevice_code: device.deviceCode,\n\t\t\t\t},\n\t\t\t\tsignal,\n\t\t\t);\n\n\t\t\tif (response.ok) {\n\t\t\t\treturn { status: \"complete\", value: credentialsFromTokenResponse(response.body) };\n\t\t\t}\n\n\t\t\tconst error = response.body.error;\n\t\t\tif (error === \"authorization_pending\") {\n\t\t\t\treturn { status: \"pending\" };\n\t\t\t}\n\t\t\tif (error === \"slow_down\") {\n\t\t\t\tconst interval = response.body.interval;\n\t\t\t\treturn { status: \"slow_down\", intervalSeconds: typeof interval === \"number\" ? interval : undefined };\n\t\t\t}\n\t\t\tif (error === \"access_denied\" || error === \"authorization_denied\") {\n\t\t\t\treturn { status: \"failed\", message: \"xAI device authorization was denied\" };\n\t\t\t}\n\t\t\tif (error === \"expired_token\") {\n\t\t\t\treturn { status: \"failed\", message: \"xAI device code expired\" };\n\t\t\t}\n\t\t\treturn { status: \"failed\", message: requestFailure(\"device token polling\", response).message };\n\t\t},\n\t});\n}\n\nasync function loginXai(interaction: AuthInteraction): Promise<OAuthCredential> {\n\tconst device = await requestDeviceCode(interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.userCode,\n\t\tverificationUri: device.verificationUriComplete ?? device.verificationUri,\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: device.expiresInSeconds,\n\t});\n\treturn pollForTokens(device, interaction.signal);\n}\n\nasync function refreshXaiToken(refreshToken: string, signal?: AbortSignal): Promise<OAuthCredential> {\n\tconst response = await postForm(\n\t\tXAI_TOKEN_URL,\n\t\t{\n\t\t\tgrant_type: \"refresh_token\",\n\t\t\tclient_id: XAI_CLIENT_ID,\n\t\t\trefresh_token: refreshToken,\n\t\t},\n\t\tsignal,\n\t);\n\tif (!response.ok) {\n\t\tthrow requestFailure(\"token refresh\", response);\n\t}\n\treturn credentialsFromTokenResponse(response.body, refreshToken);\n}\n\nexport const xaiOAuth: OAuthAuth = {\n\tname: \"xAI (Grok/X subscription)\",\n\tloginLabel: \"Sign in with SuperGrok or X Premium\",\n\tlogin: loginXai,\n\trefresh: (credential, signal) => refreshXaiToken(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* xAI OAuth device-code flow.
|
|
3
|
+
*/
|
|
4
|
+
import { pollOAuthDeviceCodeFlow } from "./device-code.js";
|
|
5
|
+
const XAI_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
|
|
6
|
+
const XAI_SCOPE = "openid profile email offline_access grok-cli:access api:access";
|
|
7
|
+
const XAI_DEVICE_CODE_URL = "https://auth.x.ai/oauth2/device/code";
|
|
8
|
+
const XAI_TOKEN_URL = "https://auth.x.ai/oauth2/token";
|
|
9
|
+
// Refresh slightly before the reported expiry to avoid using a token that dies mid-request.
|
|
10
|
+
const REFRESH_SKEW_MS = 5 * 60 * 1000;
|
|
11
|
+
const DEFAULT_TOKEN_LIFETIME_SECONDS = 3600;
|
|
12
|
+
function requiredString(body, field) {
|
|
13
|
+
const value = body[field];
|
|
14
|
+
if (typeof value !== "string" || value.length === 0) {
|
|
15
|
+
throw new Error(`Invalid xAI OAuth response field: ${field}`);
|
|
16
|
+
}
|
|
17
|
+
return value;
|
|
18
|
+
}
|
|
19
|
+
function positiveNumber(body, field) {
|
|
20
|
+
const value = body[field];
|
|
21
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
22
|
+
throw new Error(`Invalid xAI OAuth response field: ${field}`);
|
|
23
|
+
}
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
// The verification URI is opened in the user's browser; force it to be an https URL
|
|
27
|
+
// so a malicious response cannot make `open` launch something else.
|
|
28
|
+
function validateVerificationUri(raw) {
|
|
29
|
+
let url;
|
|
30
|
+
try {
|
|
31
|
+
url = new URL(raw);
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
throw new Error("Untrusted verification URI in xAI OAuth response");
|
|
35
|
+
}
|
|
36
|
+
if (url.protocol !== "https:") {
|
|
37
|
+
throw new Error("Untrusted verification URI in xAI OAuth response");
|
|
38
|
+
}
|
|
39
|
+
return url.href;
|
|
40
|
+
}
|
|
41
|
+
async function postForm(url, fields, signal) {
|
|
42
|
+
let response;
|
|
43
|
+
try {
|
|
44
|
+
response = await fetch(url, {
|
|
45
|
+
method: "POST",
|
|
46
|
+
headers: {
|
|
47
|
+
Accept: "application/json",
|
|
48
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
49
|
+
},
|
|
50
|
+
body: new URLSearchParams(fields),
|
|
51
|
+
signal,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
if (signal?.aborted) {
|
|
56
|
+
throw new Error("Login cancelled");
|
|
57
|
+
}
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
let body;
|
|
61
|
+
try {
|
|
62
|
+
const parsed = (await response.json());
|
|
63
|
+
body = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
if (signal?.aborted) {
|
|
67
|
+
throw new Error("Login cancelled");
|
|
68
|
+
}
|
|
69
|
+
throw new Error(`xAI OAuth returned invalid JSON (HTTP ${response.status})`);
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
ok: response.ok,
|
|
73
|
+
status: response.status,
|
|
74
|
+
body,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function requestFailure(action, response) {
|
|
78
|
+
const error = typeof response.body.error === "string" ? response.body.error : undefined;
|
|
79
|
+
const description = typeof response.body.error_description === "string" ? response.body.error_description : undefined;
|
|
80
|
+
const detail = [error, description].filter(Boolean).join(": ");
|
|
81
|
+
return new Error(`xAI OAuth ${action} failed (HTTP ${response.status})${detail ? `: ${detail}` : ""}`);
|
|
82
|
+
}
|
|
83
|
+
function parseDeviceCode(body) {
|
|
84
|
+
// RFC 8628 allows interval 0 (no minimum wait); fall back to the poller's
|
|
85
|
+
// default instead of failing on non-positive or malformed values.
|
|
86
|
+
const interval = body.interval;
|
|
87
|
+
const intervalSeconds = typeof interval === "number" && Number.isFinite(interval) && interval > 0 ? interval : undefined;
|
|
88
|
+
const verificationUriComplete = typeof body.verification_uri_complete === "string" && body.verification_uri_complete.length > 0
|
|
89
|
+
? validateVerificationUri(body.verification_uri_complete)
|
|
90
|
+
: undefined;
|
|
91
|
+
return {
|
|
92
|
+
deviceCode: requiredString(body, "device_code"),
|
|
93
|
+
userCode: requiredString(body, "user_code"),
|
|
94
|
+
verificationUri: validateVerificationUri(requiredString(body, "verification_uri")),
|
|
95
|
+
verificationUriComplete,
|
|
96
|
+
intervalSeconds,
|
|
97
|
+
expiresInSeconds: positiveNumber(body, "expires_in"),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function credentialsFromTokenResponse(body, previousRefreshToken) {
|
|
101
|
+
const access = requiredString(body, "access_token");
|
|
102
|
+
// xAI may omit refresh_token on refresh when the token is not rotated.
|
|
103
|
+
const refresh = body.refresh_token === undefined && previousRefreshToken
|
|
104
|
+
? previousRefreshToken
|
|
105
|
+
: requiredString(body, "refresh_token");
|
|
106
|
+
const expiresInSeconds = body.expires_in === undefined ? DEFAULT_TOKEN_LIFETIME_SECONDS : positiveNumber(body, "expires_in");
|
|
107
|
+
return {
|
|
108
|
+
type: "oauth",
|
|
109
|
+
access,
|
|
110
|
+
refresh,
|
|
111
|
+
expires: Date.now() + expiresInSeconds * 1000 - REFRESH_SKEW_MS,
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
async function requestDeviceCode(signal) {
|
|
115
|
+
const response = await postForm(XAI_DEVICE_CODE_URL, {
|
|
116
|
+
client_id: XAI_CLIENT_ID,
|
|
117
|
+
scope: XAI_SCOPE,
|
|
118
|
+
referrer: "pi",
|
|
119
|
+
}, signal);
|
|
120
|
+
if (!response.ok) {
|
|
121
|
+
throw requestFailure("device authorization", response);
|
|
122
|
+
}
|
|
123
|
+
return parseDeviceCode(response.body);
|
|
124
|
+
}
|
|
125
|
+
async function pollForTokens(device, signal) {
|
|
126
|
+
return pollOAuthDeviceCodeFlow({
|
|
127
|
+
intervalSeconds: device.intervalSeconds,
|
|
128
|
+
expiresInSeconds: device.expiresInSeconds,
|
|
129
|
+
waitBeforeFirstPoll: true,
|
|
130
|
+
signal,
|
|
131
|
+
poll: async () => {
|
|
132
|
+
const response = await postForm(XAI_TOKEN_URL, {
|
|
133
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
134
|
+
client_id: XAI_CLIENT_ID,
|
|
135
|
+
device_code: device.deviceCode,
|
|
136
|
+
}, signal);
|
|
137
|
+
if (response.ok) {
|
|
138
|
+
return { status: "complete", value: credentialsFromTokenResponse(response.body) };
|
|
139
|
+
}
|
|
140
|
+
const error = response.body.error;
|
|
141
|
+
if (error === "authorization_pending") {
|
|
142
|
+
return { status: "pending" };
|
|
143
|
+
}
|
|
144
|
+
if (error === "slow_down") {
|
|
145
|
+
const interval = response.body.interval;
|
|
146
|
+
return { status: "slow_down", intervalSeconds: typeof interval === "number" ? interval : undefined };
|
|
147
|
+
}
|
|
148
|
+
if (error === "access_denied" || error === "authorization_denied") {
|
|
149
|
+
return { status: "failed", message: "xAI device authorization was denied" };
|
|
150
|
+
}
|
|
151
|
+
if (error === "expired_token") {
|
|
152
|
+
return { status: "failed", message: "xAI device code expired" };
|
|
153
|
+
}
|
|
154
|
+
return { status: "failed", message: requestFailure("device token polling", response).message };
|
|
155
|
+
},
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
async function loginXai(interaction) {
|
|
159
|
+
const device = await requestDeviceCode(interaction.signal);
|
|
160
|
+
interaction.notify({
|
|
161
|
+
type: "device_code",
|
|
162
|
+
userCode: device.userCode,
|
|
163
|
+
verificationUri: device.verificationUriComplete ?? device.verificationUri,
|
|
164
|
+
intervalSeconds: device.intervalSeconds,
|
|
165
|
+
expiresInSeconds: device.expiresInSeconds,
|
|
166
|
+
});
|
|
167
|
+
return pollForTokens(device, interaction.signal);
|
|
168
|
+
}
|
|
169
|
+
async function refreshXaiToken(refreshToken, signal) {
|
|
170
|
+
const response = await postForm(XAI_TOKEN_URL, {
|
|
171
|
+
grant_type: "refresh_token",
|
|
172
|
+
client_id: XAI_CLIENT_ID,
|
|
173
|
+
refresh_token: refreshToken,
|
|
174
|
+
}, signal);
|
|
175
|
+
if (!response.ok) {
|
|
176
|
+
throw requestFailure("token refresh", response);
|
|
177
|
+
}
|
|
178
|
+
return credentialsFromTokenResponse(response.body, refreshToken);
|
|
179
|
+
}
|
|
180
|
+
export const xaiOAuth = {
|
|
181
|
+
name: "xAI (Grok/X subscription)",
|
|
182
|
+
loginLabel: "Sign in with SuperGrok or X Premium",
|
|
183
|
+
login: loginXai,
|
|
184
|
+
refresh: (credential, signal) => refreshXaiToken(credential.refresh, signal),
|
|
185
|
+
async toAuth(credential) {
|
|
186
|
+
return { apiKey: credential.access };
|
|
187
|
+
},
|
|
188
|
+
};
|
|
189
|
+
//# sourceMappingURL=xai.js.map
|