@bastani/pi-ai 0.9.45 → 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.
Files changed (93) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +4 -1
  3. package/dist/api/anthropic-messages.d.ts.map +1 -1
  4. package/dist/api/anthropic-messages.js +6 -12
  5. package/dist/api/anthropic-messages.js.map +1 -1
  6. package/dist/api/azure-openai-responses.d.ts.map +1 -1
  7. package/dist/api/azure-openai-responses.js +2 -0
  8. package/dist/api/azure-openai-responses.js.map +1 -1
  9. package/dist/api/bedrock-converse-stream.d.ts.map +1 -1
  10. package/dist/api/bedrock-converse-stream.js +84 -31
  11. package/dist/api/bedrock-converse-stream.js.map +1 -1
  12. package/dist/api/constrained-sampling.d.ts +4 -0
  13. package/dist/api/constrained-sampling.d.ts.map +1 -1
  14. package/dist/api/constrained-sampling.js +18 -0
  15. package/dist/api/constrained-sampling.js.map +1 -1
  16. package/dist/api/google-generative-ai.d.ts.map +1 -1
  17. package/dist/api/google-generative-ai.js +2 -0
  18. package/dist/api/google-generative-ai.js.map +1 -1
  19. package/dist/api/google-shared.d.ts.map +1 -1
  20. package/dist/api/google-shared.js +6 -1
  21. package/dist/api/google-shared.js.map +1 -1
  22. package/dist/api/google-vertex.d.ts.map +1 -1
  23. package/dist/api/google-vertex.js +2 -0
  24. package/dist/api/google-vertex.js.map +1 -1
  25. package/dist/api/mistral-conversations.d.ts.map +1 -1
  26. package/dist/api/mistral-conversations.js +6 -2
  27. package/dist/api/mistral-conversations.js.map +1 -1
  28. package/dist/api/openai-codex-responses.d.ts.map +1 -1
  29. package/dist/api/openai-codex-responses.js +3 -3
  30. package/dist/api/openai-codex-responses.js.map +1 -1
  31. package/dist/api/pi-messages.d.ts +2 -1
  32. package/dist/api/pi-messages.d.ts.map +1 -1
  33. package/dist/api/pi-messages.js +18 -2
  34. package/dist/api/pi-messages.js.map +1 -1
  35. package/dist/auth/helpers.d.ts +2 -1
  36. package/dist/auth/helpers.d.ts.map +1 -1
  37. package/dist/auth/helpers.js +1 -0
  38. package/dist/auth/helpers.js.map +1 -1
  39. package/dist/auth/oauth/github-copilot.d.ts.map +1 -1
  40. package/dist/auth/oauth/github-copilot.js +20 -18
  41. package/dist/auth/oauth/github-copilot.js.map +1 -1
  42. package/dist/auth/oauth/kimi-coding.d.ts.map +1 -1
  43. package/dist/auth/oauth/kimi-coding.js +4 -22
  44. package/dist/auth/oauth/kimi-coding.js.map +1 -1
  45. package/dist/auth/oauth/meta.d.ts.map +1 -1
  46. package/dist/auth/oauth/meta.js +1 -14
  47. package/dist/auth/oauth/meta.js.map +1 -1
  48. package/dist/auth/oauth/radius.d.ts.map +1 -1
  49. package/dist/auth/oauth/radius.js +9 -3
  50. package/dist/auth/oauth/radius.js.map +1 -1
  51. package/dist/auth/oauth/trusted-url.d.ts +7 -0
  52. package/dist/auth/oauth/trusted-url.d.ts.map +1 -0
  53. package/dist/auth/oauth/trusted-url.js +12 -0
  54. package/dist/auth/oauth/trusted-url.js.map +1 -0
  55. package/dist/auth/types.d.ts +6 -0
  56. package/dist/auth/types.d.ts.map +1 -1
  57. package/dist/auth/types.js.map +1 -1
  58. package/dist/cli.js +6 -2
  59. package/dist/cli.js.map +1 -1
  60. package/dist/models.d.ts.map +1 -1
  61. package/dist/models.js +26 -3
  62. package/dist/models.js.map +1 -1
  63. package/dist/providers/data/.manifest.json +1 -1
  64. package/dist/providers/data/amazon-bedrock.json +1 -1
  65. package/dist/providers/data/azure.json +1 -1
  66. package/dist/providers/data/github-copilot.json +1 -1
  67. package/dist/providers/data/huggingface.json +1 -1
  68. package/dist/providers/data/openai-codex.json +1 -1
  69. package/dist/providers/data/openai.json +1 -1
  70. package/dist/providers/data/opencode-go.json +1 -1
  71. package/dist/providers/data/opencode.json +1 -1
  72. package/dist/providers/data/openrouter.json +1 -1
  73. package/dist/providers/data/radius.json +1 -1
  74. package/dist/providers/data/vercel-ai-gateway.json +1 -1
  75. package/dist/providers/github-copilot.d.ts.map +1 -1
  76. package/dist/providers/github-copilot.js +13 -1
  77. package/dist/providers/github-copilot.js.map +1 -1
  78. package/dist/providers/openai-mid-convo-effort.d.ts.map +1 -1
  79. package/dist/providers/openai-mid-convo-effort.js +1 -0
  80. package/dist/providers/openai-mid-convo-effort.js.map +1 -1
  81. package/dist/utils/provider-retry.d.ts.map +1 -1
  82. package/dist/utils/provider-retry.js +5 -4
  83. package/dist/utils/provider-retry.js.map +1 -1
  84. package/dist/utils/retry-hints.d.ts +6 -3
  85. package/dist/utils/retry-hints.d.ts.map +1 -1
  86. package/dist/utils/retry-hints.js +98 -18
  87. package/dist/utils/retry-hints.js.map +1 -1
  88. package/dist/utils/retry.js +2 -2
  89. package/dist/utils/retry.js.map +1 -1
  90. package/dist/utils/version.d.ts +1 -1
  91. package/dist/utils/version.js +1 -1
  92. package/dist/utils/version.js.map +1 -1
  93. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"kimi-coding.js","sourceRoot":"","sources":["../../../src/auth/oauth/kimi-coding.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EACN,sBAAsB,EACtB,2BAA2B,EAC3B,yBAAyB,EAEzB,mBAAmB,EACnB,yBAAyB,GACzB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,MAAM,SAAS,GAAG,sCAAsC,CAAC;AACzD,MAAM,kBAAkB,GAAG,uBAAuB,CAAC;AACnD,MAAM,2BAA2B,GAAG,EAAE,GAAG,EAAE,CAAC;AAC5C,MAAM,6BAA6B,GAAG,CAAC,CAAC;AACxC,0GAA0G;AAC1G,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAAC;AACrC,4FAA4F;AAC5F,MAAM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,MAAM,CAAC,gBAAgB;KACzC,CAAC,CAAC;IACH,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IACxE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;AAChG,CAAC;AAED,MAAM,CAAC,MAAM,eAAe,GAAc;IACzC,IAAI,EAAE,0BAA0B;IAChC,cAAc,EAAE,IAAI;IACpB,UAAU,EAAE,wBAAwB;IAEpC,KAAK,EAAE,eAAe;IAEtB,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,YAAY,EAAE,EAAE,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC7E,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;IAChG,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,OAAO,EAAE,EAAE,aAAa,EAAE,UAAU,UAAU,CAAC,MAAM,EAAE,EAAE,EAAE,CAAC;IACtE,CAAC;CACD,CAAC","sourcesContent":["/**\n * Kimi Code (subscription) OAuth flow\n *\n * RFC 8628 device authorization grant against https://auth.kimi.com with JSON\n * responses. The access token authenticates requests to\n * https://api.kimi.com/coding/v1 as an `Authorization: Bearer` header.\n */\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport { sleep } from \"../../utils/sleep.ts\";\nimport {\n\tformatOAuthErrorDetail,\n\tisPermanentRefreshRejection,\n\tOAuthRefreshRejectedError,\n\ttype OAuthRefreshRejection,\n\tparseOAuthErrorBody,\n\trequestNeverReachedServer,\n} from \"../oauth-refresh-errors.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\n\nconst CLIENT_ID = \"17e5f671-d194-4dfb-9706-5516cb48c098\";\nconst DEFAULT_OAUTH_HOST = \"https://auth.kimi.com\";\nconst DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60;\nconst DEFAULT_POLL_INTERVAL_SECONDS = 5;\n/** Login requests (device authorization and polling) give up after this; a refresh request never does. */\nconst REQUEST_TIMEOUT_MS = 30 * 1000;\n/** Retries of a refresh request that never reached the server, after 1 s, 2 s, then 4 s. */\nconst REFRESH_MAX_RETRIES = 3;\nconst REFRESH_RETRY_BASE_DELAY_MS = 1000;\n\ntype DeviceAuthorization = {\n\tdeviceCode: string;\n\tuserCode: string;\n\tverificationUri: string;\n\tverificationUriComplete: string;\n\tintervalSeconds: number;\n\texpiresInSeconds: number;\n};\n\ntype TokenResponse = {\n\taccess: string;\n\trefresh: string;\n\texpires: number;\n};\n\nfunction getOauthHost(): string {\n\tconst override = getProviderEnvValue(\"KIMI_CODE_OAUTH_HOST\") || getProviderEnvValue(\"KIMI_OAUTH_HOST\");\n\treturn (override || DEFAULT_OAUTH_HOST).replace(/\\/+$/, \"\");\n}\n\nfunction requestSignal(signal: AbortSignal): AbortSignal {\n\treturn AbortSignal.any([AbortSignal.timeout(REQUEST_TIMEOUT_MS), signal]);\n}\n\nfunction formUrlEncode(fields: Record<string, string>): string {\n\treturn new URLSearchParams(fields).toString();\n}\n\nasync function readJson(response: Response): Promise<Record<string, unknown> | null> {\n\ttry {\n\t\tconst json = await response.json();\n\t\treturn json && typeof json === \"object\" ? (json as Record<string, unknown>) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\n/** The verification URI is opened in the user's browser; only http(s) URLs are trusted. */\nfunction trustedHttpUrl(value: unknown): string | null {\n\tif (typeof value !== \"string\" || !value) return null;\n\ttry {\n\t\tconst url = new URL(value);\n\t\tif (url.protocol !== \"https:\" && url.protocol !== \"http:\") return null;\n\t\treturn url.href;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function startDeviceAuthorization(oauthHost: string, signal: AbortSignal): Promise<DeviceAuthorization> {\n\tconst response = await fetch(`${oauthHost}/api/oauth/device_authorization`, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\tAccept: \"application/json\",\n\t\t},\n\t\tbody: formUrlEncode({ client_id: CLIENT_ID }),\n\t\tsignal: requestSignal(signal),\n\t});\n\n\tif (!response.ok) {\n\t\tconst text = await response.text().catch(() => \"\");\n\t\tthrow new Error(`Kimi Code device authorization failed with status ${response.status}${text ? `: ${text}` : \"\"}`);\n\t}\n\n\tconst json = await readJson(response);\n\tconst deviceCode = json?.device_code;\n\tconst userCode = json?.user_code;\n\tconst verificationUri = json?.verification_uri;\n\tconst verificationUriComplete = json?.verification_uri_complete;\n\tif (\n\t\ttypeof deviceCode !== \"string\" ||\n\t\ttypeof userCode !== \"string\" ||\n\t\ttypeof verificationUri !== \"string\" ||\n\t\ttypeof verificationUriComplete !== \"string\" ||\n\t\t!trustedHttpUrl(verificationUriComplete) ||\n\t\t!trustedHttpUrl(verificationUri)\n\t) {\n\t\tthrow new Error(`Invalid Kimi Code device authorization response: ${JSON.stringify(json)}`);\n\t}\n\n\tconst interval = json?.interval;\n\tconst expiresIn = json?.expires_in;\n\treturn {\n\t\tdeviceCode,\n\t\tuserCode,\n\t\tverificationUri,\n\t\tverificationUriComplete,\n\t\tintervalSeconds:\n\t\t\ttypeof interval === \"number\" && Number.isFinite(interval) && interval > 0\n\t\t\t\t? interval\n\t\t\t\t: DEFAULT_POLL_INTERVAL_SECONDS,\n\t\texpiresInSeconds:\n\t\t\ttypeof expiresIn === \"number\" && Number.isFinite(expiresIn) && expiresIn > 0\n\t\t\t\t? expiresIn\n\t\t\t\t: DEVICE_CODE_TIMEOUT_SECONDS,\n\t};\n}\n\nfunction parseTokenResponse(json: Record<string, unknown> | null, operation: string): TokenResponse {\n\tconst accessToken = json?.access_token;\n\tconst refreshToken = json?.refresh_token;\n\tconst expiresIn = json?.expires_in;\n\tif (\n\t\ttypeof accessToken !== \"string\" ||\n\t\t!accessToken ||\n\t\ttypeof refreshToken !== \"string\" ||\n\t\t!refreshToken ||\n\t\ttypeof expiresIn !== \"number\" ||\n\t\t!Number.isFinite(expiresIn) ||\n\t\texpiresIn <= 0\n\t) {\n\t\tthrow new Error(`Kimi Code token ${operation} response missing fields: ${JSON.stringify(json)}`);\n\t}\n\treturn {\n\t\taccess: accessToken,\n\t\trefresh: refreshToken,\n\t\texpires: Date.now() + expiresIn * 1000,\n\t};\n}\n\nasync function pollForToken(\n\toauthHost: string,\n\tdevice: DeviceAuthorization,\n\tsignal: AbortSignal,\n): Promise<TokenResponse> {\n\treturn pollOAuthDeviceCodeFlow<TokenResponse>({\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 fetch(`${oauthHost}/api/oauth/token`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: formUrlEncode({\n\t\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\t\tdevice_code: device.deviceCode,\n\t\t\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\t\t}),\n\t\t\t\tsignal: requestSignal(signal),\n\t\t\t});\n\n\t\t\tif (response.status >= 500) {\n\t\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\tmessage: `Kimi Code device token request failed with status ${response.status}${text ? `: ${text}` : \"\"}`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst json = await readJson(response);\n\t\t\tif (response.ok && typeof json?.access_token === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\treturn { status: \"complete\", value: parseTokenResponse(json, \"poll\") };\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn { status: \"failed\", message: error instanceof Error ? error.message : String(error) };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst error = json?.error;\n\t\t\tconst description = typeof json?.error_description === \"string\" ? `: ${json.error_description}` : \"\";\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 = json?.interval;\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"slow_down\",\n\t\t\t\t\tintervalSeconds: typeof interval === \"number\" && interval > 0 ? interval : undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (error === \"expired_token\") {\n\t\t\t\treturn { status: \"failed\", message: \"Kimi Code device authorization expired. Please restart login.\" };\n\t\t\t}\n\t\t\tif (error === \"access_denied\") {\n\t\t\t\treturn { status: \"failed\", message: \"Kimi Code login was denied.\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage: `Kimi Code device token request failed (status ${response.status})${typeof error === \"string\" ? `: ${error}${description}` : \"\"}`,\n\t\t\t};\n\t\t},\n\t});\n}\n\n/** Kimi treats 401 and 403 from its token endpoint as a dead login, along with the usual permanent codes. */\nfunction isUnauthorizedRefresh(rejection: OAuthRefreshRejection): boolean {\n\treturn rejection.status === 401 || rejection.status === 403 || isPermanentRefreshRejection(rejection);\n}\n\nasync function refreshToken(oauthHost: string, refreshTokenValue: string, signal: AbortSignal): Promise<TokenResponse> {\n\tfor (let attempt = 0; ; attempt++) {\n\t\tif (attempt > 0) {\n\t\t\tawait sleep(REFRESH_RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), signal);\n\t\t}\n\t\tif (signal.aborted) {\n\t\t\tthrow new Error(\"Kimi Code token refresh aborted\");\n\t\t}\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\t// No timeout of its own: once sent, the server may already have rotated the refresh token, and only\n\t\t\t// this response carries the replacement.\n\t\t\tresponse = await fetch(`${oauthHost}/api/oauth/token`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: formUrlEncode({\n\t\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\t\trefresh_token: refreshTokenValue,\n\t\t\t\t}),\n\t\t\t\tsignal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(String(error));\n\t\t\t// Presenting the same refresh token again is safe only if this attempt provably never reached the server.\n\t\t\tif (attempt < REFRESH_MAX_RETRIES && !signal.aborted && requestNeverReachedServer(failure)) continue;\n\t\t\tthrow failure;\n\t\t}\n\n\t\tif (response.ok) {\n\t\t\treturn parseTokenResponse(await readJson(response), \"refresh\");\n\t\t}\n\n\t\t// Any answer, a 429 or 5xx included, means the request was delivered and may have rotated the token, so it\n\t\t// is never retried with the same one.\n\t\tconst rejection = { status: response.status, ...parseOAuthErrorBody(await response.text().catch(() => \"\")) };\n\t\tif (isUnauthorizedRefresh(rejection)) {\n\t\t\tthrow new OAuthRefreshRejectedError(\n\t\t\t\t`Kimi Code token refresh unauthorized (status ${response.status})`,\n\t\t\t\trejection,\n\t\t\t\t[refreshTokenValue],\n\t\t\t);\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Kimi Code token refresh failed with status ${response.status}${formatOAuthErrorDetail(rejection, [refreshTokenValue])}`,\n\t\t);\n\t}\n}\n\nasync function loginKimiCoding(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst oauthHost = getOauthHost();\n\tconst device = await startDeviceAuthorization(oauthHost, interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.userCode,\n\t\tverificationUri: device.verificationUriComplete,\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: device.expiresInSeconds,\n\t});\n\tconst token = await pollForToken(oauthHost, device, interaction.signal);\n\treturn { type: \"oauth\", access: token.access, refresh: token.refresh, expires: token.expires };\n}\n\nexport const kimiCodingOAuth: OAuthAuth = {\n\tname: \"Kimi Code (subscription)\",\n\tisSubscription: true,\n\tloginLabel: \"Sign in with Kimi Code\",\n\n\tlogin: loginKimiCoding,\n\n\trefresh: async (credential, signal) => {\n\t\tconst token = await refreshToken(getOauthHost(), credential.refresh, signal);\n\t\treturn { type: \"oauth\", access: token.access, refresh: token.refresh, expires: token.expires };\n\t},\n\n\tasync toAuth(credential) {\n\t\treturn { headers: { Authorization: `Bearer ${credential.access}` } };\n\t},\n};\n"]}
1
+ {"version":3,"file":"kimi-coding.js","sourceRoot":"","sources":["../../../src/auth/oauth/kimi-coding.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAC7C,OAAO,EACN,sBAAsB,EACtB,2BAA2B,EAC3B,yBAAyB,EAEzB,mBAAmB,EACnB,yBAAyB,GACzB,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,MAAM,SAAS,GAAG,sCAAsC,CAAC;AACzD,MAAM,kBAAkB,GAAG,uBAAuB,CAAC;AACnD,MAAM,2BAA2B,GAAG,EAAE,GAAG,EAAE,CAAC;AAC5C,MAAM,6BAA6B,GAAG,CAAC,CAAC;AACxC,0GAA0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wBAAwB;IAEpC,KAAK,EAAE,eAAe;IAEtB,OAAO,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,KAAK,GAAG,MAAM,YAAY,CAAC,YAAY,EAAE,EAAE,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC,CAAC;QAC7E,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;IAChG,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,OAAO,EAAE,EAAE,aAAa,EAAE,UAAU,UAAU,CAAC,MAAM,EAAE,EAAE,EAAE,CAAC;IACtE,CAAC;CACD,CAAC","sourcesContent":["/**\n * Kimi Code (subscription) OAuth flow\n *\n * RFC 8628 device authorization grant against https://auth.kimi.com with JSON\n * responses. The access token authenticates requests to\n * https://api.kimi.com/coding/v1 as an `Authorization: Bearer` header.\n */\n\nimport { getProviderEnvValue } from \"../../utils/provider-env.ts\";\nimport { sleep } from \"../../utils/sleep.ts\";\nimport {\n\tformatOAuthErrorDetail,\n\tisPermanentRefreshRejection,\n\tOAuthRefreshRejectedError,\n\ttype OAuthRefreshRejection,\n\tparseOAuthErrorBody,\n\trequestNeverReachedServer,\n} from \"../oauth-refresh-errors.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { trustedHttpUrl } from \"./trusted-url.ts\";\n\nconst CLIENT_ID = \"17e5f671-d194-4dfb-9706-5516cb48c098\";\nconst DEFAULT_OAUTH_HOST = \"https://auth.kimi.com\";\nconst DEVICE_CODE_TIMEOUT_SECONDS = 15 * 60;\nconst DEFAULT_POLL_INTERVAL_SECONDS = 5;\n/** Login requests (device authorization and polling) give up after this; a refresh request never does. */\nconst REQUEST_TIMEOUT_MS = 30 * 1000;\n/** Retries of a refresh request that never reached the server, after 1 s, 2 s, then 4 s. */\nconst REFRESH_MAX_RETRIES = 3;\nconst REFRESH_RETRY_BASE_DELAY_MS = 1000;\n\ntype DeviceAuthorization = {\n\tdeviceCode: string;\n\tuserCode: string;\n\tverificationUri: string;\n\tverificationUriComplete: string;\n\tintervalSeconds: number;\n\texpiresInSeconds: number;\n};\n\ntype TokenResponse = {\n\taccess: string;\n\trefresh: string;\n\texpires: number;\n};\n\nfunction getOauthHost(): string {\n\tconst override = getProviderEnvValue(\"KIMI_CODE_OAUTH_HOST\") || getProviderEnvValue(\"KIMI_OAUTH_HOST\");\n\treturn (override || DEFAULT_OAUTH_HOST).replace(/\\/+$/, \"\");\n}\n\nfunction requestSignal(signal: AbortSignal): AbortSignal {\n\treturn AbortSignal.any([AbortSignal.timeout(REQUEST_TIMEOUT_MS), signal]);\n}\n\nfunction formUrlEncode(fields: Record<string, string>): string {\n\treturn new URLSearchParams(fields).toString();\n}\n\nasync function readJson(response: Response): Promise<Record<string, unknown> | null> {\n\ttry {\n\t\tconst json = await response.json();\n\t\treturn json && typeof json === \"object\" ? (json as Record<string, unknown>) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nasync function startDeviceAuthorization(oauthHost: string, signal: AbortSignal): Promise<DeviceAuthorization> {\n\tconst response = await fetch(`${oauthHost}/api/oauth/device_authorization`, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\tAccept: \"application/json\",\n\t\t},\n\t\tbody: formUrlEncode({ client_id: CLIENT_ID }),\n\t\tsignal: requestSignal(signal),\n\t});\n\n\tif (!response.ok) {\n\t\tconst text = await response.text().catch(() => \"\");\n\t\tthrow new Error(`Kimi Code device authorization failed with status ${response.status}${text ? `: ${text}` : \"\"}`);\n\t}\n\n\tconst json = await readJson(response);\n\tconst deviceCode = json?.device_code;\n\tconst userCode = json?.user_code;\n\tconst verificationUri = trustedHttpUrl(json?.verification_uri);\n\tconst verificationUriComplete = trustedHttpUrl(json?.verification_uri_complete);\n\tif (typeof deviceCode !== \"string\" || typeof userCode !== \"string\" || !verificationUri || !verificationUriComplete) {\n\t\tthrow new Error(`Invalid Kimi Code device authorization response: ${JSON.stringify(json)}`);\n\t}\n\n\tconst interval = json?.interval;\n\tconst expiresIn = json?.expires_in;\n\treturn {\n\t\tdeviceCode,\n\t\tuserCode,\n\t\tverificationUri,\n\t\tverificationUriComplete,\n\t\tintervalSeconds:\n\t\t\ttypeof interval === \"number\" && Number.isFinite(interval) && interval > 0\n\t\t\t\t? interval\n\t\t\t\t: DEFAULT_POLL_INTERVAL_SECONDS,\n\t\texpiresInSeconds:\n\t\t\ttypeof expiresIn === \"number\" && Number.isFinite(expiresIn) && expiresIn > 0\n\t\t\t\t? expiresIn\n\t\t\t\t: DEVICE_CODE_TIMEOUT_SECONDS,\n\t};\n}\n\nfunction parseTokenResponse(json: Record<string, unknown> | null, operation: string): TokenResponse {\n\tconst accessToken = json?.access_token;\n\tconst refreshToken = json?.refresh_token;\n\tconst expiresIn = json?.expires_in;\n\tif (\n\t\ttypeof accessToken !== \"string\" ||\n\t\t!accessToken ||\n\t\ttypeof refreshToken !== \"string\" ||\n\t\t!refreshToken ||\n\t\ttypeof expiresIn !== \"number\" ||\n\t\t!Number.isFinite(expiresIn) ||\n\t\texpiresIn <= 0\n\t) {\n\t\tthrow new Error(`Kimi Code token ${operation} response missing fields: ${JSON.stringify(json)}`);\n\t}\n\treturn {\n\t\taccess: accessToken,\n\t\trefresh: refreshToken,\n\t\texpires: Date.now() + expiresIn * 1000,\n\t};\n}\n\nasync function pollForToken(\n\toauthHost: string,\n\tdevice: DeviceAuthorization,\n\tsignal: AbortSignal,\n): Promise<TokenResponse> {\n\treturn pollOAuthDeviceCodeFlow<TokenResponse>({\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 fetch(`${oauthHost}/api/oauth/token`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: formUrlEncode({\n\t\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\t\tdevice_code: device.deviceCode,\n\t\t\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\t\t}),\n\t\t\t\tsignal: requestSignal(signal),\n\t\t\t});\n\n\t\t\tif (response.status >= 500) {\n\t\t\t\tconst text = await response.text().catch(() => \"\");\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\tmessage: `Kimi Code device token request failed with status ${response.status}${text ? `: ${text}` : \"\"}`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tconst json = await readJson(response);\n\t\t\tif (response.ok && typeof json?.access_token === \"string\") {\n\t\t\t\ttry {\n\t\t\t\t\treturn { status: \"complete\", value: parseTokenResponse(json, \"poll\") };\n\t\t\t\t} catch (error) {\n\t\t\t\t\treturn { status: \"failed\", message: error instanceof Error ? error.message : String(error) };\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst error = json?.error;\n\t\t\tconst description = typeof json?.error_description === \"string\" ? `: ${json.error_description}` : \"\";\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 = json?.interval;\n\t\t\t\treturn {\n\t\t\t\t\tstatus: \"slow_down\",\n\t\t\t\t\tintervalSeconds: typeof interval === \"number\" && interval > 0 ? interval : undefined,\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (error === \"expired_token\") {\n\t\t\t\treturn { status: \"failed\", message: \"Kimi Code device authorization expired. Please restart login.\" };\n\t\t\t}\n\t\t\tif (error === \"access_denied\") {\n\t\t\t\treturn { status: \"failed\", message: \"Kimi Code login was denied.\" };\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tmessage: `Kimi Code device token request failed (status ${response.status})${typeof error === \"string\" ? `: ${error}${description}` : \"\"}`,\n\t\t\t};\n\t\t},\n\t});\n}\n\n/** Kimi treats 401 and 403 from its token endpoint as a dead login, along with the usual permanent codes. */\nfunction isUnauthorizedRefresh(rejection: OAuthRefreshRejection): boolean {\n\treturn rejection.status === 401 || rejection.status === 403 || isPermanentRefreshRejection(rejection);\n}\n\nasync function refreshToken(oauthHost: string, refreshTokenValue: string, signal: AbortSignal): Promise<TokenResponse> {\n\tfor (let attempt = 0; ; attempt++) {\n\t\tif (attempt > 0) {\n\t\t\tawait sleep(REFRESH_RETRY_BASE_DELAY_MS * 2 ** (attempt - 1), signal);\n\t\t}\n\t\tif (signal.aborted) {\n\t\t\tthrow new Error(\"Kimi Code token refresh aborted\");\n\t\t}\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\t// No timeout of its own: once sent, the server may already have rotated the refresh token, and only\n\t\t\t// this response carries the replacement.\n\t\t\tresponse = await fetch(`${oauthHost}/api/oauth/token`, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: formUrlEncode({\n\t\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\t\trefresh_token: refreshTokenValue,\n\t\t\t\t}),\n\t\t\t\tsignal,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tconst failure = error instanceof Error ? error : new Error(String(error));\n\t\t\t// Presenting the same refresh token again is safe only if this attempt provably never reached the server.\n\t\t\tif (attempt < REFRESH_MAX_RETRIES && !signal.aborted && requestNeverReachedServer(failure)) continue;\n\t\t\tthrow failure;\n\t\t}\n\n\t\tif (response.ok) {\n\t\t\treturn parseTokenResponse(await readJson(response), \"refresh\");\n\t\t}\n\n\t\t// Any answer, a 429 or 5xx included, means the request was delivered and may have rotated the token, so it\n\t\t// is never retried with the same one.\n\t\tconst rejection = { status: response.status, ...parseOAuthErrorBody(await response.text().catch(() => \"\")) };\n\t\tif (isUnauthorizedRefresh(rejection)) {\n\t\t\tthrow new OAuthRefreshRejectedError(\n\t\t\t\t`Kimi Code token refresh unauthorized (status ${response.status})`,\n\t\t\t\trejection,\n\t\t\t\t[refreshTokenValue],\n\t\t\t);\n\t\t}\n\t\tthrow new Error(\n\t\t\t`Kimi Code token refresh failed with status ${response.status}${formatOAuthErrorDetail(rejection, [refreshTokenValue])}`,\n\t\t);\n\t}\n}\n\nasync function loginKimiCoding(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst oauthHost = getOauthHost();\n\tconst device = await startDeviceAuthorization(oauthHost, interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.userCode,\n\t\tverificationUri: device.verificationUriComplete,\n\t\tintervalSeconds: device.intervalSeconds,\n\t\texpiresInSeconds: device.expiresInSeconds,\n\t});\n\tconst token = await pollForToken(oauthHost, device, interaction.signal);\n\treturn { type: \"oauth\", access: token.access, refresh: token.refresh, expires: token.expires };\n}\n\nexport const kimiCodingOAuth: OAuthAuth = {\n\tname: \"Kimi Code (subscription)\",\n\tisSubscription: true,\n\tloginLabel: \"Sign in with Kimi Code\",\n\n\tlogin: loginKimiCoding,\n\n\trefresh: async (credential, signal) => {\n\t\tconst token = await refreshToken(getOauthHost(), credential.refresh, signal);\n\t\treturn { type: \"oauth\", access: token.access, refresh: token.refresh, expires: token.expires };\n\t},\n\n\tasync toAuth(credential) {\n\t\treturn { headers: { Authorization: `Bearer ${credential.access}` } };\n\t},\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"meta.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/meta.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AA0LvF,eAAO,MAAM,SAAS,EAAE,SAYvB,CAAC"}
1
+ {"version":3,"file":"meta.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/meta.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAGH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AA+KvF,eAAO,MAAM,SAAS,EAAE,SAYvB,CAAC"}
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { OAuthRefreshRejectedError } from "../oauth-refresh-errors.js";
16
16
  import { pollOAuthDeviceCodeFlow } from "./device-code.js";
17
+ import { trustedHttpUrl } from "./trusted-url.js";
17
18
  // Muse Code CLI client id.
18
19
  const CLIENT_ID = "1031625952748946";
19
20
  const AUTH_HOST = "https://auth.meta.com";
@@ -42,20 +43,6 @@ function errorDetail(json) {
42
43
  }
43
44
  return "";
44
45
  }
45
- /** The verification URI is opened in the user's browser; only http(s) URLs are trusted. */
46
- function trustedHttpUrl(value) {
47
- if (typeof value !== "string" || !value)
48
- return null;
49
- try {
50
- const url = new URL(value);
51
- if (url.protocol !== "https:" && url.protocol !== "http:")
52
- return null;
53
- return url.href;
54
- }
55
- catch {
56
- return null;
57
- }
58
- }
59
46
  function positiveNumber(value) {
60
47
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
61
48
  }
@@ -1 +1 @@
1
- {"version":3,"file":"meta.js","sourceRoot":"","sources":["../../../src/auth/oauth/meta.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAEvE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAE3D,2BAA2B;AAC3B,MAAM,SAAS,GAAG,kBAAkB,CAAC;AACrC,MAAM,SAAS,GA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C;CACD,CAAC","sourcesContent":["/**\n * Meta Model API OAuth flow\n *\n * RFC 8628 device authorization grant against https://auth.meta.com (JSON\n * responses). Meta splits identity from API access: the resulting identity\n * token is not accepted for inference, so it is exchanged for a Model API\n * key via the Muse Code key-mint endpoint (minted keys live about a day).\n * The identity token is stored as `refresh` and the minted key as `access`,\n * so the standard OAuth scheduler re-mints the key when it expires with no\n * bespoke renewal machinery. The identity token itself is not renewable\n * (auth.meta.com answers grant_type=refresh_token with 404 and issues no\n * refresh_token), so a 401/403 from mint means the session is dead and the\n * user must sign in again.\n */\n\nimport { OAuthRefreshRejectedError } from \"../oauth-refresh-errors.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\n\n// Muse Code CLI client id.\nconst CLIENT_ID = \"1031625952748946\";\nconst AUTH_HOST = \"https://auth.meta.com\";\nconst DEVICE_AUTHORIZATION_URL = `${AUTH_HOST}/oidc/device/authorization/`;\nconst DEVICE_TOKEN_URL = `${AUTH_HOST}/oidc/device/token/`;\nconst API_KEY_MINT_URL = \"https://api.meta.ai/muse-code/key\";\nconst API_KEY_LIFETIME_MS = 24 * 60 * 60 * 1000;\nconst REQUEST_TIMEOUT_MS = 30 * 1000;\n\ntype DeviceAuthorization = {\n\tdeviceCode: string;\n\tuserCode: string;\n\tverificationUri: string;\n\tintervalSeconds?: number;\n\texpiresInSeconds?: number;\n};\n\nfunction requestSignal(signal: AbortSignal): AbortSignal {\n\treturn AbortSignal.any([AbortSignal.timeout(REQUEST_TIMEOUT_MS), signal]);\n}\n\nasync function readJson(response: Response): Promise<Record<string, unknown> | null> {\n\ttry {\n\t\tconst json = await response.json();\n\t\treturn json && typeof json === \"object\" ? (json as Record<string, unknown>) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction errorDetail(json: Record<string, unknown> | null): string {\n\tfor (const key of [\"error_description\", \"detail\", \"message\", \"error\"]) {\n\t\tconst value = json?.[key];\n\t\tif (typeof value === \"string\" && value.trim()) return `: ${value.trim()}`;\n\t}\n\treturn \"\";\n}\n\n/** The verification URI is opened in the user's browser; only http(s) URLs are trusted. */\nfunction trustedHttpUrl(value: unknown): string | null {\n\tif (typeof value !== \"string\" || !value) return null;\n\ttry {\n\t\tconst url = new URL(value);\n\t\tif (url.protocol !== \"https:\" && url.protocol !== \"http:\") return null;\n\t\treturn url.href;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction positiveNumber(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\nasync function startDeviceAuthorization(signal: AbortSignal): Promise<DeviceAuthorization> {\n\tconst response = await fetch(DEVICE_AUTHORIZATION_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\tAccept: \"application/json\",\n\t\t},\n\t\tbody: new URLSearchParams({ client_id: CLIENT_ID }).toString(),\n\t\tsignal: requestSignal(signal),\n\t});\n\tconst json = await readJson(response);\n\tif (!response.ok) {\n\t\tthrow new Error(`Meta device authorization failed with status ${response.status}${errorDetail(json)}`);\n\t}\n\tconst deviceCode = json?.device_code;\n\tconst userCode = json?.user_code;\n\tconst verificationUri = trustedHttpUrl(json?.verification_uri_complete) ?? trustedHttpUrl(json?.verification_uri);\n\tif (typeof deviceCode !== \"string\" || !deviceCode || typeof userCode !== \"string\" || !userCode || !verificationUri) {\n\t\tthrow new Error(`Invalid Meta device authorization response: ${JSON.stringify(json)}`);\n\t}\n\treturn {\n\t\tdeviceCode,\n\t\tuserCode,\n\t\tverificationUri,\n\t\tintervalSeconds: positiveNumber(json?.interval),\n\t\texpiresInSeconds: positiveNumber(json?.expires_in),\n\t};\n}\n\nasync function pollForIdentityToken(device: DeviceAuthorization, signal: AbortSignal): Promise<string> {\n\treturn pollOAuthDeviceCodeFlow<string>({\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 fetch(DEVICE_TOKEN_URL, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: new URLSearchParams({\n\t\t\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\t\t\tdevice_code: device.deviceCode,\n\t\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\t}).toString(),\n\t\t\t\tsignal: requestSignal(signal),\n\t\t\t});\n\t\t\tconst json = await readJson(response);\n\t\t\tif (response.ok && typeof json?.access_token === \"string\" && json.access_token) {\n\t\t\t\treturn { status: \"complete\", value: json.access_token };\n\t\t\t}\n\t\t\tswitch (json?.error) {\n\t\t\t\tcase \"authorization_pending\":\n\t\t\t\t\treturn { status: \"pending\" };\n\t\t\t\tcase \"slow_down\":\n\t\t\t\t\treturn { status: \"slow_down\", intervalSeconds: positiveNumber(json?.interval) };\n\t\t\t\tcase \"access_denied\":\n\t\t\t\t\treturn { status: \"failed\", message: \"Meta login was denied.\" };\n\t\t\t\tcase \"expired_token\":\n\t\t\t\t\treturn { status: \"failed\", message: \"Meta device authorization expired. Please restart login.\" };\n\t\t\t\tdefault:\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\tmessage: `Meta device token request failed with status ${response.status}${errorDetail(json)}`,\n\t\t\t\t\t};\n\t\t\t}\n\t\t},\n\t});\n}\n\n/** Exchange an identity token for a Model API key. Keys are valid for about a day. */\nasync function mintApiKey(identityToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\tconst response = await fetch(API_KEY_MINT_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\tAuthorization: `Bearer ${identityToken}`,\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"x-api-version\": \"1.0.0\",\n\t\t},\n\t\tbody: \"{}\",\n\t\tsignal: requestSignal(signal),\n\t});\n\tconst json = await readJson(response);\n\tif (response.status === 401 || response.status === 403) {\n\t\t// Identity token is not renewable (see file header); only a fresh device flow helps, which the refresh\n\t\t// caller tells the user to start with /login for the provider they use.\n\t\tconst description = [\"error_description\", \"detail\", \"message\"]\n\t\t\t.map((key) => json?.[key])\n\t\t\t.find((value): value is string => typeof value === \"string\" && value.trim().length > 0);\n\t\tthrow new OAuthRefreshRejectedError(\n\t\t\t`Meta session expired (status ${response.status})`,\n\t\t\t{ status: response.status, code: typeof json?.error === \"string\" ? json.error : undefined, description },\n\t\t\t[identityToken],\n\t\t);\n\t}\n\tif (!response.ok) {\n\t\tthrow new Error(`Meta API key mint failed with status ${response.status}${errorDetail(json)}`);\n\t}\n\tconst apiKey = json?.api_key;\n\tif (typeof apiKey !== \"string\" || !apiKey) {\n\t\tconst actionUrl = trustedHttpUrl(json?.action_url);\n\t\tthrow new Error(`Meta did not issue an API key.${actionUrl ? ` Complete setup at ${actionUrl}` : \"\"}`);\n\t}\n\treturn { type: \"oauth\", refresh: identityToken, access: apiKey, expires: Date.now() + API_KEY_LIFETIME_MS };\n}\n\nasync function loginMeta(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\ttry {\n\t\tconst device = await startDeviceAuthorization(interaction.signal);\n\t\tinteraction.notify({\n\t\t\ttype: \"device_code\",\n\t\t\tuserCode: device.userCode,\n\t\t\tverificationUri: device.verificationUri,\n\t\t\tintervalSeconds: device.intervalSeconds,\n\t\t\texpiresInSeconds: device.expiresInSeconds,\n\t\t});\n\t\tconst identityToken = await pollForIdentityToken(device, interaction.signal);\n\t\tinteraction.notify({ type: \"progress\", message: \"Enabling Meta Model API access...\" });\n\t\treturn await mintApiKey(identityToken, interaction.signal);\n\t} catch (e) {\n\t\t// An in-flight fetch rejects with a DOMException on abort; the login UI matches on this message.\n\t\tif (interaction.signal.aborted) throw new Error(\"Login cancelled\");\n\t\tthrow e;\n\t}\n}\n\nexport const metaOAuth: OAuthAuth = {\n\tname: \"Meta (Muse subscription)\",\n\tisSubscription: true,\n\tloginLabel: \"Sign in with Meta\",\n\n\tlogin: loginMeta,\n\n\trefresh: (credential, signal) => mintApiKey(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
1
+ {"version":3,"file":"meta.js","sourceRoot":"","sources":["../../../src/auth/oauth/meta.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAEvE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,2BAA2B;AAC3B,MAAM,SAAS,GAAG,kBAAkB,CAAC;AACrC,MAAM,SAAS,GAAG,uBAAuB,CAAC;AAC1C,MAAM,wBAAwB,GAAG,GAAG,SAAS,6BAA6B,CAAC;AAC3E,MAAM,gBAAgB,GAAG,GAAG,SAAS,qBAAqB,CAAC;AAC3D,MAAM,gBAAgB,GAAG,mCAAmC,CAAC;AAC7D,MAAM,mBAAmB,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAChD,MAAM,kBAAkB,GAAG,EAAE,GAAG,IAAI,CAAC;AAUrC,SAAS,aAAa,CAAC,MAAmB;IACzC,OAAO,WAAW,CAAC,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,kBAAkB,CAAC,EAAE,MAAM,CAAC,CAAC,CAAC;AAC3E,CAAC;AAED,KAAK,UAAU,QAAQ,CAAC,QAAkB;IACzC,IAAI,CAAC;QACJ,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,OAAO,IAAI,IAAI,OAAO,IAAI,K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AO,EAAE,CAAC,UAAU,EAAE,MAAM,EAAE,EAAE,CAAC,UAAU,CAAC,UAAU,CAAC,OAAO,EAAE,MAAM,CAAC;IAEvE,KAAK,CAAC,MAAM,CAAC,UAAU;QACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;IACtC,CAAC;CACD,CAAC","sourcesContent":["/**\n * Meta Model API OAuth flow\n *\n * RFC 8628 device authorization grant against https://auth.meta.com (JSON\n * responses). Meta splits identity from API access: the resulting identity\n * token is not accepted for inference, so it is exchanged for a Model API\n * key via the Muse Code key-mint endpoint (minted keys live about a day).\n * The identity token is stored as `refresh` and the minted key as `access`,\n * so the standard OAuth scheduler re-mints the key when it expires with no\n * bespoke renewal machinery. The identity token itself is not renewable\n * (auth.meta.com answers grant_type=refresh_token with 404 and issues no\n * refresh_token), so a 401/403 from mint means the session is dead and the\n * user must sign in again.\n */\n\nimport { OAuthRefreshRejectedError } from \"../oauth-refresh-errors.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { trustedHttpUrl } from \"./trusted-url.ts\";\n\n// Muse Code CLI client id.\nconst CLIENT_ID = \"1031625952748946\";\nconst AUTH_HOST = \"https://auth.meta.com\";\nconst DEVICE_AUTHORIZATION_URL = `${AUTH_HOST}/oidc/device/authorization/`;\nconst DEVICE_TOKEN_URL = `${AUTH_HOST}/oidc/device/token/`;\nconst API_KEY_MINT_URL = \"https://api.meta.ai/muse-code/key\";\nconst API_KEY_LIFETIME_MS = 24 * 60 * 60 * 1000;\nconst REQUEST_TIMEOUT_MS = 30 * 1000;\n\ntype DeviceAuthorization = {\n\tdeviceCode: string;\n\tuserCode: string;\n\tverificationUri: string;\n\tintervalSeconds?: number;\n\texpiresInSeconds?: number;\n};\n\nfunction requestSignal(signal: AbortSignal): AbortSignal {\n\treturn AbortSignal.any([AbortSignal.timeout(REQUEST_TIMEOUT_MS), signal]);\n}\n\nasync function readJson(response: Response): Promise<Record<string, unknown> | null> {\n\ttry {\n\t\tconst json = await response.json();\n\t\treturn json && typeof json === \"object\" ? (json as Record<string, unknown>) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction errorDetail(json: Record<string, unknown> | null): string {\n\tfor (const key of [\"error_description\", \"detail\", \"message\", \"error\"]) {\n\t\tconst value = json?.[key];\n\t\tif (typeof value === \"string\" && value.trim()) return `: ${value.trim()}`;\n\t}\n\treturn \"\";\n}\n\nfunction positiveNumber(value: unknown): number | undefined {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : undefined;\n}\n\nasync function startDeviceAuthorization(signal: AbortSignal): Promise<DeviceAuthorization> {\n\tconst response = await fetch(DEVICE_AUTHORIZATION_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\tAccept: \"application/json\",\n\t\t},\n\t\tbody: new URLSearchParams({ client_id: CLIENT_ID }).toString(),\n\t\tsignal: requestSignal(signal),\n\t});\n\tconst json = await readJson(response);\n\tif (!response.ok) {\n\t\tthrow new Error(`Meta device authorization failed with status ${response.status}${errorDetail(json)}`);\n\t}\n\tconst deviceCode = json?.device_code;\n\tconst userCode = json?.user_code;\n\tconst verificationUri = trustedHttpUrl(json?.verification_uri_complete) ?? trustedHttpUrl(json?.verification_uri);\n\tif (typeof deviceCode !== \"string\" || !deviceCode || typeof userCode !== \"string\" || !userCode || !verificationUri) {\n\t\tthrow new Error(`Invalid Meta device authorization response: ${JSON.stringify(json)}`);\n\t}\n\treturn {\n\t\tdeviceCode,\n\t\tuserCode,\n\t\tverificationUri,\n\t\tintervalSeconds: positiveNumber(json?.interval),\n\t\texpiresInSeconds: positiveNumber(json?.expires_in),\n\t};\n}\n\nasync function pollForIdentityToken(device: DeviceAuthorization, signal: AbortSignal): Promise<string> {\n\treturn pollOAuthDeviceCodeFlow<string>({\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 fetch(DEVICE_TOKEN_URL, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t},\n\t\t\t\tbody: new URLSearchParams({\n\t\t\t\t\tgrant_type: \"urn:ietf:params:oauth:grant-type:device_code\",\n\t\t\t\t\tdevice_code: device.deviceCode,\n\t\t\t\t\tclient_id: CLIENT_ID,\n\t\t\t\t}).toString(),\n\t\t\t\tsignal: requestSignal(signal),\n\t\t\t});\n\t\t\tconst json = await readJson(response);\n\t\t\tif (response.ok && typeof json?.access_token === \"string\" && json.access_token) {\n\t\t\t\treturn { status: \"complete\", value: json.access_token };\n\t\t\t}\n\t\t\tswitch (json?.error) {\n\t\t\t\tcase \"authorization_pending\":\n\t\t\t\t\treturn { status: \"pending\" };\n\t\t\t\tcase \"slow_down\":\n\t\t\t\t\treturn { status: \"slow_down\", intervalSeconds: positiveNumber(json?.interval) };\n\t\t\t\tcase \"access_denied\":\n\t\t\t\t\treturn { status: \"failed\", message: \"Meta login was denied.\" };\n\t\t\t\tcase \"expired_token\":\n\t\t\t\t\treturn { status: \"failed\", message: \"Meta device authorization expired. Please restart login.\" };\n\t\t\t\tdefault:\n\t\t\t\t\treturn {\n\t\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\t\tmessage: `Meta device token request failed with status ${response.status}${errorDetail(json)}`,\n\t\t\t\t\t};\n\t\t\t}\n\t\t},\n\t});\n}\n\n/** Exchange an identity token for a Model API key. Keys are valid for about a day. */\nasync function mintApiKey(identityToken: string, signal: AbortSignal): Promise<OAuthCredential> {\n\tconst response = await fetch(API_KEY_MINT_URL, {\n\t\tmethod: \"POST\",\n\t\theaders: {\n\t\t\tAccept: \"application/json\",\n\t\t\tAuthorization: `Bearer ${identityToken}`,\n\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\"x-api-version\": \"1.0.0\",\n\t\t},\n\t\tbody: \"{}\",\n\t\tsignal: requestSignal(signal),\n\t});\n\tconst json = await readJson(response);\n\tif (response.status === 401 || response.status === 403) {\n\t\t// Identity token is not renewable (see file header); only a fresh device flow helps, which the refresh\n\t\t// caller tells the user to start with /login for the provider they use.\n\t\tconst description = [\"error_description\", \"detail\", \"message\"]\n\t\t\t.map((key) => json?.[key])\n\t\t\t.find((value): value is string => typeof value === \"string\" && value.trim().length > 0);\n\t\tthrow new OAuthRefreshRejectedError(\n\t\t\t`Meta session expired (status ${response.status})`,\n\t\t\t{ status: response.status, code: typeof json?.error === \"string\" ? json.error : undefined, description },\n\t\t\t[identityToken],\n\t\t);\n\t}\n\tif (!response.ok) {\n\t\tthrow new Error(`Meta API key mint failed with status ${response.status}${errorDetail(json)}`);\n\t}\n\tconst apiKey = json?.api_key;\n\tif (typeof apiKey !== \"string\" || !apiKey) {\n\t\tconst actionUrl = trustedHttpUrl(json?.action_url);\n\t\tthrow new Error(`Meta did not issue an API key.${actionUrl ? ` Complete setup at ${actionUrl}` : \"\"}`);\n\t}\n\treturn { type: \"oauth\", refresh: identityToken, access: apiKey, expires: Date.now() + API_KEY_LIFETIME_MS };\n}\n\nasync function loginMeta(interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\ttry {\n\t\tconst device = await startDeviceAuthorization(interaction.signal);\n\t\tinteraction.notify({\n\t\t\ttype: \"device_code\",\n\t\t\tuserCode: device.userCode,\n\t\t\tverificationUri: device.verificationUri,\n\t\t\tintervalSeconds: device.intervalSeconds,\n\t\t\texpiresInSeconds: device.expiresInSeconds,\n\t\t});\n\t\tconst identityToken = await pollForIdentityToken(device, interaction.signal);\n\t\tinteraction.notify({ type: \"progress\", message: \"Enabling Meta Model API access...\" });\n\t\treturn await mintApiKey(identityToken, interaction.signal);\n\t} catch (e) {\n\t\t// An in-flight fetch rejects with a DOMException on abort; the login UI matches on this message.\n\t\tif (interaction.signal.aborted) throw new Error(\"Login cancelled\");\n\t\tthrow e;\n\t}\n}\n\nexport const metaOAuth: OAuthAuth = {\n\tname: \"Meta (Muse subscription)\",\n\tisSubscription: true,\n\tloginLabel: \"Sign in with Meta\",\n\n\tlogin: loginMeta,\n\n\trefresh: (credential, signal) => mintApiKey(credential.refresh, signal),\n\n\tasync toAuth(credential) {\n\t\treturn { apiKey: credential.access };\n\t},\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"radius.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/radius.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AA4QvF,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,kBAAkB,GAAG,SAAS,CA2DxE"}
1
+ {"version":3,"file":"radius.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/radius.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAIH,OAAO,KAAK,EAAE,SAAS,EAA4C,MAAM,aAAa,CAAC;AAkRvF,MAAM,WAAW,kBAAkB;IAClC,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CAChB;AAED,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,kBAAkB,GAAG,SAAS,CA2DxE"}
@@ -13,6 +13,7 @@ import { isPermanentRefreshRejection, OAuthRefreshRejectedError } from "../oauth
13
13
  import { startOAuthCallbackServer } from "./callback-server.js";
14
14
  import { pollOAuthDeviceCodeFlow } from "./device-code.js";
15
15
  import { generatePKCE } from "./pkce.js";
16
+ import { trustedHttpUrl } from "./trusted-url.js";
16
17
  const CALLBACK_HOST = "127.0.0.1";
17
18
  const CALLBACK_PORT = 1456;
18
19
  const CALLBACK_PATH = "/oauth/callback";
@@ -32,10 +33,11 @@ async function loadRadiusOAuthDiscovery(gateway, signal) {
32
33
  throw new Error(`Could not load Radius OAuth config from ${gateway}: ${response.status} ${await response.text()}`);
33
34
  }
34
35
  const discovery = (await response.json());
35
- if (typeof discovery.authorizationEndpoint !== "string") {
36
+ const authorizationEndpoint = trustedHttpUrl(discovery.authorizationEndpoint);
37
+ if (!authorizationEndpoint) {
36
38
  throw new Error(`Invalid Radius OAuth config from ${gateway}`);
37
39
  }
38
- return { authorizationEndpoint: discovery.authorizationEndpoint };
40
+ return { authorizationEndpoint };
39
41
  }
40
42
  class OAuthResponseError extends Error {
41
43
  status;
@@ -168,10 +170,14 @@ async function requestDeviceAuthorization(gateway, signal) {
168
170
  if (!data.device_code || !data.user_code || !data.verification_uri || !data.expires_in) {
169
171
  throw new Error("Radius OAuth device authorization response is missing required fields");
170
172
  }
173
+ const verificationUri = trustedHttpUrl(data.verification_uri);
174
+ if (!verificationUri) {
175
+ throw new Error("Untrusted verification_uri in Radius OAuth device authorization response");
176
+ }
171
177
  return {
172
178
  device_code: data.device_code,
173
179
  user_code: data.user_code,
174
- verification_uri: data.verification_uri,
180
+ verification_uri: verificationUri,
175
181
  expires_in: data.expires_in,
176
182
  interval: data.interval,
177
183
  };
@@ -1 +1 @@
1
- {"version":3,"file":"radius.js","sourceRoot":"","sources":["../../../src/auth/oauth/radius.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,2BAA2B,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAEpG,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAEzC,MAAM,aAAa,GAAG,WAAW,CAAC;AAClC,MA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C,UAAU,EAAE,MAAM;YAC/B,IAAI,CAAC;gBACJ,OAAO,MAAM,iBAAiB,CAC7B,OAAO,EACP,IAAI,eAAe,CAAC;oBACnB,UAAU,EAAE,eAAe;oBAC3B,SAAS,EAAE,eAAe;oBAC1B,aAAa,EAAE,UAAU,CAAC,OAAO;iBACjC,CAAC,EACF,MAAM,CACN,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBAChB,IAAI,KAAK,YAAY,kBAAkB,EAAE,CAAC;oBACzC,MAAM,SAAS,GAAG,EAAE,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,IAAI,EAAE,KAAK,CAAC,UAAU,EAAE,WAAW,EAAE,KAAK,CAAC,gBAAgB,EAAE,CAAC;oBACxG,IAAI,2BAA2B,CAAC,SAAS,CAAC,EAAE,CAAC;wBAC5C,MAAM,IAAI,yBAAyB,CAClC,GAAG,OAAO,CAAC,IAAI,qCAAqC,KAAK,CAAC,MAAM,GAAG,EACnE,SAAS,EACT,CAAC,UAAU,CAAC,OAAO,CAAC,CACpB,CAAC;oBACH,CAAC;gBACF,CAAC;gBACD,MAAM,KAAK,CAAC;YACb,CAAC;QACF,CAAC;QAED,KAAK,CAAC,MAAM,CAAC,UAAU;YACtB,OAAO,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,CAAC;QACtC,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Radius gateway OAuth flow.\n *\n * Radius is a pi-messages gateway. OAuth client APIs live on the configured\n * gateway; only the interactive browser authorization endpoint is discovered.\n * Model catalog loading is owned by the Radius provider.\n *\n * NOTE: This module uses node:http via callback-server.ts.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport { normalizeRadiusGatewayUrl } from \"../../providers/radius-config.ts\";\nimport { isPermanentRefreshRejection, OAuthRefreshRejectedError } from \"../oauth-refresh-errors.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer } from \"./callback-server.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.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\";\nconst OAUTH_CLIENT_ID = \"pi-gateway\";\nconst OAUTH_SCOPE = \"gateway offline_access\";\nconst OAUTH_DEVICE_CODE_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\";\n\ntype RadiusOAuthDiscovery = {\n\tauthorizationEndpoint: string;\n};\n\ntype DeviceAuthorizationResponse = {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri: string;\n\texpires_in: number;\n\tinterval?: number;\n};\n\nasync function loadRadiusOAuthDiscovery(gateway: string, signal: AbortSignal): Promise<RadiusOAuthDiscovery> {\n\tconst response = await fetch(new URL(\"/v1/oauth\", gateway), {\n\t\theaders: { accept: \"application/json\" },\n\t\tsignal,\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\tconst discovery = (await response.json()) as Partial<RadiusOAuthDiscovery>;\n\tif (typeof discovery.authorizationEndpoint !== \"string\") {\n\t\tthrow new Error(`Invalid Radius OAuth config from ${gateway}`);\n\t}\n\treturn { authorizationEndpoint: discovery.authorizationEndpoint };\n}\n\nclass OAuthResponseError extends Error {\n\treadonly status: number;\n\treadonly oauthError?: string;\n\t/** `error_description` from a JSON error body; never the raw body. */\n\treadonly oauthDescription?: string;\n\n\tconstructor(\n\t\tstatus: number,\n\t\toauthError: string | undefined,\n\t\tdescription: string | undefined,\n\t\tmessage: string,\n\t\toauthDescription?: string,\n\t) {\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\tthis.oauthDescription = oauthDescription;\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\tlet oauthDescription: 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\toauthDescription = description;\n\t\t} catch {\n\t\t\tdescription = text;\n\t\t}\n\t}\n\n\treturn new OAuthResponseError(response.status, oauthError, description, message, oauthDescription);\n}\n\nasync function requestOAuthToken(\n\tgateway: string,\n\tbody: URLSearchParams,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(new URL(\"/v1/oauth/token\", gateway), {\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\nasync function loginWithBrowser(\n\tgateway: string,\n\tauthorizationEndpoint: string,\n\tinteraction: ProviderAuthInteraction,\n): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = crypto.randomUUID();\n\tconst authorizeUrl = new URL(authorizationEndpoint);\n\tauthorizeUrl.search = new URLSearchParams({\n\t\tresponse_type: \"code\",\n\t\tclient_id: OAUTH_CLIENT_ID,\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 callback = await startOAuthCallbackServer({\n\t\tproviderName: \"Radius\",\n\t\thost: CALLBACK_HOST,\n\t\tport: CALLBACK_PORT,\n\t\tpath: CALLBACK_PATH,\n\t\tstate,\n\t\tcomplete: (code) =>\n\t\t\trequestOAuthToken(\n\t\t\t\tgateway,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\n\t\t\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\t\t\tcode,\n\t\t\t\t\tcode_verifier: verifier,\n\t\t\t\t}),\n\t\t\t\tinteraction.signal,\n\t\t\t),\n\t\tsignal: interaction.signal,\n\t});\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 credential = await callback.wait();\n\t\tif (!credential) throw new Error(\"OAuth callback did not complete.\");\n\t\treturn credential;\n\t} finally {\n\t\tcallback.close();\n\t}\n}\n\nasync function requestDeviceAuthorization(gateway: string, signal: AbortSignal): Promise<DeviceAuthorizationResponse> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(new URL(\"/v1/oauth/device\", gateway), {\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_CLIENT_ID, 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.verification_uri || !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\texpires_in: data.expires_in,\n\t\tinterval: data.interval,\n\t};\n}\n\nasync function loginWithDeviceCode(gateway: string, interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst device = await requestDeviceAuthorization(gateway, interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.user_code,\n\t\tverificationUri: device.verification_uri,\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\tgateway,\n\t\t\t\t\tnew URLSearchParams({\n\t\t\t\t\t\tgrant_type: OAUTH_DEVICE_CODE_GRANT_TYPE,\n\t\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\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 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\tif (loginMethod === LOGIN_METHOD_DEVICE_CODE) {\n\t\t\t\treturn loginWithDeviceCode(gateway, interaction);\n\t\t\t}\n\t\t\tif (loginMethod === LOGIN_METHOD_BROWSER) {\n\t\t\t\tconst discovery = await loadRadiusOAuthDiscovery(gateway, interaction.signal);\n\t\t\t\treturn loginWithBrowser(gateway, discovery.authorizationEndpoint, interaction);\n\t\t\t}\n\t\t\tthrow new Error(`Unknown ${options.name} sign-in method: ${loginMethod}`);\n\t\t},\n\n\t\tasync refresh(credential, signal): Promise<OAuthCredential> {\n\t\t\ttry {\n\t\t\t\treturn await requestOAuthToken(\n\t\t\t\t\tgateway,\n\t\t\t\t\tnew URLSearchParams({\n\t\t\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\n\t\t\t\t\t\trefresh_token: credential.refresh,\n\t\t\t\t\t}),\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof OAuthResponseError) {\n\t\t\t\t\tconst rejection = { status: error.status, code: error.oauthError, description: error.oauthDescription };\n\t\t\t\t\tif (isPermanentRefreshRejection(rejection)) {\n\t\t\t\t\t\tthrow new OAuthRefreshRejectedError(\n\t\t\t\t\t\t\t`${options.name} OAuth token refresh failed (HTTP ${error.status})`,\n\t\t\t\t\t\t\trejection,\n\t\t\t\t\t\t\t[credential.refresh],\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t},\n\n\t\tasync toAuth(credential) {\n\t\t\treturn { apiKey: credential.access };\n\t\t},\n\t};\n}\n"]}
1
+ {"version":3,"file":"radius.js","sourceRoot":"","sources":["../../../src/auth/oauth/radius.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAAO,EAAE,2BAA2B,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAEpG,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EAAE,uBAAuB,EAAE,MAAM,kBAAkB,CAAC;AAC3D,OA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uth client APIs live on the configured\n * gateway; only the interactive browser authorization endpoint is discovered.\n * Model catalog loading is owned by the Radius provider.\n *\n * NOTE: This module uses node:http via callback-server.ts.\n * It is only intended for CLI use, not browser environments.\n */\n\nimport { normalizeRadiusGatewayUrl } from \"../../providers/radius-config.ts\";\nimport { isPermanentRefreshRejection, OAuthRefreshRejectedError } from \"../oauth-refresh-errors.ts\";\nimport type { OAuthAuth, OAuthCredential, ProviderAuthInteraction } from \"../types.ts\";\nimport { startOAuthCallbackServer } from \"./callback-server.ts\";\nimport { pollOAuthDeviceCodeFlow } from \"./device-code.ts\";\nimport { generatePKCE } from \"./pkce.ts\";\nimport { trustedHttpUrl } from \"./trusted-url.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\";\nconst OAUTH_CLIENT_ID = \"pi-gateway\";\nconst OAUTH_SCOPE = \"gateway offline_access\";\nconst OAUTH_DEVICE_CODE_GRANT_TYPE = \"urn:ietf:params:oauth:grant-type:device_code\";\n\ntype RadiusOAuthDiscovery = {\n\tauthorizationEndpoint: string;\n};\n\ntype DeviceAuthorizationResponse = {\n\tdevice_code: string;\n\tuser_code: string;\n\tverification_uri: string;\n\texpires_in: number;\n\tinterval?: number;\n};\n\nasync function loadRadiusOAuthDiscovery(gateway: string, signal: AbortSignal): Promise<RadiusOAuthDiscovery> {\n\tconst response = await fetch(new URL(\"/v1/oauth\", gateway), {\n\t\theaders: { accept: \"application/json\" },\n\t\tsignal,\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\tconst discovery = (await response.json()) as Partial<RadiusOAuthDiscovery>;\n\tconst authorizationEndpoint = trustedHttpUrl(discovery.authorizationEndpoint);\n\tif (!authorizationEndpoint) {\n\t\tthrow new Error(`Invalid Radius OAuth config from ${gateway}`);\n\t}\n\treturn { authorizationEndpoint };\n}\n\nclass OAuthResponseError extends Error {\n\treadonly status: number;\n\treadonly oauthError?: string;\n\t/** `error_description` from a JSON error body; never the raw body. */\n\treadonly oauthDescription?: string;\n\n\tconstructor(\n\t\tstatus: number,\n\t\toauthError: string | undefined,\n\t\tdescription: string | undefined,\n\t\tmessage: string,\n\t\toauthDescription?: string,\n\t) {\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\tthis.oauthDescription = oauthDescription;\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\tlet oauthDescription: 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\toauthDescription = description;\n\t\t} catch {\n\t\t\tdescription = text;\n\t\t}\n\t}\n\n\treturn new OAuthResponseError(response.status, oauthError, description, message, oauthDescription);\n}\n\nasync function requestOAuthToken(\n\tgateway: string,\n\tbody: URLSearchParams,\n\tsignal: AbortSignal,\n): Promise<OAuthCredential> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(new URL(\"/v1/oauth/token\", gateway), {\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\nasync function loginWithBrowser(\n\tgateway: string,\n\tauthorizationEndpoint: string,\n\tinteraction: ProviderAuthInteraction,\n): Promise<OAuthCredential> {\n\tconst { verifier, challenge } = await generatePKCE();\n\tconst state = crypto.randomUUID();\n\tconst authorizeUrl = new URL(authorizationEndpoint);\n\tauthorizeUrl.search = new URLSearchParams({\n\t\tresponse_type: \"code\",\n\t\tclient_id: OAUTH_CLIENT_ID,\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 callback = await startOAuthCallbackServer({\n\t\tproviderName: \"Radius\",\n\t\thost: CALLBACK_HOST,\n\t\tport: CALLBACK_PORT,\n\t\tpath: CALLBACK_PATH,\n\t\tstate,\n\t\tcomplete: (code) =>\n\t\t\trequestOAuthToken(\n\t\t\t\tgateway,\n\t\t\t\tnew URLSearchParams({\n\t\t\t\t\tgrant_type: \"authorization_code\",\n\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\n\t\t\t\t\tredirect_uri: REDIRECT_URI,\n\t\t\t\t\tcode,\n\t\t\t\t\tcode_verifier: verifier,\n\t\t\t\t}),\n\t\t\t\tinteraction.signal,\n\t\t\t),\n\t\tsignal: interaction.signal,\n\t});\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 credential = await callback.wait();\n\t\tif (!credential) throw new Error(\"OAuth callback did not complete.\");\n\t\treturn credential;\n\t} finally {\n\t\tcallback.close();\n\t}\n}\n\nasync function requestDeviceAuthorization(gateway: string, signal: AbortSignal): Promise<DeviceAuthorizationResponse> {\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(new URL(\"/v1/oauth/device\", gateway), {\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_CLIENT_ID, 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.verification_uri || !data.expires_in) {\n\t\tthrow new Error(\"Radius OAuth device authorization response is missing required fields\");\n\t}\n\tconst verificationUri = trustedHttpUrl(data.verification_uri);\n\tif (!verificationUri) {\n\t\tthrow new Error(\"Untrusted verification_uri in Radius OAuth device authorization response\");\n\t}\n\n\treturn {\n\t\tdevice_code: data.device_code,\n\t\tuser_code: data.user_code,\n\t\tverification_uri: verificationUri,\n\t\texpires_in: data.expires_in,\n\t\tinterval: data.interval,\n\t};\n}\n\nasync function loginWithDeviceCode(gateway: string, interaction: ProviderAuthInteraction): Promise<OAuthCredential> {\n\tconst device = await requestDeviceAuthorization(gateway, interaction.signal);\n\tinteraction.notify({\n\t\ttype: \"device_code\",\n\t\tuserCode: device.user_code,\n\t\tverificationUri: device.verification_uri,\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\tgateway,\n\t\t\t\t\tnew URLSearchParams({\n\t\t\t\t\t\tgrant_type: OAUTH_DEVICE_CODE_GRANT_TYPE,\n\t\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\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 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\tif (loginMethod === LOGIN_METHOD_DEVICE_CODE) {\n\t\t\t\treturn loginWithDeviceCode(gateway, interaction);\n\t\t\t}\n\t\t\tif (loginMethod === LOGIN_METHOD_BROWSER) {\n\t\t\t\tconst discovery = await loadRadiusOAuthDiscovery(gateway, interaction.signal);\n\t\t\t\treturn loginWithBrowser(gateway, discovery.authorizationEndpoint, interaction);\n\t\t\t}\n\t\t\tthrow new Error(`Unknown ${options.name} sign-in method: ${loginMethod}`);\n\t\t},\n\n\t\tasync refresh(credential, signal): Promise<OAuthCredential> {\n\t\t\ttry {\n\t\t\t\treturn await requestOAuthToken(\n\t\t\t\t\tgateway,\n\t\t\t\t\tnew URLSearchParams({\n\t\t\t\t\t\tgrant_type: \"refresh_token\",\n\t\t\t\t\t\tclient_id: OAUTH_CLIENT_ID,\n\t\t\t\t\t\trefresh_token: credential.refresh,\n\t\t\t\t\t}),\n\t\t\t\t\tsignal,\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof OAuthResponseError) {\n\t\t\t\t\tconst rejection = { status: error.status, code: error.oauthError, description: error.oauthDescription };\n\t\t\t\t\tif (isPermanentRefreshRejection(rejection)) {\n\t\t\t\t\t\tthrow new OAuthRefreshRejectedError(\n\t\t\t\t\t\t\t`${options.name} OAuth token refresh failed (HTTP ${error.status})`,\n\t\t\t\t\t\t\trejection,\n\t\t\t\t\t\t\t[credential.refresh],\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}\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,7 @@
1
+ /**
2
+ * The `http:` or `https:` URL `value` names, normalized, or null. Login flows open server-supplied URLs with the
3
+ * platform URL handler, which would also launch a `file:` URL or a custom protocol handler. Normalizing
4
+ * percent-encodes control characters, so the URL can also be embedded in terminal hyperlinks.
5
+ */
6
+ export declare function trustedHttpUrl(value: unknown): string | null;
7
+ //# sourceMappingURL=trusted-url.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trusted-url.d.ts","sourceRoot":"","sources":["../../../src/auth/oauth/trusted-url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAI5D"}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The `http:` or `https:` URL `value` names, normalized, or null. Login flows open server-supplied URLs with the
3
+ * platform URL handler, which would also launch a `file:` URL or a custom protocol handler. Normalizing
4
+ * percent-encodes control characters, so the URL can also be embedded in terminal hyperlinks.
5
+ */
6
+ export function trustedHttpUrl(value) {
7
+ if (typeof value !== "string" || !URL.canParse(value))
8
+ return null;
9
+ const url = new URL(value);
10
+ return url.protocol === "https:" || url.protocol === "http:" ? url.href : null;
11
+ }
12
+ //# sourceMappingURL=trusted-url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trusted-url.js","sourceRoot":"","sources":["../../../src/auth/oauth/trusted-url.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,UAAU,cAAc,CAAC,KAAc;IAC5C,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACnE,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IAC3B,OAAO,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,GAAG,CAAC,QAAQ,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC;AAChF,CAAC","sourcesContent":["/**\n * The `http:` or `https:` URL `value` names, normalized, or null. Login flows open server-supplied URLs with the\n * platform URL handler, which would also launch a `file:` URL or a custom protocol handler. Normalizing\n * percent-encodes control characters, so the URL can also be embedded in terminal hyperlinks.\n */\nexport function trustedHttpUrl(value: unknown): string | null {\n\tif (typeof value !== \"string\" || !URL.canParse(value)) return null;\n\tconst url = new URL(value);\n\treturn url.protocol === \"https:\" || url.protocol === \"http:\" ? url.href : null;\n}\n"]}
@@ -235,6 +235,12 @@ export interface OAuthAuth {
235
235
  * (invalid_grant etc.). `Models` runs this under the store lock.
236
236
  */
237
237
  refresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;
238
+ /**
239
+ * Optional: whether an unexpired stored credential still lacks data that only `refresh`
240
+ * restores, such as an account model list an older login never saved. `Models.refresh()` with
241
+ * network access refreshes such a credential once per call; request auth is unaffected.
242
+ */
243
+ needsRefresh?(credential: OAuthCredential): boolean;
238
244
  /**
239
245
  * Side-effect-free derivation of request auth from a valid credential.
240
246
  * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAEhE;;;GAGG;AACH,MAAM,WAAW,SAAS;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAChC,IAAI,EAAE,SAAS,CAAC;IAChB,G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,OAAO,CAAC;IAE7B,KAAK,CAAC,WAAW,EAAE,uBAAuB,EAAE,OAAO,CAAC,EAAE,YAAY,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAE9F;;;OAGG;IACH,OAAO,CAAC,UAAU,EAAE,eAAe,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,eAAe,CAAC,CAAC;IAEpF;;;;OAIG;IACH,YAAY,CAAC,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC;IAEpD;;;;OAIG;IACH,MAAM,CAAC,UAAU,EAAE,eAAe,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC;CACxD;AAED;;;;GAIG;AACH,MAAM,WAAW,YAAY;IAC5B,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,KAAK,CAAC,EAAE,SAAS,CAAC;CAClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/** Optional cancellation for public auth and credential operations. */\nexport interface AuthOperationOptions {\n\tsignal?: AbortSignal;\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\t/** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */\n\t\t\topenBrowserOnConfirm?: boolean;\n\t\t\t/** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */\n\t\t\tcopyCodeOnConfirm?: boolean;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/** Normalized interaction passed to provider login implementations. */\nexport type ProviderAuthInteraction = AuthInteraction & { signal: AbortSignal };\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Provider ids whose stored api-key credentials this provider reuses, in\n\t * precedence order. A borrowing provider has no stored credential of its\n\t * own; anything stored under its id is ignored. The first\n\t * listed provider with a stored api-key credential that has a key is passed\n\t * to `resolve()` as `credential`; stored OAuth credentials and key-less\n\t * api-key credentials are skipped. When none qualifies, `resolve()` runs\n\t * without a credential, so ambient sources (env vars) still apply. Pair with\n\t * an absent `login`.\n\t */\n\tborrowCredentialsFrom?: readonly string[];\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthResult | undefined>;\n}\n\n/** App context supplied to provider login flows. */\nexport interface LoginOptions {\n\t/** Stable UUID for this installation, created lazily by the app. */\n\tgetDeviceId?: () => string;\n\t/** App name used for OpenAI's agent name hint and Codex browser login originator. */\n\tagentName?: string;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Whether access through this auth method is backed by a provider subscription. */\n\tisSubscription?: boolean;\n\n\t/** Selector label for the OAuth login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tusesCallbackServer?: boolean;\n\n\tlogin(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ProviderEnv, ProviderHeaders } from \"../types.ts\";\n\n/**\n * Request auth for a single model request. If a value cannot be expressed as\n * `apiKey`, `headers`, or `baseUrl`, it is provider config, not auth.\n */\nexport interface ModelAuth {\n\tapiKey?: string;\n\theaders?: ProviderHeaders;\n\tbaseUrl?: string;\n}\n\n/**\n * Stored api-key credential. `env` holds provider-scoped environment/config\n * values such as Cloudflare account/gateway ids.\n */\nexport interface ApiKeyCredential {\n\ttype: \"api_key\";\n\tkey?: string;\n\tenv?: ProviderEnv;\n}\n\n/** OAuth token data returned by extension compatibility flows. */\nexport interface OAuthCredentials {\n\trefresh: string;\n\taccess: string;\n\texpires: number;\n\t[key: string]: unknown;\n}\n\n/** Stored canonical OAuth credential. */\nexport interface OAuthCredential extends OAuthCredentials {\n\ttype: \"oauth\";\n}\n\n/** One type-tagged credential per provider — the shape of today's auth.json. */\nexport type Credential = ApiKeyCredential | OAuthCredential;\n\n/** Non-secret credential metadata for account/status enumeration. */\nexport interface CredentialInfo {\n\tproviderId: string;\n\ttype: Credential[\"type\"];\n}\n\n/** Optional cancellation for public auth and credential operations. */\nexport interface AuthOperationOptions {\n\tsignal?: AbortSignal;\n}\n\n/**\n * App-owned credential storage, keyed by `Provider.id`, one credential per\n * provider. `modify` is the only write path, so every mutation is a\n * serialized read-modify-write; `Models.getAuth()` runs OAuth refresh inside\n * `modify` so concurrent requests cannot double-refresh a rotated token. The\n * app persists a credential after login via\n * `modify(provider.id, async () => credential)`. Login/logout orchestration\n * is app-owned.\n *\n * Error semantics: `read` resolves `undefined` for missing entries. Methods\n * reject only on storage failure; `Models` wraps such rejections in\n * `ModelsError` with code \"auth\". Best-effort stores that serve an in-memory\n * view and record persistence errors internally (like coding-agent's\n * AuthStorage) are valid implementations.\n */\nexport interface CredentialStore {\n\t/**\n\t * Read the stored credential, possibly expired. Display/status use;\n\t * resolved request auth comes from `Models.getAuth()`.\n\t */\n\tread(providerId: string, options?: AuthOperationOptions): Promise<Credential | undefined>;\n\n\t/**\n\t * List stored credential metadata without resolving or exposing secrets.\n\t * Implementations must not execute configured API-key commands while listing.\n\t */\n\tlist(options?: AuthOperationOptions): Promise<readonly CredentialInfo[]>;\n\n\t/**\n\t * Serialized write — the only write path. `fn` sees the current credential\n\t * because correct writes (refresh, login-during-refresh) depend on it;\n\t * return the new credential, or undefined to leave the entry unchanged.\n\t * Mutual exclusion per provider id, cross-process too where the backing\n\t * store supports it (e.g. a file lock). Resolves with the post-write\n\t * credential. Rejections from `fn` propagate.\n\t */\n\tmodify(\n\t\tproviderId: string,\n\t\tfn: (current: Credential | undefined) => Promise<Credential | undefined>,\n\t\toptions?: AuthOperationOptions,\n\t): Promise<Credential | undefined>;\n\n\t/** Remove a credential (logout). Implementations serialize this against `modify`. */\n\tdelete(providerId: string, options?: AuthOperationOptions): Promise<void>;\n}\n\n/** Environment access for auth resolution. Injectable for tests and browsers. */\nexport interface AuthContext {\n\tenv(name: string): Promise<string | undefined>;\n\t/** Check whether a file exists. Supports a leading `~`. Always false in browsers. */\n\tfileExists(path: string): Promise<boolean>;\n}\n\n/** Result of resolving auth for a model. */\nexport interface AuthResult {\n\tauth: ModelAuth;\n\t/** Provider-scoped environment/config values resolved from credentials and ambient context. */\n\tenv?: ProviderEnv;\n\t/** Human-readable label for status UI: \"ANTHROPIC_API_KEY\", \"OAuth\", \"~/.aws/credentials\". */\n\tsource?: string;\n}\n\nexport interface AuthCheck {\n\tsource?: string;\n\ttype: \"api_key\" | \"oauth\";\n}\n\nexport type AuthType = \"api_key\" | \"oauth\";\n\n/**\n * Prompt shown to the user during login. `signal` lets the flow cancel a\n * pending prompt when an out-of-band event resolves the step, e.g. a\n * `manual_code` prompt raced against a callback server, aborted when the\n * callback wins.\n */\nexport type AuthPrompt = { signal?: AbortSignal } & (\n\t| { type: \"text\"; message: string; placeholder?: string }\n\t| { type: \"secret\"; message: string; placeholder?: string }\n\t| { type: \"select\"; message: string; options: readonly { id: string; label: string; description?: string }[] }\n\t| { type: \"manual_code\"; message: string; placeholder?: string }\n);\n\nexport interface AuthInfoLink {\n\turl: string;\n\tlabel?: string;\n}\n\nexport type AuthEvent =\n\t| { type: \"info\"; message: string; links?: readonly AuthInfoLink[] }\n\t| { type: \"auth_url\"; url: string; instructions?: string }\n\t| {\n\t\t\ttype: \"device_code\";\n\t\t\tuserCode: string;\n\t\t\tverificationUri: string;\n\t\t\t/** Offer best-effort browser opening on user confirmation. Defaults to true; clients may ignore it. */\n\t\t\topenBrowserOnConfirm?: boolean;\n\t\t\t/** Offer copying of userCode on user confirmation, replacing the clipboard. Defaults to true. */\n\t\t\tcopyCodeOnConfirm?: boolean;\n\t\t\tintervalSeconds?: number;\n\t\t\texpiresInSeconds?: number;\n\t }\n\t| { type: \"progress\"; message: string };\n\n/**\n * Login interaction callbacks serving both api-key and OAuth flows.\n *\n * `prompt()` returns the entered/selected string (`select` returns the option\n * id). Rejects on cancel/abort. `signal` aborts the whole login flow;\n * per-prompt cancellation uses `AuthPrompt.signal`.\n */\nexport interface AuthInteraction {\n\tsignal?: AbortSignal;\n\n\tprompt(prompt: AuthPrompt): Promise<string>;\n\tnotify(event: AuthEvent): void;\n}\n\n/** Normalized interaction passed to provider login implementations. */\nexport type ProviderAuthInteraction = AuthInteraction & { signal: AbortSignal };\n\n/**\n * Api-key auth: stored key/provider env plus ambient sources (env vars, AWS\n * profiles, ADC files). Ambient-only providers omit `login`.\n */\nexport interface ApiKeyAuth {\n\t/** Display name, e.g. \"Anthropic API key\". */\n\tname: string;\n\n\t/** Interactive setup (prompt for key/provider env). Absent = ambient-only. */\n\tlogin?(interaction: ProviderAuthInteraction): Promise<ApiKeyCredential>;\n\n\t/**\n\t * Provider ids whose stored api-key credentials this provider reuses, in\n\t * precedence order. A borrowing provider has no stored credential of its\n\t * own; anything stored under its id is ignored. The first\n\t * listed provider with a stored api-key credential that has a key is passed\n\t * to `resolve()` as `credential`; stored OAuth credentials and key-less\n\t * api-key credentials are skipped. When none qualifies, `resolve()` runs\n\t * without a credential, so ambient sources (env vars) still apply. Pair with\n\t * an absent `login`.\n\t */\n\tborrowCredentialsFrom?: readonly string[];\n\n\t/**\n\t * Optional side-effect-free availability check. Use this when `resolve()` may\n\t * execute commands or perform other request-time work. Missing means Models\n\t * checks availability by resolving auth.\n\t */\n\tcheck?(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthCheck | undefined>;\n\n\t/**\n\t * Resolve auth from the stored credential and/or ambient sources, merging\n\t * per field (`credential.key ?? env(\"...\")`, `credential.env?.NAME ?? env(\"...\")`).\n\t * undefined = not configured. Resolution is provider-scoped; model-specific\n\t * endpoint preparation happens after auth has been resolved.\n\t */\n\tresolve(input: {\n\t\tctx: AuthContext;\n\t\tcredential?: ApiKeyCredential;\n\t\tsignal: AbortSignal;\n\t}): Promise<AuthResult | undefined>;\n}\n\n/** App context supplied to provider login flows. */\nexport interface LoginOptions {\n\t/** Stable UUID for this installation, created lazily by the app. */\n\tgetDeviceId?: () => string;\n\t/** App name used for OpenAI's agent name hint and Codex browser login originator. */\n\tagentName?: string;\n}\n\n/**\n * OAuth auth. The `refresh`/`toAuth` split lets `Models` own the locked\n * refresh pattern: `refresh` produces a credential, `toAuth` derives request\n * auth from whatever credential ends up stored.\n */\nexport interface OAuthAuth {\n\t/** Display name, e.g. \"Anthropic (Claude Pro/Max)\". */\n\tname: string;\n\n\t/** Whether access through this auth method is backed by a provider subscription. */\n\tisSubscription?: boolean;\n\n\t/** Selector label for the OAuth login option, e.g. \"Sign in with SuperGrok or X Premium\". */\n\tloginLabel?: string;\n\n\tusesCallbackServer?: boolean;\n\n\tlogin(interaction: ProviderAuthInteraction, options?: LoginOptions): Promise<OAuthCredential>;\n\n\t/**\n\t * Exchange the refresh token. Network call; throws on failure\n\t * (invalid_grant etc.). `Models` runs this under the store lock.\n\t */\n\trefresh(credential: OAuthCredential, signal: AbortSignal): Promise<OAuthCredential>;\n\n\t/**\n\t * Optional: whether an unexpired stored credential still lacks data that only `refresh`\n\t * restores, such as an account model list an older login never saved. `Models.refresh()` with\n\t * network access refreshes such a credential once per call; request auth is unaffected.\n\t */\n\tneedsRefresh?(credential: OAuthCredential): boolean;\n\n\t/**\n\t * Side-effect-free derivation of request auth from a valid credential.\n\t * Covers per-credential baseUrl (GitHub Copilot). Async so lazy wrappers\n\t * can load the implementation on first use.\n\t */\n\ttoAuth(credential: OAuthCredential): Promise<ModelAuth>;\n}\n\n/**\n * Provider auth. At least one of `apiKey`/`oauth` must be present: even\n * ambient-credential providers and keyless local servers provide `apiKey`\n * auth whose `resolve()` reports whether the provider is configured.\n */\nexport interface ProviderAuth {\n\tapiKey?: ApiKeyAuth;\n\toauth?: OAuthAuth;\n}\n"]}
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { randomUUID } from "node:crypto";
3
- import { existsSync, readFileSync, writeFileSync } from "node:fs";
3
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
4
4
  import { createInterface } from "node:readline";
5
5
  import { builtinProviders } from "./providers/all.js";
6
6
  const AUTH_FILE = "auth.json";
@@ -19,7 +19,11 @@ function loadAuth() {
19
19
  }
20
20
  }
21
21
  function saveAuth(auth) {
22
- writeFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), "utf-8");
22
+ // OAuth tokens: readable by the user only. `mode` applies when the file is created; chmod covers a file an older
23
+ // version created, before the new tokens are in it.
24
+ if (existsSync(AUTH_FILE))
25
+ chmodSync(AUTH_FILE, 0o600);
26
+ writeFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), { encoding: "utf-8", mode: 0o600 });
23
27
  }
24
28
  async function answerPrompt(rl, authPrompt) {
25
29
  if (authPrompt.type === "select") {
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAClE,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAEhD,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtD,MAAM,SAAS,GAAG,WAAW,CAAC;AAC9B,MAAM,SAAS,GAAG,gBAAgB,E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AAE,KAAK,UAAU,CAAC,EAAE,CAAC;YAC9E,MAAM,IAAI,KAAK,CAAC,qBAAqB,UAAU,IAAI,EAAE,EAAE,CAAC,CAAC;QAC1D,CAAC;QACD,MAAM,KAAK,CAAC,UAAU,CAAC,CAAC;QACxB,OAAO;IACR,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,oBAAoB,OAAO,EAAE,CAAC,CAAC;AAChD,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC/B,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAChF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { randomUUID } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport type { AuthPrompt, OAuthCredential, Provider } from \"./index.ts\";\nimport { builtinProviders } from \"./providers/all.ts\";\n\nconst AUTH_FILE = \"auth.json\";\nconst PROVIDERS = builtinProviders().filter(\n\t(provider): provider is Provider & { auth: { oauth: NonNullable<Provider[\"auth\"][\"oauth\"]> } } =>\n\t\tprovider.auth.oauth !== undefined,\n);\n\nfunction prompt(rl: ReturnType<typeof createInterface>, question: string): Promise<string> {\n\treturn new Promise((resolve) => rl.question(question, resolve));\n}\n\nfunction loadAuth(): Record<string, OAuthCredential> {\n\tif (!existsSync(AUTH_FILE)) return {};\n\ttry {\n\t\treturn JSON.parse(readFileSync(AUTH_FILE, \"utf-8\")) as Record<string, OAuthCredential>;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction saveAuth(auth: Record<string, OAuthCredential>): void {\n\twriteFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), \"utf-8\");\n}\n\nasync function answerPrompt(rl: ReturnType<typeof createInterface>, authPrompt: AuthPrompt): Promise<string> {\n\tif (authPrompt.type === \"select\") {\n\t\tconsole.log(`\\n${authPrompt.message}`);\n\t\tfor (let index = 0; index < authPrompt.options.length; index++) {\n\t\t\tconsole.log(` ${index + 1}. ${authPrompt.options[index].label}`);\n\t\t}\n\t\tconst choice = Number.parseInt(await prompt(rl, `Enter number (1-${authPrompt.options.length}): `), 10) - 1;\n\t\tconst selected = authPrompt.options[choice];\n\t\tif (!selected) throw new Error(\"Invalid selection\");\n\t\treturn selected.id;\n\t}\n\treturn prompt(rl, `${authPrompt.message}${authPrompt.placeholder ? ` (${authPrompt.placeholder})` : \"\"}: `);\n}\n\nasync function login(providerId: string): Promise<void> {\n\tconst provider = PROVIDERS.find((entry) => entry.id === providerId);\n\tif (!provider) throw new Error(`Unknown provider: ${providerId}`);\n\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\ttry {\n\t\tconst credential = await provider.auth.oauth.login(\n\t\t\t{\n\t\t\t\tsignal: new AbortController().signal,\n\t\t\t\tprompt: (authPrompt) => answerPrompt(rl, authPrompt),\n\t\t\t\tnotify: (event) => {\n\t\t\t\t\tswitch (event.type) {\n\t\t\t\t\t\tcase \"auth_url\":\n\t\t\t\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${event.url}`);\n\t\t\t\t\t\t\tif (event.instructions) console.log(event.instructions);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"device_code\":\n\t\t\t\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${event.verificationUri}`);\n\t\t\t\t\t\t\tconsole.log(`Enter code: ${event.userCode}`);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"info\":\n\t\t\t\t\t\tcase \"progress\":\n\t\t\t\t\t\t\tconsole.log(event.message);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ getDeviceId: randomUUID },\n\t\t);\n\t\tconst auth = loadAuth();\n\t\tauth[providerId] = credential;\n\t\tsaveAuth(auth);\n\t\tconsole.log(`\\nCredentials saved to ${AUTH_FILE}`);\n\t} finally {\n\t\trl.close();\n\t}\n}\n\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\tconst command = args[0];\n\tif (!command || command === \"help\" || command === \"--help\" || command === \"-h\") {\n\t\tconst providerList = PROVIDERS.map((provider) => ` ${provider.id.padEnd(20)} ${provider.name}`).join(\"\\n\");\n\t\tconsole.log(\n\t\t\t`Usage: npx @bastani/pi-ai <command> [provider]\\n\\nCommands:\\n login [provider] Login to an OAuth provider\\n list List available providers\\n\\nProviders:\\n${providerList}`,\n\t\t);\n\t\treturn;\n\t}\n\tif (command === \"list\") {\n\t\tfor (const provider of PROVIDERS) console.log(`${provider.id.padEnd(20)} ${provider.name}`);\n\t\treturn;\n\t}\n\tif (command === \"login\") {\n\t\tlet providerId = args[1];\n\t\tif (!providerId) {\n\t\t\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\t\t\ttry {\n\t\t\t\tfor (let index = 0; index < PROVIDERS.length; index++) {\n\t\t\t\t\tconsole.log(` ${index + 1}. ${PROVIDERS[index].name}`);\n\t\t\t\t}\n\t\t\t\tconst index = Number.parseInt(await prompt(rl, `Enter number (1-${PROVIDERS.length}): `), 10) - 1;\n\t\t\t\tproviderId = PROVIDERS[index]?.id;\n\t\t\t} finally {\n\t\t\t\trl.close();\n\t\t\t}\n\t\t}\n\t\tif (!providerId || !PROVIDERS.some((provider) => provider.id === providerId)) {\n\t\t\tthrow new Error(`Unknown provider: ${providerId ?? \"\"}`);\n\t\t}\n\t\tawait login(providerId);\n\t\treturn;\n\t}\n\tthrow new Error(`Unknown command: ${command}`);\n}\n\nmain().catch((error: unknown) => {\n\tconsole.error(\"Error:\", error instanceof Error ? error.message : String(error));\n\tprocess.exit(1);\n});\n"]}
1
+ {"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":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AC,KAAK,SAAS,CAAC,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;gBACzD,CAAC;gBACD,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,MAAM,CAAC,EAAE,EAAE,mBAAmB,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;gBAClG,UAAU,GAAG,SAAS,CAAC,KAAK,CAAC,EAAE,EAAE,CAAC;YACnC,CAAC;oBAAS,CAAC;gBACV,EAAE,CAAC,KAAK,EAAE,CAAC;YACZ,CAAC;QACF,CAAC;QACD,IAAI,CAAC,UAAU,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,KAAK,UAAU,CAAC,EAAE,CAAC;YAC9E,MAAM,IAAI,KAAK,CAAC,qBAAqB,UAAU,IAAI,EAAE,EAAE,CAAC,CAAC;QAC1D,CAAC;QACD,MAAM,KAAK,CAAC,UAAU,CAAC,CAAC;QACxB,OAAO;IACR,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,oBAAoB,OAAO,EAAE,CAAC,CAAC;AAChD,CAAC;AAED,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;IAC/B,OAAO,CAAC,KAAK,CAAC,QAAQ,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IAChF,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACjB,CAAC,CAAC,CAAC","sourcesContent":["#!/usr/bin/env node\n\nimport { randomUUID } from \"node:crypto\";\nimport { chmodSync, existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { createInterface } from \"node:readline\";\nimport type { AuthPrompt, OAuthCredential, Provider } from \"./index.ts\";\nimport { builtinProviders } from \"./providers/all.ts\";\n\nconst AUTH_FILE = \"auth.json\";\nconst PROVIDERS = builtinProviders().filter(\n\t(provider): provider is Provider & { auth: { oauth: NonNullable<Provider[\"auth\"][\"oauth\"]> } } =>\n\t\tprovider.auth.oauth !== undefined,\n);\n\nfunction prompt(rl: ReturnType<typeof createInterface>, question: string): Promise<string> {\n\treturn new Promise((resolve) => rl.question(question, resolve));\n}\n\nfunction loadAuth(): Record<string, OAuthCredential> {\n\tif (!existsSync(AUTH_FILE)) return {};\n\ttry {\n\t\treturn JSON.parse(readFileSync(AUTH_FILE, \"utf-8\")) as Record<string, OAuthCredential>;\n\t} catch {\n\t\treturn {};\n\t}\n}\n\nfunction saveAuth(auth: Record<string, OAuthCredential>): void {\n\t// OAuth tokens: readable by the user only. `mode` applies when the file is created; chmod covers a file an older\n\t// version created, before the new tokens are in it.\n\tif (existsSync(AUTH_FILE)) chmodSync(AUTH_FILE, 0o600);\n\twriteFileSync(AUTH_FILE, JSON.stringify(auth, null, 2), { encoding: \"utf-8\", mode: 0o600 });\n}\n\nasync function answerPrompt(rl: ReturnType<typeof createInterface>, authPrompt: AuthPrompt): Promise<string> {\n\tif (authPrompt.type === \"select\") {\n\t\tconsole.log(`\\n${authPrompt.message}`);\n\t\tfor (let index = 0; index < authPrompt.options.length; index++) {\n\t\t\tconsole.log(` ${index + 1}. ${authPrompt.options[index].label}`);\n\t\t}\n\t\tconst choice = Number.parseInt(await prompt(rl, `Enter number (1-${authPrompt.options.length}): `), 10) - 1;\n\t\tconst selected = authPrompt.options[choice];\n\t\tif (!selected) throw new Error(\"Invalid selection\");\n\t\treturn selected.id;\n\t}\n\treturn prompt(rl, `${authPrompt.message}${authPrompt.placeholder ? ` (${authPrompt.placeholder})` : \"\"}: `);\n}\n\nasync function login(providerId: string): Promise<void> {\n\tconst provider = PROVIDERS.find((entry) => entry.id === providerId);\n\tif (!provider) throw new Error(`Unknown provider: ${providerId}`);\n\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\ttry {\n\t\tconst credential = await provider.auth.oauth.login(\n\t\t\t{\n\t\t\t\tsignal: new AbortController().signal,\n\t\t\t\tprompt: (authPrompt) => answerPrompt(rl, authPrompt),\n\t\t\t\tnotify: (event) => {\n\t\t\t\t\tswitch (event.type) {\n\t\t\t\t\t\tcase \"auth_url\":\n\t\t\t\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${event.url}`);\n\t\t\t\t\t\t\tif (event.instructions) console.log(event.instructions);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"device_code\":\n\t\t\t\t\t\t\tconsole.log(`\\nOpen this URL in your browser:\\n${event.verificationUri}`);\n\t\t\t\t\t\t\tconsole.log(`Enter code: ${event.userCode}`);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"info\":\n\t\t\t\t\t\tcase \"progress\":\n\t\t\t\t\t\t\tconsole.log(event.message);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{ getDeviceId: randomUUID },\n\t\t);\n\t\tconst auth = loadAuth();\n\t\tauth[providerId] = credential;\n\t\tsaveAuth(auth);\n\t\tconsole.log(`\\nCredentials saved to ${AUTH_FILE}`);\n\t} finally {\n\t\trl.close();\n\t}\n}\n\nasync function main(): Promise<void> {\n\tconst args = process.argv.slice(2);\n\tconst command = args[0];\n\tif (!command || command === \"help\" || command === \"--help\" || command === \"-h\") {\n\t\tconst providerList = PROVIDERS.map((provider) => ` ${provider.id.padEnd(20)} ${provider.name}`).join(\"\\n\");\n\t\tconsole.log(\n\t\t\t`Usage: npx @bastani/pi-ai <command> [provider]\\n\\nCommands:\\n login [provider] Login to an OAuth provider\\n list List available providers\\n\\nProviders:\\n${providerList}`,\n\t\t);\n\t\treturn;\n\t}\n\tif (command === \"list\") {\n\t\tfor (const provider of PROVIDERS) console.log(`${provider.id.padEnd(20)} ${provider.name}`);\n\t\treturn;\n\t}\n\tif (command === \"login\") {\n\t\tlet providerId = args[1];\n\t\tif (!providerId) {\n\t\t\tconst rl = createInterface({ input: process.stdin, output: process.stdout });\n\t\t\ttry {\n\t\t\t\tfor (let index = 0; index < PROVIDERS.length; index++) {\n\t\t\t\t\tconsole.log(` ${index + 1}. ${PROVIDERS[index].name}`);\n\t\t\t\t}\n\t\t\t\tconst index = Number.parseInt(await prompt(rl, `Enter number (1-${PROVIDERS.length}): `), 10) - 1;\n\t\t\t\tproviderId = PROVIDERS[index]?.id;\n\t\t\t} finally {\n\t\t\t\trl.close();\n\t\t\t}\n\t\t}\n\t\tif (!providerId || !PROVIDERS.some((provider) => provider.id === providerId)) {\n\t\t\tthrow new Error(`Unknown provider: ${providerId ?? \"\"}`);\n\t\t}\n\t\tawait login(providerId);\n\t\treturn;\n\t}\n\tthrow new Error(`Unknown command: ${command}`);\n}\n\nmain().catch((error: unknown) => {\n\tconsole.error(\"Error:\", error instanceof Error ? error.message : String(error));\n\tprocess.exit(1);\n});\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"models.d.ts","sourceRoot":"","sources":["../src/models.ts"],"names":[],"mappings":"AAGA,OAAO,EACN,KAAK,uBAAuB,EAK5B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EACX,SAAS,EACT,WAAW,EACX,eAAe,EACf,oBAAoB,EACpB,UAAU,EACV,QAAQ,EACR,UAAU,EACV,eAAe,EACf,YAAY,EACZ,YAAY,EACZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAuB,KAAK,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAEjG,OAAO,KAAK,EACX,QAAQ,EACR,GAAG,EACH,gBAAgB,EAChB,eAAe,EACf,gBAAgB,EAChB,2BAA2B,EAC3B,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,iBAAiB,EACjB,gBAAgB,EAChB,cAAc,EACd,OAAO,EACP,qBAAqB,EACrB,oBAAoB,EACpB,cAAc,EACd,QAAQ,EACR,eAAe,EACf,UAAU,EACV,aAAa,EACb,aAAa,EACb,K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