From fb16ebb6f67538bf847f6ad16b0b3c1e73dc8740 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Thu, 16 Jul 2026 22:56:56 +0500 Subject: [PATCH 01/17] feat(aimlapi): harden guided onboarding and top-up --- README.md | 2 +- docs/aimlapi-setup.md | 44 +- src/cli/handlers/aimlapi.ts | 9 +- src/components/ConsoleOAuthFlow.test.tsx | 2 +- src/components/ProviderManager.test.tsx | 579 +++++++- src/components/ProviderManager.tsx | 1187 +++++++++++++---- src/integrations/aimlapi/client.test.ts | 157 +++ src/integrations/aimlapi/client.ts | 273 ++-- src/integrations/aimlapi/config.test.ts | 79 ++ src/integrations/aimlapi/config.ts | 78 +- src/integrations/aimlapi/index.ts | 12 + src/integrations/aimlapi/messages.ts | 28 + src/integrations/aimlapi/onboarding.test.ts | 115 ++ src/integrations/aimlapi/onboarding.ts | 70 + src/integrations/aimlapi/prompt.ts | 34 +- src/integrations/aimlapi/topup.test.ts | 373 ++++++ src/integrations/aimlapi/topup.ts | 643 +++++---- src/integrations/aimlapi/validation.ts | 32 + src/integrations/artifactGenerator.test.ts | 19 + src/integrations/artifactGenerator.ts | 11 +- src/integrations/discoveryService.test.ts | 19 +- src/integrations/gateways/aimlapi.ts | 22 +- .../integrationManifest.generated.ts | 36 +- src/integrations/routeMetadata.test.ts | 4 +- src/integrations/runtimeMetadata.test.ts | 29 + src/integrations/runtimeMetadata.ts | 44 +- src/main.tsx | 13 +- src/services/api/client.test.ts | 2 +- src/utils/providerDiscovery.test.ts | 2 +- src/utils/providerProfiles.test.ts | 24 +- src/utils/providerProfiles.ts | 8 +- src/utils/status.test.ts | 2 +- 32 files changed, 3207 insertions(+), 745 deletions(-) create mode 100644 src/integrations/aimlapi/client.test.ts create mode 100644 src/integrations/aimlapi/config.test.ts create mode 100644 src/integrations/aimlapi/messages.ts create mode 100644 src/integrations/aimlapi/onboarding.test.ts create mode 100644 src/integrations/aimlapi/onboarding.ts create mode 100644 src/integrations/aimlapi/topup.test.ts create mode 100644 src/integrations/aimlapi/validation.ts diff --git a/README.md b/README.md index 98e5211d23..ade48325d9 100644 --- a/README.md +++ b/README.md @@ -307,7 +307,7 @@ OpenClaude supports multiple providers, but behavior is not identical across all - Tool quality depends heavily on the selected model - Smaller local models can struggle with long multi-step tool flows - Some providers impose lower output caps than the CLI defaults, and OpenClaude adapts where possible -- AI/ML API uses the OpenAI-compatible route, defaults to `gpt-4o`, and only surfaces chat-capable models from its public catalog +- AI/ML API uses the OpenAI-compatible route, defaults to `anthropic/claude-sonnet-5`, supports passwordless guided onboarding/top-up, and only surfaces chat-capable models from its public catalog - Gitlawb Opengateway is the fresh-install startup default and requires an API key from https://gitlawb.com/opengateway/keys. It uses one OpenAI-compatible base URL; switch between `mimo-*` and `google/gemini-3.1-flash-lite-preview` with `/model`, and do not pin the base URL to `/v1/xiaomi-mimo`. - Z.AI GLM Coding Plan uses `https://api.z.ai/api/coding/paas/v4` with `glm-5.2` by default. Use `glm-5.2?reasoning=high` for enhanced reasoning, `glm-5.2?reasoning=xhigh` to request Z.AI `reasoning_effort=max`, or `glm-5.2?thinking=disabled` for faster direct answers. - Xiaomi MiMo uses `api-key` header auth on the direct OpenAI-compatible route and currently does not support `/usage` reporting in OpenClaude diff --git a/docs/aimlapi-setup.md b/docs/aimlapi-setup.md index 06af0de0fc..c0efc93124 100644 --- a/docs/aimlapi-setup.md +++ b/docs/aimlapi-setup.md @@ -4,41 +4,49 @@ OpenClaude connects to [AI/ML API](https://aimlapi.com) through its OpenAI-compa ## Overview -AI/ML API is an aggregating gateway that exposes many chat models behind a single OpenAI-compatible API. OpenClaude ships a first-class `AI/ML API` provider preset: it stores credentials under `AIMLAPI_API_KEY`, sends the OpenClaude attribution headers, and discovers chat-capable models from the public `/models` catalog. It defaults to `gpt-4o`. +AI/ML API is an aggregating gateway that exposes many chat models behind a single OpenAI-compatible API. OpenClaude ships a first-class `AI/ML API` provider preset: it uses `AIMLAPI_API_KEY`, sends the OpenClaude attribution headers, and discovers chat-capable models from the public `/models` catalog. It defaults to `anthropic/claude-sonnet-5`. ## Prerequisites -None. You don't need to visit first — the guided top-up flow below can create an AI/ML API account and issue a key for you. If you already have a key from the dashboard, you can paste it directly instead. +None. You do not need to visit first - the guided top-up flow can create an account and issue a key. If you already have a dashboard key or set `AIMLAPI_API_KEY`, OpenClaude can use that credential instead. -## Option 1 — Interactive (`/provider`) +## Option 1 - Interactive (`/provider`) 1. Start OpenClaude and run `/provider`. -2. Choose **AI/ML API**, then confirm the default model (Step 1 of 2). -3. Step 2 of 2 — choose how to get an API key: - - **Top up and get API key** — enter your AI/ML API email and password (an account is created automatically if you don't have one yet), pick a top-up amount ($20–$10,000) and payment method (card or crypto), complete payment in the browser, and OpenClaude saves the issued key for you. - - **Enter existing API key** — paste a key you already have from the AI/ML API dashboard. +2. Choose **AI/ML API**. +3. If AI/ML API is already configured, choose one of: + - **Use existing configuration** - validate the saved key or `AIMLAPI_API_KEY`, check its balance, optionally top up a low balance, then choose a model. + - **Configure again** - enter the normal new-user or existing-key flow. +4. Otherwise choose how to get an API key: + - **I am a new user** - enter your email. OpenClaude creates a passwordless account, lets you pick a top-up amount and automatic top-up preference, opens card checkout, then saves the issued key. + - **I already have an AI/ML API key** - paste a key from the dashboard. OpenClaude validates it, checks its balance, and offers an optional API-key top-up when the balance is low. -Either way, the base URL (`https://api.aimlapi.com/v1`) and default model (`gpt-4o`) are filled in automatically. +For an email that already has an account, AI/ML API sends a 6-digit sign-in code. OpenClaude creates a new API key for that account, checks its balance, and only offers checkout when the balance is low. You can top up or save the key and skip funding for now. -Switch models any time with `/model` — only chat-capable models from the AI/ML API catalog are listed. +When `AIMLAPI_API_KEY` supplies the credential, OpenClaude uses its runtime value for validation and balance checks but saves an empty credential in the provider profile. The literal environment value is not copied into configuration. -## Option 2 — CLI (`openclaude aimlapi topup`) +Checkout progress is retained while the provider flow remains open. Retrying an ambiguous payment or exchange failure resumes the original partner session instead of creating a second checkout. -Run the same guided top-up flow non-interactively: +The base URL (`https://api.aimlapi.com/v1`) and default model (`anthropic/claude-sonnet-5`) are filled in automatically. Switch models any time with `/model`; only chat-capable models from the AI/ML API catalog are listed. + +## Option 2 - CLI (`openclaude aimlapi topup`) + +Run the guided account top-up flow from the CLI: ```bash -openclaude aimlapi topup --email you@example.com --amount 25 --method card +openclaude aimlapi topup --email you@example.com --amount 25 ``` -- Credentials: pass `--email` (or set `AIMLAPI_EMAIL`) and set `AIMLAPI_PASSWORD`; if either is missing you're prompted interactively (password entry is hidden). +- Pass `--email` (or set `AIMLAPI_EMAIL`). Existing accounts also need the emailed `--code` (or `AIMLAPI_CODE`); interactive terminals prompt for missing values. - `--amount`: top-up amount in USD (min 20, max 10000; defaults to 25). -- `--method`: `card` (Stripe, default) or `crypto` (NOWPayments). -- `--model`: default model id written into the provider profile (defaults to `gpt-4o`). +- Checkout always uses card payment; there is no separate payment-method step. +- `--auto-top-up`: enroll the account in automatic top-up at checkout. +- `--model`: default model id written into the provider profile (defaults to `anthropic/claude-sonnet-5`). - `--no-open`: print the payment URL instead of auto-opening a browser. The issued key is written into OpenClaude's provider profile automatically once payment clears. -## Option 3 — Environment variables +## Option 3 - Environment variables Setting `AIMLAPI_API_KEY` alone is enough; OpenClaude auto-detects the AI/ML API route: @@ -52,7 +60,7 @@ To configure the OpenAI-compatible route explicitly: export CLAUDE_CODE_USE_OPENAI=1 export AIMLAPI_API_KEY="your-aimlapi-key" export OPENAI_BASE_URL="https://api.aimlapi.com/v1" -export OPENAI_MODEL="gpt-4o" +export OPENAI_MODEL="anthropic/claude-sonnet-5" ``` `OPENAI_API_KEY` also works as a fallback credential for the route. @@ -67,4 +75,6 @@ export OPENAI_MODEL="gpt-4o" - Model discovery uses the public, unauthenticated `GET /models` endpoint and surfaces only chat-completions models; image, audio, embeddings, and other modalities are intentionally not routed through the coding workflow. - Requests carry `X-AIMLAPI-Integration-*` attribution headers (owner/repo/version) plus the `HTTP-Referer: OpenClaude` and `X-Title: OpenClaude` headers that AI/ML API uses to attribute integration traffic. +- `AIMLAPI_AUTH_URL`, `AIMLAPI_APP_URL`, `AIMLAPI_PAY_URL`, `AIMLAPI_INFERENCE_URL`, and `AIMLAPI_VERIFICATION_BASE_URL` can point the complete flow at another environment. `AIMLAPI_RETURN_URL` overrides only the browser landing page. +- Checkout success is detected by polling. The browser return target is an HTTPS page; OpenClaude does not install a custom URL-scheme handler. - Usage (`/usage`) reporting is not supported for this provider. diff --git a/src/cli/handlers/aimlapi.ts b/src/cli/handlers/aimlapi.ts index ac8e5f7c61..b6cc75ddb0 100644 --- a/src/cli/handlers/aimlapi.ts +++ b/src/cli/handlers/aimlapi.ts @@ -1,6 +1,7 @@ /* eslint-disable custom-rules/no-process-exit -- CLI subcommand handler intentionally exits */ import chalk from 'chalk' +import { redactSensitiveInfo } from '../../utils/redaction.js' import { AimlapiApiError } from '../../integrations/aimlapi/client.js' import { @@ -13,12 +14,14 @@ export async function aimlapiTopup(options: AimlapiTopupOptions): Promise await runAimlapiTopup(options) } catch (error) { if (error instanceof AimlapiApiError) { - console.error(chalk.red(`\n ✗ ${error.message}`)) + console.error(chalk.red(`\n ✗ ${redactSensitiveInfo(error.message)}`)) if (error.body) { - console.error(chalk.dim(` ${error.body}`)) + console.error(chalk.dim(` ${redactSensitiveInfo(error.body)}`)) } } else { - const message = error instanceof Error ? error.message : String(error) + const message = redactSensitiveInfo( + error instanceof Error ? error.message : String(error), + ) console.error(chalk.red(`\n ✗ ${message}`)) } process.exit(1) diff --git a/src/components/ConsoleOAuthFlow.test.tsx b/src/components/ConsoleOAuthFlow.test.tsx index 11b493e81d..d81a1fb9d9 100644 --- a/src/components/ConsoleOAuthFlow.test.tsx +++ b/src/components/ConsoleOAuthFlow.test.tsx @@ -135,7 +135,7 @@ test('third-party provider branch opens the first-run provider manager', async ( expect(output).toContain('Set up provider') // Keep the sentinels near the top of the preset list so adding another // provider does not push the assertion outside the 13-row test frame. - expect(output).toContain('AI/ML API') + expect(output).toContain('aimlapi.com') expect(output).toContain('Anthropic') expect(output).toContain('Azure OpenAI') expect(output).toContain('DeepSeek') diff --git a/src/components/ProviderManager.test.tsx b/src/components/ProviderManager.test.tsx index 9d108b5651..6e55148f1a 100644 --- a/src/components/ProviderManager.test.tsx +++ b/src/components/ProviderManager.test.tsx @@ -7,6 +7,7 @@ import { stripVTControlCharacters as stripAnsi } from 'node:util' import { createRoot } from '../ink.js' import { KeybindingSetup } from '../keybindings/KeybindingProviderSetup.js' import { AppStateProvider } from '../state/AppState.js' +import { AIMLAPI_MESSAGES } from '../integrations/aimlapi/messages.js' import { acquireSharedMutationLock, releaseSharedMutationLock, @@ -31,7 +32,9 @@ const ORIGINAL_ENV = { GITHUB_TOKEN: process.env.GITHUB_TOKEN, GH_TOKEN: process.env.GH_TOKEN, AIMLAPI_EMAIL: process.env.AIMLAPI_EMAIL, - AIMLAPI_PASSWORD: process.env.AIMLAPI_PASSWORD, + AIMLAPI_CODE: process.env.AIMLAPI_CODE, + AIMLAPI_API_KEY: process.env.AIMLAPI_API_KEY, + AIMLAPI_INFERENCE_URL: process.env.AIMLAPI_INFERENCE_URL, } function extractLastFrame(output: string): string { @@ -114,8 +117,8 @@ async function waitForCondition( } // Provider list is sorted from generated preset metadata by description, with -// Gitlawb Opengateway pinned first, Anthropic second, Codex OAuth injected -// after DeepSeek, and the custom endpoints always pinned last. Keep the target-by-label +// Gitlawb Opengateway pinned first, aimlapi.com second, Anthropic third, Codex OAuth injected +// after DeepSeek, and Custom always pinned last. Keep the target-by-label // indirection here so // these tests survive future list edits without hardcoding raw key counts. // @@ -123,8 +126,8 @@ async function waitForCondition( // canUseCodexOAuth === true (default in mocked tests). const PRESET_ORDER = [ 'Gitlawb Opengateway', + 'aimlapi.com', 'Anthropic', - 'AI/ML API', 'Alibaba Coding Plan (China)', 'Alibaba Coding Plan', 'Atlas Cloud', @@ -267,9 +270,9 @@ function mockProviderProfilesModule(options?: { if (preset === 'aimlapi') { return { provider: 'aimlapi', - name: 'AI/ML API', + name: 'aimlapi.com', baseUrl: 'https://api.aimlapi.com/v1', - model: 'gpt-4o', + model: 'anthropic/claude-sonnet-5', apiKey: '', requiresApiKey: true, } @@ -345,6 +348,10 @@ function mockProviderManagerDependencies( updateProviderProfile?: (...args: any[]) => unknown setActiveProviderProfile?: (...args: any[]) => unknown provisionAimlapiKey?: (...args: any[]) => Promise + topUpAimlapiByApiKey?: (...args: any[]) => Promise + beginAimlapiEmailOnboarding?: (...args: any[]) => Promise + completeAimlapiCodeSignIn?: (...args: any[]) => Promise + validateAimlapiApiKey?: (...args: any[]) => Promise useCodexOAuthFlow?: (options: { onAuthenticated: ( tokens: { @@ -460,11 +467,48 @@ function mockProviderManagerDependencies( })) mock.module('../integrations/aimlapi/index.js', () => ({ + AIMLAPI_MESSAGES, + AimlapiApiError: class AimlapiApiError extends Error { + constructor( + message: string, + readonly status: number, + readonly body = '', + ) { + super(message) + } + }, + beginAimlapiEmailOnboarding: + options?.beginAimlapiEmailOnboarding ?? + (async () => ({ action: 'new-account', sessionToken: 'session_test' })), + completeAimlapiCodeSignIn: + options?.completeAimlapiCodeSignIn ?? + (async () => ({ + sessionToken: 'session_test', + apiKey: 'issued_test', + apiKeyId: 'key_test', + lowBalance: false, + })), + validateAimlapiApiKey: + options?.validateAimlapiApiKey ?? + (async () => ({ balance: 25, lowBalance: false, lowBalanceThreshold: 20 })), + parseAimlapiAmountUsd: (value: string | undefined) => { + const amount = Number(value || 25) + if (!Number.isFinite(amount) || amount < 20 || amount > 10000) { + throw new Error('Invalid top-up amount.') + } + return Math.round(amount * 100) + }, + isValidAimlapiEmail: (value: string) => /^[^\s@]+@[^\s@]+\.[A-Za-z]{2,}$/.test(value), provisionAimlapiKey: options?.provisionAimlapiKey ?? (async () => { throw new Error('Unexpected AI/ML API top-up in test') }), + topUpAimlapiByApiKey: + options?.topUpAimlapiByApiKey ?? + (async () => { + throw new Error('Unexpected AI/ML API by-key top-up in test') + }), })) mock.module('./useCodexOAuthFlow.js', () => ({ @@ -926,9 +970,15 @@ test('ProviderManager saves AI/ML API preset with OpenAI-compatible defaults', a id: 'aimlapi_profile', ...payload, })) + const validateAimlapiApiKey = mock(async () => ({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + })) mockProviderManagerDependencies(() => undefined, async () => undefined, { addProviderProfile, + validateAimlapiApiKey, }) const nonce = `${Date.now()}-${Math.random()}` @@ -945,43 +995,61 @@ test('ProviderManager saves AI/ML API preset with OpenAI-compatible defaults', a frame.includes('Choose provider preset'), ) - await navigateToPreset(mounted.stdin, 'AI/ML API') + await navigateToPreset(mounted.stdin, 'aimlapi.com') mounted.stdin.write('\r') const modelOutput = await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Create provider profile') && frame.includes('Step 1 of 2: Default model'), ) - expect(modelOutput).toContain('AI/ML API') - expect(modelOutput).toContain('gpt-4o') + expect(modelOutput).toContain('aimlapi.com') + expect(modelOutput).toContain('anthropic/claude-sonnet-5') expect(modelOutput).not.toContain('Provider name') expect(modelOutput).not.toContain('Base URL') mounted.stdin.write('\r') const choiceOutput = await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Step 2 of 2: API key'), + frame.includes('Do you have aimlapi.com key?'), ) - expect(choiceOutput).toContain('Top up and get API key') - expect(choiceOutput).toContain('Enter existing API key') + expect(choiceOutput).toContain('I am a new user') + expect(choiceOutput).toContain('I already have aimlapi.com key') + expect(choiceOutput).not.toContain('One click set up') + expect(choiceOutput).not.toContain('Proceed to paste the key') mounted.stdin.write('j') await Bun.sleep(25) mounted.stdin.write('\r') - await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Enter the API key for AI/ML API'), + const apiKeyOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Enter your aimlapi.com key.'), + ) + expect(apiKeyOutput).toContain( + 'Your API key will be hidden and verified automatically.', ) + expect(apiKeyOutput).toContain('API key:') + expect(apiKeyOutput).not.toContain('Create provider profile') + expect(apiKeyOutput).not.toContain('Provider type:') + expect(apiKeyOutput).not.toContain('Step 2 of 2: API key') mounted.stdin.write('aimlapi-test-key') await Bun.sleep(25) mounted.stdin.write('\r') await waitForCondition(() => addProviderProfile.mock.calls.length > 0) + expect(validateAimlapiApiKey).toHaveBeenCalledWith( + 'aimlapi-test-key', + expect.any(AbortSignal), + 'https://api.aimlapi.com/v1', + ) + const doneOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Everything is ready.'), + ) + expect(doneOutput).toContain('Press Enter to continue.') expect(addProviderProfile).toHaveBeenCalledWith( expect.objectContaining({ provider: 'aimlapi', - name: 'AI/ML API', + name: 'aimlapi.com', baseUrl: 'https://api.aimlapi.com/v1', - model: 'gpt-4o', + model: 'anthropic/claude-sonnet-5', apiKey: 'aimlapi-test-key', apiFormat: 'chat_completions', }), @@ -992,24 +1060,433 @@ test('ProviderManager saves AI/ML API preset with OpenAI-compatible defaults', a } }) +test('ProviderManager offers and reuses an existing AIMLAPI profile', async () => { + delete process.env.AIMLAPI_API_KEY + const profile = { + id: 'aimlapi_existing', + provider: 'aimlapi', + name: 'aimlapi.com', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'old-model', + apiKey: 'saved-key', + apiFormat: 'chat_completions', + } + const updateProviderProfile = mock((id: string, payload: any) => ({ + id, + ...payload, + })) + const validateAimlapiApiKey = mock(async () => ({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + getProviderProfiles: () => [profile], + getActiveProviderProfile: () => profile, + updateProviderProfile, + validateAimlapiApiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + const configured = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('aimlapi.com account is already configured'), + ) + expect(configured).toContain('Continue with your saved API key') + expect(configured).toContain('Set up a new key or switch account') + expect(configured).not.toContain('Use existing configuration') + expect(configured).not.toContain('Configure again') + + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + expect(validateAimlapiApiKey).toHaveBeenCalledWith( + 'saved-key', + expect.any(AbortSignal), + 'https://api.aimlapi.com/v1', + ) + mounted.stdin.write('\r') + await waitForCondition(() => updateProviderProfile.mock.calls.length > 0) + expect(updateProviderProfile).toHaveBeenCalledWith( + 'aimlapi_existing', + expect.objectContaining({ apiKey: 'saved-key' }), + ) + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager first run keeps AIMLAPI_API_KEY out of the saved profile', async () => { + process.env.AIMLAPI_API_KEY = 'env-runtime-key' + process.env.AIMLAPI_INFERENCE_URL = 'https://proxy.example.test/v1' + const addProviderProfile = mock((payload: any) => ({ + id: 'aimlapi_env', + ...payload, + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + addProviderProfile, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager, { mode: 'first-run' }) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Set up provider')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + mounted.stdin.write('\r') + await waitForCondition(() => addProviderProfile.mock.calls.length > 0) + expect(addProviderProfile).toHaveBeenCalledWith( + expect.objectContaining({ + provider: 'aimlapi', + baseUrl: 'https://proxy.example.test/v1', + apiKey: '', + }), + expect.objectContaining({ makeActive: true }), + ) + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager rejects an invalid AIMLAPI key using the Zero error copy', async () => { + const addProviderProfile = mock(() => null) + const validateAimlapiApiKey = mock(async () => { + throw Object.assign(new Error('Unauthorized'), { status: 401 }) + }) + + mockProviderManagerDependencies(() => undefined, async () => undefined, { + addProviderProfile, + validateAimlapiApiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + + try { + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Provider manager'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Choose provider preset'), + ) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Step 1 of 2: Default model'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Do you have aimlapi.com key?'), + ) + mounted.stdin.write('j') + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Enter your aimlapi.com key.'), + ) + + mounted.stdin.write('bad-aimlapi-key') + await Bun.sleep(25) + mounted.stdin.write('\r') + + const invalidOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes( + 'API key is invalid. Please make sure you enter a valid aimlapi.com key.', + ), + ) + expect(invalidOutput).toContain('Enter your aimlapi.com key.') + expect(validateAimlapiApiKey).toHaveBeenCalledWith( + 'bad-aimlapi-key', + expect.any(AbortSignal), + 'https://api.aimlapi.com/v1', + ) + expect(addProviderProfile).not.toHaveBeenCalled() + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager matches the AIMLAPI code and low-credit screen copy', async () => { + const beginAimlapiEmailOnboarding = mock(async () => ({ action: 'code-sent' as const })) + const completeAimlapiCodeSignIn = mock(async () => ({ + sessionToken: 'session_test', + apiKey: 'issued_test', + apiKeyId: 'key_test', + lowBalance: true, + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + beginAimlapiEmailOnboarding, + completeAimlapiCodeSignIn, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Provider manager'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Choose provider preset'), + ) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Step 1 of 2: Default model'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Do you have aimlapi.com key?'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Enter your email.'), + ) + mounted.stdin.write('stan@aimlapi.com') + await Bun.sleep(25) + mounted.stdin.write('\r') + + const codeOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Enter the 6-digit code sent to stan@aimlapi.com.'), + ) + expect(codeOutput).not.toContain('Enter it below to continue.') + expect(codeOutput).not.toContain('We sent a 6-digit code') + mounted.stdin.write('123456') + await Bun.sleep(25) + mounted.stdin.write('\r') + + const lowCreditOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Your aimlapi.com credits are running low - top up now?'), + ) + expect(lowCreditOutput).toContain("Sure, let's do that") + expect(lowCreditOutput).toContain("I'll skip for now") + expect(lowCreditOutput).not.toContain( + 'It is recommended to top up your balance.', + ) + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager rejects an empty AIMLAPI top-up amount instead of charging the default', async () => { + delete process.env.AIMLAPI_EMAIL + const provisionAimlapiKey = mock(async () => ({ + apiKey: 'unexpected', + apiKeyId: 'unexpected', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'anthropic/claude-sonnet-5', + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + provisionAimlapiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Step 1 of 2: Default model')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('I am a new user')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Enter your email.')) + mounted.stdin.write('user@example.com') + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Add credits')) + + mounted.stdin.write('\x7f\x7f') + await Bun.sleep(25) + mounted.stdin.write('\r') + const output = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Please enter a top-up amount.'), + ) + expect(output).toContain('Please enter a top-up amount.') + expect(provisionAimlapiKey).not.toHaveBeenCalled() + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager drops a retained checkout when the onboarding email changes', async () => { + delete process.env.AIMLAPI_EMAIL + const addProviderProfile = mock((payload: any) => ({ id: 'aimlapi_profile', ...payload })) + let accountSequence = 0 + const beginAimlapiEmailOnboarding = mock(async () => ({ + action: 'new-account' as const, + sessionToken: `account-session-${++accountSequence}`, + })) + let provisionSequence = 0 + const provisionAimlapiKey = mock(async (options: any) => { + provisionSequence += 1 + if (provisionSequence === 1) { + options.onSession?.('checkout-for-first-account') + throw new Error('temporary checkout failure') + } + return { + apiKey: 'issued-for-second-account', + apiKeyId: 'key_second', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'anthropic/claude-sonnet-5', + } + }) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + addProviderProfile, + beginAimlapiEmailOnboarding, + provisionAimlapiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Step 1 of 2: Default model')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('I am a new user')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Enter your email.')) + const firstEmail = 'first@example.com' + mounted.stdin.write(firstEmail) + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Add credits')) + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForCondition(() => provisionAimlapiKey.mock.calls.length === 1) + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('temporary checkout failure')) + + mounted.stdin.write('\x1b') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Enter your email.')) + mounted.stdin.write('\x7f'.repeat(firstEmail.length)) + mounted.stdin.write('second@example.com') + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Add credits')) + mounted.stdin.write('\r') + await waitForCondition(() => provisionAimlapiKey.mock.calls.length === 2) + + const firstOptions = provisionAimlapiKey.mock.calls[0]?.[0] as any + const secondOptions = provisionAimlapiKey.mock.calls[1]?.[0] as any + expect(firstOptions.sessionToken).toBe('account-session-1') + expect(secondOptions.sessionToken).toBe('account-session-2') + expect(secondOptions.resumeSessionToken).toBe('') + expect(secondOptions.paymentSessionId).not.toBe(firstOptions.paymentSessionId) + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager cancellation returns a live checkout to the resumable amount screen', async () => { + delete process.env.AIMLAPI_EMAIL + let provisionSequence = 0 + const provisionAimlapiKey = mock(async (options: any) => { + provisionSequence += 1 + if (provisionSequence === 1) { + options.onSession?.('live-checkout') + await new Promise((_resolve, reject) => { + options.signal.addEventListener('abort', () => reject(options.signal.reason), { + once: true, + }) + }) + } + return { + apiKey: 'issued-after-resume', + apiKeyId: 'key_after_resume', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'anthropic/claude-sonnet-5', + } + }) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + provisionAimlapiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Step 1 of 2: Default model')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('I am a new user')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Enter your email.')) + mounted.stdin.write('user@example.com') + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Add credits')) + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForCondition(() => provisionAimlapiKey.mock.calls.length === 1) + + const firstOptions = provisionAimlapiKey.mock.calls[0]?.[0] as any + mounted.stdin.write('\x1b') + const amountOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Add credits'), + ) + expect(amountOutput).not.toContain('Do you have aimlapi.com key?') + expect(firstOptions.signal.aborted).toBe(true) + + await Bun.sleep(25) + mounted.stdin.write('\r') + await waitForCondition(() => provisionAimlapiKey.mock.calls.length === 2) + const secondOptions = provisionAimlapiKey.mock.calls[1]?.[0] as any + expect(secondOptions.resumeSessionToken).toBe('live-checkout') + expect(secondOptions.paymentSessionId).toBe(firstOptions.paymentSessionId) + } finally { + await mounted.dispose() + } +}) + test('ProviderManager can top up AI/ML API and save the issued key', async () => { delete process.env.AIMLAPI_EMAIL - delete process.env.AIMLAPI_PASSWORD + delete process.env.AIMLAPI_CODE const addProviderProfile = mock((payload: any) => ({ id: 'aimlapi_profile', ...payload, })) + const checkoutUrl = + 'https://checkout.stripe.com/c/pay/cs_test_1234567890#signed-checkout-fragment-that-must-remain-visible-across-terminal-lines-tail' const provisionAimlapiKey = mock(async (options: any) => { options.onStatus?.('creating-session') - options.onStatus?.('opening-checkout', 'https://app.aimlapi.com/checkout/test') + await Bun.sleep(150) + options.onStatus?.('opening-checkout', checkoutUrl) + await Bun.sleep(150) options.onStatus?.('waiting-payment') options.onStatus?.('provisioning-key') return { apiKey: 'aimlapi-issued-key', apiKeyId: 'key_test', baseUrl: 'https://api.aimlapi.com/v1', - model: 'gpt-4o', + model: 'anthropic/claude-sonnet-5', } }) @@ -1032,7 +1509,7 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => frame.includes('Choose provider preset'), ) - await navigateToPreset(mounted.stdin, 'AI/ML API') + await navigateToPreset(mounted.stdin, 'aimlapi.com') mounted.stdin.write('\r') await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Step 1 of 2: Default model'), @@ -1040,56 +1517,76 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => mounted.stdin.write('\r') await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Top up and get API key'), + frame.includes('I am a new user'), ) mounted.stdin.write('\r') await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Enter your AI/ML API account email'), + frame.includes('Enter your email.'), ) mounted.stdin.write('user@example.com') await Bun.sleep(25) mounted.stdin.write('\r') await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Enter your AI/ML API password'), + frame.includes('Add credits') && + frame.includes('Auto top up: on/off'), ) - mounted.stdin.write('secret-password') + await Bun.sleep(25) + mounted.stdin.write('\t') + await Bun.sleep(25) + mounted.stdin.write(' ') + await Bun.sleep(25) + mounted.stdin.write('\t') await Bun.sleep(25) mounted.stdin.write('\r') - await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Choose a top-up amount in USD') && - frame.includes('25'), + await waitForCondition(() => provisionAimlapiKey.mock.calls.length > 0) + const spinnerOutput = await waitForFrameOutput(mounted.getOutput, frame => + !frame.includes('Auto top up:') && + !frame.includes('Top-up successful -'), ) - mounted.stdin.write('\r') + expect(spinnerOutput).not.toContain('Creating checkout session...') + expect(spinnerOutput).not.toContain('Waiting for payment...') + expect(spinnerOutput).not.toContain('Issuing API key...') - await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Payment method') && - frame.includes('Card') && - frame.includes('Crypto'), + const paymentOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Opening checkout in browser...'), ) - mounted.stdin.write('j') - await Bun.sleep(25) - mounted.stdin.write('\r') + expect(paymentOutput).toContain( + 'If the browser did not open automatically please use this link to top up your account:', + ) + expect(paymentOutput).toContain('https://checkout.stripe.com/c/pay/cs_test_1234567890') + expect(paymentOutput.replace(/\s/g, '')).toContain(checkoutUrl) await waitForCondition(() => addProviderProfile.mock.calls.length > 0) + const doneOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Top-up successful - $25 credited to your account'), + ) + expect(doneOutput).not.toContain('has been added to your balance') + expect(doneOutput).toContain( + "We've emailed you a magic link to user@example.com. Use it to access your aimlapi.com account and review your usage.", + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Provider manager'), + ) expect(provisionAimlapiKey).toHaveBeenCalledWith( expect.objectContaining({ - email: 'user@example.com', - password: 'secret-password', amountUsd: '25', - method: 'crypto', - model: 'gpt-4o', + model: 'anthropic/claude-sonnet-5', + sessionToken: 'session_test', + exchange: true, + autoTopUp: false, onStatus: expect.any(Function), }), ) expect(addProviderProfile).toHaveBeenCalledWith( expect.objectContaining({ provider: 'aimlapi', - name: 'AI/ML API', + name: 'aimlapi.com', baseUrl: 'https://api.aimlapi.com/v1', - model: 'gpt-4o', + model: 'anthropic/claude-sonnet-5', apiKey: 'aimlapi-issued-key', apiFormat: 'chat_completions', }), diff --git a/src/components/ProviderManager.tsx b/src/components/ProviderManager.tsx index 63326dd844..761f90ade8 100644 --- a/src/components/ProviderManager.tsx +++ b/src/components/ProviderManager.tsx @@ -1,7 +1,8 @@ +import { randomUUID } from 'node:crypto' import figures from 'figures' import * as React from 'react' import { DEFAULT_CODEX_BASE_URL } from '../services/api/providerConfig.js' -import { Box, Text } from '../ink.js' +import { Box, Text, useInput } from '../ink.js' import { useTerminalSize } from '../hooks/useTerminalSize.js' import { useKeybinding } from '../keybindings/useKeybinding.js' import { useSetAppState } from '../state/AppState.js' @@ -48,14 +49,21 @@ import { } from '../integrations/index.js' import { provisionAimlapiKey, + topUpAimlapiByApiKey, + parseAimlapiAmountUsd, + isValidAimlapiEmail, + beginAimlapiEmailOnboarding, + completeAimlapiCodeSignIn, + validateAimlapiApiKey, + AimlapiApiError, + AIMLAPI_MESSAGES, type AimlapiTopupStatus, } from '../integrations/aimlapi/index.js' import { DEFAULT_AMOUNT_USD_MINOR, - MAX_AMOUNT_USD_MINOR, - MIN_AMOUNT_USD_MINOR, + isCanonicalAimlapiInferenceBaseUrl, + resolveEndpoints, } from '../integrations/aimlapi/config.js' -import type { PaymentMethod } from '../integrations/aimlapi/client.js' import { openAIShimSupportsApiFormatForModel } from '../integrations/runtimeMetadata.js' import { probeRouteReadiness } from '../integrations/discoveryService.js' import { @@ -90,13 +98,15 @@ import { recommendOllamaModel, } from '../utils/providerRecommendation.js' import { clearStartupProviderOverrides } from '../utils/providerStartupOverrides.js' -import { redactUrlForDisplay } from '../utils/redaction.js' +import { redactSensitiveInfo, redactUrlForDisplay } from '../utils/redaction.js' +import { registerCleanup } from '../utils/cleanupRegistry.js' import { updateSettingsForSource } from '../utils/settings/settings.js' import { type OptionWithDescription, Select, } from './CustomSelect/index.js' import { Pane } from './design-system/Pane.js' +import { Spinner } from './Spinner.js' import TextInput from './TextInput.js' import { useCodexOAuthFlow } from './useCodexOAuthFlow.js' import { useXaiOAuthFlow } from './useXaiOAuthFlow.js' @@ -124,11 +134,13 @@ type Screen = | 'form' | 'preset-model' | 'aimlapi-api-key-choice' + | 'aimlapi-configured' | 'aimlapi-topup-email' - | 'aimlapi-topup-password' + | 'aimlapi-signin-code' + | 'aimlapi-low-balance' | 'aimlapi-topup-amount' - | 'aimlapi-topup-method' | 'aimlapi-topup-progress' + | 'aimlapi-done' | 'preset-api-key' | 'select-active' | 'select-edit' @@ -789,6 +801,120 @@ function CodexOAuthSetup({ ) } +type AimlapiTopupFormProps = { + amountUsd: string + autoTopUp: boolean + columns: number + cursorOffset: number + onAmountChange: (value: string) => void + onCursorOffsetChange: (offset: number) => void + onAutoTopUpChange: (enabled: boolean) => void + onSubmit: () => void +} + +function wrapAimlapiCheckoutUrl(url: string, width: number): string[] { + const characters = Array.from(url.trim()) + const chunkSize = Math.max(20, width) + const lines: string[] = [] + for (let offset = 0; offset < characters.length; offset += chunkSize) { + lines.push(characters.slice(offset, offset + chunkSize).join('')) + } + return lines +} + +function safeAimlapiErrorMessage( + error: unknown, + secrets: Array = [], +): string { + // AimlapiApiError.message deliberately excludes its server-controlled body. + // Redact exact active values as well as keys matching known credential shapes. + let message = error instanceof Error ? error.message : String(error) + for (const secret of secrets) { + const value = secret?.trim() + if (value) message = message.split(value).join('[REDACTED]') + } + return redactSensitiveInfo(message) +} + +function AimlapiTopupForm({ + amountUsd, + autoTopUp, + columns, + cursorOffset, + onAmountChange, + onCursorOffsetChange, + onAutoTopUpChange, + onSubmit, +}: AimlapiTopupFormProps): React.ReactNode { + const [focusedField, setFocusedField] = React.useState<'amount' | 'auto'>( + 'amount', + ) + + // This small form intentionally mirrors Zero's two-row top-up control while + // keeping OpenClaude's native input and event system. + useInput((input, key, event) => { + if (key.tab || key.upArrow || key.downArrow) { + setFocusedField(field => (field === 'amount' ? 'auto' : 'amount')) + event.stopImmediatePropagation() + return + } + if (focusedField !== 'auto') return + if (key.leftArrow || key.rightArrow || input === ' ') { + onAutoTopUpChange(!autoTopUp) + event.stopImmediatePropagation() + return + } + if (key.return) { + onSubmit() + event.stopImmediatePropagation() + return + } + if (!key.escape) event.stopImmediatePropagation() + }) + + const amountFocused = focusedField === 'amount' + const autoFocused = focusedField === 'auto' + return ( + + + + {amountFocused ? `${figures.pointer} ` : ' '}Amount: $ + + onSubmit()} + focus={amountFocused} + showCursor={amountFocused} + columns={columns} + cursorOffset={cursorOffset} + onChangeCursorOffset={onCursorOffsetChange} + /> + + + + {autoFocused ? `${figures.pointer} ` : ' '}Auto top up:{' '} + + + on + + / + + off + + + + ) +} + export function ProviderManager({ mode, onDone }: Props): React.ReactNode { const { columns: terminalColumns } = useTerminalSize() const inputColumns = Math.max(20, Math.min(80, terminalColumns - 4)) @@ -833,13 +959,52 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { const [aimlapiTopupAmountUsd, setAimlapiTopupAmountUsd] = React.useState( String(DEFAULT_AMOUNT_USD_MINOR / 100), ) - const [aimlapiTopupMethod, setAimlapiTopupMethod] = - React.useState('card') - const [aimlapiTopupPassword, setAimlapiTopupPassword] = React.useState('') + const [aimlapiSignInCode, setAimlapiSignInCode] = React.useState('') + const [aimlapiSessionToken, setAimlapiSessionToken] = React.useState('') + const [aimlapiIssuedKey, setAimlapiIssuedKey] = React.useState('') + const [aimlapiIssuedKeyId, setAimlapiIssuedKeyId] = React.useState('') + const [aimlapiTopupByKey, setAimlapiTopupByKey] = React.useState(false) + const [aimlapiResumeSessionToken, setAimlapiResumeSessionToken] = React.useState('') + const [aimlapiPaymentSessionId, setAimlapiPaymentSessionId] = React.useState('') + const [aimlapiExistingProfileId, setAimlapiExistingProfileId] = React.useState(null) + const [aimlapiExistingUsesEnv, setAimlapiExistingUsesEnv] = React.useState(false) + const [aimlapiInferenceBaseUrl, setAimlapiInferenceBaseUrl] = React.useState( + () => resolveEndpoints().inferenceBaseUrl, + ) + const [aimlapiNewAccount, setAimlapiNewAccount] = React.useState(false) + const [aimlapiAutoTopUp, setAimlapiAutoTopUp] = React.useState(true) const [aimlapiTopupStatus, setAimlapiTopupStatus] = React.useState() const [aimlapiTopupDetail, setAimlapiTopupDetail] = React.useState() - const [isAimlapiTopupRunning, setIsAimlapiTopupRunning] = React.useState(false) + const [aimlapiDoneKind, setAimlapiDoneKind] = React.useState<'ready' | 'topup'>( + 'ready', + ) + const [, setIsAimlapiTopupRunning] = React.useState(false) + const [isAimlapiKeyValidating, setIsAimlapiKeyValidating] = React.useState(false) + const aimlapiAbortRef = React.useRef(null) + + function resetAimlapiCheckoutIntent(): void { + setAimlapiResumeSessionToken('') + setAimlapiPaymentSessionId('') + } + + function resetAimlapiOnboardingIdentity(): void { + resetAimlapiCheckoutIntent() + setAimlapiSessionToken('') + setAimlapiIssuedKey('') + setAimlapiIssuedKeyId('') + setAimlapiTopupByKey(false) + setAimlapiNewAccount(false) + } + + React.useEffect(() => { + const cancelAimlapi = (): void => aimlapiAbortRef.current?.abort() + const unregister = registerCleanup(cancelAimlapi) + return () => { + unregister() + cancelAimlapi() + } + }, []) const [menuFocusValue, setMenuFocusValue] = React.useState() const [hasStoredCodexOAuthCredentials, setHasStoredCodexOAuthCredentials] = React.useState(false) @@ -1477,6 +1642,8 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { } function closeWithCancelled(message: string): void { + aimlapiAbortRef.current?.abort() + aimlapiAbortRef.current = null onDone({ action: 'cancelled', message: @@ -1578,7 +1745,10 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { const provider = defaults.provider ?? 'openai' const nextDraft = { name: defaults.name, - baseUrl: defaults.baseUrl, + baseUrl: + preset === 'aimlapi' + ? resolveEndpoints().inferenceBaseUrl + : defaults.baseUrl, model: defaults.model, apiKey: defaults.apiKey ?? '', apiFormat: 'chat_completions', @@ -1592,15 +1762,34 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setPresetRequiresApiKey(defaults.requiresApiKey) setAimlapiTopupEmail('') setAimlapiTopupAmountUsd(String(DEFAULT_AMOUNT_USD_MINOR / 100)) - setAimlapiTopupMethod('card') - setAimlapiTopupPassword('') + aimlapiAbortRef.current?.abort() + aimlapiAbortRef.current = null + setAimlapiSignInCode('') + setAimlapiSessionToken('') + setAimlapiIssuedKey('') + setAimlapiIssuedKeyId('') + setAimlapiTopupByKey(false) + setAimlapiResumeSessionToken('') + setAimlapiPaymentSessionId('') + setAimlapiExistingProfileId(null) + setAimlapiExistingUsesEnv(false) + setAimlapiInferenceBaseUrl( + preset === 'aimlapi' ? nextDraft.baseUrl : resolveEndpoints().inferenceBaseUrl, + ) + setAimlapiNewAccount(false) + setAimlapiAutoTopUp(true) setAimlapiTopupStatus(undefined) setAimlapiTopupDetail(undefined) + setAimlapiDoneKind('ready') setIsAimlapiTopupRunning(false) setFormStepIndex(0) setCursorOffset(nextDraft.name.length) setErrorMessage(undefined) + if (preset === 'aimlapi' && mode === 'manage' && startExistingAimlapi(nextDraft)) { + return + } + if (preset === 'ollama') { setOllamaSelection({ state: 'loading' }) setScreen('select-ollama-model') @@ -1647,6 +1836,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { nextDraft: ProviderDraft = draft, provider: ProviderProfile['provider'] = draftProvider, profileId: string | null = editingProfileId, + options: { deferNavigation?: boolean; onSaved?: () => void } = {}, ): void { if ( provider === 'custom-anthropic' && @@ -1745,6 +1935,11 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { : finalSuccessMessage, ) + if (options.deferNavigation) { + options.onSaved?.() + return + } + if (mode === 'first-run') { onDone({ action: 'saved', @@ -1997,6 +2192,11 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { }) function handleBackFromPresetApiKey(): void { + if (draftProvider === 'aimlapi') { + aimlapiAbortRef.current?.abort() + aimlapiAbortRef.current = null + setIsAimlapiKeyValidating(false) + } setErrorMessage(undefined) setCursorOffset(draft.model.length) setScreen(draftProvider === 'aimlapi' ? 'aimlapi-api-key-choice' : 'preset-model') @@ -2018,7 +2218,21 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { isActive: screen === 'aimlapi-api-key-choice', }) + function handleBackFromAimlapiConfigured(): void { + aimlapiAbortRef.current?.abort() + aimlapiAbortRef.current = null + setIsAimlapiKeyValidating(false) + setErrorMessage(undefined) + setScreen('select-preset') + } + + useKeybinding('confirm:no', handleBackFromAimlapiConfigured, { + context: 'Settings', + isActive: screen === 'aimlapi-configured', + }) + function handleBackFromAimlapiTopupEmail(): void { + aimlapiAbortRef.current?.abort() setErrorMessage(undefined) setCursorOffset(0) setScreen('aimlapi-api-key-choice') @@ -2031,8 +2245,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { function handleBackFromAimlapiTopupAmount(): void { setErrorMessage(undefined) - setCursorOffset(aimlapiTopupPassword.length) - setScreen('aimlapi-topup-password') + setScreen(aimlapiNewAccount ? 'aimlapi-topup-email' : 'aimlapi-low-balance') } useKeybinding('confirm:no', handleBackFromAimlapiTopupAmount, { @@ -2040,35 +2253,48 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { isActive: screen === 'aimlapi-topup-amount', }) - function handleBackFromAimlapiTopupPassword(): void { + function handleBackFromAimlapiSignInCode(): void { + aimlapiAbortRef.current?.abort() setErrorMessage(undefined) - setAimlapiTopupPassword('') + setAimlapiSignInCode('') setCursorOffset(aimlapiTopupEmail.length) setScreen('aimlapi-topup-email') } - useKeybinding('confirm:no', handleBackFromAimlapiTopupPassword, { + useKeybinding('confirm:no', handleBackFromAimlapiSignInCode, { context: 'Settings', - isActive: screen === 'aimlapi-topup-password', + isActive: screen === 'aimlapi-signin-code', }) - function handleBackFromAimlapiTopupMethod(): void { + function handleBackFromAimlapiLowBalance(): void { setErrorMessage(undefined) - setCursorOffset(aimlapiTopupAmountUsd.length) - setScreen('aimlapi-topup-amount') + setScreen( + aimlapiExistingProfileId || aimlapiExistingUsesEnv + ? 'aimlapi-configured' + : 'aimlapi-api-key-choice', + ) } - useKeybinding('confirm:no', handleBackFromAimlapiTopupMethod, { + useKeybinding('confirm:no', handleBackFromAimlapiLowBalance, { context: 'Settings', - isActive: screen === 'aimlapi-topup-method', + isActive: screen === 'aimlapi-low-balance', }) function handleCancelAimlapiTopupProgress(): void { - if (isAimlapiTopupRunning) { - return - } + aimlapiAbortRef.current?.abort() + aimlapiAbortRef.current = null + setIsAimlapiTopupRunning(false) setErrorMessage(undefined) - setScreen('aimlapi-api-key-choice') + setScreen( + aimlapiTopupStatus === 'checking-account' || + aimlapiTopupStatus === 'sending-code' || + aimlapiTopupStatus === 'creating-account' + ? 'aimlapi-topup-email' + : aimlapiTopupStatus === 'verifying-code' || + aimlapiTopupStatus === 'creating-key' + ? 'aimlapi-signin-code' + : 'aimlapi-topup-amount', + ) } useKeybinding('confirm:no', handleCancelAimlapiTopupProgress, { @@ -2076,6 +2302,31 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { isActive: screen === 'aimlapi-topup-progress', }) + function finishAimlapiDone(): void { + if (mode === 'first-run') { + const active = getActiveProviderProfile() + onDone({ + action: 'saved', + activeProfileId: active?.id, + activeProviderName: active?.name, + activeProviderModel: active ? getPrimaryModel(active.model) : undefined, + message: `Provider configured: ${active?.name ?? 'aimlapi.com'}`, + }) + return + } + returnToMenu() + } + + useKeybinding('confirm:yes', finishAimlapiDone, { + context: 'Confirmation', + isActive: screen === 'aimlapi-done', + }) + + useKeybinding('confirm:no', finishAimlapiDone, { + context: 'Confirmation', + isActive: screen === 'aimlapi-done', + }) + // xAI OAuth setup renders a TextInput for the manual-code recovery // path, which registers its own useInput listener. The child-component // useKeybinding inside XaiOAuthSetup ends up racing the input handler @@ -2313,6 +2564,29 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setDraft(nextDraft) setErrorMessage(undefined) + if (draftProvider === 'aimlapi') { + const envKey = process.env.AIMLAPI_API_KEY?.trim() + if (mode === 'first-run' && envKey) { + setAimlapiIssuedKey(envKey) + setAimlapiExistingUsesEnv(true) + persistAimlapiKey( + envKey, + nextDraft.baseUrl, + nextDraft.model, + 'ready', + { preserveEnv: true }, + ) + return + } + if (aimlapiExistingProfileId || aimlapiExistingUsesEnv) { + persistExistingAimlapi(nextDraft.model) + return + } + if (mode === 'manage' && startExistingAimlapi(nextDraft)) { + return + } + } + if (needsApiKey) { setCursorOffset(0) setScreen( @@ -2342,14 +2616,72 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { } function renderPresetApiKey(): React.ReactNode { + const submitApiKey = (value: string): void => { + const apiKey = value.trim() + if (!apiKey) { + setErrorMessage(`API key is required for ${draft.name}.`) + return + } + + const nextDraft = applyPresetApiFormat( + { + ...draft, + apiKey, + }, + draftProvider, + ) + setDraft(nextDraft) + setErrorMessage(undefined) + if (draftProvider === 'aimlapi') { + void validateAndPersistAimlapiKey(apiKey, nextDraft.baseUrl, nextDraft.model) + return + } + persistDraft(nextDraft, draftProvider, null) + } + + if (draftProvider === 'aimlapi') { + return ( + + + {AIMLAPI_MESSAGES.apiKeyInputPrompt} + + {AIMLAPI_MESSAGES.apiKeyHiddenHint} + + API key: + + setDraft(prev => ({ + ...prev, + apiKey: value, + })) + } + onSubmit={submitApiKey} + focus={!isAimlapiKeyValidating} + showCursor={!isAimlapiKeyValidating} + placeholder={`Paste your key${figures.ellipsis}`} + mask="*" + columns={inputColumns} + cursorOffset={cursorOffset} + onChangeCursorOffset={setCursorOffset} + /> + + {isAimlapiKeyValidating ? : null} + {errorMessage && {errorMessage}} + + Press Enter to save. Press Esc to go back. + + + ) + } + return ( Create provider profile - Enter the API key for {draft.name}. Other preset details are already - configured. + Enter the API key for {draft.name}. Other preset details are already configured. Provider type:{' '} @@ -2366,24 +2698,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { apiKey: value, })) } - onSubmit={value => { - const apiKey = value.trim() - if (!apiKey) { - setErrorMessage(`API key is required for ${draft.name}.`) - return - } - - const nextDraft = applyPresetApiFormat( - { - ...draft, - apiKey, - }, - draftProvider, - ) - setDraft(nextDraft) - setErrorMessage(undefined) - persistDraft(nextDraft, draftProvider, null) - }} + onSubmit={submitApiKey} focus={true} showCursor={true} placeholder={`Enter API key${figures.ellipsis}`} @@ -2401,125 +2716,508 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { ) } - function startAimlapiTopup( - email: string, - password: string, - method: PaymentMethod = aimlapiTopupMethod, + async function validateAndPersistAimlapiKey( + apiKey: string, + baseUrl: string, + model: string, + ): Promise { + aimlapiAbortRef.current?.abort() + const controller = new AbortController() + aimlapiAbortRef.current = controller + setIsAimlapiKeyValidating(true) + setErrorMessage(undefined) + + try { + const balance = await validateAimlapiApiKey( + apiKey, + controller.signal, + baseUrl, + ) + if (controller.signal.aborted) return + if (balance.lowBalance) { + setAimlapiIssuedKey(apiKey.trim()) + setAimlapiIssuedKeyId('') + setAimlapiTopupByKey(true) + setIsAimlapiKeyValidating(false) + setScreen('aimlapi-low-balance') + return + } + persistAimlapiKey(apiKey, baseUrl, model, 'ready') + } catch (error) { + if (controller.signal.aborted) return + const status = + typeof error === 'object' && error !== null && 'status' in error + ? Number(error.status) + : undefined + if (status === 401 || status === 403) { + setDraft(prev => ({ ...prev, apiKey: '' })) + setCursorOffset(0) + setErrorMessage(AIMLAPI_MESSAGES.apiKeyInvalid) + return + } + const detail = safeAimlapiErrorMessage(error, [apiKey]) + setErrorMessage(detail) + } finally { + if (aimlapiAbortRef.current === controller) aimlapiAbortRef.current = null + if (!controller.signal.aborted) setIsAimlapiKeyValidating(false) + } + } + + function existingAimlapiCredential(): { + apiKey: string + profile?: ProviderProfile + usesEnv: boolean + inferenceBaseUrl: string + } | null { + const isAimlapiProfile = (profile: ProviderProfile): boolean => + profile.provider === 'aimlapi' || + resolveRouteIdFromBaseUrl(profile.baseUrl) === 'aimlapi' + const envKey = process.env.AIMLAPI_API_KEY?.trim() + const active = profiles.find(profile => profile.id === activeProfileId) + const candidates = active + ? [active, ...profiles.filter(profile => profile.id !== active.id)] + : profiles + for (const profile of candidates) { + if (!isAimlapiProfile(profile)) continue + // Saved credentials are eligible for the guided balance/top-up preflight + // only on the production catalog endpoint. A proxy/staging profile remains + // usable normally, but its key must never be sent to another environment. + if (!isCanonicalAimlapiInferenceBaseUrl(profile.baseUrl)) continue + const apiKey = profile.apiKey?.trim() + if (apiKey) { + return { + apiKey, + profile, + usesEnv: false, + inferenceBaseUrl: profile.baseUrl, + } + } + if (envKey) { + return { + apiKey: envKey, + profile, + usesEnv: true, + inferenceBaseUrl: profile.baseUrl, + } + } + } + return envKey + ? { + apiKey: envKey, + usesEnv: true, + inferenceBaseUrl: resolveEndpoints().inferenceBaseUrl, + } + : null + } + + function persistExistingAimlapi(model = draft.model): void { + const profile = aimlapiExistingProfileId + ? profiles.find(candidate => candidate.id === aimlapiExistingProfileId) + : undefined + if (profile) { + const nextDraft = applyPresetApiFormat( + { ...toDraft(profile), model }, + profile.provider, + ) + setDraft(nextDraft) + persistDraft(nextDraft, profile.provider, profile.id, { + deferNavigation: true, + onSaved: () => { + setAimlapiDoneKind(aimlapiTopupByKey ? 'topup' : 'ready') + setErrorMessage(undefined) + setScreen('aimlapi-done') + }, + }) + return + } + persistAimlapiKey( + aimlapiIssuedKey, + resolveEndpoints().inferenceBaseUrl, + model, + aimlapiTopupByKey ? 'topup' : 'ready', + { preserveEnv: aimlapiExistingUsesEnv }, + ) + } + + function startExistingAimlapi(nextDraft: ProviderDraft): boolean { + const existing = existingAimlapiCredential() + if (!existing) return false + setDraft({ + ...nextDraft, + baseUrl: existing.profile?.baseUrl ?? existing.inferenceBaseUrl, + }) + setAimlapiIssuedKey(existing.apiKey) + setAimlapiIssuedKeyId('') + setAimlapiExistingProfileId(existing.profile?.id ?? null) + setAimlapiExistingUsesEnv(existing.usesEnv) + setAimlapiInferenceBaseUrl(existing.inferenceBaseUrl) + setAimlapiTopupByKey(true) + setScreen('aimlapi-configured') + return true + } + + function useExistingAimlapi(): void { + const apiKey = aimlapiIssuedKey.trim() + if (!apiKey) { + setErrorMessage('The existing AI/ML API key is unavailable. Configure again.') + return + } + aimlapiAbortRef.current?.abort() + const controller = new AbortController() + aimlapiAbortRef.current = controller + setIsAimlapiKeyValidating(true) + setErrorMessage(undefined) + void (async () => { + try { + const balance = await validateAimlapiApiKey( + apiKey, + controller.signal, + aimlapiInferenceBaseUrl, + ) + if (controller.signal.aborted) return + setIsAimlapiKeyValidating(false) + if (balance.lowBalance) { + setScreen('aimlapi-low-balance') + } else { + setCursorOffset(draft.model.length) + setScreen('preset-model') + } + } catch (error) { + if (controller.signal.aborted) return + setIsAimlapiKeyValidating(false) + const status = error instanceof AimlapiApiError ? error.status : undefined + setErrorMessage( + status === 401 || status === 403 + ? 'The existing AI/ML API key is invalid. Configure again.' + : safeAimlapiErrorMessage(error, [apiKey]), + ) + } finally { + if (aimlapiAbortRef.current === controller) aimlapiAbortRef.current = null + } + })() + } + + function persistAimlapiKey( + apiKey: string, + baseUrl: string, + model = draft.model, + doneKind: 'ready' | 'topup' = 'ready', + options: { preserveEnv?: boolean } = {}, ): void { + const nextDraft = applyPresetApiFormat( + { + ...draft, + apiKey: options.preserveEnv ? '' : apiKey.trim(), + baseUrl, + model, + }, + draftProvider, + ) + setDraft(nextDraft) + persistDraft(nextDraft, draftProvider, null, { + deferNavigation: true, + onSaved: () => { + setAimlapiDoneKind(doneKind) + setErrorMessage(undefined) + setScreen('aimlapi-done') + }, + }) + } + + function startAimlapiEmailOnboarding(email: string): void { const trimmedEmail = email.trim() - const amountUsd = aimlapiTopupAmountUsd.trim() - const parsedAmountUsd = Number(amountUsd) - if (!trimmedEmail) { - setErrorMessage('AI/ML API email is required.') - setScreen('aimlapi-topup-email') + if (!isValidAimlapiEmail(trimmedEmail)) { + setErrorMessage(AIMLAPI_MESSAGES.emailInvalid) return } - if (!Number.isFinite(parsedAmountUsd) || parsedAmountUsd <= 0) { - setErrorMessage('Enter a valid top-up amount in USD.') - setScreen('aimlapi-topup-amount') + // Submitting the email starts a fresh account-bound flow. Retaining a + // checkout from an earlier email/key path could poll or exchange the wrong + // payment intent, so retries that should resume stay on the amount screen. + resetAimlapiOnboardingIdentity() + aimlapiAbortRef.current?.abort() + const controller = new AbortController() + aimlapiAbortRef.current = controller + setAimlapiTopupEmail(trimmedEmail) + setAimlapiTopupStatus('checking-account') + setAimlapiTopupDetail(undefined) + setErrorMessage(undefined) + setIsAimlapiTopupRunning(true) + setScreen('aimlapi-topup-progress') + + void (async () => { + try { + const account = await beginAimlapiEmailOnboarding( + trimmedEmail, + controller.signal, + ) + if (account.action === 'code-sent') { + setAimlapiTopupStatus('sending-code') + if (controller.signal.aborted) return + setAimlapiNewAccount(false) + setAimlapiSignInCode('') + setCursorOffset(0) + setIsAimlapiTopupRunning(false) + setScreen('aimlapi-signin-code') + return + } + setAimlapiTopupStatus('creating-account') + if (controller.signal.aborted) return + setAimlapiNewAccount(true) + setAimlapiSessionToken(account.sessionToken) + setCursorOffset(aimlapiTopupAmountUsd.length) + setIsAimlapiTopupRunning(false) + setScreen('aimlapi-topup-amount') + } catch (error) { + if (controller.signal.aborted) return + setIsAimlapiTopupRunning(false) + setErrorMessage( + safeAimlapiErrorMessage(error, [trimmedEmail]), + ) + setCursorOffset(trimmedEmail.length) + setScreen('aimlapi-topup-email') + } finally { + if (aimlapiAbortRef.current === controller) aimlapiAbortRef.current = null + } + })() + } + + function verifyAimlapiSignInCode(code: string): void { + const trimmedCode = code.trim() + if (!trimmedCode) { + setErrorMessage(AIMLAPI_MESSAGES.codeIncorrect) return } - if (Math.round(parsedAmountUsd * 100) < MIN_AMOUNT_USD_MINOR) { - setErrorMessage(`Minimum AI/ML API top-up is $${MIN_AMOUNT_USD_MINOR / 100}.`) + aimlapiAbortRef.current?.abort() + const controller = new AbortController() + aimlapiAbortRef.current = controller + setAimlapiTopupStatus('verifying-code') + setErrorMessage(undefined) + setIsAimlapiTopupRunning(true) + setScreen('aimlapi-topup-progress') + + void (async () => { + try { + const result = await completeAimlapiCodeSignIn( + aimlapiTopupEmail, + trimmedCode, + controller.signal, + aimlapiInferenceBaseUrl, + ) + setAimlapiSessionToken(result.sessionToken) + setAimlapiIssuedKey(result.apiKey) + setAimlapiIssuedKeyId(result.apiKeyId) + if (controller.signal.aborted) return + setIsAimlapiTopupRunning(false) + if (result.lowBalance) { + setScreen('aimlapi-low-balance') + } else { + persistAimlapiKey(result.apiKey, aimlapiInferenceBaseUrl) + } + } catch (error) { + if (controller.signal.aborted) return + setIsAimlapiTopupRunning(false) + setErrorMessage( + error instanceof AimlapiApiError && error.status === 400 + ? AIMLAPI_MESSAGES.codeIncorrect + : safeAimlapiErrorMessage(error, [ + aimlapiTopupEmail, + trimmedCode, + aimlapiSessionToken, + ]), + ) + setCursorOffset(trimmedCode.length) + setScreen('aimlapi-signin-code') + } finally { + if (aimlapiAbortRef.current === controller) aimlapiAbortRef.current = null + } + })() + } + + function startAimlapiTopup(autoTopUp = aimlapiAutoTopUp): void { + const amountUsd = aimlapiTopupAmountUsd.trim() + if (!amountUsd) { + setErrorMessage(AIMLAPI_MESSAGES.amountRequired) setScreen('aimlapi-topup-amount') return } - if (Math.round(parsedAmountUsd * 100) > MAX_AMOUNT_USD_MINOR) { - setErrorMessage(`Maximum AI/ML API top-up is $${MAX_AMOUNT_USD_MINOR / 100}.`) + try { + parseAimlapiAmountUsd(amountUsd) + } catch (error) { + setErrorMessage(error instanceof Error ? error.message : String(error)) setScreen('aimlapi-topup-amount') return } - if (!password) { - setErrorMessage('AI/ML API password is required.') - setScreen('aimlapi-topup-password') + if (!aimlapiTopupByKey && !aimlapiSessionToken.trim()) { + setErrorMessage('Your AI/ML API session expired. Enter your email again.') + setScreen('aimlapi-topup-email') return } + aimlapiAbortRef.current?.abort() + const controller = new AbortController() + aimlapiAbortRef.current = controller setScreen('aimlapi-topup-progress') setErrorMessage(undefined) - setAimlapiTopupStatus('signing-in') + setAimlapiTopupStatus('creating-session') setAimlapiTopupDetail(undefined) setIsAimlapiTopupRunning(true) + const paymentSessionId = aimlapiPaymentSessionId || randomUUID() + if (!aimlapiPaymentSessionId) setAimlapiPaymentSessionId(paymentSessionId) void (async () => { try { - const provisioned = await provisionAimlapiKey({ - email: trimmedEmail, - password, - amountUsd, - method, - model: draft.model, - onStatus: (status, detail) => { - setAimlapiTopupStatus(status) - setAimlapiTopupDetail(detail) - }, - }) - const nextDraft = applyPresetApiFormat( - { - ...draft, - apiKey: provisioned.apiKey, - baseUrl: provisioned.baseUrl, - model: provisioned.model, - }, - draftProvider, - ) - setDraft(nextDraft) - setAimlapiTopupPassword('') + const reportStatus = (status: AimlapiTopupStatus, detail?: string): void => { + setAimlapiTopupStatus(status) + if (detail?.trim()) setAimlapiTopupDetail(detail) + } + const reportSession = (sessionToken: string): void => { + setAimlapiResumeSessionToken(sessionToken) + if (!sessionToken) setAimlapiPaymentSessionId('') + } + const provisioned = aimlapiTopupByKey + ? await topUpAimlapiByApiKey({ + apiKey: aimlapiIssuedKey, + inferenceBaseUrl: aimlapiInferenceBaseUrl, + amountUsd, + autoTopUp, + model: draft.model, + paymentSessionId, + resumeSessionToken: aimlapiResumeSessionToken, + signal: controller.signal, + onStatus: reportStatus, + onSession: reportSession, + }) + : await provisionAimlapiKey({ + amountUsd, + autoTopUp, + model: draft.model, + sessionToken: aimlapiSessionToken, + inferenceBaseUrl: aimlapiInferenceBaseUrl, + exchange: aimlapiNewAccount, + paymentSessionId, + existingApiKey: aimlapiIssuedKey, + existingApiKeyId: aimlapiIssuedKeyId, + resumeSessionToken: aimlapiResumeSessionToken, + signal: controller.signal, + onStatus: reportStatus, + onSession: reportSession, + }) + if (controller.signal.aborted) return setIsAimlapiTopupRunning(false) - persistDraft(nextDraft, draftProvider, null) + setAimlapiResumeSessionToken('') + setAimlapiPaymentSessionId('') + if (aimlapiTopupByKey) { + if (aimlapiExistingProfileId || aimlapiExistingUsesEnv) { + setCursorOffset(provisioned.model.length) + setScreen('preset-model') + } else { + persistExistingAimlapi(provisioned.model) + } + } else { + persistAimlapiKey( + provisioned.apiKey, + provisioned.baseUrl, + provisioned.model, + 'topup', + ) + } } catch (error) { - const detail = error instanceof Error ? error.message : String(error) + if (controller.signal.aborted) return + const detail = safeAimlapiErrorMessage(error, [ + aimlapiIssuedKey, + aimlapiTopupEmail, + aimlapiSignInCode, + aimlapiSessionToken, + aimlapiResumeSessionToken, + ]) setIsAimlapiTopupRunning(false) - setErrorMessage(`Could not finish AI/ML API top-up: ${detail}`) + setErrorMessage(`${AIMLAPI_MESSAGES.topUpFailed} ${detail}`) + setCursorOffset(amountUsd.length) + setScreen('aimlapi-topup-amount') + } finally { + if (aimlapiAbortRef.current === controller) aimlapiAbortRef.current = null } })() } + function renderAimlapiConfigured(): React.ReactNode { + if (isAimlapiKeyValidating) { + return ( + + aimlapi.com account is already configured + + + Checking balance... + + + ) + } + return ( + + aimlapi.com account is already configured + { setErrorMessage(undefined) if (value === 'manual') { + resetAimlapiOnboardingIdentity() setCursorOffset(draft.apiKey.length) setScreen('preset-api-key') return } + resetAimlapiOnboardingIdentity() const envEmail = process.env.AIMLAPI_EMAIL?.trim() ?? '' - const envPassword = process.env.AIMLAPI_PASSWORD ?? '' - if (envEmail && envPassword) { - setAimlapiTopupEmail(envEmail) - setAimlapiTopupPassword(envPassword) - setCursorOffset(aimlapiTopupAmountUsd.length) - setScreen('aimlapi-topup-amount') - return - } setCursorOffset(envEmail.length) setAimlapiTopupEmail(envEmail) setScreen('aimlapi-topup-email') @@ -2539,13 +3237,8 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { return ( - AI/ML API top-up + {AIMLAPI_MESSAGES.enterEmail} - - Enter your AI/ML API account email. The checkout flow will use it to - register or sign in. - - Step 2 of 2: Top up account {figures.pointer} { const email = value.trim() - if (!email) { - setErrorMessage('AI/ML API email is required.') - return - } - setAimlapiTopupEmail(email) - setErrorMessage(undefined) - setCursorOffset(0) - setScreen('aimlapi-topup-password') + startAimlapiEmailOnboarding(email) }} focus={true} showCursor={true} @@ -2578,169 +3264,148 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { ) } - function renderAimlapiTopupAmount(): React.ReactNode { + function renderAimlapiSignInCode(): React.ReactNode { return ( - AI/ML API top-up + {AIMLAPI_MESSAGES.codeSent(aimlapiTopupEmail)} - - Choose a top-up amount in USD. Minimum is ${MIN_AMOUNT_USD_MINOR / 100}. - - Step 2 of 2: Top up account {figures.pointer} { - const amountUsd = value.trim() - const parsedAmountUsd = Number(amountUsd) - if (!Number.isFinite(parsedAmountUsd) || parsedAmountUsd <= 0) { - setErrorMessage('Enter a valid top-up amount in USD.') - return - } - if (Math.round(parsedAmountUsd * 100) < MIN_AMOUNT_USD_MINOR) { - setErrorMessage(`Minimum AI/ML API top-up is $${MIN_AMOUNT_USD_MINOR / 100}.`) - return - } - if (Math.round(parsedAmountUsd * 100) > MAX_AMOUNT_USD_MINOR) { - setErrorMessage(`Maximum AI/ML API top-up is $${MAX_AMOUNT_USD_MINOR / 100}.`) - return - } - setAimlapiTopupAmountUsd(amountUsd) - setErrorMessage(undefined) - setScreen('aimlapi-topup-method') - }} + value={aimlapiSignInCode} + onChange={setAimlapiSignInCode} + onSubmit={verifyAimlapiSignInCode} focus={true} showCursor={true} - placeholder={`Enter amount${figures.ellipsis}`} + placeholder={`6-digit code${figures.ellipsis}`} columns={inputColumns} cursorOffset={cursorOffset} onChangeCursorOffset={setCursorOffset} /> {errorMessage && {errorMessage}} - - Press Enter to continue. Press Esc to go back. - + Press Enter to continue. Press Esc to go back. ) } - function renderAimlapiTopupPassword(): React.ReactNode { + function renderAimlapiLowBalance(): React.ReactNode { return ( - - AI/ML API top-up - - - Enter your AI/ML API password. The CLI will open checkout and save the - issued API key after payment. - - Step 2 of 2: Top up account - - {figures.pointer} - { - if (!value) { - setErrorMessage('AI/ML API password is required.') - return + {AIMLAPI_MESSAGES.lowBalance} + { - const method: PaymentMethod = value === 'crypto' ? 'crypto' : 'card' - setAimlapiTopupMethod(method) - startAimlapiTopup(aimlapiTopupEmail, aimlapiTopupPassword, method) + { + if (value !== aimlapiTopupAmountUsd) { + setAimlapiResumeSessionToken('') + setAimlapiPaymentSessionId('') + } + setAimlapiTopupAmountUsd(value) + setErrorMessage(undefined) }} - onCancel={handleBackFromAimlapiTopupMethod} - visibleOptionCount={2} + onCursorOffsetChange={setCursorOffset} + onAutoTopUpChange={value => { + if (value !== aimlapiAutoTopUp) { + setAimlapiResumeSessionToken('') + setAimlapiPaymentSessionId('') + } + setAimlapiAutoTopUp(value) + }} + onSubmit={startAimlapiTopup} /> {errorMessage && {errorMessage}} - - Press Enter to open checkout. Press Esc to go back. - ) } function renderAimlapiTopupProgress(): React.ReactNode { - const labels: Record = { - registering: 'Registering AI/ML API account...', - registered: 'Account registered.', - 'signing-in': 'Signing in to AI/ML API...', - 'signed-in': 'Signed in.', - 'creating-session': 'Creating checkout session...', - 'opening-checkout': 'Opening checkout...', - 'waiting-payment': 'Waiting for payment...', - 'provisioning-key': 'Issuing API key...', - } - const status = aimlapiTopupStatus - ? labels[aimlapiTopupStatus] - : 'Preparing AI/ML API top-up...' - return ( - - AI/ML API top-up - - {status} - {aimlapiTopupDetail ? {aimlapiTopupDetail} : null} + {aimlapiTopupDetail ? ( + <> + Opening checkout in browser... + {AIMLAPI_MESSAGES.topUpBrowserFallback} + {/* Stripe Checkout URLs are signed and can require their query and + fragment verbatim. This is an explicit user-facing fallback, + not a log field, so redacting it would make the link unusable. */} + + {wrapAimlapiCheckoutUrl( + aimlapiTopupDetail, + terminalColumns - 4, + ).map((line, index) => ( + {line} + ))} + + + ) : ( + + )} {errorMessage ? {errorMessage} : null} - - {isAimlapiTopupRunning - ? 'Complete checkout in the browser. This screen will continue automatically.' - : 'Press Esc to go back.'} - + + ) + } + + function renderAimlapiDone(): React.ReactNode { + const amountUsdMinor = parseAimlapiAmountUsd(aimlapiTopupAmountUsd) + const amountUsd = + amountUsdMinor % 100 === 0 + ? String(amountUsdMinor / 100) + : (amountUsdMinor / 100).toFixed(2) + return ( + + {aimlapiDoneKind === 'topup' ? ( + <> + {AIMLAPI_MESSAGES.topUpSuccess(amountUsd)} + {aimlapiNewAccount ? ( + <> + + {AIMLAPI_MESSAGES.successMagicLink(aimlapiTopupEmail)} + + ) : null} + + ) : ( + {AIMLAPI_MESSAGES.everythingRuns} + )} + + Press Enter to continue. ) } @@ -3175,21 +3840,27 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { case 'aimlapi-api-key-choice': content = renderAimlapiApiKeyChoice() break + case 'aimlapi-configured': + content = renderAimlapiConfigured() + break case 'aimlapi-topup-email': content = renderAimlapiTopupEmail() break - case 'aimlapi-topup-amount': - content = renderAimlapiTopupAmount() + case 'aimlapi-signin-code': + content = renderAimlapiSignInCode() break - case 'aimlapi-topup-password': - content = renderAimlapiTopupPassword() + case 'aimlapi-low-balance': + content = renderAimlapiLowBalance() break - case 'aimlapi-topup-method': - content = renderAimlapiTopupMethod() + case 'aimlapi-topup-amount': + content = renderAimlapiTopupAmount() break case 'aimlapi-topup-progress': content = renderAimlapiTopupProgress() break + case 'aimlapi-done': + content = renderAimlapiDone() + break case 'preset-api-key': content = renderPresetApiKey() break diff --git a/src/integrations/aimlapi/client.test.ts b/src/integrations/aimlapi/client.test.ts new file mode 100644 index 0000000000..1793d46575 --- /dev/null +++ b/src/integrations/aimlapi/client.test.ts @@ -0,0 +1,157 @@ +import { afterEach, expect, mock, test } from 'bun:test' + +import { AimlapiClient } from './client.js' +import type { AimlapiEndpoints } from './config.js' + +const originalFetch = globalThis.fetch +afterEach(() => { + globalThis.fetch = originalFetch +}) + +const endpoints: AimlapiEndpoints = { + authBaseUrl: 'https://auth.example.test', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.example.test/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://front.example.test', +} + +function jsonResponse(value: unknown): Response { + return new Response(JSON.stringify(value), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }) +} + +test('passwordless onboarding methods use the current backend contracts', async () => { + const calls: Array<{ url: string; init?: RequestInit; body?: unknown }> = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + calls.push({ + url, + init, + body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined, + }) + if (url.endsWith('/v1/auth/account') && init?.method === 'PATCH') { + return jsonResponse({ action: 'sign-in' }) + } + if (url.endsWith('/code/verify')) return jsonResponse({ token: 'bearer', exp: 1 }) + if (url.endsWith('/passwordless')) return jsonResponse({ token: 'new-bearer', exp: 2 }) + if (url.endsWith('/v1/keys')) return jsonResponse({ key: 'key_test', id: 'id_test' }) + if (url.endsWith('/billing/balance')) { + return jsonResponse({ balance: 10, lowBalance: true, lowBalanceThreshold: 20 }) + } + return new Response('', { status: 204 }) + }) as unknown as typeof fetch + + const client = new AimlapiClient(endpoints) + expect(await client.checkAccount('user@example.com')).toEqual({ action: 'sign-in' }) + await client.sendSignInCode('user@example.com') + expect(await client.verifySignInCode('user@example.com', '123456')).toEqual({ + token: 'bearer', + exp: 1, + }) + expect(await client.createPasswordlessAccount('new@example.com')).toEqual({ + token: 'new-bearer', + exp: 2, + }) + expect(await client.createKey('bearer', 'OpenClaude CLI')).toEqual({ + key: 'key_test', + id: 'id_test', + }) + expect((await client.getBalance('key_test')).lowBalance).toBe(true) + + expect(calls.map(call => [call.init?.method, call.url, call.body])).toEqual([ + ['PATCH', 'https://auth.example.test/v1/auth/account', { email: 'user@example.com' }], + ['POST', 'https://auth.example.test/v1/auth/sign-in/code', { email: 'user@example.com' }], + ['POST', 'https://auth.example.test/v1/auth/sign-in/code/verify', { email: 'user@example.com', code: '123456' }], + ['POST', 'https://auth.example.test/v1/auth/account/passwordless', { email: 'new@example.com' }], + ['POST', 'https://app.example.test/v1/keys', { name: 'OpenClaude CLI' }], + ['GET', 'https://api.example.test/v1/billing/balance', undefined], + ]) +}) + +test('pay only sends autoTopUp when it is enabled', async () => { + const bodies: unknown[] = [] + globalThis.fetch = mock(async (_input: string | URL | Request, init?: RequestInit) => { + bodies.push(typeof init?.body === 'string' ? JSON.parse(init.body) : undefined) + return jsonResponse({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test' }, + partnerCheckout: { sessionToken: 'session' }, + }) + }) as unknown as typeof fetch + + const client = new AimlapiClient(endpoints) + await client.pay('bearer', 'session', { + amountUsdMinor: 2500, + paymentSessionId: 'payment-id', + }) + await client.pay('bearer', 'session', { + amountUsdMinor: 2500, + paymentSessionId: 'payment-id', + autoTopUp: true, + }) + expect(bodies).toEqual([ + { amountUsdMinor: 2500, paymentSessionId: 'payment-id', method: 'card' }, + { amountUsdMinor: 2500, paymentSessionId: 'payment-id', method: 'card', autoTopUp: true }, + ]) +}) + +test('topUpByKey uses the v2 billing endpoint and API key bearer', async () => { + let seenUrl = '' + let seenHeaders = new Headers() + let seenBody: unknown + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + seenUrl = String(input) + seenHeaders = new Headers(init?.headers) + seenBody = typeof init?.body === 'string' ? JSON.parse(init.body) : undefined + return jsonResponse({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test' }, + partnerCheckout: { sessionToken: 'session' }, + }) + }) as unknown as typeof fetch + + const client = new AimlapiClient(endpoints) + await client.topUpByKey('key_test', { + sessionToken: 'session', + amountUsdMinor: 2500, + paymentSessionId: 'payment-id', + autoTopUp: true, + }) + + expect(seenUrl).toBe('https://api.example.test/v2/billing/topup') + expect(seenHeaders.get('Authorization')).toBe('Bearer key_test') + expect(seenBody).toEqual({ + sessionToken: 'session', + amountUsdMinor: 2500, + paymentSessionId: 'payment-id', + autoTopUp: true, + }) +}) + +test('typed requests reject an empty successful response', async () => { + globalThis.fetch = mock(async () => new Response('', { status: 204 })) as unknown as typeof fetch + const client = new AimlapiClient(endpoints) + await expect(client.getBalance('key_test')).rejects.toThrow('returned empty body') +}) + +test('response bodies are capped before decoding or surfacing errors', async () => { + globalThis.fetch = mock( + async () => new Response('x'.repeat((1 << 20) + 1), { status: 502 }), + ) as unknown as typeof fetch + const client = new AimlapiClient(endpoints) + await expect(client.getBalance('key_test')).rejects.toThrow( + 'response body exceeds 1048576 bytes', + ) +}) + +test('token-producing methods reject an empty token', async () => { + globalThis.fetch = mock(async () => jsonResponse({ token: '', exp: 1 })) as unknown as typeof fetch + const client = new AimlapiClient(endpoints) + await expect(client.verifySignInCode('user@example.com', '123456')).rejects.toThrow( + 'did not return an auth token', + ) + await expect(client.createPasswordlessAccount('user@example.com')).rejects.toThrow( + 'did not return an auth token', + ) +}) diff --git a/src/integrations/aimlapi/client.ts b/src/integrations/aimlapi/client.ts index 201754dc16..f4fc984fc6 100644 --- a/src/integrations/aimlapi/client.ts +++ b/src/integrations/aimlapi/client.ts @@ -1,14 +1,4 @@ -/** - * AI/ML API partner-checkout HTTP client. - * - * Talks to two services: - * - app/auth (`authBaseUrl`) - `POST /v1/auth/account` (signup) / - * `PUT /v1/auth/account` (login) -> Bearer token - * - app/gateway(`appBaseUrl`) - `/v3/partner-checkout/*` - * - * Uses the global `fetch` (Node >= 22). All error bodies are surfaced verbatim - * so failures are debuggable. - */ +/** AI/ML API passwordless onboarding and partner-checkout HTTP client. */ import { createCombinedAbortSignal } from '../../utils/combinedAbortSignal.js' import type { AimlapiEndpoints } from './config.js' @@ -45,15 +35,57 @@ export type PayResult = { partnerCheckout: PartnerCheckoutSession } -export type ExchangeResult = { - apiKey: string - apiKeyId: string -} +export type TopUpByKeyResult = PayResult -export type PaymentMethod = 'card' | 'crypto' +export type ExchangeResult = { apiKey: string; apiKeyId: string } export type AuthResult = { token: string; exp: number } +export type AccountCheckResult = { + action: 'sign-in' | 'sign-up' + provider?: string | null +} +export type CreatedKey = { key: string; id: string } +export type BalanceResult = { + balance: number + lowBalance: boolean + lowBalanceThreshold: number +} + +const REQUEST_TIMEOUT_MS = 60_000 +const MAX_RESPONSE_BODY_BYTES = 1 << 20 -const REQUEST_TIMEOUT_MS = 30_000 +class AimlapiResponseTooLargeError extends Error { + constructor() { + super(`AI/ML API response body exceeds ${MAX_RESPONSE_BODY_BYTES} bytes.`) + this.name = 'AimlapiResponseTooLargeError' + } +} + +async function readResponseText(response: Response): Promise { + if (!response.body) return '' + const reader = response.body.getReader() + const decoder = new TextDecoder() + let totalBytes = 0 + let text = '' + try { + while (true) { + const { done, value } = await reader.read() + if (done) break + totalBytes += value.byteLength + if (totalBytes > MAX_RESPONSE_BODY_BYTES) { + try { + await reader.cancel() + } catch { + // Keep the deterministic size-limit error if stream cancellation fails. + } + throw new AimlapiResponseTooLargeError() + } + text += decoder.decode(value, { stream: true }) + } + return text + decoder.decode() + } finally { + reader.releaseLock() + } +} export class AimlapiApiError extends Error { constructor( @@ -69,39 +101,73 @@ export class AimlapiApiError extends Error { export class AimlapiClient { constructor(private readonly endpoints: AimlapiEndpoints) {} - /** Register a new AI/ML API account -> access (Bearer) token. */ - async signup(input: { - email: string - password: string - inviteCode?: string - }): Promise { - return this.request( - `${this.endpoints.authBaseUrl}/v1/auth/account`, - { - method: 'POST', - body: { - email: input.email, - password: input.password, - ...(input.inviteCode ? { inviteCode: input.inviteCode } : {}), - }, - }, + async checkAccount(email: string, signal?: AbortSignal): Promise { + return this.request(`${this.endpoints.authBaseUrl}/v1/auth/account`, { + method: 'PATCH', + body: { email }, + signal, + }) + } + + async sendSignInCode(email: string, signal?: AbortSignal): Promise { + await this.request(`${this.endpoints.authBaseUrl}/v1/auth/sign-in/code`, { + method: 'POST', + body: { email }, + signal, + expectJson: false, + }) + } + + async verifySignInCode( + email: string, + code: string, + signal?: AbortSignal, + ): Promise { + const result = await this.request( + `${this.endpoints.authBaseUrl}/v1/auth/sign-in/code/verify`, + { method: 'POST', body: { email, code }, signal }, + ) + if (!result.token?.trim()) throw new Error('AI/ML API did not return an auth token.') + return result + } + + async createPasswordlessAccount(email: string, signal?: AbortSignal): Promise { + const result = await this.request( + `${this.endpoints.authBaseUrl}/v1/auth/account/passwordless`, + { method: 'POST', body: { email }, signal }, ) + if (!result.token?.trim()) throw new Error('AI/ML API did not return an auth token.') + return result + } + + async createKey( + bearer: string, + name: string, + signal?: AbortSignal, + ): Promise { + const result = await this.request(`${this.endpoints.appBaseUrl}/v1/keys`, { + method: 'POST', + bearer, + body: name.trim() ? { name: name.trim() } : {}, + signal, + }) + if (!result.key?.trim()) { + throw new Error('AI/ML API did not return an API key.') + } + return result } - /** Sign in with email + password -> access (Bearer) token. */ - async login(email: string, password: string): Promise { - return this.request( - `${this.endpoints.authBaseUrl}/v1/auth/account`, - { method: 'PUT', body: { email, password } }, + async getBalance(apiKey: string, signal?: AbortSignal): Promise { + return this.request( + `${this.endpoints.inferenceBaseUrl.replace(/\/+$/, '')}/billing/balance`, + { method: 'GET', bearer: apiKey, signal }, ) } - /** Create a partner-checkout session (public - no auth). */ - async createSession(input: { - partnerId: string - partnerName?: string | null - returnUrl?: string | null - }): Promise { + async createSession( + input: { partnerId: string; partnerName?: string | null; returnUrl?: string | null }, + signal?: AbortSignal, + ): Promise { return this.request( `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions`, { @@ -111,36 +177,32 @@ export class AimlapiClient { ...(input.partnerName ? { partnerName: input.partnerName } : {}), ...(input.returnUrl ? { returnUrl: input.returnUrl } : {}), }, + signal, }, ) } - /** Poll a session by its one-time token (public - no auth). */ - async getSession(sessionToken: string): Promise { + async getSession( + sessionToken: string, + signal?: AbortSignal, + ): Promise { return this.request( `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}`, - { method: 'GET' }, + { method: 'GET', signal }, ) } - /** - * Bind the session to the logged-in user and open a hosted payment page. - * Requires the Bearer token. Returns `checkout.payUrl` to open in a browser. - * - * `successUrl`/`cancelUrl` are the co-branded `/checkout` return URLs the - * payment provider redirects the browser to after pay/cancel (see - * `buildPartnerCheckoutReturnUrls`). When omitted the backend falls back to a - * bare, non-co-branded `/checkout?checkout=success`. - */ async pay( bearer: string, sessionToken: string, input: { amountUsdMinor: number - method: PaymentMethod + paymentSessionId: string successUrl?: string cancelUrl?: string + autoTopUp?: boolean }, + signal?: AbortSignal, ): Promise { return this.request( `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}/pay`, @@ -149,60 +211,107 @@ export class AimlapiClient { bearer, body: { amountUsdMinor: input.amountUsdMinor, - method: input.method, + paymentSessionId: input.paymentSessionId, + method: 'card', ...(input.successUrl ? { successUrl: input.successUrl } : {}), ...(input.cancelUrl ? { cancelUrl: input.cancelUrl } : {}), + ...(input.autoTopUp ? { autoTopUp: true } : {}), }, + signal, }, ) } - /** - * Exchange a PAID session for the raw CLI key. One-shot: a second call after - * a successful exchange loses the claim and returns no key. Requires Bearer. - */ - async exchange(bearer: string, sessionToken: string): Promise { + async topUpByKey( + apiKey: string, + input: { + sessionToken: string + amountUsdMinor: number + paymentSessionId: string + successUrl?: string + cancelUrl?: string + autoTopUp?: boolean + }, + signal?: AbortSignal, + ): Promise { + const inferenceBase = this.endpoints.inferenceBaseUrl + .trim() + .replace(/\/+$/, '') + .replace(/\/v1$/i, '') + return this.request(`${inferenceBase}/v2/billing/topup`, { + method: 'POST', + bearer: apiKey, + body: { + sessionToken: input.sessionToken, + amountUsdMinor: input.amountUsdMinor, + paymentSessionId: input.paymentSessionId, + ...(input.successUrl ? { successUrl: input.successUrl } : {}), + ...(input.cancelUrl ? { cancelUrl: input.cancelUrl } : {}), + ...(input.autoTopUp ? { autoTopUp: true } : {}), + }, + signal, + }) + } + + async exchange( + bearer: string, + sessionToken: string, + signal?: AbortSignal, + ): Promise { return this.request( `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}/exchange`, - { method: 'POST', bearer }, + { method: 'POST', bearer, signal }, ) } private async request( url: string, options: { - method: 'GET' | 'POST' | 'PUT' + method: 'GET' | 'POST' | 'PATCH' body?: unknown bearer?: string + signal?: AbortSignal + expectJson?: boolean }, ): Promise { const headers: Record = { Accept: 'application/json' } - if (options.body !== undefined) { - headers['Content-Type'] = 'application/json' - } - if (options.bearer) { - headers.Authorization = `Bearer ${options.bearer}` - } + if (options.body !== undefined) headers['Content-Type'] = 'application/json' + if (options.bearer) headers.Authorization = `Bearer ${options.bearer.trim()}` - const { signal, cleanup } = createCombinedAbortSignal(undefined, { + const combined = createCombinedAbortSignal(options.signal, { timeoutMs: REQUEST_TIMEOUT_MS, }) - let response: Response - let text: string try { response = await fetch(url, { method: options.method, headers, - signal, + signal: combined.signal, ...(options.body !== undefined ? { body: JSON.stringify(options.body) } : {}), }) - text = await response.text() } catch (error) { + combined.cleanup() + if (options.signal?.aborted) throw error const reason = error instanceof Error ? error.message : String(error) throw new AimlapiApiError(`Network request to ${url} failed: ${reason}`, 0, '') + } + + let text: string + try { + text = await readResponseText(response) + } catch (error) { + if (options.signal?.aborted) throw error + if (error instanceof AimlapiResponseTooLargeError) { + throw new AimlapiApiError( + `${options.method} ${url} response body exceeds ${MAX_RESPONSE_BODY_BYTES} bytes`, + response.status, + '', + ) + } + const reason = error instanceof Error ? error.message : String(error) + throw new AimlapiApiError(`Network response from ${url} failed: ${reason}`, 0, '') } finally { - cleanup() + combined.cleanup() } if (!response.ok) { @@ -212,9 +321,13 @@ export class AimlapiClient { text, ) } - - if (!text) { - return undefined as T + if (!text.trim()) { + if (options.expectJson === false) return undefined as T + throw new AimlapiApiError( + `${options.method} ${url} returned empty body`, + response.status, + '', + ) } try { return JSON.parse(text) as T diff --git a/src/integrations/aimlapi/config.test.ts b/src/integrations/aimlapi/config.test.ts new file mode 100644 index 0000000000..96b5d842b8 --- /dev/null +++ b/src/integrations/aimlapi/config.test.ts @@ -0,0 +1,79 @@ +import { afterEach, expect, test } from 'bun:test' + +import { + buildPartnerCheckoutReturnUrls, + buildPartnerReturnUrl, + isCanonicalAimlapiInferenceBaseUrl, + resolvePartnerId, + resolveEndpoints, + withResolvedPartnerHeader, +} from './config.js' + +const envNames = [ + 'AIMLAPI_AUTH_URL', + 'AIMLAPI_APP_URL', + 'AIMLAPI_INFERENCE_URL', + 'AIMLAPI_PAY_URL', + 'AIMLAPI_VERIFICATION_BASE_URL', + 'AIMLAPI_RETURN_URL', + 'AIMLAPI_PARTNER_ID', +] as const +const originalEnv = Object.fromEntries(envNames.map(name => [name, process.env[name]])) + +afterEach(() => { + for (const name of envNames) { + const value = originalEnv[name] + if (value === undefined) delete process.env[name] + else process.env[name] = value + } +}) + +test('resolveEndpoints returns the production passwordless and checkout endpoints', () => { + for (const name of envNames) delete process.env[name] + expect(resolveEndpoints()).toEqual({ + authBaseUrl: 'https://auth.aimlapi.com', + appBaseUrl: 'https://app.aimlapi.com', + inferenceBaseUrl: 'https://api.aimlapi.com/v1', + payBaseUrl: 'https://pay.aimlapi.com', + verificationBaseUrl: 'https://aimlapi.com/app', + }) +}) + +test('checkout and browser return URLs stay in the selected environment', () => { + expect(buildPartnerCheckoutReturnUrls('https://pay.example.test/', 'a/b')).toEqual({ + successUrl: + 'https://pay.example.test/checkout?checkout=success&partnerCheckout=1&sessionToken=a%2Fb', + cancelUrl: + 'https://pay.example.test/checkout?checkout=cancel&partnerCheckout=1&sessionToken=a%2Fb', + }) + expect(buildPartnerCheckoutReturnUrls('', 'token')).toEqual({}) + expect(buildPartnerReturnUrl('https://front.example.test/')).toBe( + 'https://front.example.test', + ) +}) + +test('AIMLAPI_RETURN_URL overrides the browser landing page', () => { + process.env.AIMLAPI_RETURN_URL = 'https://return.example.test/done' + expect(buildPartnerReturnUrl('https://front.example.test')).toBe( + 'https://return.example.test/done', + ) +}) + +test('partner id override is shared with the inference header', () => { + process.env.AIMLAPI_PARTNER_ID = 'part_override' + expect(resolvePartnerId()).toBe('part_override') + expect( + withResolvedPartnerHeader({ + 'x-aimlapi-partner-id': 'part_catalog', + 'X-Title': 'OpenClaude', + }), + ).toEqual({ + 'X-AIMLAPI-Partner-ID': 'part_override', + 'X-Title': 'OpenClaude', + }) +}) + +test('canonical endpoint check excludes proxies', () => { + expect(isCanonicalAimlapiInferenceBaseUrl('https://api.aimlapi.com/v1/')).toBe(true) + expect(isCanonicalAimlapiInferenceBaseUrl('https://proxy.example.test/v1')).toBe(false) +}) diff --git a/src/integrations/aimlapi/config.ts b/src/integrations/aimlapi/config.ts index 985efc3484..508b5e5eba 100644 --- a/src/integrations/aimlapi/config.ts +++ b/src/integrations/aimlapi/config.ts @@ -1,13 +1,12 @@ /** * AI/ML API (aimlapi.com) integration - endpoint configuration. * - * Wires OpenClaude to the AI/ML API "partner checkout" flow so a user can log - * in, top up their balance, and have the issued key written back into + * Wires OpenClaude to the AI/ML API passwordless onboarding and partner + * checkout flow so a user can sign in, top up their balance, and have the issued key written back into * OpenClaude's provider profile automatically. Usage attributes to the Gitlawb * rebate partner (see the partner id below). * - * Override any single URL via the `AIMLAPI_AUTH_URL`, `AIMLAPI_APP_URL`, or - * `AIMLAPI_INFERENCE_URL` env vars. + * Override any single URL via the corresponding `AIMLAPI_*_URL` env var. */ export type AimlapiEndpoints = { @@ -15,14 +14,20 @@ export type AimlapiEndpoints = { authBaseUrl: string /** app/gateway BFF - hosts `/v3/partner-checkout/*`. */ appBaseUrl: string + /** hosted checkout frontend base URL. */ + payBaseUrl: string /** OpenAI-compatible inference base URL written into the provider profile. */ inferenceBaseUrl: string + /** browser landing page after checkout / consent completes. */ + verificationBaseUrl: string } const DEFAULT_ENDPOINTS: AimlapiEndpoints = { authBaseUrl: 'https://auth.aimlapi.com', appBaseUrl: 'https://app.aimlapi.com', + payBaseUrl: 'https://pay.aimlapi.com', inferenceBaseUrl: 'https://api.aimlapi.com/v1', + verificationBaseUrl: 'https://aimlapi.com/app', } /** @@ -34,9 +39,11 @@ const DEFAULT_ENDPOINTS: AimlapiEndpoints = { */ export const DEFAULT_PARTNER_ID = 'part_62yQoGYDq4Yqnrj2R1iGrDNJ' export const DEFAULT_PARTNER_NAME = 'Gitlawb' +export const PARTNER_HEADER_NAME = 'X-AIMLAPI-Partner-ID' /** Default model id written into the profile - override with `--model`. */ -export const DEFAULT_MODEL = 'gpt-4o' +export const DEFAULT_MODEL = 'anthropic/claude-sonnet-5' +export const DEFAULT_RETURN_URL = 'https://aimlapi.com/app' /** Top-up bounds enforced by the backend DTO (USD minor units / cents). */ export const MIN_AMOUNT_USD_MINOR = 2000 // $20 @@ -47,11 +54,51 @@ export function resolveEndpoints(): AimlapiEndpoints { return { authBaseUrl: process.env.AIMLAPI_AUTH_URL?.trim() || DEFAULT_ENDPOINTS.authBaseUrl, appBaseUrl: process.env.AIMLAPI_APP_URL?.trim() || DEFAULT_ENDPOINTS.appBaseUrl, + payBaseUrl: process.env.AIMLAPI_PAY_URL?.trim() || DEFAULT_ENDPOINTS.payBaseUrl, inferenceBaseUrl: process.env.AIMLAPI_INFERENCE_URL?.trim() || DEFAULT_ENDPOINTS.inferenceBaseUrl, + verificationBaseUrl: + process.env.AIMLAPI_VERIFICATION_BASE_URL?.trim() || + DEFAULT_ENDPOINTS.verificationBaseUrl, } } +/** Resolve checkout and inference attribution with one shared precedence. */ +export function resolvePartnerId(explicit?: string): string { + return ( + explicit?.trim() || + process.env.AIMLAPI_PARTNER_ID?.trim() || + DEFAULT_PARTNER_ID + ) +} + +/** + * Return a header copy with the effective partner id. Header matching is + * case-insensitive so an override replaces the catalog spelling instead of + * creating a duplicate header. + */ +export function withResolvedPartnerHeader( + headers: Readonly>, + explicit?: string, +): Record { + const resolved: Record = {} + for (const [name, value] of Object.entries(headers)) { + if (name.trim().toLowerCase() === PARTNER_HEADER_NAME.toLowerCase()) continue + resolved[name] = value + } + resolved[PARTNER_HEADER_NAME] = resolvePartnerId(explicit) + return resolved +} + +function normalizeBaseUrl(value: string): string { + return value.trim().replace(/\/+$/, '').toLowerCase() +} + +/** Catalog attribution and existing-key preflight are production-only. */ +export function isCanonicalAimlapiInferenceBaseUrl(value: string): boolean { + return normalizeBaseUrl(value) === normalizeBaseUrl(DEFAULT_ENDPOINTS.inferenceBaseUrl) +} + /** * Build the co-branded checkout return URLs the hosted payment page redirects * to after the user pays or cancels. Carrying `sessionToken` + `partnerCheckout=1` @@ -61,10 +108,13 @@ export function resolveEndpoints(): AimlapiEndpoints { * `/checkout?checkout=success` that is NOT co-branded. */ export function buildPartnerCheckoutReturnUrls( - appBaseUrl: string, + payBaseUrl: string, sessionToken: string, -): { successUrl: string; cancelUrl: string } { - const base = appBaseUrl.replace(/\/+$/, '') +): { successUrl?: string; cancelUrl?: string } { + const base = payBaseUrl.trim().replace(/\/+$/, '') + if (!base) { + return {} + } const token = encodeURIComponent(sessionToken) const query = (status: string): string => `checkout=${status}&partnerCheckout=1&sessionToken=${token}` @@ -73,3 +123,15 @@ export function buildPartnerCheckoutReturnUrls( cancelUrl: `${base}/checkout?${query('cancel')}`, } } + +/** + * Browser landing URL after checkout. OpenClaude learns success by polling, so + * this must be an ordinary HTTPS page rather than an unregistered custom scheme. + */ +export function buildPartnerReturnUrl(frontendBaseUrl: string): string { + return ( + process.env.AIMLAPI_RETURN_URL?.trim() || + frontendBaseUrl.trim().replace(/\/+$/, '') || + DEFAULT_RETURN_URL + ) +} diff --git a/src/integrations/aimlapi/index.ts b/src/integrations/aimlapi/index.ts index b25d5bb52d..1409e87fa0 100644 --- a/src/integrations/aimlapi/index.ts +++ b/src/integrations/aimlapi/index.ts @@ -1,12 +1,24 @@ export { provisionAimlapiKey, runAimlapiTopup, + topUpAimlapiByApiKey, + type AimlapiByKeyTopupOptions, type AimlapiProvisionOptions, type AimlapiProvisionedKey, type AimlapiTopupOptions, type AimlapiTopupStatus, + pollUntilPaid, } from './topup.js' +export { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' +export { + beginAimlapiEmailOnboarding, + completeAimlapiCodeSignIn, + validateAimlapiApiKey, + type AimlapiCodeSignInResult, + type AimlapiEmailOnboardingResult, +} from './onboarding.js' export { AimlapiClient, AimlapiApiError } from './client.js' +export { AIMLAPI_MESSAGES } from './messages.js' export type { AimlapiEndpoints, } from './config.js' diff --git a/src/integrations/aimlapi/messages.ts b/src/integrations/aimlapi/messages.ts new file mode 100644 index 0000000000..78f2fe8ff8 --- /dev/null +++ b/src/integrations/aimlapi/messages.ts @@ -0,0 +1,28 @@ +/** Canonical AIMLAPI onboarding copy ported from Zero. */ + +export const AIMLAPI_MESSAGES = { + apiKeyInputPrompt: 'Enter your aimlapi.com key.', + apiKeyHiddenHint: 'Your API key will be hidden and verified automatically.', + apiKeyInvalid: + 'API key is invalid. Please make sure you enter a valid aimlapi.com key.', + pickPathPrompt: 'Do you have aimlapi.com key?', + pickPathHaveKey: 'I already have aimlapi.com key', + pickPathNewUser: 'I am a new user', + enterEmail: 'Enter your email.', + emailInvalid: 'Email format is incorrect.', + codeSent: (email: string) => `Enter the 6-digit code sent to ${email}.`, + codeIncorrect: "Code you've entered is incorrect.", + lowBalance: 'Your aimlapi.com credits are running low - top up now?', + lowBalanceTopUp: "Sure, let's do that", + lowBalanceSkip: "I'll skip for now", + topUpPrompt: 'Add credits (min $20).', + amountRequired: 'Please enter a top-up amount.', + topUpBrowserFallback: + 'If the browser did not open automatically please use this link to top up your account:', + topUpFailed: 'Top up failed. Please try again.', + everythingRuns: 'Everything is ready.', + topUpSuccess: (amountUsd: string) => + `Top-up successful - $${amountUsd} credited to your account`, + successMagicLink: (email: string) => + `We've emailed you a magic link to ${email}. Use it to access your aimlapi.com account and review your usage.`, +} as const diff --git a/src/integrations/aimlapi/onboarding.test.ts b/src/integrations/aimlapi/onboarding.test.ts new file mode 100644 index 0000000000..3d625f40ec --- /dev/null +++ b/src/integrations/aimlapi/onboarding.test.ts @@ -0,0 +1,115 @@ +import { afterEach, expect, mock, test } from 'bun:test' + +import { + beginAimlapiEmailOnboarding, + completeAimlapiCodeSignIn, + validateAimlapiApiKey, +} from './onboarding.js' + +const originalFetch = globalThis.fetch +const originalEnv = { + AIMLAPI_AUTH_URL: process.env.AIMLAPI_AUTH_URL, + AIMLAPI_APP_URL: process.env.AIMLAPI_APP_URL, + AIMLAPI_INFERENCE_URL: process.env.AIMLAPI_INFERENCE_URL, +} + +afterEach(() => { + globalThis.fetch = originalFetch + for (const [name, value] of Object.entries(originalEnv)) { + if (value === undefined) delete process.env[name] + else process.env[name] = value + } +}) + +function response(value: unknown, status = 200): Response { + return new Response(JSON.stringify(value), { status }) +} + +test('existing account onboarding sends a code, creates a key, and reports low balance', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + calls.push(`${init?.method} ${url}`) + if (url.endsWith('/v1/auth/account')) return response({ action: 'sign-in' }) + if (url.endsWith('/v1/auth/sign-in/code')) return new Response('', { status: 204 }) + if (url.endsWith('/code/verify')) return response({ token: 'session', exp: 1 }) + if (url.endsWith('/v1/keys')) return response({ key: 'key_test', id: 'id_test' }) + if (url.endsWith('/billing/balance')) { + return response({ balance: 5, lowBalance: true, lowBalanceThreshold: 20 }) + } + return response({}, 404) + }) as unknown as typeof fetch + + expect(await beginAimlapiEmailOnboarding('user@example.com')).toEqual({ + action: 'code-sent', + }) + expect(await completeAimlapiCodeSignIn('user@example.com', '123456')).toEqual({ + sessionToken: 'session', + apiKey: 'key_test', + apiKeyId: 'id_test', + lowBalance: true, + }) + expect(calls).toEqual([ + 'PATCH https://auth.example.test/v1/auth/account', + 'POST https://auth.example.test/v1/auth/sign-in/code', + 'POST https://auth.example.test/v1/auth/sign-in/code/verify', + 'POST https://app.example.test/v1/keys', + 'GET https://api.example.test/v1/billing/balance', + ]) +}) + +test('new account onboarding returns a passwordless session', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + return url.endsWith('/passwordless') + ? response({ token: 'new-session', exp: 1 }) + : response({ action: 'sign-up' }) + }) as unknown as typeof fetch + + expect(await beginAimlapiEmailOnboarding('new@example.com')).toEqual({ + action: 'new-account', + sessionToken: 'new-session', + }) +}) + +test('existing API key validation uses the balance endpoint', async () => { + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + expect(String(input)).toBe('https://api.example.test/v1/billing/balance') + expect(init?.method).toBe('GET') + expect(new Headers(init?.headers).get('Authorization')).toBe('Bearer key_test') + return response({ balance: 25, lowBalance: false, lowBalanceThreshold: 20 }) + }) as unknown as typeof fetch + + expect(await validateAimlapiApiKey(' key_test ')).toEqual({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + }) +}) + +test('existing API key validation can pin the validated endpoint', async () => { + process.env.AIMLAPI_INFERENCE_URL = 'https://override.example.test/v1' + globalThis.fetch = mock(async (input: string | URL | Request) => { + expect(String(input)).toBe('https://api.aimlapi.com/v1/billing/balance') + return response({ balance: 25, lowBalance: false, lowBalanceThreshold: 20 }) + }) as unknown as typeof fetch + + await validateAimlapiApiKey( + 'key_test', + undefined, + 'https://api.aimlapi.com/v1', + ) +}) + +test('unknown account actions are rejected instead of signing up', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + globalThis.fetch = mock(async () => response({ action: 'migrate' })) as unknown as typeof fetch + await expect(beginAimlapiEmailOnboarding('user@example.com')).rejects.toThrow( + 'unsupported account action', + ) +}) diff --git a/src/integrations/aimlapi/onboarding.ts b/src/integrations/aimlapi/onboarding.ts new file mode 100644 index 0000000000..774dd04b86 --- /dev/null +++ b/src/integrations/aimlapi/onboarding.ts @@ -0,0 +1,70 @@ +import { AimlapiClient, type BalanceResult } from './client.js' +import { resolveEndpoints } from './config.js' + +function clientForInferenceBaseUrl(inferenceBaseUrl?: string): AimlapiClient { + const endpoints = resolveEndpoints() + if (inferenceBaseUrl?.trim()) endpoints.inferenceBaseUrl = inferenceBaseUrl.trim() + return new AimlapiClient(endpoints) +} + +export type AimlapiEmailOnboardingResult = + | { action: 'code-sent' } + | { action: 'new-account'; sessionToken: string } + +export type AimlapiCodeSignInResult = { + sessionToken: string + apiKey: string + apiKeyId: string + lowBalance: boolean +} + +export async function validateAimlapiApiKey( + apiKey: string, + signal?: AbortSignal, + inferenceBaseUrl?: string, +): Promise { + return clientForInferenceBaseUrl(inferenceBaseUrl).getBalance(apiKey.trim(), signal) +} + +export async function beginAimlapiEmailOnboarding( + email: string, + signal?: AbortSignal, +): Promise { + const client = new AimlapiClient(resolveEndpoints()) + const account = await client.checkAccount(email, signal) + switch (account.action) { + case 'sign-in': + await client.sendSignInCode(email, signal) + return { action: 'code-sent' } + case 'sign-up': { + const auth = await client.createPasswordlessAccount(email, signal) + return { action: 'new-account', sessionToken: auth.token } + } + default: + throw new Error(`AI/ML API returned an unsupported account action.`) + } +} + +export async function completeAimlapiCodeSignIn( + email: string, + code: string, + signal?: AbortSignal, + inferenceBaseUrl?: string, +): Promise { + const client = clientForInferenceBaseUrl(inferenceBaseUrl) + const auth = await client.verifySignInCode(email, code, signal) + const created = await client.createKey(auth.token, 'OpenClaude CLI', signal) + let lowBalance = false + try { + lowBalance = (await client.getBalance(created.key, signal)).lowBalance + } catch (error) { + if (signal?.aborted) throw error + // The key is already issued; a balance read failure must not discard it. + } + return { + sessionToken: auth.token, + apiKey: created.key, + apiKeyId: created.id, + lowBalance, + } +} diff --git a/src/integrations/aimlapi/prompt.ts b/src/integrations/aimlapi/prompt.ts index 348aff48fb..ea035c3c49 100644 --- a/src/integrations/aimlapi/prompt.ts +++ b/src/integrations/aimlapi/prompt.ts @@ -4,12 +4,12 @@ * they are not supplied via flags/env. */ -import { createInterface, type Interface } from 'node:readline' +import { createInterface } from 'node:readline' function assertInteractive(): void { if (!process.stdin.isTTY) { throw new Error( - 'No interactive terminal available. Provide credentials via --email (or AIMLAPI_EMAIL) and the AIMLAPI_PASSWORD env var.', + 'No interactive terminal available. Provide --email (or AIMLAPI_EMAIL) and, for an existing account, --code (or AIMLAPI_CODE).', ) } } @@ -31,33 +31,3 @@ export async function promptText( rl.close() } } - -/** Prompt for a secret without echoing keystrokes to the terminal. */ -export async function promptHidden(question: string): Promise { - assertInteractive() - const rl = createInterface({ - input: process.stdin, - output: process.stdout, - }) as Interface & { _writeToOutput?: (chunk: string) => void } - - // Mask everything except the prompt itself. - let muted = false - rl._writeToOutput = (chunk: string): void => { - if (muted) { - process.stdout.write('*') - } else { - process.stdout.write(chunk) - } - } - - try { - const answer = await new Promise((resolve) => { - rl.question(`${question}: `, resolve) - muted = true - }) - process.stdout.write('\n') - return answer - } finally { - rl.close() - } -} diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts new file mode 100644 index 0000000000..68c9ccb3cb --- /dev/null +++ b/src/integrations/aimlapi/topup.test.ts @@ -0,0 +1,373 @@ +import { afterEach, expect, mock, test } from 'bun:test' + +import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' + +mock.module('../../utils/browser.js', () => ({ + openBrowser: async () => {}, +})) +mock.module('../../utils/providerProfile.js', () => ({ + saveProfileFile: () => 'profile.json', +})) +mock.module('./prompt.js', () => ({ + promptText: async () => '', +})) +const { pollUntilPaid, provisionAimlapiKey, topUpAimlapiByApiKey } = + await import('./topup.js') +const { AimlapiClient } = await import('./client.js') + +const originalFetch = globalThis.fetch +const originalEnv = { + AIMLAPI_APP_URL: process.env.AIMLAPI_APP_URL, + AIMLAPI_INFERENCE_URL: process.env.AIMLAPI_INFERENCE_URL, + AIMLAPI_PAY_URL: process.env.AIMLAPI_PAY_URL, +} + +afterEach(() => { + globalThis.fetch = originalFetch + for (const [name, value] of Object.entries(originalEnv)) { + if (value === undefined) delete process.env[name] + else process.env[name] = value + } +}) + +test('parseAimlapiAmountUsd enforces checkout bounds', () => { + expect(parseAimlapiAmountUsd(undefined)).toBe(2500) + expect(parseAimlapiAmountUsd('20')).toBe(2000) + expect(parseAimlapiAmountUsd('25.25')).toBe(2525) + expect(parseAimlapiAmountUsd('10000')).toBe(1_000_000) + expect(() => parseAimlapiAmountUsd('19.99')).toThrow('Minimum top-up is $20') + expect(() => parseAimlapiAmountUsd('10000.01')).toThrow('Maximum top-up is $10000') + expect(() => parseAimlapiAmountUsd('nope')).toThrow('Pass a positive number of USD') + expect(() => parseAimlapiAmountUsd('Infinity')).toThrow('Pass a positive number of USD') +}) + +test('isValidAimlapiEmail rejects incomplete domains', () => { + expect(isValidAimlapiEmail('user@example.com')).toBe(true) + expect(isValidAimlapiEmail('user@example')).toBe(false) + expect(isValidAimlapiEmail('user@example.c')).toBe(false) + expect(isValidAimlapiEmail('user@.example.com')).toBe(false) +}) + +test('topUpAimlapiByApiKey funds the key account without exchange', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + calls.push(`${init?.method} ${url}`) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + } + if (url.endsWith('/v2/billing/topup')) { + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + } + if (url.endsWith('/v3/partner-checkout/sessions/session')) { + return Response.json({ sessionToken: 'session', status: 'paid' }) + } + return new Response('', { status: 404 }) + }) as unknown as typeof fetch + + const sessions: string[] = [] + const result = await topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + amountUsd: '25', + noOpen: true, + onSession: session => sessions.push(session), + }) + + expect(result.apiKey).toBe('key_test') + expect(sessions).toEqual(['session']) + expect(calls).toEqual([ + 'POST https://app.example.test/v3/partner-checkout/sessions', + 'POST https://api.example.test/v2/billing/topup', + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + ]) + expect(calls.some(call => call.endsWith('/exchange'))).toBe(false) +}) + +test('topUpAimlapiByApiKey resumes a paid session without charging again', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + calls.push(`${init?.method} ${String(input)}`) + return Response.json({ sessionToken: 'session', status: 'paid' }) + }) as unknown as typeof fetch + + await topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + resumeSessionToken: 'session', + amountUsd: '25', + noOpen: true, + }) + + expect(calls).toEqual([ + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + ]) +}) + +test('a pending resumed session is polled without paying again', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + const calls: string[] = [] + let reads = 0 + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + calls.push(`${init?.method} ${String(input)}`) + reads += 1 + return Response.json({ + sessionToken: 'session', + status: reads === 1 ? 'pending_payment' : 'paid', + }) + }) as unknown as typeof fetch + + await topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + resumeSessionToken: 'session', + amountUsd: '25', + noOpen: true, + }) + + expect(calls).toEqual([ + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + ]) +}) + +test('provisionAimlapiKey does not repeat an already completed exchange', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + calls.push(`${init?.method} ${String(input)}`) + return Response.json({ sessionToken: 'session', status: 'exchanged' }) + }) as unknown as typeof fetch + + await expect( + provisionAimlapiKey({ + sessionToken: 'account-session', + resumeSessionToken: 'session', + paymentSessionId: 'payment-id', + exchange: true, + amountUsd: '25', + noOpen: true, + }), + ).rejects.toThrow('Session was already exchanged') + + expect(calls).toEqual([ + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + ]) +}) + +test('an in-progress exchange is observed without issuing a second exchange', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + const calls: string[] = [] + let reads = 0 + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + calls.push(`${init?.method} ${String(input)}`) + reads += 1 + return Response.json({ + sessionToken: 'session', + status: reads === 1 ? 'exchanging' : 'exchanged', + }) + }) as unknown as typeof fetch + + await expect( + provisionAimlapiKey({ + sessionToken: 'account-session', + resumeSessionToken: 'session', + paymentSessionId: 'payment-id', + exchange: true, + amountUsd: '25', + noOpen: true, + }), + ).rejects.toThrow('Session was already exchanged') + expect(calls.every(call => call.startsWith('GET '))).toBe(true) +}) + +test('email-session checkout carries the stable payment id', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' + let payBody: Record | undefined + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + } + if (url.endsWith('/pay')) { + payBody = JSON.parse(String(init?.body)) as Record + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test/pay' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + } + return Response.json({ sessionToken: 'session', status: 'paid' }) + }) as unknown as typeof fetch + + await provisionAimlapiKey({ + sessionToken: 'account-session', + paymentSessionId: 'stable-payment-id', + exchange: false, + existingApiKey: 'key_test', + amountUsd: '25', + noOpen: true, + }) + + expect(payBody?.paymentSessionId).toBe('stable-payment-id') +}) + +test('checkout URL must be an absolute credential-free HTTPS URL', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + } + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'file:///tmp/checkout' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + }) as unknown as typeof fetch + + await expect( + topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + amountUsd: '25', + noOpen: true, + }), + ).rejects.toThrow('valid HTTPS checkout URL') +}) + +test('terminal resumed-session errors clear retained checkout state', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + globalThis.fetch = mock(async () => new Response('gone', { status: 404 })) as unknown as typeof fetch + const sessions: string[] = [] + + await expect( + topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + resumeSessionToken: 'dead-session', + amountUsd: '25', + noOpen: true, + onSession: session => sessions.push(session), + }), + ).rejects.toThrow('404') + expect(sessions).toEqual(['']) +}) + +test('dead sessions observed while polling are cleared immediately', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + } + if (url.endsWith('/v2/billing/topup')) { + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test/pay' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + } + return Response.json({ sessionToken: 'session', status: 'expired' }) + }) as unknown as typeof fetch + const sessions: string[] = [] + + await expect( + topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + amountUsd: '25', + noOpen: true, + onSession: session => sessions.push(session), + }), + ).rejects.toThrow('Payment expired') + expect(sessions).toEqual(['session', '']) +}) + +test('terminal API errors observed while polling clear retained checkout state', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + } + if (url.endsWith('/v2/billing/topup')) { + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test/pay' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + } + return new Response('gone', { status: 410 }) + }) as unknown as typeof fetch + const sessions: string[] = [] + + await expect( + topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + amountUsd: '25', + noOpen: true, + onSession: session => sessions.push(session), + }), + ).rejects.toThrow('410') + expect(sessions).toEqual(['session', '']) +}) + +test('polling retries a transient transport failure', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + let attempts = 0 + globalThis.fetch = mock(async () => { + attempts += 1 + if (attempts === 1) throw new TypeError('temporary connection reset') + return Response.json({ sessionToken: 'session', status: 'paid' }) + }) as unknown as typeof fetch + const client = new AimlapiClient({ + authBaseUrl: 'https://auth.example.test', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.example.test/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://front.example.test', + }) + + await expect(pollUntilPaid(client, 'session')).resolves.toEqual( + expect.objectContaining({ status: 'paid' }), + ) + expect(attempts).toBe(2) +}) + +test('by-key billing stays on the endpoint that validated the key', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://override.example.test/v1' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + calls.push(url) + if (url.endsWith('/v3/partner-checkout/sessions')) { + return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + } + if (url.endsWith('/v2/billing/topup')) { + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test/pay' }, + partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, + }) + } + return Response.json({ sessionToken: 'session', status: 'paid' }) + }) as unknown as typeof fetch + + await topUpAimlapiByApiKey({ + apiKey: 'production-key', + inferenceBaseUrl: 'https://api.aimlapi.com/v1', + paymentSessionId: 'payment-id', + amountUsd: '25', + noOpen: true, + }) + expect(calls).toContain('https://api.aimlapi.com/v2/billing/topup') + expect(calls).not.toContain('https://override.example.test/v2/billing/topup') +}) diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index a4348259d1..3fe65cf9ad 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -1,24 +1,6 @@ -/** - * AI/ML API seamless top-up flow. - * - * End to end: - * 1. Log in with AI/ML API credentials -> Bearer token (held by the CLI) - * 2. Create a partner-checkout session -> one-time sessionToken - * 3. `pay` binds the session + opens a hosted payment page (Stripe / crypto) - * 4. Open the browser for the user to pay -> no second login ("auto-login": - * the hosted page needs no AI/ML API account, the CLI already holds auth) - * 5. Poll the session until it is `paid` - * 6. Exchange the paid session for a raw key (once) - * 7. Write the key into OpenClaude's provider profile -> the agent now runs - * on AI/ML API's OpenAI-compatible endpoint - * - * After pay/cancel the provider redirects the browser to the co-branded AI/ML - * API `/checkout` success / failure screen - see - * `buildPartnerCheckoutReturnUrls`. - * - * Uses the AI/ML API endpoints from config.ts. - */ +/** AI/ML API passwordless onboarding and partner-checkout orchestration. */ +import { randomUUID } from 'crypto' import chalk from 'chalk' import { openBrowser } from '../../utils/browser.js' @@ -27,32 +9,30 @@ import { AimlapiApiError, AimlapiClient, type PartnerCheckoutSession, - type PaymentMethod, } from './client.js' import { buildPartnerCheckoutReturnUrls, - DEFAULT_AMOUNT_USD_MINOR, + buildPartnerReturnUrl, DEFAULT_MODEL, - DEFAULT_PARTNER_ID, DEFAULT_PARTNER_NAME, - MAX_AMOUNT_USD_MINOR, - MIN_AMOUNT_USD_MINOR, resolveEndpoints, + resolvePartnerId, } from './config.js' -import { promptHidden, promptText } from './prompt.js' +import { promptText } from './prompt.js' +import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' export type AimlapiTopupOptions = { email?: string - password?: string + code?: string /** Top-up amount in whole USD (e.g. "25"). */ amountUsd?: string - method?: PaymentMethod + autoTopUp?: boolean model?: string partnerId?: string partnerName?: string - inviteCode?: string /** Skip opening the browser (print the URL instead). */ noOpen?: boolean + signal?: AbortSignal } export type AimlapiProvisionedKey = { @@ -63,297 +43,456 @@ export type AimlapiProvisionedKey = { } export type AimlapiTopupStatus = - | 'registering' - | 'registered' - | 'signing-in' - | 'signed-in' + | 'checking-account' + | 'sending-code' + | 'verifying-code' + | 'creating-account' + | 'creating-key' | 'creating-session' | 'opening-checkout' | 'waiting-payment' | 'provisioning-key' -export type AimlapiProvisionOptions = AimlapiTopupOptions & { +export type AimlapiProvisionOptions = Omit & { + sessionToken: string + /** Endpoint that validated an existing key and must own any key-bound billing. */ + inferenceBaseUrl?: string + exchange: boolean + existingApiKey?: string + existingApiKeyId?: string + resumeSessionToken?: string + /** Stable idempotency handle retained for one amount/auto-top-up intent. */ + paymentSessionId: string + onSession?: (sessionToken: string) => void onStatus?: (status: AimlapiTopupStatus, detail?: string) => void } -const POLL_INTERVAL_MS = 3000 -const POLL_TIMEOUT_MS = 20 * 60 * 1000 // 20 minutes +export type AimlapiByKeyTopupOptions = Omit & { + apiKey: string + inferenceBaseUrl?: string + paymentSessionId: string + resumeSessionToken?: string + onSession?: (sessionToken: string) => void + onStatus?: (status: AimlapiTopupStatus, detail?: string) => void +} -const sleep = (ms: number): Promise => - new Promise((resolve) => setTimeout(resolve, ms)) +type TopupPhase = 'pay' | 'poll' | 'exchange' | 'wait-exchange' -function maskKey(key: string): string { - if (key.length <= 10) { - return '****' - } - return `${key.slice(0, 6)}...${key.slice(-4)}` -} +const POLL_INTERVAL_MS = 3000 +const POLL_TIMEOUT_MS = 20 * 60 * 1000 -function parseAmount(amountUsd: string | undefined): number { - if (!amountUsd) { - return DEFAULT_AMOUNT_USD_MINOR - } - const dollars = Number(amountUsd) - if (!Number.isFinite(dollars) || dollars <= 0) { - throw new Error(`Invalid amount: "${amountUsd}". Pass a positive number of USD.`) - } - const minor = Math.round(dollars * 100) - if (minor < MIN_AMOUNT_USD_MINOR) { - throw new Error(`Minimum top-up is $${MIN_AMOUNT_USD_MINOR / 100}.`) - } - if (minor > MAX_AMOUNT_USD_MINOR) { - throw new Error(`Maximum top-up is $${MAX_AMOUNT_USD_MINOR / 100}.`) - } - return minor +function abortError(signal?: AbortSignal): unknown { + return signal?.reason ?? new DOMException('The operation was aborted.', 'AbortError') } -function describeAimlapiAuthError(error: unknown): string { - if (error instanceof AimlapiApiError) { - const body = error.body.trim() - return body - ? `HTTP ${error.status}: ${body}` - : `HTTP ${error.status}: ${error.message}` - } - return error instanceof Error ? error.message : String(error) +async function sleep(ms: number, signal?: AbortSignal): Promise { + if (signal?.aborted) throw abortError(signal) + await new Promise((resolve, reject) => { + const cleanup = (): void => signal?.removeEventListener('abort', onAbort) + const timer = setTimeout(() => { + cleanup() + resolve() + }, ms) + const onAbort = (): void => { + clearTimeout(timer) + cleanup() + reject(abortError(signal)) + } + signal?.addEventListener('abort', onAbort, { once: true }) + }) } -async function authenticateAimlapiAccount( - client: AimlapiClient, - options: { - email: string - password: string - inviteCode?: string - onStatus?: (status: AimlapiTopupStatus, detail?: string) => void - }, -): Promise { - let signupError: unknown - try { - options.onStatus?.('registering') - const { token } = await client.signup({ - email: options.email, - password: options.password, - inviteCode: options.inviteCode, - }) - options.onStatus?.('registered') - return token - } catch (error) { - signupError = error - } - - try { - options.onStatus?.('signing-in') - const { token } = await client.login(options.email, options.password) - options.onStatus?.('signed-in') - return token - } catch (loginError) { - throw new Error( - `Could not register or log in to AI/ML API. Registration: ${describeAimlapiAuthError(signupError)}. Login: ${describeAimlapiAuthError(loginError)}.`, - ) - } +function maskKey(key: string): string { + return key.length <= 10 ? '****' : `${key.slice(0, 6)}...${key.slice(-4)}` } export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { const endpoints = resolveEndpoints() const client = new AimlapiClient(endpoints) - - const partnerId = options.partnerId?.trim() || process.env.AIMLAPI_PARTNER_ID?.trim() || DEFAULT_PARTNER_ID - const partnerName = options.partnerName?.trim() || DEFAULT_PARTNER_NAME - const method: PaymentMethod = options.method === 'crypto' ? 'crypto' : 'card' - const model = options.model?.trim() || DEFAULT_MODEL - const amountUsdMinor = parseAmount(options.amountUsd) - - console.log( - chalk.bold(`\n AI/ML API top-up`) + - chalk.dim(` - ${endpoints.appBaseUrl}\n`), - ) - - // 1. Credentials -> Bearer token. - const email = options.email?.trim() || process.env.AIMLAPI_EMAIL?.trim() || (await promptText('AI/ML API email')) - const password = options.password || process.env.AIMLAPI_PASSWORD || (await promptHidden('AI/ML API password')) - if (!email || !password) { - throw new Error('Email and password are required.') - } - - console.log(chalk.dim(' -> Signing in...')) - const token = await authenticateAimlapiAccount(client, { - email, - password, - inviteCode: options.inviteCode || process.env.AIMLAPI_INVITE_CODE, - }) - console.log(chalk.green(' [OK] Signed in')) - - // 2. Partner-checkout session. - const session = await client.createSession({ partnerId, partnerName }) - console.log(chalk.dim(` -> Session ${session.id}`)) - - // 3. Bind + open hosted payment page. The co-branded return URLs make the - // post-payment browser redirect land on the AI/ML API success / failure - // screen for this partner. - const { successUrl, cancelUrl } = buildPartnerCheckoutReturnUrls( - endpoints.appBaseUrl, - session.sessionToken, - ) - const { checkout } = await client.pay(token, session.sessionToken, { - amountUsdMinor, - method, - successUrl, - cancelUrl, - }) - if (!checkout.payUrl) { - throw new Error('Payment provider did not return a checkout URL.') - } - - console.log( - chalk.bold(`\n Pay $${(amountUsdMinor / 100).toFixed(2)} (${method}) to top up:\n`) + - ` ${chalk.cyan(checkout.payUrl)}\n`, - ) - if (options.noOpen) { - console.log(chalk.dim(' (open the link above to complete payment)')) + const email = + options.email?.trim() || + process.env.AIMLAPI_EMAIL?.trim() || + (await promptText('AI/ML API email')) + if (!isValidAimlapiEmail(email)) throw new Error('Email format is incorrect.') + + console.log(chalk.bold('\n AI/ML API top-up') + chalk.dim(` - ${endpoints.appBaseUrl}\n`)) + const account = await client.checkAccount(email, options.signal) + let sessionToken: string + let apiKey = '' + let apiKeyId = '' + let exchange = account.action !== 'sign-in' + + if (account.action === 'sign-in') { + await client.sendSignInCode(email, options.signal) + const code = + options.code?.trim() || + process.env.AIMLAPI_CODE?.trim() || + (await promptText('6-digit code')) + if (!code) throw new Error('Sign-in code is required.') + sessionToken = (await client.verifySignInCode(email, code, options.signal)).token + const created = await client.createKey(sessionToken, 'OpenClaude CLI', options.signal) + apiKey = created.key + apiKeyId = created.id + exchange = false } else { - const opened = await openBrowser(checkout.payUrl) - if (!opened) { - console.log(chalk.dim(' (could not auto-open a browser - open the link above manually)')) - } + sessionToken = (await client.createPasswordlessAccount(email, options.signal)).token } - // 4./5. Poll until paid. - console.log(chalk.dim('\n Waiting for payment...')) - const paid = await pollUntilPaid(client, session.sessionToken) - - // 6. Exchange the paid session for the raw key (once). - console.log(chalk.dim(' -> Provisioning API key...')) - const { apiKey, apiKeyId } = await client.exchange(token, paid.sessionToken) + const provisioned = await provisionAimlapiKey({ + amountUsd: options.amountUsd, + autoTopUp: options.autoTopUp, + model: options.model, + partnerId: options.partnerId, + partnerName: options.partnerName, + noOpen: options.noOpen, + signal: options.signal, + sessionToken, + exchange, + paymentSessionId: randomUUID(), + existingApiKey: apiKey, + existingApiKeyId: apiKeyId, + onStatus: (status, detail) => { + if (status === 'opening-checkout' && detail) console.log(` ${chalk.cyan(detail)}`) + if (status === 'waiting-payment') console.log(chalk.dim(' Waiting for payment...')) + }, + }) - // 7. Persist into OpenClaude's provider profile. const profilePath = saveProfileFile({ profile: 'openai', env: { - OPENAI_BASE_URL: endpoints.inferenceBaseUrl, - OPENAI_API_KEY: apiKey, - OPENAI_MODEL: model, + OPENAI_BASE_URL: provisioned.baseUrl, + OPENAI_API_KEY: provisioned.apiKey, + AIMLAPI_API_KEY: provisioned.apiKey, + OPENAI_MODEL: provisioned.model, + CLAUDE_CODE_PROVIDER_ROUTE_ID: 'aimlapi', }, createdAt: new Date().toISOString(), }) - console.log(chalk.green(`\n [OK] Balance topped up and provider configured.`)) - console.log(` key ${chalk.dim(maskKey(apiKey))} (id ${apiKeyId})`) - console.log(` base URL ${chalk.dim(endpoints.inferenceBaseUrl)}`) - console.log(` model ${chalk.dim(model)}`) + console.log(chalk.green('\n [OK] Balance topped up and provider configured.')) + console.log(` key ${chalk.dim(maskKey(provisioned.apiKey))} (id ${provisioned.apiKeyId})`) + console.log(` base URL ${chalk.dim(provisioned.baseUrl)}`) + console.log(` model ${chalk.dim(provisioned.model)}`) console.log(` profile ${chalk.dim(profilePath)}`) - console.log(chalk.dim(`\n Run ${chalk.bold('openclaude')} to start coding on AI/ML API.\n`)) } export async function provisionAimlapiKey( options: AimlapiProvisionOptions, ): Promise { + if (!options.sessionToken.trim()) throw new Error('A session is required to top up.') + if (!options.paymentSessionId?.trim()) { + throw new Error('A payment session id is required to top up.') + } const endpoints = resolveEndpoints() + if (options.inferenceBaseUrl?.trim()) { + endpoints.inferenceBaseUrl = options.inferenceBaseUrl.trim() + } const client = new AimlapiClient(endpoints) - - const partnerId = - options.partnerId?.trim() || - process.env.AIMLAPI_PARTNER_ID?.trim() || - DEFAULT_PARTNER_ID + const amountUsdMinor = parseAimlapiAmountUsd(options.amountUsd) + const partnerId = resolvePartnerId(options.partnerId) const partnerName = options.partnerName?.trim() || DEFAULT_PARTNER_NAME - const method: PaymentMethod = options.method === 'crypto' ? 'crypto' : 'card' - const model = options.model?.trim() || DEFAULT_MODEL - const amountUsdMinor = parseAmount(options.amountUsd) - - const email = - options.email?.trim() || - process.env.AIMLAPI_EMAIL?.trim() || - (await promptText('AI/ML API email')) - const password = - options.password || - process.env.AIMLAPI_PASSWORD || - (await promptHidden('AI/ML API password')) - if (!email || !password) { - throw new Error('Email and password are required.') - } - - const token = await authenticateAimlapiAccount(client, { - email, - password, - inviteCode: options.inviteCode || process.env.AIMLAPI_INVITE_CODE, - onStatus: options.onStatus, - }) options.onStatus?.('creating-session') - const session = await client.createSession({ partnerId, partnerName }) - - options.onStatus?.('opening-checkout') - const { successUrl, cancelUrl } = buildPartnerCheckoutReturnUrls( - endpoints.appBaseUrl, - session.sessionToken, - ) - const { checkout } = await client.pay(token, session.sessionToken, { - amountUsdMinor, - method, - successUrl, - cancelUrl, + const { sessionToken, phase } = await resolveTopupSession(client, { + resumeSessionToken: options.resumeSessionToken, + partnerId, + partnerName, + verificationBaseUrl: endpoints.verificationBaseUrl, + signal: options.signal, + onSession: options.onSession, }) - if (!checkout.payUrl) { - throw new Error('Payment provider did not return a checkout URL.') + options.onSession?.(sessionToken) + + if (phase === 'pay') { + const returnUrls = buildPartnerCheckoutReturnUrls(endpoints.payBaseUrl, sessionToken) + options.onStatus?.('opening-checkout') + const { checkout } = await client.pay( + options.sessionToken, + sessionToken, + { + amountUsdMinor, + paymentSessionId: options.paymentSessionId, + ...returnUrls, + autoTopUp: options.autoTopUp, + }, + options.signal, + ) + await announceCheckout(checkout.payUrl, options) } - if (options.noOpen) { - options.onStatus?.('opening-checkout', checkout.payUrl) - } else { - const opened = await openBrowser(checkout.payUrl) - options.onStatus?.( - 'opening-checkout', - opened ? checkout.payUrl : `Open manually: ${checkout.payUrl}`, + let paidToken = sessionToken + let settledPhase = phase + if (phase === 'pay' || phase === 'poll') { + options.onStatus?.('waiting-payment') + const paid = await pollUntilPaid( + client, + sessionToken, + options.signal, + options.onSession, + ) + paidToken = paid.sessionToken + if (paid.status === 'exchanging') settledPhase = 'wait-exchange' + } + let apiKey = options.existingApiKey?.trim() || '' + let apiKeyId = options.existingApiKeyId?.trim() || '' + if (options.exchange) { + options.onStatus?.('provisioning-key') + if (settledPhase === 'wait-exchange') { + await pollUntilExchangeSettled( + client, + sessionToken, + options.signal, + options.onSession, + ) + } + const exchanged = await client.exchange( + options.sessionToken, + paidToken, + options.signal, ) + apiKey = exchanged.apiKey?.trim() + apiKeyId = exchanged.apiKeyId?.trim() } + if (!apiKey) throw new Error('AI/ML API did not return an API key.') - options.onStatus?.('waiting-payment') - const paid = await pollUntilPaid(client, session.sessionToken) + return { + apiKey, + apiKeyId, + baseUrl: endpoints.inferenceBaseUrl, + model: options.model?.trim() || DEFAULT_MODEL, + } +} - options.onStatus?.('provisioning-key') - const { apiKey, apiKeyId } = await client.exchange(token, paid.sessionToken) +export async function topUpAimlapiByApiKey( + options: AimlapiByKeyTopupOptions, +): Promise { + const apiKey = options.apiKey.trim() + if (!apiKey) throw new Error('An API key is required to top up.') + if (!options.paymentSessionId.trim()) { + throw new Error('A payment session id is required to top up.') + } + const endpoints = resolveEndpoints() + if (options.inferenceBaseUrl?.trim()) { + endpoints.inferenceBaseUrl = options.inferenceBaseUrl.trim() + } + const client = new AimlapiClient(endpoints) + const amountUsdMinor = parseAimlapiAmountUsd(options.amountUsd) + const partnerId = resolvePartnerId(options.partnerId) + const partnerName = options.partnerName?.trim() || DEFAULT_PARTNER_NAME + + options.onStatus?.('creating-session') + const { sessionToken, phase } = await resolveTopupSession(client, { + resumeSessionToken: options.resumeSessionToken, + partnerId, + partnerName, + verificationBaseUrl: endpoints.verificationBaseUrl, + signal: options.signal, + onSession: options.onSession, + byKey: true, + }) + options.onSession?.(sessionToken) + + if (phase === 'pay') { + const returnUrls = buildPartnerCheckoutReturnUrls(endpoints.payBaseUrl, sessionToken) + options.onStatus?.('opening-checkout') + const { checkout } = await client.topUpByKey( + apiKey, + { + sessionToken, + amountUsdMinor, + paymentSessionId: options.paymentSessionId, + ...returnUrls, + autoTopUp: options.autoTopUp, + }, + options.signal, + ) + await announceCheckout(checkout.payUrl, options) + } + if (phase === 'pay' || phase === 'poll') { + options.onStatus?.('waiting-payment') + await pollUntilPaid(client, sessionToken, options.signal, options.onSession) + } return { apiKey, - apiKeyId, + apiKeyId: '', baseUrl: endpoints.inferenceBaseUrl, - model, + model: options.model?.trim() || DEFAULT_MODEL, } } -async function pollUntilPaid( +async function announceCheckout( + payUrl: string | null, + options: Pick & { + onStatus?: (status: AimlapiTopupStatus, detail?: string) => void + }, +): Promise { + const checkoutUrl = payUrl?.trim() + if (!checkoutUrl) throw new Error('Payment provider did not return a valid HTTPS checkout URL.') + let parsed: URL + try { + parsed = new URL(checkoutUrl) + } catch { + throw new Error('Payment provider did not return a valid HTTPS checkout URL.') + } + if ( + parsed.protocol !== 'https:' || + !parsed.hostname || + parsed.username !== '' || + parsed.password !== '' + ) { + throw new Error('Payment provider did not return a valid HTTPS checkout URL.') + } + if (!options.noOpen) await openBrowser(checkoutUrl) + options.onStatus?.('opening-checkout', checkoutUrl) +} + +async function resolveTopupSession( + client: AimlapiClient, + options: { + resumeSessionToken?: string + partnerId: string + partnerName: string + verificationBaseUrl: string + signal?: AbortSignal + onSession?: (sessionToken: string) => void + byKey?: boolean + }, +): Promise<{ sessionToken: string; phase: TopupPhase }> { + const resume = options.resumeSessionToken?.trim() + if (!resume) { + const session = await client.createSession( + { + partnerId: options.partnerId, + partnerName: options.partnerName, + returnUrl: buildPartnerReturnUrl(options.verificationBaseUrl), + }, + options.signal, + ) + return { sessionToken: session.sessionToken, phase: 'pay' } + } + let session: PartnerCheckoutSession + try { + session = await client.getSession(resume, options.signal) + } catch (error) { + if (isTerminalSessionApiError(error)) options.onSession?.('') + throw error + } + switch (session.status) { + case 'pending_auth': + return { sessionToken: resume, phase: 'pay' } + case 'pending_payment': + return { sessionToken: resume, phase: 'poll' } + case 'paid': + return { sessionToken: resume, phase: 'exchange' } + case 'exchanging': + return { + sessionToken: resume, + phase: options.byKey ? 'exchange' : 'wait-exchange', + } + case 'exchanged': + if (options.byKey) return { sessionToken: resume, phase: 'exchange' } + throw new Error( + 'Session was already exchanged. Rotate the key from the AI/ML API dashboard.', + ) + default: + options.onSession?.('') + throw new Error(`Payment ${session.status}. Re-run the top-up to try again.`) + } +} + +async function pollUntilExchangeSettled( client: AimlapiClient, sessionToken: string, -): Promise { + signal?: AbortSignal, + onSession?: (sessionToken: string) => void, +): Promise { const deadline = Date.now() + POLL_TIMEOUT_MS while (Date.now() < deadline) { - let session: PartnerCheckoutSession + if (signal?.aborted) throw abortError(signal) try { - session = await client.getSession(sessionToken) + const session = await client.getSession(sessionToken, signal) + if (session.status === 'exchanged') { + throw new Error( + 'Session was already exchanged. Rotate the key from the AI/ML API dashboard.', + ) + } + if ( + session.status === 'cancelled' || + session.status === 'expired' || + session.status === 'failed' + ) { + onSession?.('') + throw new Error( + `Key provisioning ${session.status}. Rotate the key from the AI/ML API dashboard.`, + ) + } + if (session.status !== 'exchanging') { + throw new Error( + `Key provisioning returned to ${session.status}. Re-run the top-up.`, + ) + } } catch (error) { - // Transient poll failures shouldn't abort a payment in progress. - // status 0 is a network-level failure (see client.ts), not a real HTTP response. - if (error instanceof AimlapiApiError && (error.status === 0 || error.status >= 500)) { - await sleep(POLL_INTERVAL_MS) + if (signal?.aborted) throw abortError(signal) + if ( + error instanceof AimlapiApiError && + (error.status === 0 || error.status >= 500) + ) { + await sleep(POLL_INTERVAL_MS, signal) continue } + if (isTerminalSessionApiError(error)) onSession?.('') throw error } + await sleep(POLL_INTERVAL_MS, signal) + } + throw new Error( + 'Timed out waiting for key provisioning. Retry to check the same session.', + ) +} - switch (session.status) { - case 'paid': - case 'exchanging': - return session - case 'exchanged': - throw new Error( - 'Session was already exchanged. The key can only be issued once - rotate it from the AI/ML API dashboard.', - ) - case 'cancelled': - case 'expired': - case 'failed': - throw new Error(`Payment ${session.status}. Re-run the top-up to try again.`) - default: - // pending_auth / pending_payment -> keep waiting. - await sleep(POLL_INTERVAL_MS) +export async function pollUntilPaid( + client: AimlapiClient, + sessionToken: string, + signal?: AbortSignal, + onSession?: (sessionToken: string) => void, +): Promise { + const deadline = Date.now() + POLL_TIMEOUT_MS + while (Date.now() < deadline) { + if (signal?.aborted) throw abortError(signal) + try { + const session = await client.getSession(sessionToken, signal) + switch (session.status) { + case 'paid': + case 'exchanging': + return session + case 'exchanged': + throw new Error('Session was already exchanged. Rotate the key from the AI/ML API dashboard.') + case 'cancelled': + case 'expired': + case 'failed': + onSession?.('') + throw new Error(`Payment ${session.status}. Re-run the top-up to try again.`) + default: + await sleep(POLL_INTERVAL_MS, signal) + } + } catch (error) { + if (signal?.aborted) throw abortError(signal) + if (error instanceof AimlapiApiError && (error.status === 0 || error.status >= 500)) { + await sleep(POLL_INTERVAL_MS, signal) + continue + } + if (isTerminalSessionApiError(error)) onSession?.('') + throw error } } throw new Error('Timed out waiting for payment. Re-run once the payment clears.') } + +function isTerminalSessionApiError(error: unknown): boolean { + return ( + error instanceof AimlapiApiError && + error.status >= 400 && + error.status < 500 + ) +} diff --git a/src/integrations/aimlapi/validation.ts b/src/integrations/aimlapi/validation.ts new file mode 100644 index 0000000000..512fefd3a0 --- /dev/null +++ b/src/integrations/aimlapi/validation.ts @@ -0,0 +1,32 @@ +import { + DEFAULT_AMOUNT_USD_MINOR, + MAX_AMOUNT_USD_MINOR, + MIN_AMOUNT_USD_MINOR, +} from './config.js' + +export function parseAimlapiAmountUsd(amountUsd: string | undefined): number { + if (!amountUsd?.trim()) return DEFAULT_AMOUNT_USD_MINOR + const dollars = Number(amountUsd) + if (!Number.isFinite(dollars) || dollars <= 0) { + throw new Error(`Invalid amount: "${amountUsd}". Pass a positive number of USD.`) + } + const minor = Math.round(dollars * 100) + if (minor < MIN_AMOUNT_USD_MINOR) { + throw new Error(`Minimum top-up is $${MIN_AMOUNT_USD_MINOR / 100}.`) + } + if (minor > MAX_AMOUNT_USD_MINOR) { + throw new Error(`Maximum top-up is $${MAX_AMOUNT_USD_MINOR / 100}.`) + } + return minor +} + +export function isValidAimlapiEmail(value: string): boolean { + const email = value.trim() + const match = /^[^\s@]+@([^\s@]+)$/.exec(email) + if (!match) return false + const domain = match[1] + if (domain.startsWith('.') || domain.endsWith('.') || domain.includes('..')) return false + const labels = domain.split('.') + const tld = labels.at(-1) ?? '' + return labels.length >= 2 && /^[A-Za-z]{2,}$/.test(tld) +} diff --git a/src/integrations/artifactGenerator.test.ts b/src/integrations/artifactGenerator.test.ts index f9fc62d016..1803a9bde3 100644 --- a/src/integrations/artifactGenerator.test.ts +++ b/src/integrations/artifactGenerator.test.ts @@ -69,6 +69,25 @@ describe('integration artifact generator', () => { await expect(generatedIntegrationArtifactsAreCurrent()).resolves.toBe(true) }) + test('pins aimlapi.com as the second provider preset', async () => { + const { manifestContent } = splitGeneratedArtifacts( + await generateIntegrationArtifacts(), + ) + const orderedMatch = manifestContent.match( + /export const ORDERED_PROVIDER_PRESETS = \[\n([\s\S]*?)\n\] as const/, + ) + expect(orderedMatch).not.toBeNull() + const orderedPresetIds = Array.from( + orderedMatch![1]!.matchAll(/"([^"]+)"/g), + match => match[1]!, + ) + expect(orderedPresetIds.slice(0, 3)).toEqual([ + 'gitlawb-opengateway', + 'aimlapi', + 'anthropic', + ]) + }) + test('derives loader and preset manifest entries for a preset gateway from descriptor files', async () => { await withFixtureRepo( { diff --git a/src/integrations/artifactGenerator.ts b/src/integrations/artifactGenerator.ts index 41e65b47cf..2adbd30e34 100644 --- a/src/integrations/artifactGenerator.ts +++ b/src/integrations/artifactGenerator.ts @@ -234,8 +234,8 @@ function compareProviderPresetEntries( return 0 } - // Pin Gitlawb Opengateway first so the startup-default provider is also - // the first guided setup option when users need to add an API key. + // Keep the primary guided providers at the top of setup: Gitlawb + // Opengateway first, aimlapi.com second, then the native Anthropic option. if (leftPreset === 'gitlawb-opengateway') { return -1 } @@ -243,6 +243,13 @@ function compareProviderPresetEntries( return 1 } + if (leftPreset === 'aimlapi') { + return -1 + } + if (rightPreset === 'aimlapi') { + return 1 + } + if (leftPreset === 'anthropic') { return -1 } diff --git a/src/integrations/discoveryService.test.ts b/src/integrations/discoveryService.test.ts index bb56f6c9d5..32316b9938 100644 --- a/src/integrations/discoveryService.test.ts +++ b/src/integrations/discoveryService.test.ts @@ -468,13 +468,18 @@ describe('discoverModelsForRoute', () => { 'X-Title': 'OpenClaude', }) expect(result?.models.map((model: { apiName: string }) => model.apiName)).toEqual([ + 'anthropic/claude-sonnet-5', + 'google/gemini-3.5-flash', + 'openai/gpt-5.5-2026-04-23', + 'qwen/qwen-3.7-max', + 'deepseek/deepseek-v4-pro', 'gpt-4o', 'gemini-2.5-pro', 'GLM-5.2', ]) expect(result?.models.find((model: { apiName: string }) => model.apiName === 'gpt-4o')).toMatchObject({ - id: 'aimlapi-gpt-4o', - label: 'GPT-4o', + id: 'gpt-4o', + label: 'GPT-4o (OpenAI)', }) expect(result?.models.find((model: { apiName: string }) => model.apiName === 'gemini-2.5-pro')).toMatchObject({ label: 'Gemini 2.5 Pro (Google)', @@ -538,10 +543,14 @@ describe('discoverModelsForRoute', () => { // Only `openai/chat-completions` entries survive discovery; the duplicate // gpt-3.5-turbo (responses/submit), embeddings, image, and anthropic - // endpoint types are dropped. The curated `gpt-4o` rides along from the - // hybrid catalog. + // endpoint types are dropped. The curated flagship fallback models ride + // along from the hybrid catalog. expect(result?.models.map((model: { apiName: string }) => model.apiName)).toEqual([ - 'gpt-4o', + 'anthropic/claude-sonnet-5', + 'google/gemini-3.5-flash', + 'openai/gpt-5.5-2026-04-23', + 'qwen/qwen-3.7-max', + 'deepseek/deepseek-v4-pro', 'gpt-3.5-turbo', 'claude-opus-4-1-20250805', ]) diff --git a/src/integrations/gateways/aimlapi.ts b/src/integrations/gateways/aimlapi.ts index 106b103ed1..290ddefb5f 100644 --- a/src/integrations/gateways/aimlapi.ts +++ b/src/integrations/gateways/aimlapi.ts @@ -1,5 +1,6 @@ import { defineGateway } from '../define.js' import { publicBuildVersion } from '../../utils/version.js' +import { withResolvedPartnerHeader } from '../aimlapi/config.js' const AIMLAPI_CHAT_MODEL_TYPES = new Set([ 'openai/chat-completions', @@ -57,10 +58,10 @@ function mapAimlapiModel(raw: unknown) { export default defineGateway({ id: 'aimlapi', - label: 'AI/ML API', + label: 'aimlapi.com', category: 'aggregating', defaultBaseUrl: 'https://api.aimlapi.com/v1', - defaultModel: 'gpt-4o', + defaultModel: 'anthropic/claude-sonnet-5', supportsModelRouting: true, setup: { requiresAuth: true, @@ -73,7 +74,7 @@ export default defineGateway({ transportConfig: { kind: 'openai-compatible', openaiShim: { - headers: { + headers: withResolvedPartnerHeader({ 'X-AIMLAPI-Partner-ID': 'part_62yQoGYDq4Yqnrj2R1iGrDNJ', 'X-AIMLAPI-Integration-Repo': 'Gitlawb/openclaude', 'X-AIMLAPI-Integration-Version': publicBuildVersion, @@ -81,13 +82,13 @@ export default defineGateway({ // (issue #835). `HTTP-Referer`/`X-Title` identify the referring app. 'HTTP-Referer': 'OpenClaude', 'X-Title': 'OpenClaude', - }, + }), supportsAuthHeaders: false, }, }, preset: { id: 'aimlapi', - description: '1,000+ models OpenAI compatible endpoint', + description: '1,000+ models, one-click setup', badge: { text: 'Recommended', color: 'success' }, apiKeyEnvVars: ['AIMLAPI_API_KEY'], modelEnvVars: ['OPENAI_MODEL'], @@ -114,12 +115,11 @@ export default defineGateway({ discoveryRefreshMode: 'startup', allowManualRefresh: true, models: [ - { - id: 'aimlapi-gpt-4o', - apiName: 'gpt-4o', - label: 'GPT-4o', - modelDescriptorId: 'gpt-4o', - }, + { id: 'aimlapi-claude-sonnet-5', apiName: 'anthropic/claude-sonnet-5', label: 'Claude Sonnet 5' }, + { id: 'aimlapi-gemini-3.5-flash', apiName: 'google/gemini-3.5-flash', label: 'Gemini 3.5 Flash' }, + { id: 'aimlapi-gpt-5.5', apiName: 'openai/gpt-5.5-2026-04-23', label: 'GPT-5.5' }, + { id: 'aimlapi-qwen-3.7-max', apiName: 'qwen/qwen-3.7-max', label: 'Qwen 3.7 Max' }, + { id: 'aimlapi-deepseek-v4', apiName: 'deepseek/deepseek-v4-pro', label: 'DeepSeek V4' }, ], }, usage: { supported: false }, diff --git a/src/integrations/generated/integrationManifest.generated.ts b/src/integrations/generated/integrationManifest.generated.ts index 014e53eea2..6799f3803c 100644 --- a/src/integrations/generated/integrationManifest.generated.ts +++ b/src/integrations/generated/integrationManifest.generated.ts @@ -34,29 +34,13 @@ export const PROVIDER_PRESET_MANIFEST = [ "color": "success" } }, - { - "preset": "anthropic", - "routeKind": "vendor", - "routeId": "anthropic", - "vendorId": "anthropic", - "description": "Native Claude API (x-api-key auth)", - "apiKeyEnvVars": [ - "ANTHROPIC_API_KEY" - ], - "baseUrlEnvVars": [ - "ANTHROPIC_BASE_URL" - ], - "modelEnvVars": [ - "ANTHROPIC_MODEL" - ] - }, { "preset": "aimlapi", "routeKind": "gateway", "routeId": "aimlapi", "vendorId": "openai", "gatewayId": "aimlapi", - "description": "1,000+ models OpenAI compatible endpoint", + "description": "1,000+ models, one-click setup", "apiKeyEnvVars": [ "AIMLAPI_API_KEY" ], @@ -68,6 +52,22 @@ export const PROVIDER_PRESET_MANIFEST = [ "color": "success" } }, + { + "preset": "anthropic", + "routeKind": "vendor", + "routeId": "anthropic", + "vendorId": "anthropic", + "description": "Native Claude API (x-api-key auth)", + "apiKeyEnvVars": [ + "ANTHROPIC_API_KEY" + ], + "baseUrlEnvVars": [ + "ANTHROPIC_BASE_URL" + ], + "modelEnvVars": [ + "ANTHROPIC_MODEL" + ] + }, { "preset": "dashscope-cn", "routeKind": "gateway", @@ -508,8 +508,8 @@ export const PROVIDER_PRESET_MANIFEST = [ export type ProviderPreset = (typeof PROVIDER_PRESET_MANIFEST)[number]['preset'] export const ORDERED_PROVIDER_PRESETS = [ "gitlawb-opengateway", - "anthropic", "aimlapi", + "anthropic", "dashscope-cn", "dashscope-intl", "atlas-cloud", diff --git a/src/integrations/routeMetadata.test.ts b/src/integrations/routeMetadata.test.ts index ac62a9f45d..40b88c04b9 100644 --- a/src/integrations/routeMetadata.test.ts +++ b/src/integrations/routeMetadata.test.ts @@ -277,7 +277,7 @@ test('Venice route metadata uses official OpenAI-compatible defaults', () => { test('AI/ML API route metadata uses official OpenAI-compatible defaults', () => { expect(getRouteDefaultBaseUrl('aimlapi')).toBe('https://api.aimlapi.com/v1') - expect(getRouteDefaultModel('aimlapi')).toBe('gpt-4o') + expect(getRouteDefaultModel('aimlapi')).toBe('anthropic/claude-sonnet-5') expect(resolveRouteIdFromBaseUrl('https://api.aimlapi.com/v1')).toBe('aimlapi') expect(resolveRouteIdFromBaseUrl('https://api.aimlapi.com/v1/chat/completions')).toBe('aimlapi') }) @@ -556,7 +556,7 @@ test.each([ ['OpenRouter', 'https://openrouter.ai/api/v1', 'openai/gpt-5-mini', 'openrouter'], ['DeepSeek', 'https://api.deepseek.com/v1', 'deepseek-v4-pro', 'deepseek'], ['Hicap', 'https://api.hicap.ai/v1', 'claude-opus-4.8', 'hicap'], - ['AI/ML API', 'https://api.aimlapi.com/v1', 'gpt-4o', 'aimlapi'], + ['aimlapi.com', 'https://api.aimlapi.com/v1', 'anthropic/claude-sonnet-5', 'aimlapi'], ['Xiaomi MiMo', 'https://api.xiaomimimo.com/v1', 'mimo-v2.5-pro', 'xiaomi-mimo'], ['Venice', 'https://api.venice.ai/api/v1', 'venice-uncensored', 'venice'], ])( diff --git a/src/integrations/runtimeMetadata.test.ts b/src/integrations/runtimeMetadata.test.ts index 042da33dd2..388558d6d3 100644 --- a/src/integrations/runtimeMetadata.test.ts +++ b/src/integrations/runtimeMetadata.test.ts @@ -162,6 +162,35 @@ describe('resolveModelRuntimeLimits', () => { }) }) +describe('AIMLAPI runtime attribution', () => { + it('uses the partner override only on the canonical endpoint', () => { + const previous = process.env.AIMLAPI_PARTNER_ID + process.env.AIMLAPI_PARTNER_ID = 'part_runtime_override' + try { + const canonical = resolveOpenAIShimRuntimeContext({ + activeProfileProvider: 'aimlapi', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'anthropic/claude-sonnet-5', + }) + expect(canonical.openaiShimConfig.headers?.['X-AIMLAPI-Partner-ID']).toBe( + 'part_runtime_override', + ) + + const proxy = resolveOpenAIShimRuntimeContext({ + activeProfileProvider: 'aimlapi', + baseUrl: 'https://proxy.example.test/v1', + model: 'anthropic/claude-sonnet-5', + }) + expect(proxy.openaiShimConfig.headers?.['X-AIMLAPI-Partner-ID']).toBeUndefined() + expect(proxy.openaiShimConfig.headers?.['X-AIMLAPI-Integration-Repo']).toBeUndefined() + expect(proxy.openaiShimConfig.headers?.['HTTP-Referer']).toBeUndefined() + } finally { + if (previous === undefined) delete process.env.AIMLAPI_PARTNER_ID + else process.env.AIMLAPI_PARTNER_ID = previous + } + }) +}) + describe('resolveOpenAIShimRuntimeContext - Z.A.I GLM-5.2', () => { it.each([ 'glm-5.2', diff --git a/src/integrations/runtimeMetadata.ts b/src/integrations/runtimeMetadata.ts index e9b17a1de1..1ce7ff5c96 100644 --- a/src/integrations/runtimeMetadata.ts +++ b/src/integrations/runtimeMetadata.ts @@ -27,6 +27,42 @@ import { import { parseCustomHeadersEnv } from '../utils/providerCustomHeaders.js' import { firstUsableCredential } from '../services/api/credentialPool.js' import { ZAI_GLM_OPENAI_SHIM } from './transport/zaiGlmShim.js' +import { + isCanonicalAimlapiInferenceBaseUrl, + PARTNER_HEADER_NAME, + resolvePartnerId, +} from './aimlapi/config.js' + +const AIMLAPI_CATALOG_HEADER_NAMES = new Set([ + PARTNER_HEADER_NAME.toLowerCase(), + 'x-aimlapi-integration-repo', + 'x-aimlapi-integration-version', + 'http-referer', + 'x-title', +]) + +function resolveRouteOpenAIShimConfig( + routeId: string | null, + baseUrl: string | undefined, + config: OpenAIShimTransportConfig | undefined, +): OpenAIShimTransportConfig | undefined { + if (routeId !== 'aimlapi' || !config?.headers) return config + + const headers = Object.fromEntries( + Object.entries(config.headers).filter( + ([name]) => !AIMLAPI_CATALOG_HEADER_NAMES.has(name.trim().toLowerCase()), + ), + ) + if (!baseUrl || isCanonicalAimlapiInferenceBaseUrl(baseUrl)) { + headers[PARTNER_HEADER_NAME] = resolvePartnerId() + for (const [name, value] of Object.entries(config.headers)) { + if (name.trim().toLowerCase() !== PARTNER_HEADER_NAME.toLowerCase()) { + headers[name] = value + } + } + } + return { ...config, headers } +} function normalizeModelApiName( value: string | undefined, @@ -281,6 +317,8 @@ export function resolveOpenAIShimRuntimeContext(options?: { routeId && routeId !== 'anthropic' ? getRouteDescriptor(routeId) : null + const effectiveBaseUrl = + options?.baseUrl ?? runtimeEnv.OPENAI_BASE_URL ?? runtimeEnv.OPENAI_API_BASE const catalogEntry = descriptor && routeId ? getCatalogEntryForModel(routeId, options?.model) @@ -297,7 +335,11 @@ export function resolveOpenAIShimRuntimeContext(options?: { descriptor, catalogEntry, openaiShimConfig: mergeOpenAIShimConfig( - descriptor?.transportConfig.openaiShim, + resolveRouteOpenAIShimConfig( + routeId, + effectiveBaseUrl, + descriptor?.transportConfig.openaiShim, + ), catalogEntry?.transportOverrides?.openaiShim, inferredConfig, ), diff --git a/src/main.tsx b/src/main.tsx index a7832be9b6..fb54ee432a 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -4017,17 +4017,19 @@ async function run(): Promise { // auto-configure the provider with the issued key. const aimlapi = program.command('aimlapi').description('AI/ML API (aimlapi.com) — top up balance and configure the provider').configureHelp(createSortedHelpConfig()); aimlapi.command('topup') - .description("Log in, open AI/ML API top-up, then set the issued key as OpenClaude's provider") + .description("Use passwordless sign-in, open AI/ML API top-up, then configure OpenClaude") .option('--email ', 'AI/ML API account email (or AIMLAPI_EMAIL env)') + .option('--code ', '6-digit code for an existing account (or AIMLAPI_CODE env)') .option('--amount ', `Top-up amount in USD (min ${MIN_AMOUNT_USD_MINOR / 100}, max ${MAX_AMOUNT_USD_MINOR / 100})`) - .addOption(new Option('--method ', 'Payment method: card (Stripe) or crypto (NOWPayments)').choices(['card', 'crypto']).default('card')) - .option('--model ', 'Default model id written into the provider profile', 'gpt-4o') + .option('--auto-top-up', 'Enable automatic top-up at checkout') + .option('--model ', 'Default model id written into the provider profile', 'anthropic/claude-sonnet-5') .option('--partner-id ', 'Partner id for rebate attribution (part_...)') .option('--no-open', 'Do not auto-open the browser; print the payment URL instead') .action(async (opts: { email?: string; + code?: string; amount?: string; - method?: string; + autoTopUp?: boolean; model?: string; partnerId?: string; open?: boolean; @@ -4035,8 +4037,9 @@ async function run(): Promise { const { aimlapiTopup } = await import('./cli/handlers/aimlapi.js'); await aimlapiTopup({ email: opts.email, + code: opts.code, amountUsd: opts.amount, - method: opts.method === 'crypto' ? 'crypto' : 'card', + autoTopUp: opts.autoTopUp, model: opts.model, partnerId: opts.partnerId, noOpen: opts.open === false, diff --git a/src/services/api/client.test.ts b/src/services/api/client.test.ts index 9f5a776105..c75700cfeb 100644 --- a/src/services/api/client.test.ts +++ b/src/services/api/client.test.ts @@ -814,7 +814,7 @@ test('routes env-only AI/ML API requests through the OpenAI-compatible shim desp expect(capturedBody?.model).toBe('gpt-4o') expect(process.env.CLAUDE_CODE_USE_OPENAI).toBe('1') expect(process.env.OPENAI_BASE_URL).toBe('https://api.aimlapi.com/v1') - expect(process.env.OPENAI_MODEL).toBe('gpt-4o') + expect(process.env.OPENAI_MODEL).toBe('anthropic/claude-sonnet-5') expect(process.env.OPENAI_API_KEY).toBe('aimlapi-test-key') expect(response).toMatchObject({ role: 'assistant', diff --git a/src/utils/providerDiscovery.test.ts b/src/utils/providerDiscovery.test.ts index 13961640a8..66f0388960 100644 --- a/src/utils/providerDiscovery.test.ts +++ b/src/utils/providerDiscovery.test.ts @@ -118,7 +118,7 @@ test('detects AI/ML API from descriptor route metadata', async () => { expect( getLocalOpenAICompatibleProviderLabel('https://api.aimlapi.com/v1'), - ).toBe('AI/ML API') + ).toBe('aimlapi.com') }) test('detects Z.AI from descriptor route metadata', async () => { diff --git a/src/utils/providerProfiles.test.ts b/src/utils/providerProfiles.test.ts index 5157568163..068010729a 100644 --- a/src/utils/providerProfiles.test.ts +++ b/src/utils/providerProfiles.test.ts @@ -1031,6 +1031,26 @@ describe('applyProviderProfileToProcessEnv', () => { expect(process.env.CLAUDE_CODE_PROVIDER_ROUTE_ID).toBe('aimlapi') }, 20_000) + test('keyless AIMLAPI profile resolves AIMLAPI_API_KEY without persisting it', async () => { + const { applyProviderProfileToProcessEnv } = + await importFreshProviderProfileModules() + process.env.AIMLAPI_API_KEY = 'ambient-aimlapi-key' + + applyProviderProfileToProcessEnv( + buildProfile({ + name: 'AI/ML API', + provider: 'aimlapi', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'gpt-4o', + apiKey: undefined, + }), + ) + + expect(process.env.OPENAI_API_KEY).toBe('ambient-aimlapi-key') + expect(process.env.AIMLAPI_API_KEY).toBe('ambient-aimlapi-key') + expect(process.env.CLAUDE_CODE_PROVIDER_ROUTE_ID).toBe('aimlapi') + }, 20_000) + test('openai profile on AI/ML API route mirrors AIMLAPI_API_KEY', async () => { const { applyProviderProfileToProcessEnv } = await importFreshProviderProfileModules() @@ -2403,9 +2423,9 @@ describe('getProviderPresetDefaults', () => { const defaults = getProviderPresetDefaults('aimlapi') expect(defaults.provider).toBe('aimlapi') - expect(defaults.name).toBe('AI/ML API') + expect(defaults.name).toBe('aimlapi.com') expect(defaults.baseUrl).toBe('https://api.aimlapi.com/v1') - expect(defaults.model).toBe('gpt-4o') + expect(defaults.model).toBe('anthropic/claude-sonnet-5') expect(defaults.apiKey).toBe('aimlapi-live-key') expect(defaults.requiresApiKey).toBe(true) }) diff --git a/src/utils/providerProfiles.ts b/src/utils/providerProfiles.ts index 9351b16892..edfc56c3d1 100644 --- a/src/utils/providerProfiles.ts +++ b/src/utils/providerProfiles.ts @@ -994,12 +994,14 @@ export function applyProviderProfileToProcessEnv( } } if (isAimlapiProfile) { - const ambientOpenAIKey = trimOrUndefined(process.env.OPENAI_API_KEY) + const ambientAimlapiKey = + trimOrUndefined(process.env.AIMLAPI_API_KEY) ?? + trimOrUndefined(process.env.OPENAI_API_KEY) openAIProfileEnv.CLAUDE_CODE_PROVIDER_ROUTE_ID = 'aimlapi' openAIProfileEnv.OPENAI_API_KEY = - openAIProfileEnv.OPENAI_API_KEY ?? ambientOpenAIKey + openAIProfileEnv.OPENAI_API_KEY ?? ambientAimlapiKey openAIProfileEnv.AIMLAPI_API_KEY = - openAIProfileEnv.AIMLAPI_API_KEY ?? ambientOpenAIKey + openAIProfileEnv.AIMLAPI_API_KEY ?? ambientAimlapiKey } if (route.gatewayId === 'nvidia-nim') { openAIProfileEnv.NVIDIA_NIM = '1' diff --git a/src/utils/status.test.ts b/src/utils/status.test.ts index 234f3e3e5c..59d26f7e75 100644 --- a/src/utils/status.test.ts +++ b/src/utils/status.test.ts @@ -143,7 +143,7 @@ test('buildAPIProviderProperties uses the resolved route label for AI/ML API ses process.env.OPENAI_BASE_URL = 'https://api.aimlapi.com/v1' process.env.OPENAI_MODEL = 'gpt-4o' - expect(await readPropertyValue('Provider route', 'openai')).toBe('AI/ML API') + expect(await readPropertyValue('Provider route', 'openai')).toBe('aimlapi.com') expect(await readPropertyValue('OpenAI base URL', 'openai')).toBe( 'https://api.aimlapi.com/v1', ) From 6f0a87b7d2b100ce8111db400f1b89893eabed45 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Fri, 17 Jul 2026 00:32:46 +0500 Subject: [PATCH 02/17] fix(aimlapi): address review feedback --- src/cli/aimlapiCommand.test.ts | 49 +++++++++++ src/cli/aimlapiCommand.ts | 57 +++++++++++++ src/components/ProviderManager.test.tsx | 80 +++++++++++++++-- src/components/ProviderManager.tsx | 18 +++- src/components/providerManagerAimlapi.ts | 38 +++++++++ src/integrations/aimlapi/client.test.ts | 44 ++++++++++ src/integrations/aimlapi/client.ts | 85 ++++++++++++++++--- src/integrations/aimlapi/config.test.ts | 21 +++++ src/integrations/aimlapi/config.ts | 32 +++++-- src/integrations/aimlapi/onboarding.test.ts | 23 +++++ src/integrations/aimlapi/onboarding.ts | 29 ++++--- src/integrations/aimlapi/prompt.test.ts | 63 ++++++++++++++ src/integrations/aimlapi/prompt.ts | 11 ++- src/integrations/aimlapi/topup.test.ts | 32 +++++-- src/integrations/aimlapi/topup.ts | 24 ++++-- src/integrations/aimlapi/topupDependencies.ts | 10 +++ src/integrations/aimlapi/validation.ts | 7 +- src/integrations/gateways/aimlapi.ts | 10 +-- src/integrations/models/claude.ts | 18 ++++ src/integrations/runtimeMetadata.ts | 19 +++-- src/main.tsx | 33 +------ 21 files changed, 602 insertions(+), 101 deletions(-) create mode 100644 src/cli/aimlapiCommand.test.ts create mode 100644 src/cli/aimlapiCommand.ts create mode 100644 src/components/providerManagerAimlapi.ts create mode 100644 src/integrations/aimlapi/prompt.test.ts create mode 100644 src/integrations/aimlapi/topupDependencies.ts diff --git a/src/cli/aimlapiCommand.test.ts b/src/cli/aimlapiCommand.test.ts new file mode 100644 index 0000000000..d712ed2931 --- /dev/null +++ b/src/cli/aimlapiCommand.test.ts @@ -0,0 +1,49 @@ +import { expect, mock, test } from 'bun:test' +import { Command as CommanderCommand } from '@commander-js/extra-typings' + +import { registerAimlapiCommand } from './aimlapiCommand.js' + +test('aimlapi topup forwards the passwordless CLI contract', async () => { + const handler = mock(async () => {}) + const program = new CommanderCommand().exitOverride() + registerAimlapiCommand(program, async () => handler) + + await program.parseAsync([ + 'node', + 'openclaude', + 'aimlapi', + 'topup', + '--email', + 'user@example.com', + '--code', + '123456', + '--auto-top-up', + '--no-open', + ]) + + expect(handler).toHaveBeenCalledWith({ + email: 'user@example.com', + code: '123456', + amountUsd: undefined, + autoTopUp: true, + model: 'anthropic/claude-sonnet-5', + partnerId: undefined, + noOpen: true, + }) +}) + +test('aimlapi topup rejects the removed method option', async () => { + const program = new CommanderCommand().exitOverride() + registerAimlapiCommand(program, async () => async () => {}) + + await expect( + program.parseAsync([ + 'node', + 'openclaude', + 'aimlapi', + 'topup', + '--method', + 'card', + ]), + ).rejects.toMatchObject({ code: 'commander.unknownOption' }) +}) diff --git a/src/cli/aimlapiCommand.ts b/src/cli/aimlapiCommand.ts new file mode 100644 index 0000000000..c17636be87 --- /dev/null +++ b/src/cli/aimlapiCommand.ts @@ -0,0 +1,57 @@ +import { Command as CommanderCommand } from '@commander-js/extra-typings' + +import { + MAX_AMOUNT_USD_MINOR, + MIN_AMOUNT_USD_MINOR, +} from '../integrations/aimlapi/config.js' +import type { AimlapiTopupOptions } from '../integrations/aimlapi/topup.js' + +type AimlapiTopupHandler = (options: AimlapiTopupOptions) => Promise +type LoadAimlapiTopupHandler = () => Promise + +const loadAimlapiTopupHandler: LoadAimlapiTopupHandler = async () => { + const { aimlapiTopup } = await import('./handlers/aimlapi.js') + return aimlapiTopup +} + +export function registerAimlapiCommand( + program: CommanderCommand, + loadHandler: LoadAimlapiTopupHandler = loadAimlapiTopupHandler, +): CommanderCommand { + const aimlapi = program + .command('aimlapi') + .description('AI/ML API (aimlapi.com) — top up balance and configure the provider') + aimlapi + .command('topup') + .description( + 'Use passwordless sign-in, open AI/ML API top-up, then configure OpenClaude', + ) + .option('--email ', 'AI/ML API account email (or AIMLAPI_EMAIL env)') + .option('--code ', '6-digit code for an existing account (or AIMLAPI_CODE env)') + .option( + '--amount ', + `Top-up amount in USD (min ${MIN_AMOUNT_USD_MINOR / 100}, max ${MAX_AMOUNT_USD_MINOR / 100})`, + ) + .option('--auto-top-up', 'Enable automatic top-up at checkout') + .option( + '--model ', + 'Default model id written into the provider profile', + 'anthropic/claude-sonnet-5', + ) + .option('--partner-id ', 'Partner id for rebate attribution (part_...)') + .option('--no-open', 'Do not auto-open the browser; print the payment URL instead') + .action(async opts => { + const handler = await loadHandler() + await handler({ + email: opts.email, + code: opts.code, + amountUsd: opts.amount, + autoTopUp: opts.autoTopUp, + model: opts.model, + partnerId: opts.partnerId, + noOpen: opts.open === false, + }) + }) + + return aimlapi +} diff --git a/src/components/ProviderManager.test.tsx b/src/components/ProviderManager.test.tsx index 6e55148f1a..56de2ca1ff 100644 --- a/src/components/ProviderManager.test.tsx +++ b/src/components/ProviderManager.test.tsx @@ -22,7 +22,6 @@ const actualSettingsModule = (await import( const actualProviderStartupOverridesModule = (await import( `../utils/providerStartupOverrides.ts?providerManagerStartupOverridesActual=${Date.now()}-${Math.random()}` )) as ProviderStartupOverridesModule - const SYNC_START = '\x1B[?2026h' const SYNC_END = '\x1B[?2026l' @@ -466,7 +465,7 @@ function mockProviderManagerDependencies( updateSettingsForSource: () => ({ error: null }), })) - mock.module('../integrations/aimlapi/index.js', () => ({ + mock.module('./providerManagerAimlapi.js', () => ({ AIMLAPI_MESSAGES, AimlapiApiError: class AimlapiApiError extends Error { constructor( @@ -486,6 +485,7 @@ function mockProviderManagerDependencies( sessionToken: 'session_test', apiKey: 'issued_test', apiKeyId: 'key_test', + balanceStatus: 'confirmed' as const, lowBalance: false, })), validateAimlapiApiKey: @@ -525,7 +525,7 @@ function mockProviderManagerDependencies( async function waitForFrameOutput( getOutput: () => string, predicate: (output: string) => boolean, - timeoutMs = 2500, + timeoutMs = 5000, ): Promise { let output = '' @@ -1113,8 +1113,11 @@ test('ProviderManager offers and reuses an existing AIMLAPI profile', async () = expect.any(AbortSignal), 'https://api.aimlapi.com/v1', ) + await Bun.sleep(25) mounted.stdin.write('\r') - await waitForCondition(() => updateProviderProfile.mock.calls.length > 0) + await waitForCondition(() => updateProviderProfile.mock.calls.length > 0, { + timeoutMs: 5000, + }) expect(updateProviderProfile).toHaveBeenCalledWith( 'aimlapi_existing', expect.objectContaining({ apiKey: 'saved-key' }), @@ -1122,7 +1125,7 @@ test('ProviderManager offers and reuses an existing AIMLAPI profile', async () = } finally { await mounted.dispose() } -}) +}, 10_000) test('ProviderManager first run keeps AIMLAPI_API_KEY out of the saved profile', async () => { process.env.AIMLAPI_API_KEY = 'env-runtime-key' @@ -1131,8 +1134,14 @@ test('ProviderManager first run keeps AIMLAPI_API_KEY out of the saved profile', id: 'aimlapi_env', ...payload, })) + const validateAimlapiApiKey = mock(async () => ({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + })) mockProviderManagerDependencies(() => undefined, async () => undefined, { addProviderProfile, + validateAimlapiApiKey, }) const nonce = `${Date.now()}-${Math.random()}` @@ -1155,11 +1164,61 @@ test('ProviderManager first run keeps AIMLAPI_API_KEY out of the saved profile', }), expect.objectContaining({ makeActive: true }), ) + expect(validateAimlapiApiKey).toHaveBeenCalledWith( + 'env-runtime-key', + expect.any(AbortSignal), + 'https://proxy.example.test/v1', + ) } finally { await mounted.dispose() } }) +test('ProviderManager does not persist an invalid or low-balance first-run AIMLAPI env key', async () => { + process.env.AIMLAPI_API_KEY = 'env-runtime-key' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.aimlapi.com/v1' + + for (const scenario of ['invalid', 'low-balance'] as const) { + const addProviderProfile = mock(() => null) + const validateAimlapiApiKey = mock(async () => { + if (scenario === 'invalid') { + throw Object.assign(new Error('Unauthorized'), { status: 401 }) + } + return { balance: 5, lowBalance: true, lowBalanceThreshold: 20 } + }) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + addProviderProfile, + validateAimlapiApiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager, { mode: 'first-run' }) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Set up provider')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + scenario === 'invalid' + ? frame.includes('API key is invalid.') + : frame.includes('credits are running low'), + ) + expect(validateAimlapiApiKey).toHaveBeenCalledWith( + 'env-runtime-key', + expect.any(AbortSignal), + 'https://api.aimlapi.com/v1', + ) + expect(addProviderProfile).not.toHaveBeenCalled() + } finally { + await mounted.dispose() + } + } +}) + test('ProviderManager rejects an invalid AIMLAPI key using the Zero error copy', async () => { const addProviderProfile = mock(() => null) const validateAimlapiApiKey = mock(async () => { @@ -1226,6 +1285,7 @@ test('ProviderManager matches the AIMLAPI code and low-credit screen copy', asyn sessionToken: 'session_test', apiKey: 'issued_test', apiKeyId: 'key_test', + balanceStatus: 'confirmed' as const, lowBalance: true, })) mockProviderManagerDependencies(() => undefined, async () => undefined, { @@ -1314,7 +1374,7 @@ test('ProviderManager rejects an empty AIMLAPI top-up amount instead of charging mounted.stdin.write('\r') await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Add credits')) - mounted.stdin.write('\x7f\x7f') + mounted.stdin.write('\x15') await Bun.sleep(25) mounted.stdin.write('\r') const output = await waitForFrameOutput(mounted.getOutput, frame => @@ -1325,7 +1385,7 @@ test('ProviderManager rejects an empty AIMLAPI top-up amount instead of charging } finally { await mounted.dispose() } -}) +}, 10_000) test('ProviderManager drops a retained checkout when the onboarding email changes', async () => { delete process.env.AIMLAPI_EMAIL @@ -1568,8 +1628,10 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => "We've emailed you a magic link to user@example.com. Use it to access your aimlapi.com account and review your usage.", ) mounted.stdin.write('\r') - await waitForFrameOutput(mounted.getOutput, frame => - frame.includes('Provider manager'), + await waitForFrameOutput( + mounted.getOutput, + frame => frame.includes('Provider manager'), + 8_000, ) expect(provisionAimlapiKey).toHaveBeenCalledWith( expect.objectContaining({ diff --git a/src/components/ProviderManager.tsx b/src/components/ProviderManager.tsx index 761f90ade8..46356b4bc8 100644 --- a/src/components/ProviderManager.tsx +++ b/src/components/ProviderManager.tsx @@ -58,7 +58,7 @@ import { AimlapiApiError, AIMLAPI_MESSAGES, type AimlapiTopupStatus, -} from '../integrations/aimlapi/index.js' +} from './providerManagerAimlapi.js' import { DEFAULT_AMOUNT_USD_MINOR, isCanonicalAimlapiInferenceBaseUrl, @@ -2569,11 +2569,10 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { if (mode === 'first-run' && envKey) { setAimlapiIssuedKey(envKey) setAimlapiExistingUsesEnv(true) - persistAimlapiKey( + void validateAndPersistAimlapiKey( envKey, nextDraft.baseUrl, nextDraft.model, - 'ready', { preserveEnv: true }, ) return @@ -2720,6 +2719,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { apiKey: string, baseUrl: string, model: string, + options: { preserveEnv?: boolean } = {}, ): Promise { aimlapiAbortRef.current?.abort() const controller = new AbortController() @@ -2738,11 +2738,12 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setAimlapiIssuedKey(apiKey.trim()) setAimlapiIssuedKeyId('') setAimlapiTopupByKey(true) + setAimlapiExistingUsesEnv(options.preserveEnv === true) setIsAimlapiKeyValidating(false) setScreen('aimlapi-low-balance') return } - persistAimlapiKey(apiKey, baseUrl, model, 'ready') + persistAimlapiKey(apiKey, baseUrl, model, 'ready', options) } catch (error) { if (controller.signal.aborted) return const status = @@ -3008,6 +3009,15 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setAimlapiIssuedKeyId(result.apiKeyId) if (controller.signal.aborted) return setIsAimlapiTopupRunning(false) + if (result.balanceStatus === 'unknown') { + setDraft(prev => ({ ...prev, apiKey: result.apiKey })) + setCursorOffset(result.apiKey.length) + setErrorMessage( + safeAimlapiErrorMessage(result.balanceError, [result.apiKey]), + ) + setScreen('preset-api-key') + return + } if (result.lowBalance) { setScreen('aimlapi-low-balance') } else { diff --git a/src/components/providerManagerAimlapi.ts b/src/components/providerManagerAimlapi.ts new file mode 100644 index 0000000000..0ea8f01807 --- /dev/null +++ b/src/components/providerManagerAimlapi.ts @@ -0,0 +1,38 @@ +import { + provisionAimlapiKey as provisionAimlapiKeyImpl, + topUpAimlapiByApiKey as topUpAimlapiByApiKeyImpl, + parseAimlapiAmountUsd as parseAimlapiAmountUsdImpl, + isValidAimlapiEmail as isValidAimlapiEmailImpl, + beginAimlapiEmailOnboarding as beginAimlapiEmailOnboardingImpl, + completeAimlapiCodeSignIn as completeAimlapiCodeSignInImpl, + validateAimlapiApiKey as validateAimlapiApiKeyImpl, +} from '../integrations/aimlapi/index.js' + +export { + AimlapiApiError, + AIMLAPI_MESSAGES, + type AimlapiTopupStatus, +} from '../integrations/aimlapi/index.js' + +export const provisionAimlapiKey: typeof provisionAimlapiKeyImpl = options => + provisionAimlapiKeyImpl(options) + +export const topUpAimlapiByApiKey: typeof topUpAimlapiByApiKeyImpl = options => + topUpAimlapiByApiKeyImpl(options) + +export const parseAimlapiAmountUsd: typeof parseAimlapiAmountUsdImpl = value => + parseAimlapiAmountUsdImpl(value) + +export const isValidAimlapiEmail: typeof isValidAimlapiEmailImpl = value => + isValidAimlapiEmailImpl(value) + +export const beginAimlapiEmailOnboarding: typeof beginAimlapiEmailOnboardingImpl = ( + ...args +) => beginAimlapiEmailOnboardingImpl(...args) + +export const completeAimlapiCodeSignIn: typeof completeAimlapiCodeSignInImpl = ( + ...args +) => completeAimlapiCodeSignInImpl(...args) + +export const validateAimlapiApiKey: typeof validateAimlapiApiKeyImpl = (...args) => + validateAimlapiApiKeyImpl(...args) diff --git a/src/integrations/aimlapi/client.test.ts b/src/integrations/aimlapi/client.test.ts index 1793d46575..b394a6c64a 100644 --- a/src/integrations/aimlapi/client.test.ts +++ b/src/integrations/aimlapi/client.test.ts @@ -135,6 +135,50 @@ test('typed requests reject an empty successful response', async () => { await expect(client.getBalance('key_test')).rejects.toThrow('returned empty body') }) +test('getBalance rejects malformed successful payloads', async () => { + const client = new AimlapiClient(endpoints) + for (const payload of [ + {}, + { balance: 25, lowBalance: false }, + { balance: '25', lowBalance: false, lowBalanceThreshold: 20 }, + { balance: 25, lowBalance: 'false', lowBalanceThreshold: 20 }, + { balance: 25, lowBalance: false, lowBalanceThreshold: null }, + ]) { + globalThis.fetch = mock(async () => jsonResponse(payload)) as unknown as typeof fetch + await expect(client.getBalance('key_test')).rejects.toThrow( + 'returned invalid balance response', + ) + } +}) + +test('session tokens are excluded from HTTP and network errors', async () => { + const client = new AimlapiClient(endpoints) + const token = 'session-secret-token' + + globalThis.fetch = mock(async () => new Response('failed', { status: 500 })) as unknown as typeof fetch + let httpError: unknown + try { + await client.getSession(token) + } catch (error) { + httpError = error + } + expect(httpError).toBeInstanceOf(Error) + expect((httpError as Error).message).toContain('https://app.example.test') + expect((httpError as Error).message).not.toContain(token) + + globalThis.fetch = mock(async () => { + throw new Error(`transport failed for ${token}`) + }) as unknown as typeof fetch + let networkError: unknown + try { + await client.exchange('bearer', token) + } catch (error) { + networkError = error + } + expect(networkError).toBeInstanceOf(Error) + expect((networkError as Error).message).not.toContain(token) +}) + test('response bodies are capped before decoding or surfacing errors', async () => { globalThis.fetch = mock( async () => new Response('x'.repeat((1 << 20) + 1), { status: 502 }), diff --git a/src/integrations/aimlapi/client.ts b/src/integrations/aimlapi/client.ts index f4fc984fc6..66eea5fb6c 100644 --- a/src/integrations/aimlapi/client.ts +++ b/src/integrations/aimlapi/client.ts @@ -53,6 +53,53 @@ export type BalanceResult = { const REQUEST_TIMEOUT_MS = 60_000 const MAX_RESPONSE_BODY_BYTES = 1 << 20 +function requestLabel(url: string): string { + try { + return new URL(url).origin + } catch { + return 'AI/ML API endpoint' + } +} + +function redactRequestSecrets( + message: string, + url: string, + bearer: string | undefined, +): string { + const secrets = new Set() + if (bearer?.trim()) secrets.add(bearer.trim()) + try { + for (const segment of new URL(url).pathname.split('/')) { + if (segment.length < 6) continue + secrets.add(segment) + try { + secrets.add(decodeURIComponent(segment)) + } catch { + // Keep the encoded segment when it is not valid percent-encoding. + } + } + } catch { + // The request label already handles malformed URLs without exposing them. + } + let redacted = message + for (const secret of secrets) { + if (secret) redacted = redacted.split(secret).join('[REDACTED]') + } + return redacted +} + +function isBalanceResult(value: unknown): value is BalanceResult { + if (typeof value !== 'object' || value === null) return false + const result = value as Record + return ( + typeof result.balance === 'number' && + Number.isFinite(result.balance) && + typeof result.lowBalance === 'boolean' && + typeof result.lowBalanceThreshold === 'number' && + Number.isFinite(result.lowBalanceThreshold) + ) +} + class AimlapiResponseTooLargeError extends Error { constructor() { super(`AI/ML API response body exceeds ${MAX_RESPONSE_BODY_BYTES} bytes.`) @@ -158,10 +205,19 @@ export class AimlapiClient { } async getBalance(apiKey: string, signal?: AbortSignal): Promise { - return this.request( - `${this.endpoints.inferenceBaseUrl.replace(/\/+$/, '')}/billing/balance`, + const url = `${this.endpoints.inferenceBaseUrl.replace(/\/+$/, '')}/billing/balance` + const result = await this.request( + url, { method: 'GET', bearer: apiKey, signal }, ) + if (!isBalanceResult(result)) { + throw new AimlapiApiError( + `GET ${requestLabel(url)} returned invalid balance response`, + 200, + '', + ) + } + return result } async createSession( @@ -274,6 +330,7 @@ export class AimlapiClient { expectJson?: boolean }, ): Promise { + const label = requestLabel(url) const headers: Record = { Accept: 'application/json' } if (options.body !== undefined) headers['Content-Type'] = 'application/json' if (options.bearer) headers.Authorization = `Bearer ${options.bearer.trim()}` @@ -292,8 +349,12 @@ export class AimlapiClient { } catch (error) { combined.cleanup() if (options.signal?.aborted) throw error - const reason = error instanceof Error ? error.message : String(error) - throw new AimlapiApiError(`Network request to ${url} failed: ${reason}`, 0, '') + const reason = redactRequestSecrets( + error instanceof Error ? error.message : String(error), + url, + options.bearer, + ) + throw new AimlapiApiError(`Network request to ${label} failed: ${reason}`, 0, '') } let text: string @@ -303,20 +364,24 @@ export class AimlapiClient { if (options.signal?.aborted) throw error if (error instanceof AimlapiResponseTooLargeError) { throw new AimlapiApiError( - `${options.method} ${url} response body exceeds ${MAX_RESPONSE_BODY_BYTES} bytes`, + `${options.method} ${label} response body exceeds ${MAX_RESPONSE_BODY_BYTES} bytes`, response.status, '', ) } - const reason = error instanceof Error ? error.message : String(error) - throw new AimlapiApiError(`Network response from ${url} failed: ${reason}`, 0, '') + const reason = redactRequestSecrets( + error instanceof Error ? error.message : String(error), + url, + options.bearer, + ) + throw new AimlapiApiError(`Network response from ${label} failed: ${reason}`, 0, '') } finally { combined.cleanup() } if (!response.ok) { throw new AimlapiApiError( - `${options.method} ${url} -> ${response.status}`, + `${options.method} ${label} -> ${response.status}`, response.status, text, ) @@ -324,7 +389,7 @@ export class AimlapiClient { if (!text.trim()) { if (options.expectJson === false) return undefined as T throw new AimlapiApiError( - `${options.method} ${url} returned empty body`, + `${options.method} ${label} returned empty body`, response.status, '', ) @@ -333,7 +398,7 @@ export class AimlapiClient { return JSON.parse(text) as T } catch { throw new AimlapiApiError( - `${options.method} ${url} returned non-JSON body`, + `${options.method} ${label} returned non-JSON body`, response.status, text, ) diff --git a/src/integrations/aimlapi/config.test.ts b/src/integrations/aimlapi/config.test.ts index 96b5d842b8..72688e79d2 100644 --- a/src/integrations/aimlapi/config.test.ts +++ b/src/integrations/aimlapi/config.test.ts @@ -59,6 +59,27 @@ test('AIMLAPI_RETURN_URL overrides the browser landing page', () => { ) }) +test('unsafe checkout and return URL overrides are rejected', () => { + expect(buildPartnerCheckoutReturnUrls('file:///tmp/pay', 'token')).toEqual({}) + expect( + buildPartnerCheckoutReturnUrls('https://user:secret@pay.example.test', 'token'), + ).toEqual({}) + expect(buildPartnerCheckoutReturnUrls('not a URL', 'token')).toEqual({}) + + for (const override of [ + 'file:///tmp/return', + 'https://user:secret@return.example.test', + 'not a URL', + ]) { + process.env.AIMLAPI_RETURN_URL = override + expect(buildPartnerReturnUrl('https://front.example.test/')).toBe( + 'https://front.example.test', + ) + } + process.env.AIMLAPI_RETURN_URL = 'javascript:alert(1)' + expect(buildPartnerReturnUrl('also invalid')).toBe('https://aimlapi.com/app') +}) + test('partner id override is shared with the inference header', () => { process.env.AIMLAPI_PARTNER_ID = 'part_override' expect(resolvePartnerId()).toBe('part_override') diff --git a/src/integrations/aimlapi/config.ts b/src/integrations/aimlapi/config.ts index 508b5e5eba..95c10662aa 100644 --- a/src/integrations/aimlapi/config.ts +++ b/src/integrations/aimlapi/config.ts @@ -111,10 +111,8 @@ export function buildPartnerCheckoutReturnUrls( payBaseUrl: string, sessionToken: string, ): { successUrl?: string; cancelUrl?: string } { - const base = payBaseUrl.trim().replace(/\/+$/, '') - if (!base) { - return {} - } + const base = safeHttpBaseUrl(payBaseUrl) + if (!base) return {} const token = encodeURIComponent(sessionToken) const query = (status: string): string => `checkout=${status}&partnerCheckout=1&sessionToken=${token}` @@ -129,9 +127,25 @@ export function buildPartnerCheckoutReturnUrls( * this must be an ordinary HTTPS page rather than an unregistered custom scheme. */ export function buildPartnerReturnUrl(frontendBaseUrl: string): string { - return ( - process.env.AIMLAPI_RETURN_URL?.trim() || - frontendBaseUrl.trim().replace(/\/+$/, '') || - DEFAULT_RETURN_URL - ) + const override = safeHttpBaseUrl(process.env.AIMLAPI_RETURN_URL) + if (override) return override + return safeHttpBaseUrl(frontendBaseUrl) ?? DEFAULT_RETURN_URL +} + +function safeHttpBaseUrl(value: string | undefined): string | null { + const candidate = value?.trim() + if (!candidate) return null + try { + const url = new URL(candidate) + if ( + (url.protocol !== 'https:' && url.protocol !== 'http:') || + url.username || + url.password + ) { + return null + } + return url.href.replace(/\/+$/, '') + } catch { + return null + } } diff --git a/src/integrations/aimlapi/onboarding.test.ts b/src/integrations/aimlapi/onboarding.test.ts index 3d625f40ec..1dd4853dc1 100644 --- a/src/integrations/aimlapi/onboarding.test.ts +++ b/src/integrations/aimlapi/onboarding.test.ts @@ -50,6 +50,7 @@ test('existing account onboarding sends a code, creates a key, and reports low b sessionToken: 'session', apiKey: 'key_test', apiKeyId: 'id_test', + balanceStatus: 'confirmed', lowBalance: true, }) expect(calls).toEqual([ @@ -61,6 +62,28 @@ test('existing account onboarding sends a code, creates a key, and reports low b ]) }) +test('balance failures preserve the issued key without marking it ready', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + if (url.endsWith('/code/verify')) return response({ token: 'session', exp: 1 }) + if (url.endsWith('/v1/keys')) return response({ key: 'key_test', id: 'id_test' }) + return response({ error: 'unavailable' }, 503) + }) as unknown as typeof fetch + + const result = await completeAimlapiCodeSignIn('user@example.com', '123456') + expect(result).toEqual({ + sessionToken: 'session', + apiKey: 'key_test', + apiKeyId: 'id_test', + balanceStatus: 'unknown', + balanceError: 'GET https://api.example.test -> 503', + }) + expect(result).not.toHaveProperty('lowBalance') +}) + test('new account onboarding returns a passwordless session', async () => { process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' globalThis.fetch = mock(async (input: string | URL | Request) => { diff --git a/src/integrations/aimlapi/onboarding.ts b/src/integrations/aimlapi/onboarding.ts index 774dd04b86..3342ba6d58 100644 --- a/src/integrations/aimlapi/onboarding.ts +++ b/src/integrations/aimlapi/onboarding.ts @@ -15,8 +15,10 @@ export type AimlapiCodeSignInResult = { sessionToken: string apiKey: string apiKeyId: string - lowBalance: boolean -} +} & ( + | { balanceStatus: 'confirmed'; lowBalance: boolean } + | { balanceStatus: 'unknown'; balanceError: string } +) export async function validateAimlapiApiKey( apiKey: string, @@ -54,17 +56,24 @@ export async function completeAimlapiCodeSignIn( const client = clientForInferenceBaseUrl(inferenceBaseUrl) const auth = await client.verifySignInCode(email, code, signal) const created = await client.createKey(auth.token, 'OpenClaude CLI', signal) - let lowBalance = false try { - lowBalance = (await client.getBalance(created.key, signal)).lowBalance + const balance = await client.getBalance(created.key, signal) + return { + sessionToken: auth.token, + apiKey: created.key, + apiKeyId: created.id, + balanceStatus: 'confirmed', + lowBalance: balance.lowBalance, + } } catch (error) { if (signal?.aborted) throw error // The key is already issued; a balance read failure must not discard it. - } - return { - sessionToken: auth.token, - apiKey: created.key, - apiKeyId: created.id, - lowBalance, + return { + sessionToken: auth.token, + apiKey: created.key, + apiKeyId: created.id, + balanceStatus: 'unknown', + balanceError: error instanceof Error ? error.message : String(error), + } } } diff --git a/src/integrations/aimlapi/prompt.test.ts b/src/integrations/aimlapi/prompt.test.ts new file mode 100644 index 0000000000..29ffffed94 --- /dev/null +++ b/src/integrations/aimlapi/prompt.test.ts @@ -0,0 +1,63 @@ +import { afterEach, expect, mock, test } from 'bun:test' + +import { promptText } from './prompt.js' + +const originalIsTTY = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY') + +afterEach(() => { + if (originalIsTTY) { + Object.defineProperty(process.stdin, 'isTTY', originalIsTTY) + } else { + Reflect.deleteProperty(process.stdin, 'isTTY') + } +}) + +function setInteractive(): void { + Object.defineProperty(process.stdin, 'isTTY', { + configurable: true, + value: true, + }) +} + +test('promptText trims answers and closes readline', async () => { + setInteractive() + const close = mock(() => {}) + const createReadline = mock(() => ({ + question: (_question: string, resolve: (answer: string) => void) => + resolve(' answer '), + close, + })) + + await expect(promptText('Question', {}, createReadline)).resolves.toBe('answer') + expect(close).toHaveBeenCalledTimes(1) +}) + +test('promptText uses the default for an empty answer', async () => { + setInteractive() + const close = mock(() => {}) + const createReadline = mock(() => ({ + question: (_question: string, resolve: (answer: string) => void) => resolve(' '), + close, + })) + + await expect( + promptText('Question', { defaultValue: 'default' }, createReadline), + ).resolves.toBe('default') + expect(close).toHaveBeenCalledTimes(1) +}) + +test('promptText closes readline when question fails', async () => { + setInteractive() + const close = mock(() => {}) + const createReadline = mock(() => ({ + question: () => { + throw new Error('readline failed') + }, + close, + })) + + await expect(promptText('Question', {}, createReadline)).rejects.toThrow( + 'readline failed', + ) + expect(close).toHaveBeenCalledTimes(1) +}) diff --git a/src/integrations/aimlapi/prompt.ts b/src/integrations/aimlapi/prompt.ts index ea035c3c49..9457a4c54e 100644 --- a/src/integrations/aimlapi/prompt.ts +++ b/src/integrations/aimlapi/prompt.ts @@ -6,6 +6,14 @@ import { createInterface } from 'node:readline' +type ReadlineInterface = { + question(question: string, callback: (answer: string) => void): void + close(): void +} +type CreateReadlineInterface = ( + options: Parameters[0], +) => ReadlineInterface + function assertInteractive(): void { if (!process.stdin.isTTY) { throw new Error( @@ -17,10 +25,11 @@ function assertInteractive(): void { export async function promptText( question: string, opts: { defaultValue?: string } = {}, + createReadline: CreateReadlineInterface = createInterface as CreateReadlineInterface, ): Promise { assertInteractive() const suffix = opts.defaultValue ? ` [${opts.defaultValue}]` : '' - const rl = createInterface({ input: process.stdin, output: process.stdout }) + const rl = createReadline({ input: process.stdin, output: process.stdout }) try { const answer = await new Promise((resolve) => { rl.question(`${question}${suffix}: `, resolve) diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index 68c9ccb3cb..acb94e626c 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -2,13 +2,9 @@ import { afterEach, expect, mock, test } from 'bun:test' import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' -mock.module('../../utils/browser.js', () => ({ +mock.module('./topupDependencies.js', () => ({ openBrowser: async () => {}, -})) -mock.module('../../utils/providerProfile.js', () => ({ saveProfileFile: () => 'profile.json', -})) -mock.module('./prompt.js', () => ({ promptText: async () => '', })) const { pollUntilPaid, provisionAimlapiKey, topUpAimlapiByApiKey } = @@ -37,6 +33,8 @@ test('parseAimlapiAmountUsd enforces checkout bounds', () => { expect(parseAimlapiAmountUsd('10000')).toBe(1_000_000) expect(() => parseAimlapiAmountUsd('19.99')).toThrow('Minimum top-up is $20') expect(() => parseAimlapiAmountUsd('10000.01')).toThrow('Maximum top-up is $10000') + expect(() => parseAimlapiAmountUsd('19.999')).toThrow('Pass a valid USD amount') + expect(() => parseAimlapiAmountUsd('10000.004')).toThrow('Pass a valid USD amount') expect(() => parseAimlapiAmountUsd('nope')).toThrow('Pass a positive number of USD') expect(() => parseAimlapiAmountUsd('Infinity')).toThrow('Pass a positive number of USD') }) @@ -342,6 +340,30 @@ test('polling retries a transient transport failure', async () => { expect(attempts).toBe(2) }) +test('polling retains and retries the same session after a rate limit', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + let attempts = 0 + globalThis.fetch = mock(async () => { + attempts += 1 + if (attempts === 1) return new Response('rate limited', { status: 429 }) + return Response.json({ sessionToken: 'session', status: 'paid' }) + }) as unknown as typeof fetch + const client = new AimlapiClient({ + authBaseUrl: 'https://auth.example.test', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.example.test/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://front.example.test', + }) + const sessions: string[] = [] + + await expect( + pollUntilPaid(client, 'session', undefined, value => sessions.push(value)), + ).resolves.toEqual(expect.objectContaining({ status: 'paid' })) + expect(attempts).toBe(2) + expect(sessions).toEqual([]) +}) + test('by-key billing stays on the endpoint that validated the key', async () => { process.env.AIMLAPI_APP_URL = 'https://app.example.test' process.env.AIMLAPI_INFERENCE_URL = 'https://override.example.test/v1' diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index 3fe65cf9ad..2fed4a5b29 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -3,8 +3,6 @@ import { randomUUID } from 'crypto' import chalk from 'chalk' -import { openBrowser } from '../../utils/browser.js' -import { saveProfileFile } from '../../utils/providerProfile.js' import { AimlapiApiError, AimlapiClient, @@ -18,7 +16,7 @@ import { resolveEndpoints, resolvePartnerId, } from './config.js' -import { promptText } from './prompt.js' +import { openBrowser, promptText, saveProfileFile } from './topupDependencies.js' import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' export type AimlapiTopupOptions = { @@ -434,10 +432,7 @@ async function pollUntilExchangeSettled( } } catch (error) { if (signal?.aborted) throw abortError(signal) - if ( - error instanceof AimlapiApiError && - (error.status === 0 || error.status >= 500) - ) { + if (isRetryableSessionApiError(error)) { await sleep(POLL_INTERVAL_MS, signal) continue } @@ -478,7 +473,7 @@ export async function pollUntilPaid( } } catch (error) { if (signal?.aborted) throw abortError(signal) - if (error instanceof AimlapiApiError && (error.status === 0 || error.status >= 500)) { + if (isRetryableSessionApiError(error)) { await sleep(POLL_INTERVAL_MS, signal) continue } @@ -493,6 +488,17 @@ function isTerminalSessionApiError(error: unknown): boolean { return ( error instanceof AimlapiApiError && error.status >= 400 && - error.status < 500 + error.status < 500 && + !isRetryableSessionApiError(error) + ) +} + +function isRetryableSessionApiError(error: unknown): boolean { + return ( + error instanceof AimlapiApiError && + (error.status === 0 || + error.status === 408 || + error.status === 429 || + error.status >= 500) ) } diff --git a/src/integrations/aimlapi/topupDependencies.ts b/src/integrations/aimlapi/topupDependencies.ts new file mode 100644 index 0000000000..37fca21b4f --- /dev/null +++ b/src/integrations/aimlapi/topupDependencies.ts @@ -0,0 +1,10 @@ +import { openBrowser as openBrowserImpl } from '../../utils/browser.js' +import { saveProfileFile as saveProfileFileImpl } from '../../utils/providerProfile.js' +import { promptText as promptTextImpl } from './prompt.js' + +export const openBrowser: typeof openBrowserImpl = url => openBrowserImpl(url) + +export const saveProfileFile: typeof saveProfileFileImpl = options => + saveProfileFileImpl(options) + +export const promptText: typeof promptTextImpl = (...args) => promptTextImpl(...args) diff --git a/src/integrations/aimlapi/validation.ts b/src/integrations/aimlapi/validation.ts index 512fefd3a0..c67837b7c6 100644 --- a/src/integrations/aimlapi/validation.ts +++ b/src/integrations/aimlapi/validation.ts @@ -6,10 +6,15 @@ import { export function parseAimlapiAmountUsd(amountUsd: string | undefined): number { if (!amountUsd?.trim()) return DEFAULT_AMOUNT_USD_MINOR - const dollars = Number(amountUsd) + const normalized = amountUsd.trim() + const dollars = Number(normalized) if (!Number.isFinite(dollars) || dollars <= 0) { throw new Error(`Invalid amount: "${amountUsd}". Pass a positive number of USD.`) } + const decimal = /^\d+\.(\d+)$/.exec(normalized) + if (decimal && decimal[1].length > 2) { + throw new Error(`Invalid amount: "${amountUsd}". Pass a valid USD amount.`) + } const minor = Math.round(dollars * 100) if (minor < MIN_AMOUNT_USD_MINOR) { throw new Error(`Minimum top-up is $${MIN_AMOUNT_USD_MINOR / 100}.`) diff --git a/src/integrations/gateways/aimlapi.ts b/src/integrations/gateways/aimlapi.ts index 290ddefb5f..16f90c3299 100644 --- a/src/integrations/gateways/aimlapi.ts +++ b/src/integrations/gateways/aimlapi.ts @@ -115,11 +115,11 @@ export default defineGateway({ discoveryRefreshMode: 'startup', allowManualRefresh: true, models: [ - { id: 'aimlapi-claude-sonnet-5', apiName: 'anthropic/claude-sonnet-5', label: 'Claude Sonnet 5' }, - { id: 'aimlapi-gemini-3.5-flash', apiName: 'google/gemini-3.5-flash', label: 'Gemini 3.5 Flash' }, - { id: 'aimlapi-gpt-5.5', apiName: 'openai/gpt-5.5-2026-04-23', label: 'GPT-5.5' }, - { id: 'aimlapi-qwen-3.7-max', apiName: 'qwen/qwen-3.7-max', label: 'Qwen 3.7 Max' }, - { id: 'aimlapi-deepseek-v4', apiName: 'deepseek/deepseek-v4-pro', label: 'DeepSeek V4' }, + { id: 'aimlapi-claude-sonnet-5', apiName: 'anthropic/claude-sonnet-5', modelDescriptorId: 'claude-sonnet-5', label: 'Claude Sonnet 5' }, + { id: 'aimlapi-gemini-3.5-flash', apiName: 'google/gemini-3.5-flash', modelDescriptorId: 'gemini-3.5-flash', label: 'Gemini 3.5 Flash' }, + { id: 'aimlapi-gpt-5.5', apiName: 'openai/gpt-5.5-2026-04-23', modelDescriptorId: 'gpt-5.5', label: 'GPT-5.5' }, + { id: 'aimlapi-qwen-3.7-max', apiName: 'qwen/qwen-3.7-max', modelDescriptorId: 'qwen3.7-max', label: 'Qwen 3.7 Max' }, + { id: 'aimlapi-deepseek-v4', apiName: 'deepseek/deepseek-v4-pro', modelDescriptorId: 'deepseek-v4-pro', label: 'DeepSeek V4' }, ], }, usage: { supported: false }, diff --git a/src/integrations/models/claude.ts b/src/integrations/models/claude.ts index eb2d6a9581..521ff82280 100644 --- a/src/integrations/models/claude.ts +++ b/src/integrations/models/claude.ts @@ -1,6 +1,24 @@ import { defineModel } from '../define.js' export default [ + defineModel({ + id: 'claude-sonnet-5', + label: 'Claude Sonnet 5', + brandId: 'claude', + vendorId: 'anthropic', + classification: ['chat', 'reasoning', 'vision', 'coding'], + defaultModel: 'claude-sonnet-5', + capabilities: { + supportsVision: true, + supportsStreaming: true, + supportsFunctionCalling: true, + supportsJsonMode: true, + supportsReasoning: true, + supportsPreciseTokenCount: false, + }, + contextWindow: 1_000_000, + maxOutputTokens: 128_000, + }), defineModel({ id: 'claude-opus-4-8', label: 'Claude Opus 4.8', diff --git a/src/integrations/runtimeMetadata.ts b/src/integrations/runtimeMetadata.ts index 1ce7ff5c96..2d5101f108 100644 --- a/src/integrations/runtimeMetadata.ts +++ b/src/integrations/runtimeMetadata.ts @@ -48,20 +48,25 @@ function resolveRouteOpenAIShimConfig( ): OpenAIShimTransportConfig | undefined { if (routeId !== 'aimlapi' || !config?.headers) return config - const headers = Object.fromEntries( - Object.entries(config.headers).filter( - ([name]) => !AIMLAPI_CATALOG_HEADER_NAMES.has(name.trim().toLowerCase()), - ), - ) if (!baseUrl || isCanonicalAimlapiInferenceBaseUrl(baseUrl)) { - headers[PARTNER_HEADER_NAME] = resolvePartnerId() + const headers: Record = {} for (const [name, value] of Object.entries(config.headers)) { if (name.trim().toLowerCase() !== PARTNER_HEADER_NAME.toLowerCase()) { headers[name] = value } } + headers[PARTNER_HEADER_NAME] = resolvePartnerId() + return { ...config, headers } + } + + return { + ...config, + headers: Object.fromEntries( + Object.entries(config.headers).filter( + ([name]) => !AIMLAPI_CATALOG_HEADER_NAMES.has(name.trim().toLowerCase()), + ), + ), } - return { ...config, headers } } function normalizeModelApiName( diff --git a/src/main.tsx b/src/main.tsx index fb54ee432a..5ed3cafeff 100644 --- a/src/main.tsx +++ b/src/main.tsx @@ -36,7 +36,7 @@ import { launchRepl } from './replLauncher.js'; import { refreshGrowthBookAfterAuthChange } from './services/analytics/growthbook.js'; import { fetchBootstrapData } from './services/api/bootstrap.js'; import { refreshStartupDiscoveryForActiveRoute } from './integrations/discoveryService.js'; -import { MAX_AMOUNT_USD_MINOR, MIN_AMOUNT_USD_MINOR } from './integrations/aimlapi/config.js'; +import { registerAimlapiCommand } from './cli/aimlapiCommand.js'; import { prefetchOllamaModels } from './utils/model/ollamaModels.js'; import { type DownloadResult, downloadSessionFiles, type FilesApiConfig, parseFileSpecs } from './services/api/filesApi.js'; import { prefetchPassesEligibility } from './services/api/referral.js'; @@ -4015,36 +4015,7 @@ async function run(): Promise { // AI/ML API (aimlapi.com) — log in, open the co-branded top-up page, and // auto-configure the provider with the issued key. - const aimlapi = program.command('aimlapi').description('AI/ML API (aimlapi.com) — top up balance and configure the provider').configureHelp(createSortedHelpConfig()); - aimlapi.command('topup') - .description("Use passwordless sign-in, open AI/ML API top-up, then configure OpenClaude") - .option('--email ', 'AI/ML API account email (or AIMLAPI_EMAIL env)') - .option('--code ', '6-digit code for an existing account (or AIMLAPI_CODE env)') - .option('--amount ', `Top-up amount in USD (min ${MIN_AMOUNT_USD_MINOR / 100}, max ${MAX_AMOUNT_USD_MINOR / 100})`) - .option('--auto-top-up', 'Enable automatic top-up at checkout') - .option('--model ', 'Default model id written into the provider profile', 'anthropic/claude-sonnet-5') - .option('--partner-id ', 'Partner id for rebate attribution (part_...)') - .option('--no-open', 'Do not auto-open the browser; print the payment URL instead') - .action(async (opts: { - email?: string; - code?: string; - amount?: string; - autoTopUp?: boolean; - model?: string; - partnerId?: string; - open?: boolean; - }) => { - const { aimlapiTopup } = await import('./cli/handlers/aimlapi.js'); - await aimlapiTopup({ - email: opts.email, - code: opts.code, - amountUsd: opts.amount, - autoTopUp: opts.autoTopUp, - model: opts.model, - partnerId: opts.partnerId, - noOpen: opts.open === false, - }); - }); + registerAimlapiCommand(program).configureHelp(createSortedHelpConfig()); /** * Helper function to handle marketplace command errors consistently. From 2b058ea989dc2268e4108bbcc8e9f18425f01b63 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Fri, 17 Jul 2026 01:08:05 +0500 Subject: [PATCH 03/17] fix(aimlapi): address follow-up review --- src/integrations/aimlapi/config.test.ts | 18 ++++ src/integrations/aimlapi/config.ts | 10 ++- src/integrations/aimlapi/topup.test.ts | 73 +++++++++++++++- src/integrations/aimlapi/topup.ts | 38 +++++++- src/integrations/aimlapi/topupState.test.ts | 74 ++++++++++++++++ src/integrations/aimlapi/topupState.ts | 97 +++++++++++++++++++++ src/integrations/runtimeMetadata.ts | 11 +-- 7 files changed, 306 insertions(+), 15 deletions(-) create mode 100644 src/integrations/aimlapi/topupState.test.ts create mode 100644 src/integrations/aimlapi/topupState.ts diff --git a/src/integrations/aimlapi/config.test.ts b/src/integrations/aimlapi/config.test.ts index 72688e79d2..ef053e80d5 100644 --- a/src/integrations/aimlapi/config.test.ts +++ b/src/integrations/aimlapi/config.test.ts @@ -65,10 +65,28 @@ test('unsafe checkout and return URL overrides are rejected', () => { buildPartnerCheckoutReturnUrls('https://user:secret@pay.example.test', 'token'), ).toEqual({}) expect(buildPartnerCheckoutReturnUrls('not a URL', 'token')).toEqual({}) + expect(buildPartnerCheckoutReturnUrls('http://pay.example.test', 'token')).toEqual( + {}, + ) + expect( + buildPartnerCheckoutReturnUrls('https://pay.example.test?environment=test', 'token'), + ).toEqual({}) + expect( + buildPartnerCheckoutReturnUrls('https://pay.example.test/#checkout', 'token'), + ).toEqual({}) + expect(buildPartnerCheckoutReturnUrls('http://127.0.0.1:3000/', 'token')).toEqual({ + successUrl: + 'http://127.0.0.1:3000/checkout?checkout=success&partnerCheckout=1&sessionToken=token', + cancelUrl: + 'http://127.0.0.1:3000/checkout?checkout=cancel&partnerCheckout=1&sessionToken=token', + }) for (const override of [ 'file:///tmp/return', 'https://user:secret@return.example.test', + 'http://return.example.test', + 'https://return.example.test/done?source=test', + 'https://return.example.test/done#checkout', 'not a URL', ]) { process.env.AIMLAPI_RETURN_URL = override diff --git a/src/integrations/aimlapi/config.ts b/src/integrations/aimlapi/config.ts index 95c10662aa..18fd2b80fe 100644 --- a/src/integrations/aimlapi/config.ts +++ b/src/integrations/aimlapi/config.ts @@ -137,10 +137,16 @@ function safeHttpBaseUrl(value: string | undefined): string | null { if (!candidate) return null try { const url = new URL(candidate) + const loopback = + url.hostname === 'localhost' || + url.hostname.startsWith('127.') || + url.hostname === '[::1]' if ( - (url.protocol !== 'https:' && url.protocol !== 'http:') || + (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || url.username || - url.password + url.password || + url.search || + url.hash ) { return null } diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index acb94e626c..c182864dd9 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -1,5 +1,9 @@ import { afterEach, expect, mock, test } from 'bun:test' +import { mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { setClaudeConfigHomeDirForTesting } from '../../utils/envUtils.js' import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' mock.module('./topupDependencies.js', () => ({ @@ -7,19 +11,25 @@ mock.module('./topupDependencies.js', () => ({ saveProfileFile: () => 'profile.json', promptText: async () => '', })) -const { pollUntilPaid, provisionAimlapiKey, topUpAimlapiByApiKey } = +const { pollUntilPaid, provisionAimlapiKey, runAimlapiTopup, topUpAimlapiByApiKey } = await import('./topup.js') const { AimlapiClient } = await import('./client.js') const originalFetch = globalThis.fetch const originalEnv = { + AIMLAPI_AUTH_URL: process.env.AIMLAPI_AUTH_URL, AIMLAPI_APP_URL: process.env.AIMLAPI_APP_URL, AIMLAPI_INFERENCE_URL: process.env.AIMLAPI_INFERENCE_URL, AIMLAPI_PAY_URL: process.env.AIMLAPI_PAY_URL, } +const temporaryDirectories: string[] = [] afterEach(() => { globalThis.fetch = originalFetch + setClaudeConfigHomeDirForTesting(undefined) + for (const directory of temporaryDirectories.splice(0)) { + rmSync(directory, { force: true, recursive: true }) + } for (const [name, value] of Object.entries(originalEnv)) { if (value === undefined) delete process.env[name] else process.env[name] = value @@ -46,6 +56,67 @@ test('isValidAimlapiEmail rejects incomplete domains', () => { expect(isValidAimlapiEmail('user@.example.com')).toBe(false) }) +test('CLI retries reuse the persisted checkout session and payment id', async () => { + const configDirectory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-cli-')) + temporaryDirectories.push(configDirectory) + setClaudeConfigHomeDirForTesting(configDirectory) + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' + + let accountChecks = 0 + const payBodies: Array> = [] + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + if (url.endsWith('/v1/auth/account')) { + accountChecks += 1 + return Response.json({ action: accountChecks === 1 ? 'sign-up' : 'sign-in' }) + } + if (url.endsWith('/passwordless')) { + return Response.json({ token: 'account-token-one', exp: 1 }) + } + if (url.endsWith('/sign-in/code')) return new Response(null, { status: 204 }) + if (url.endsWith('/code/verify')) { + return Response.json({ token: 'account-token-two', exp: 2 }) + } + if (url.endsWith('/v1/keys')) { + return Response.json({ key: 'key_test', id: 'key_id' }) + } + if (url.endsWith('/v3/partner-checkout/sessions') && init?.method === 'POST') { + return Response.json({ sessionToken: 'checkout-session', status: 'pending_auth' }) + } + if (url.endsWith('/pay')) { + payBodies.push(JSON.parse(String(init?.body)) as Record) + throw new Error('ambiguous payment response') + } + if (url.endsWith('/v3/partner-checkout/sessions/checkout-session')) { + return Response.json({ sessionToken: 'checkout-session', status: 'paid' }) + } + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + await expect( + runAimlapiTopup({ email: 'user@example.com', amountUsd: '25', noOpen: true }), + ).rejects.toThrow('ambiguous payment response') + + const saved = JSON.parse( + readFileSync(join(configDirectory, 'aimlapi-topup.json'), 'utf8'), + ) as { paymentSessionId: string; resumeSessionToken: string } + expect(saved.paymentSessionId).toBeTruthy() + expect(saved.resumeSessionToken).toBe('checkout-session') + expect(payBodies).toHaveLength(1) + expect(payBodies[0]?.paymentSessionId).toBe(saved.paymentSessionId) + + await runAimlapiTopup({ + email: 'user@example.com', + code: '123456', + amountUsd: '25', + noOpen: true, + }) + expect(payBodies).toHaveLength(1) + expect(() => readFileSync(join(configDirectory, 'aimlapi-topup.json'))).toThrow() +}) + test('topUpAimlapiByApiKey funds the key account without exchange', async () => { process.env.AIMLAPI_APP_URL = 'https://app.example.test' process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index 2fed4a5b29..4fbdab6d66 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -17,6 +17,12 @@ import { resolvePartnerId, } from './config.js' import { openBrowser, promptText, saveProfileFile } from './topupDependencies.js' +import { + clearAimlapiTopupState, + loadAimlapiTopupState, + saveAimlapiTopupState, + type AimlapiTopupIntent, +} from './topupState.js' import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' export type AimlapiTopupOptions = { @@ -136,19 +142,44 @@ export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { + checkoutState.resumeSessionToken = resumeSessionToken + saveAimlapiTopupState({ ...intent, ...checkoutState }) + } + saveAimlapiTopupState({ ...intent, ...checkoutState }) + const provisioned = await provisionAimlapiKey({ amountUsd: options.amountUsd, autoTopUp: options.autoTopUp, model: options.model, - partnerId: options.partnerId, - partnerName: options.partnerName, + partnerId, + partnerName, noOpen: options.noOpen, signal: options.signal, sessionToken, exchange, - paymentSessionId: randomUUID(), + paymentSessionId: checkoutState.paymentSessionId, + resumeSessionToken: checkoutState.resumeSessionToken, existingApiKey: apiKey, existingApiKeyId: apiKeyId, + onSession: persistSession, onStatus: (status, detail) => { if (status === 'opening-checkout' && detail) console.log(` ${chalk.cyan(detail)}`) if (status === 'waiting-payment') console.log(chalk.dim(' Waiting for payment...')) @@ -166,6 +197,7 @@ export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { + setClaudeConfigHomeDirForTesting(undefined) + for (const directory of directories.splice(0)) { + rmSync(directory, { force: true, recursive: true }) + } +}) + +function useTemporaryConfig(): string { + const directory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-topup-')) + directories.push(directory) + setClaudeConfigHomeDirForTesting(directory) + return directory +} + +const intent: AimlapiTopupIntent = { + email: 'user@example.com', + amountUsdMinor: 2500, + autoTopUp: false, + partnerId: 'part_test', + partnerName: 'OpenClaude', + appBaseUrl: 'https://app.example.test', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://front.example.test', +} + +test('top-up state round-trips only for the same checkout intent', () => { + const directory = useTemporaryConfig() + saveAimlapiTopupState({ + ...intent, + paymentSessionId: 'payment-id', + resumeSessionToken: 'session-token', + }) + + expect(loadAimlapiTopupState(intent)).toEqual({ + paymentSessionId: 'payment-id', + resumeSessionToken: 'session-token', + }) + expect(loadAimlapiTopupState({ ...intent, amountUsdMinor: 3000 })).toBeNull() + expect(readFileSync(join(directory, 'aimlapi-topup.json'), 'utf8')).toContain( + 'session-token', + ) + if (process.platform !== 'win32') { + expect(statSync(join(directory, 'aimlapi-topup.json')).mode & 0o777).toBe(0o600) + } +}) + +test('top-up state is cleared only by its matching intent', () => { + useTemporaryConfig() + saveAimlapiTopupState({ + ...intent, + paymentSessionId: 'payment-id', + resumeSessionToken: 'session-token', + }) + + clearAimlapiTopupState({ ...intent, email: 'other@example.com' }) + expect(loadAimlapiTopupState(intent)).not.toBeNull() + clearAimlapiTopupState(intent) + expect(loadAimlapiTopupState(intent)).toBeNull() +}) diff --git a/src/integrations/aimlapi/topupState.ts b/src/integrations/aimlapi/topupState.ts new file mode 100644 index 0000000000..7221522a79 --- /dev/null +++ b/src/integrations/aimlapi/topupState.ts @@ -0,0 +1,97 @@ +import { + chmodSync, + mkdirSync, + readFileSync, + renameSync, + rmSync, + writeFileSync, +} from 'node:fs' +import { dirname, join } from 'node:path' +import { randomUUID } from 'node:crypto' + +import { getClaudeConfigHomeDir } from '../../utils/envUtils.js' + +export type AimlapiTopupIntent = { + email: string + amountUsdMinor: number + autoTopUp: boolean + partnerId: string + partnerName: string + appBaseUrl: string + payBaseUrl: string + verificationBaseUrl: string +} + +export type AimlapiPersistedTopup = AimlapiTopupIntent & { + paymentSessionId: string + resumeSessionToken: string +} + +function statePath(): string { + return join(getClaudeConfigHomeDir(), 'aimlapi-topup.json') +} + +function matchesIntent( + state: AimlapiPersistedTopup, + intent: AimlapiTopupIntent, +): boolean { + return (Object.keys(intent) as Array).every( + key => state[key] === intent[key], + ) +} + +function isPersistedTopup(value: unknown): value is AimlapiPersistedTopup { + if (typeof value !== 'object' || value === null) return false + const state = value as Record + return ( + typeof state.email === 'string' && + typeof state.amountUsdMinor === 'number' && + Number.isSafeInteger(state.amountUsdMinor) && + typeof state.autoTopUp === 'boolean' && + typeof state.partnerId === 'string' && + typeof state.partnerName === 'string' && + typeof state.appBaseUrl === 'string' && + typeof state.payBaseUrl === 'string' && + typeof state.verificationBaseUrl === 'string' && + typeof state.paymentSessionId === 'string' && + Boolean(state.paymentSessionId.trim()) && + typeof state.resumeSessionToken === 'string' + ) +} + +export function loadAimlapiTopupState( + intent: AimlapiTopupIntent, +): Pick | null { + try { + const state: unknown = JSON.parse(readFileSync(statePath(), 'utf8')) + if (!isPersistedTopup(state) || !matchesIntent(state, intent)) return null + return { + paymentSessionId: state.paymentSessionId, + resumeSessionToken: state.resumeSessionToken, + } + } catch { + return null + } +} + +export function saveAimlapiTopupState(state: AimlapiPersistedTopup): void { + const target = statePath() + mkdirSync(dirname(target), { recursive: true }) + const temporary = `${target}.${process.pid}.${randomUUID()}.tmp` + try { + writeFileSync(temporary, `${JSON.stringify(state, null, 2)}\n`, { + encoding: 'utf8', + flag: 'wx', + mode: 0o600, + }) + chmodSync(temporary, 0o600) + renameSync(temporary, target) + } finally { + rmSync(temporary, { force: true }) + } +} + +export function clearAimlapiTopupState(intent: AimlapiTopupIntent): void { + const current = loadAimlapiTopupState(intent) + if (current) rmSync(statePath(), { force: true }) +} diff --git a/src/integrations/runtimeMetadata.ts b/src/integrations/runtimeMetadata.ts index 2d5101f108..49a4a13fc1 100644 --- a/src/integrations/runtimeMetadata.ts +++ b/src/integrations/runtimeMetadata.ts @@ -30,7 +30,7 @@ import { ZAI_GLM_OPENAI_SHIM } from './transport/zaiGlmShim.js' import { isCanonicalAimlapiInferenceBaseUrl, PARTNER_HEADER_NAME, - resolvePartnerId, + withResolvedPartnerHeader, } from './aimlapi/config.js' const AIMLAPI_CATALOG_HEADER_NAMES = new Set([ @@ -49,14 +49,7 @@ function resolveRouteOpenAIShimConfig( if (routeId !== 'aimlapi' || !config?.headers) return config if (!baseUrl || isCanonicalAimlapiInferenceBaseUrl(baseUrl)) { - const headers: Record = {} - for (const [name, value] of Object.entries(config.headers)) { - if (name.trim().toLowerCase() !== PARTNER_HEADER_NAME.toLowerCase()) { - headers[name] = value - } - } - headers[PARTNER_HEADER_NAME] = resolvePartnerId() - return { ...config, headers } + return { ...config, headers: withResolvedPartnerHeader(config.headers) } } return { From b52f620f9b0c6f1e401f49da91c4119009abe2e6 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Fri, 17 Jul 2026 01:20:10 +0500 Subject: [PATCH 04/17] test(aimlapi): clean up top-up mocks --- src/components/ProviderManager.test.tsx | 2 +- src/integrations/aimlapi/config.test.ts | 6 ++++++ src/integrations/aimlapi/config.ts | 2 +- src/integrations/aimlapi/topup.test.ts | 7 ++++++- 4 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/components/ProviderManager.test.tsx b/src/components/ProviderManager.test.tsx index 56de2ca1ff..dc9dcbf11e 100644 --- a/src/components/ProviderManager.test.tsx +++ b/src/components/ProviderManager.test.tsx @@ -1657,7 +1657,7 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => } finally { await mounted.dispose() } -}) +}, 10_000) test('ProviderManager saves MiniMax preset with Anthropic-compatible endpoint and type', async () => { const addProviderProfile = mock((payload: any) => ({ diff --git a/src/integrations/aimlapi/config.test.ts b/src/integrations/aimlapi/config.test.ts index ef053e80d5..6dd6118a1e 100644 --- a/src/integrations/aimlapi/config.test.ts +++ b/src/integrations/aimlapi/config.test.ts @@ -68,6 +68,9 @@ test('unsafe checkout and return URL overrides are rejected', () => { expect(buildPartnerCheckoutReturnUrls('http://pay.example.test', 'token')).toEqual( {}, ) + expect( + buildPartnerCheckoutReturnUrls('http://127.0.0.1.evil.example', 'token'), + ).toEqual({}) expect( buildPartnerCheckoutReturnUrls('https://pay.example.test?environment=test', 'token'), ).toEqual({}) @@ -80,6 +83,9 @@ test('unsafe checkout and return URL overrides are rejected', () => { cancelUrl: 'http://127.0.0.1:3000/checkout?checkout=cancel&partnerCheckout=1&sessionToken=token', }) + expect(buildPartnerReturnUrl('http://127.1:3000/')).toBe( + 'http://127.0.0.1:3000', + ) for (const override of [ 'file:///tmp/return', diff --git a/src/integrations/aimlapi/config.ts b/src/integrations/aimlapi/config.ts index 18fd2b80fe..a590938366 100644 --- a/src/integrations/aimlapi/config.ts +++ b/src/integrations/aimlapi/config.ts @@ -139,7 +139,7 @@ function safeHttpBaseUrl(value: string | undefined): string | null { const url = new URL(candidate) const loopback = url.hostname === 'localhost' || - url.hostname.startsWith('127.') || + /^127(?:\.\d+){3}$/.test(url.hostname) || url.hostname === '[::1]' if ( (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) || diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index c182864dd9..e0bcdceda8 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -1,9 +1,10 @@ -import { afterEach, expect, mock, test } from 'bun:test' +import { afterAll, afterEach, expect, mock, test } from 'bun:test' import { mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { setClaudeConfigHomeDirForTesting } from '../../utils/envUtils.js' +import * as realTopupDependencies from './topupDependencies.js' import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' mock.module('./topupDependencies.js', () => ({ @@ -24,6 +25,10 @@ const originalEnv = { } const temporaryDirectories: string[] = [] +afterAll(() => { + mock.module('./topupDependencies.js', () => realTopupDependencies) +}) + afterEach(() => { globalThis.fetch = originalFetch setClaudeConfigHomeDirForTesting(undefined) From 9a03f93e9600608dbba632c0848e8bd97250d43d Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Fri, 17 Jul 2026 03:15:27 +0500 Subject: [PATCH 05/17] fix(aimlapi): harden checkout recovery --- src/cli/aimlapiCommand.ts | 3 +- src/components/ProviderManager.test.tsx | 115 +++++++++++++++++++- src/components/ProviderManager.tsx | 83 +++++++++++--- src/components/providerManagerAimlapi.ts | 19 ++++ src/integrations/aimlapi/prompt.test.ts | 22 ++++ src/integrations/aimlapi/prompt.ts | 26 ++++- src/integrations/aimlapi/topup.test.ts | 67 +++++++++++- src/integrations/aimlapi/topup.ts | 38 ++++--- src/integrations/aimlapi/topupState.test.ts | 11 ++ src/integrations/aimlapi/topupState.ts | 68 ++++++++++++ src/integrations/discoveryService.test.ts | 18 +-- src/integrations/gateways/aimlapi.ts | 11 +- src/integrations/index.ts | 1 + src/integrations/models/claude.ts | 18 --- 14 files changed, 421 insertions(+), 79 deletions(-) diff --git a/src/cli/aimlapiCommand.ts b/src/cli/aimlapiCommand.ts index c17636be87..9a9827e1ec 100644 --- a/src/cli/aimlapiCommand.ts +++ b/src/cli/aimlapiCommand.ts @@ -1,6 +1,7 @@ import { Command as CommanderCommand } from '@commander-js/extra-typings' import { + DEFAULT_MODEL, MAX_AMOUNT_USD_MINOR, MIN_AMOUNT_USD_MINOR, } from '../integrations/aimlapi/config.js' @@ -36,7 +37,7 @@ export function registerAimlapiCommand( .option( '--model ', 'Default model id written into the provider profile', - 'anthropic/claude-sonnet-5', + DEFAULT_MODEL, ) .option('--partner-id ', 'Partner id for rebate attribution (part_...)') .option('--no-open', 'Do not auto-open the browser; print the payment URL instead') diff --git a/src/components/ProviderManager.test.tsx b/src/components/ProviderManager.test.tsx index dc9dcbf11e..8bf650d509 100644 --- a/src/components/ProviderManager.test.tsx +++ b/src/components/ProviderManager.test.tsx @@ -34,6 +34,8 @@ const ORIGINAL_ENV = { AIMLAPI_CODE: process.env.AIMLAPI_CODE, AIMLAPI_API_KEY: process.env.AIMLAPI_API_KEY, AIMLAPI_INFERENCE_URL: process.env.AIMLAPI_INFERENCE_URL, + OPENAI_API_KEY: process.env.OPENAI_API_KEY, + OPENAI_API_KEYS: process.env.OPENAI_API_KEYS, } function extractLastFrame(output: string): string { @@ -351,6 +353,9 @@ function mockProviderManagerDependencies( beginAimlapiEmailOnboarding?: (...args: any[]) => Promise completeAimlapiCodeSignIn?: (...args: any[]) => Promise validateAimlapiApiKey?: (...args: any[]) => Promise + claimAimlapiTopupState?: (...args: any[]) => unknown + clearAimlapiTopupState?: (...args: any[]) => unknown + saveAimlapiTopupState?: (...args: any[]) => unknown useCodexOAuthFlow?: (options: { onAuthenticated: ( tokens: { @@ -376,6 +381,14 @@ function mockProviderManagerDependencies( } }, ): void { + let persistedAimlapiTopup: Record | undefined + let aimlapiPaymentSequence = 0 + const matchesAimlapiIntent = ( + state: Record | undefined, + intent: Record, + ): boolean => + Boolean(state) && Object.keys(intent).every(key => state?.[key] === intent[key]) + mockProviderProfilesModule({ addProviderProfile: options?.addProviderProfile, getActiveProviderProfile: options?.getActiveProviderProfile, @@ -491,6 +504,37 @@ function mockProviderManagerDependencies( validateAimlapiApiKey: options?.validateAimlapiApiKey ?? (async () => ({ balance: 25, lowBalance: false, lowBalanceThreshold: 20 })), + claimAimlapiTopupState: + options?.claimAimlapiTopupState ?? + ((intent: Record) => { + if (matchesAimlapiIntent(persistedAimlapiTopup, intent)) { + return { + paymentSessionId: persistedAimlapiTopup?.paymentSessionId, + resumeSessionToken: persistedAimlapiTopup?.resumeSessionToken, + } + } + persistedAimlapiTopup = { + ...intent, + paymentSessionId: `payment-${++aimlapiPaymentSequence}`, + resumeSessionToken: '', + } + return { + paymentSessionId: persistedAimlapiTopup.paymentSessionId, + resumeSessionToken: '', + } + }), + clearAimlapiTopupState: + options?.clearAimlapiTopupState ?? + ((intent: Record) => { + if (matchesAimlapiIntent(persistedAimlapiTopup, intent)) { + persistedAimlapiTopup = undefined + } + }), + saveAimlapiTopupState: + options?.saveAimlapiTopupState ?? + ((state: Record) => { + persistedAimlapiTopup = state + }), parseAimlapiAmountUsd: (value: string | undefined) => { const amount = Number(value || 25) if (!Number.isFinite(amount) || amount < 20 || amount > 10000) { @@ -1127,8 +1171,60 @@ test('ProviderManager offers and reuses an existing AIMLAPI profile', async () = } }, 10_000) -test('ProviderManager first run keeps AIMLAPI_API_KEY out of the saved profile', async () => { - process.env.AIMLAPI_API_KEY = 'env-runtime-key' +test('ProviderManager uses OPENAI_API_KEY for an existing keyless AIMLAPI profile', async () => { + delete process.env.AIMLAPI_API_KEY + delete process.env.OPENAI_API_KEYS + process.env.OPENAI_API_KEY = 'openai-fallback-key' + const profile = { + id: 'aimlapi_existing', + provider: 'aimlapi', + name: 'aimlapi.com', + baseUrl: 'https://api.aimlapi.com/v1', + model: 'anthropic/claude-sonnet-5', + apiKey: undefined, + apiFormat: 'chat_completions', + } + const validateAimlapiApiKey = mock(async () => ({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + getProviderProfiles: () => [profile], + getActiveProviderProfile: () => profile, + validateAimlapiApiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('aimlapi.com account is already configured'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + expect(validateAimlapiApiKey).toHaveBeenCalledWith( + 'openai-fallback-key', + expect.any(AbortSignal), + 'https://api.aimlapi.com/v1', + ) + } finally { + await mounted.dispose() + } +}, 10_000) + +test('ProviderManager first run recognizes the OPENAI_API_KEY fallback without persisting it', async () => { + delete process.env.AIMLAPI_API_KEY + delete process.env.OPENAI_API_KEYS + process.env.OPENAI_API_KEY = 'env-runtime-key' process.env.AIMLAPI_INFERENCE_URL = 'https://proxy.example.test/v1' const addProviderProfile = mock((payload: any) => ({ id: 'aimlapi_env', @@ -1549,10 +1645,17 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => model: 'anthropic/claude-sonnet-5', } }) + const claimAimlapiTopupState = mock(() => ({ + paymentSessionId: 'persisted-payment-id', + resumeSessionToken: 'persisted-checkout-session', + })) + const clearAimlapiTopupState = mock(() => {}) mockProviderManagerDependencies(() => undefined, async () => undefined, { addProviderProfile, provisionAimlapiKey, + claimAimlapiTopupState, + clearAimlapiTopupState, }) const nonce = `${Date.now()}-${Math.random()}` @@ -1631,13 +1734,15 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => await waitForFrameOutput( mounted.getOutput, frame => frame.includes('Provider manager'), - 8_000, + 12_000, ) expect(provisionAimlapiKey).toHaveBeenCalledWith( expect.objectContaining({ amountUsd: '25', model: 'anthropic/claude-sonnet-5', sessionToken: 'session_test', + paymentSessionId: 'persisted-payment-id', + resumeSessionToken: 'persisted-checkout-session', exchange: true, autoTopUp: false, onStatus: expect.any(Function), @@ -1654,10 +1759,12 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => }), expect.objectContaining({ makeActive: true }), ) + expect(claimAimlapiTopupState).toHaveBeenCalledTimes(1) + expect(clearAimlapiTopupState).toHaveBeenCalledTimes(1) } finally { await mounted.dispose() } -}, 10_000) +}, 20_000) test('ProviderManager saves MiniMax preset with Anthropic-compatible endpoint and type', async () => { const addProviderProfile = mock((payload: any) => ({ diff --git a/src/components/ProviderManager.tsx b/src/components/ProviderManager.tsx index 46356b4bc8..f9ca4f789a 100644 --- a/src/components/ProviderManager.tsx +++ b/src/components/ProviderManager.tsx @@ -1,4 +1,4 @@ -import { randomUUID } from 'node:crypto' +import { createHash } from 'node:crypto' import figures from 'figures' import * as React from 'react' import { DEFAULT_CODEX_BASE_URL } from '../services/api/providerConfig.js' @@ -45,6 +45,7 @@ import { routeShowsAuthHeaderValue, routeShowsCustomHeaders, resolveProfileRoute, + resolveRouteCredentialValue, resolveRouteIdFromBaseUrl, } from '../integrations/index.js' import { @@ -57,12 +58,18 @@ import { validateAimlapiApiKey, AimlapiApiError, AIMLAPI_MESSAGES, + claimAimlapiTopupState, + clearAimlapiTopupState, + saveAimlapiTopupState, + type AimlapiTopupIntent, type AimlapiTopupStatus, } from './providerManagerAimlapi.js' import { DEFAULT_AMOUNT_USD_MINOR, + DEFAULT_PARTNER_NAME, isCanonicalAimlapiInferenceBaseUrl, resolveEndpoints, + resolvePartnerId, } from '../integrations/aimlapi/config.js' import { openAIShimSupportsApiFormatForModel } from '../integrations/runtimeMetadata.js' import { probeRouteReadiness } from '../integrations/discoveryService.js' @@ -965,7 +972,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { const [aimlapiIssuedKeyId, setAimlapiIssuedKeyId] = React.useState('') const [aimlapiTopupByKey, setAimlapiTopupByKey] = React.useState(false) const [aimlapiResumeSessionToken, setAimlapiResumeSessionToken] = React.useState('') - const [aimlapiPaymentSessionId, setAimlapiPaymentSessionId] = React.useState('') + const [, setAimlapiPaymentSessionId] = React.useState('') const [aimlapiExistingProfileId, setAimlapiExistingProfileId] = React.useState(null) const [aimlapiExistingUsesEnv, setAimlapiExistingUsesEnv] = React.useState(false) const [aimlapiInferenceBaseUrl, setAimlapiInferenceBaseUrl] = React.useState( @@ -982,8 +989,13 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { const [, setIsAimlapiTopupRunning] = React.useState(false) const [isAimlapiKeyValidating, setIsAimlapiKeyValidating] = React.useState(false) const aimlapiAbortRef = React.useRef(null) + const aimlapiPersistedIntentRef = React.useRef(null) function resetAimlapiCheckoutIntent(): void { + if (aimlapiPersistedIntentRef.current) { + clearAimlapiTopupState(aimlapiPersistedIntentRef.current) + aimlapiPersistedIntentRef.current = null + } setAimlapiResumeSessionToken('') setAimlapiPaymentSessionId('') } @@ -2565,7 +2577,10 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setErrorMessage(undefined) if (draftProvider === 'aimlapi') { - const envKey = process.env.AIMLAPI_API_KEY?.trim() + const envKey = resolveRouteCredentialValue({ + routeId: 'aimlapi', + baseUrl: nextDraft.baseUrl, + })?.trim() if (mode === 'first-run' && envKey) { setAimlapiIssuedKey(envKey) setAimlapiExistingUsesEnv(true) @@ -2773,7 +2788,10 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { const isAimlapiProfile = (profile: ProviderProfile): boolean => profile.provider === 'aimlapi' || resolveRouteIdFromBaseUrl(profile.baseUrl) === 'aimlapi' - const envKey = process.env.AIMLAPI_API_KEY?.trim() + const envKey = resolveRouteCredentialValue({ + routeId: 'aimlapi', + baseUrl: resolveEndpoints().inferenceBaseUrl, + })?.trim() const active = profiles.find(profile => profile.id === activeProfileId) const candidates = active ? [active, ...profiles.filter(profile => profile.id !== active.id)] @@ -2824,6 +2842,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { persistDraft(nextDraft, profile.provider, profile.id, { deferNavigation: true, onSaved: () => { + resetAimlapiCheckoutIntent() setAimlapiDoneKind(aimlapiTopupByKey ? 'topup' : 'ready') setErrorMessage(undefined) setScreen('aimlapi-done') @@ -2918,6 +2937,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { persistDraft(nextDraft, draftProvider, null, { deferNavigation: true, onSaved: () => { + resetAimlapiCheckoutIntent() setAimlapiDoneKind(doneKind) setErrorMessage(undefined) setScreen('aimlapi-done') @@ -3050,8 +3070,9 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setScreen('aimlapi-topup-amount') return } + let amountUsdMinor: number try { - parseAimlapiAmountUsd(amountUsd) + amountUsdMinor = parseAimlapiAmountUsd(amountUsd) } catch (error) { setErrorMessage(error instanceof Error ? error.message : String(error)) setScreen('aimlapi-topup-amount') @@ -3063,6 +3084,33 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { return } + const endpoints = resolveEndpoints() + const intentIdentity = aimlapiTopupByKey + ? `key:${createHash('sha256').update(aimlapiIssuedKey).digest('hex')}` + : aimlapiTopupEmail.trim().toLowerCase() + const intent: AimlapiTopupIntent = { + email: intentIdentity, + amountUsdMinor, + autoTopUp, + partnerId: resolvePartnerId(), + partnerName: DEFAULT_PARTNER_NAME, + appBaseUrl: endpoints.appBaseUrl.trim().replace(/\/+$/, ''), + inferenceBaseUrl: aimlapiInferenceBaseUrl.trim().replace(/\/+$/, ''), + payBaseUrl: endpoints.payBaseUrl.trim().replace(/\/+$/, ''), + verificationBaseUrl: endpoints.verificationBaseUrl.trim().replace(/\/+$/, ''), + } + let checkoutState: ReturnType + try { + checkoutState = claimAimlapiTopupState(intent) + } catch (error) { + setErrorMessage(safeAimlapiErrorMessage(error, [aimlapiIssuedKey])) + setScreen('aimlapi-topup-amount') + return + } + aimlapiPersistedIntentRef.current = intent + setAimlapiPaymentSessionId(checkoutState.paymentSessionId) + setAimlapiResumeSessionToken(checkoutState.resumeSessionToken) + aimlapiAbortRef.current?.abort() const controller = new AbortController() aimlapiAbortRef.current = controller @@ -3071,8 +3119,6 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setAimlapiTopupStatus('creating-session') setAimlapiTopupDetail(undefined) setIsAimlapiTopupRunning(true) - const paymentSessionId = aimlapiPaymentSessionId || randomUUID() - if (!aimlapiPaymentSessionId) setAimlapiPaymentSessionId(paymentSessionId) void (async () => { try { @@ -3081,8 +3127,13 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { if (detail?.trim()) setAimlapiTopupDetail(detail) } const reportSession = (sessionToken: string): void => { + if (!sessionToken) { + resetAimlapiCheckoutIntent() + return + } + checkoutState.resumeSessionToken = sessionToken + saveAimlapiTopupState({ ...intent, ...checkoutState }) setAimlapiResumeSessionToken(sessionToken) - if (!sessionToken) setAimlapiPaymentSessionId('') } const provisioned = aimlapiTopupByKey ? await topUpAimlapiByApiKey({ @@ -3091,8 +3142,8 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { amountUsd, autoTopUp, model: draft.model, - paymentSessionId, - resumeSessionToken: aimlapiResumeSessionToken, + paymentSessionId: checkoutState.paymentSessionId, + resumeSessionToken: checkoutState.resumeSessionToken, signal: controller.signal, onStatus: reportStatus, onSession: reportSession, @@ -3104,18 +3155,16 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { sessionToken: aimlapiSessionToken, inferenceBaseUrl: aimlapiInferenceBaseUrl, exchange: aimlapiNewAccount, - paymentSessionId, + paymentSessionId: checkoutState.paymentSessionId, existingApiKey: aimlapiIssuedKey, existingApiKeyId: aimlapiIssuedKeyId, - resumeSessionToken: aimlapiResumeSessionToken, + resumeSessionToken: checkoutState.resumeSessionToken, signal: controller.signal, onStatus: reportStatus, onSession: reportSession, }) if (controller.signal.aborted) return setIsAimlapiTopupRunning(false) - setAimlapiResumeSessionToken('') - setAimlapiPaymentSessionId('') if (aimlapiTopupByKey) { if (aimlapiExistingProfileId || aimlapiExistingUsesEnv) { setCursorOffset(provisioned.model.length) @@ -3345,8 +3394,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { cursorOffset={cursorOffset} onAmountChange={value => { if (value !== aimlapiTopupAmountUsd) { - setAimlapiResumeSessionToken('') - setAimlapiPaymentSessionId('') + resetAimlapiCheckoutIntent() } setAimlapiTopupAmountUsd(value) setErrorMessage(undefined) @@ -3354,8 +3402,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { onCursorOffsetChange={setCursorOffset} onAutoTopUpChange={value => { if (value !== aimlapiAutoTopUp) { - setAimlapiResumeSessionToken('') - setAimlapiPaymentSessionId('') + resetAimlapiCheckoutIntent() } setAimlapiAutoTopUp(value) }} diff --git a/src/components/providerManagerAimlapi.ts b/src/components/providerManagerAimlapi.ts index 0ea8f01807..7cb31f95ce 100644 --- a/src/components/providerManagerAimlapi.ts +++ b/src/components/providerManagerAimlapi.ts @@ -7,12 +7,22 @@ import { completeAimlapiCodeSignIn as completeAimlapiCodeSignInImpl, validateAimlapiApiKey as validateAimlapiApiKeyImpl, } from '../integrations/aimlapi/index.js' +import { + claimAimlapiTopupState as claimAimlapiTopupStateImpl, + clearAimlapiTopupState as clearAimlapiTopupStateImpl, + saveAimlapiTopupState as saveAimlapiTopupStateImpl, +} from '../integrations/aimlapi/topupState.js' +import type { + AimlapiPersistedTopup, + AimlapiTopupIntent, +} from '../integrations/aimlapi/topupState.js' export { AimlapiApiError, AIMLAPI_MESSAGES, type AimlapiTopupStatus, } from '../integrations/aimlapi/index.js' +export type { AimlapiPersistedTopup, AimlapiTopupIntent } export const provisionAimlapiKey: typeof provisionAimlapiKeyImpl = options => provisionAimlapiKeyImpl(options) @@ -36,3 +46,12 @@ export const completeAimlapiCodeSignIn: typeof completeAimlapiCodeSignInImpl = ( export const validateAimlapiApiKey: typeof validateAimlapiApiKeyImpl = (...args) => validateAimlapiApiKeyImpl(...args) + +export const claimAimlapiTopupState: typeof claimAimlapiTopupStateImpl = intent => + claimAimlapiTopupStateImpl(intent) + +export const clearAimlapiTopupState: typeof clearAimlapiTopupStateImpl = intent => + clearAimlapiTopupStateImpl(intent) + +export const saveAimlapiTopupState: typeof saveAimlapiTopupStateImpl = state => + saveAimlapiTopupStateImpl(state) diff --git a/src/integrations/aimlapi/prompt.test.ts b/src/integrations/aimlapi/prompt.test.ts index 29ffffed94..6efa525bdf 100644 --- a/src/integrations/aimlapi/prompt.test.ts +++ b/src/integrations/aimlapi/prompt.test.ts @@ -1,4 +1,5 @@ import { afterEach, expect, mock, test } from 'bun:test' +import type { createInterface } from 'node:readline' import { promptText } from './prompt.js' @@ -61,3 +62,24 @@ test('promptText closes readline when question fails', async () => { ) expect(close).toHaveBeenCalledTimes(1) }) + +test('promptText masks secret input from terminal output', async () => { + setInteractive() + const written: string[] = [] + const output = { + columns: 80, + write: (chunk: string) => written.push(chunk), + } + const createReadline = mock((options: Parameters[0]) => ({ + question: (_question: string, resolve: (answer: string) => void) => { + options.output?.write('123456') + resolve('123456') + }, + close: () => {}, + })) + + await expect( + promptText('6-digit code', { mask: true }, createReadline, output), + ).resolves.toBe('123456') + expect(written.join('')).toBe('6-digit code: \n') +}) diff --git a/src/integrations/aimlapi/prompt.ts b/src/integrations/aimlapi/prompt.ts index 9457a4c54e..acbd9933e7 100644 --- a/src/integrations/aimlapi/prompt.ts +++ b/src/integrations/aimlapi/prompt.ts @@ -5,6 +5,7 @@ */ import { createInterface } from 'node:readline' +import { Writable } from 'node:stream' type ReadlineInterface = { question(question: string, callback: (answer: string) => void): void @@ -13,6 +14,10 @@ type ReadlineInterface = { type CreateReadlineInterface = ( options: Parameters[0], ) => ReadlineInterface +type PromptOutput = { + write(chunk: string): unknown + columns?: number +} function assertInteractive(): void { if (!process.stdin.isTTY) { @@ -24,19 +29,34 @@ function assertInteractive(): void { export async function promptText( question: string, - opts: { defaultValue?: string } = {}, + opts: { defaultValue?: string; mask?: boolean } = {}, createReadline: CreateReadlineInterface = createInterface as CreateReadlineInterface, + output: PromptOutput = process.stdout, ): Promise { assertInteractive() const suffix = opts.defaultValue ? ` [${opts.defaultValue}]` : '' - const rl = createReadline({ input: process.stdin, output: process.stdout }) + const label = `${question}${suffix}: ` + const mutedOutput = new Writable({ + write(_chunk, _encoding, done) { + done() + }, + }) as Writable & { columns?: number; isTTY?: boolean } + mutedOutput.columns = output.columns + mutedOutput.isTTY = true + if (opts.mask) output.write(label) + const rl = createReadline({ + input: process.stdin, + output: opts.mask ? mutedOutput : process.stdout, + ...(opts.mask ? { terminal: true } : {}), + }) try { const answer = await new Promise((resolve) => { - rl.question(`${question}${suffix}: `, resolve) + rl.question(opts.mask ? '' : label, resolve) }) const trimmed = answer.trim() return trimmed || opts.defaultValue || '' } finally { rl.close() + if (opts.mask) output.write('\n') } } diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index e0bcdceda8..578b300860 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import { setClaudeConfigHomeDirForTesting } from '../../utils/envUtils.js' import * as realTopupDependencies from './topupDependencies.js' +import { saveAimlapiTopupState } from './topupState.js' import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' mock.module('./topupDependencies.js', () => ({ @@ -122,6 +123,58 @@ test('CLI retries reuse the persisted checkout session and payment id', async () expect(() => readFileSync(join(configDirectory, 'aimlapi-topup.json'))).toThrow() }) +test('CLI clears an already-exchanged persisted checkout and points to key recovery', async () => { + const configDirectory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-cli-')) + temporaryDirectories.push(configDirectory) + setClaudeConfigHomeDirForTesting(configDirectory) + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' + saveAimlapiTopupState({ + email: 'user@example.com', + amountUsdMinor: 2500, + autoTopUp: false, + partnerId: 'part_62yQoGYDq4Yqnrj2R1iGrDNJ', + partnerName: 'Gitlawb', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.aimlapi.com/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://aimlapi.com/app', + paymentSessionId: 'persisted-payment', + resumeSessionToken: 'exchanged-session', + }) + + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + if (url.endsWith('/v1/auth/account')) return Response.json({ action: 'sign-in' }) + if (url.endsWith('/sign-in/code')) return new Response(null, { status: 204 }) + if (url.endsWith('/code/verify')) { + return Response.json({ token: 'account-token', exp: 1 }) + } + if (url.endsWith('/v1/keys')) { + return Response.json({ key: 'key_test', id: 'created-key' }) + } + if (url.endsWith('/sessions/exchanged-session')) { + return Response.json({ + sessionToken: 'exchanged-session', + status: 'exchanged', + issuedKeyId: 'issued-key-id', + }) + } + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + await expect( + runAimlapiTopup({ + email: 'user@example.com', + code: '123456', + amountUsd: '25', + noOpen: true, + }), + ).rejects.toThrow('Open https://aimlapi.com/app') + expect(() => readFileSync(join(configDirectory, 'aimlapi-topup.json'))).toThrow() +}) + test('topUpAimlapiByApiKey funds the key account without exchange', async () => { process.env.AIMLAPI_APP_URL = 'https://app.example.test' process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' @@ -218,8 +271,13 @@ test('provisionAimlapiKey does not repeat an already completed exchange', async const calls: string[] = [] globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { calls.push(`${init?.method} ${String(input)}`) - return Response.json({ sessionToken: 'session', status: 'exchanged' }) + return Response.json({ + sessionToken: 'session', + status: 'exchanged', + issuedKeyId: 'key_recoverable', + }) }) as unknown as typeof fetch + const sessions: string[] = [] await expect( provisionAimlapiKey({ @@ -229,18 +287,21 @@ test('provisionAimlapiKey does not repeat an already completed exchange', async exchange: true, amountUsd: '25', noOpen: true, + onSession: session => sessions.push(session), }), - ).rejects.toThrow('Session was already exchanged') + ).rejects.toThrow('issued key key_recoverable') expect(calls).toEqual([ 'GET https://app.example.test/v3/partner-checkout/sessions/session', ]) + expect(sessions).toEqual(['']) }) test('an in-progress exchange is observed without issuing a second exchange', async () => { process.env.AIMLAPI_APP_URL = 'https://app.example.test' const calls: string[] = [] let reads = 0 + const sessions: string[] = [] globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { calls.push(`${init?.method} ${String(input)}`) reads += 1 @@ -258,9 +319,11 @@ test('an in-progress exchange is observed without issuing a second exchange', as exchange: true, amountUsd: '25', noOpen: true, + onSession: session => sessions.push(session), }), ).rejects.toThrow('Session was already exchanged') expect(calls.every(call => call.startsWith('GET '))).toBe(true) + expect(sessions).toEqual(['session', '']) }) test('email-session checkout carries the stable payment id', async () => { diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index 4fbdab6d66..502c63eae4 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -1,6 +1,5 @@ /** AI/ML API passwordless onboarding and partner-checkout orchestration. */ -import { randomUUID } from 'crypto' import chalk from 'chalk' import { @@ -18,8 +17,8 @@ import { } from './config.js' import { openBrowser, promptText, saveProfileFile } from './topupDependencies.js' import { + claimAimlapiTopupState, clearAimlapiTopupState, - loadAimlapiTopupState, saveAimlapiTopupState, type AimlapiTopupIntent, } from './topupState.js' @@ -110,6 +109,15 @@ function maskKey(key: string): string { return key.length <= 10 ? '****' : `${key.slice(0, 6)}...${key.slice(-4)}` } +function alreadyExchangedError(session: PartnerCheckoutSession): Error { + const keyHint = session.issuedKeyId?.trim() + ? ` for issued key ${session.issuedKeyId.trim()}` + : '' + return new Error( + `Session was already exchanged${keyHint}. Open https://aimlapi.com/app and rotate the issued key to recover access.`, + ) +} + export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { const endpoints = resolveEndpoints() const client = new AimlapiClient(endpoints) @@ -131,7 +139,7 @@ export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { + if (!resumeSessionToken) { + clearAimlapiTopupState(intent) + return + } checkoutState.resumeSessionToken = resumeSessionToken saveAimlapiTopupState({ ...intent, ...checkoutState }) } - saveAimlapiTopupState({ ...intent, ...checkoutState }) const provisioned = await provisionAimlapiKey({ amountUsd: options.amountUsd, @@ -422,9 +431,8 @@ async function resolveTopupSession( } case 'exchanged': if (options.byKey) return { sessionToken: resume, phase: 'exchange' } - throw new Error( - 'Session was already exchanged. Rotate the key from the AI/ML API dashboard.', - ) + options.onSession?.('') + throw alreadyExchangedError(session) default: options.onSession?.('') throw new Error(`Payment ${session.status}. Re-run the top-up to try again.`) @@ -443,9 +451,8 @@ async function pollUntilExchangeSettled( try { const session = await client.getSession(sessionToken, signal) if (session.status === 'exchanged') { - throw new Error( - 'Session was already exchanged. Rotate the key from the AI/ML API dashboard.', - ) + onSession?.('') + throw alreadyExchangedError(session) } if ( session.status === 'cancelled' || @@ -494,7 +501,8 @@ export async function pollUntilPaid( case 'exchanging': return session case 'exchanged': - throw new Error('Session was already exchanged. Rotate the key from the AI/ML API dashboard.') + onSession?.('') + throw alreadyExchangedError(session) case 'cancelled': case 'expired': case 'failed': diff --git a/src/integrations/aimlapi/topupState.test.ts b/src/integrations/aimlapi/topupState.test.ts index ed3e001dd4..6a94bd5d91 100644 --- a/src/integrations/aimlapi/topupState.test.ts +++ b/src/integrations/aimlapi/topupState.test.ts @@ -5,6 +5,7 @@ import { join } from 'node:path' import { setClaudeConfigHomeDirForTesting } from '../../utils/envUtils.js' import { + claimAimlapiTopupState, clearAimlapiTopupState, loadAimlapiTopupState, saveAimlapiTopupState, @@ -34,6 +35,7 @@ const intent: AimlapiTopupIntent = { partnerId: 'part_test', partnerName: 'OpenClaude', appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.example.test/v1', payBaseUrl: 'https://pay.example.test', verificationBaseUrl: 'https://front.example.test', } @@ -72,3 +74,12 @@ test('top-up state is cleared only by its matching intent', () => { clearAimlapiTopupState(intent) expect(loadAimlapiTopupState(intent)).toBeNull() }) + +test('claiming the same checkout intent reuses one payment id', () => { + useTemporaryConfig() + const first = claimAimlapiTopupState(intent) + const second = claimAimlapiTopupState(intent) + + expect(first.paymentSessionId).toBeTruthy() + expect(second).toEqual(first) +}) diff --git a/src/integrations/aimlapi/topupState.ts b/src/integrations/aimlapi/topupState.ts index 7221522a79..aff567156f 100644 --- a/src/integrations/aimlapi/topupState.ts +++ b/src/integrations/aimlapi/topupState.ts @@ -1,9 +1,12 @@ import { chmodSync, + closeSync, mkdirSync, + openSync, readFileSync, renameSync, rmSync, + statSync, writeFileSync, } from 'node:fs' import { dirname, join } from 'node:path' @@ -18,6 +21,7 @@ export type AimlapiTopupIntent = { partnerId: string partnerName: string appBaseUrl: string + inferenceBaseUrl: string payBaseUrl: string verificationBaseUrl: string } @@ -31,6 +35,54 @@ function statePath(): string { return join(getClaudeConfigHomeDir(), 'aimlapi-topup.json') } +const LOCK_RETRY_MS = 25 +const LOCK_TIMEOUT_MS = 5_000 +const LOCK_STALE_MS = 30_000 + +function waitForLock(): void { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, LOCK_RETRY_MS) +} + +function withStateLock(operation: () => T): T { + const target = statePath() + const lockPath = `${target}.lock` + mkdirSync(dirname(target), { recursive: true }) + const deadline = Date.now() + LOCK_TIMEOUT_MS + let descriptor: number | undefined + + while (descriptor === undefined) { + try { + descriptor = openSync(lockPath, 'wx', 0o600) + } catch (error) { + const code = + typeof error === 'object' && error !== null && 'code' in error + ? String(error.code) + : undefined + if (code !== 'EEXIST') throw error + try { + const lock = statSync(lockPath) + if (Date.now() - lock.mtimeMs > LOCK_STALE_MS) { + rmSync(lockPath, { force: true }) + continue + } + } catch { + continue + } + if (Date.now() >= deadline) { + throw new Error('Timed out waiting for the AI/ML API checkout state lock.') + } + waitForLock() + } + } + + try { + return operation() + } finally { + closeSync(descriptor) + rmSync(lockPath, { force: true }) + } +} + function matchesIntent( state: AimlapiPersistedTopup, intent: AimlapiTopupIntent, @@ -51,6 +103,7 @@ function isPersistedTopup(value: unknown): value is AimlapiPersistedTopup { typeof state.partnerId === 'string' && typeof state.partnerName === 'string' && typeof state.appBaseUrl === 'string' && + typeof state.inferenceBaseUrl === 'string' && typeof state.payBaseUrl === 'string' && typeof state.verificationBaseUrl === 'string' && typeof state.paymentSessionId === 'string' && @@ -91,6 +144,21 @@ export function saveAimlapiTopupState(state: AimlapiPersistedTopup): void { } } +export function claimAimlapiTopupState( + intent: AimlapiTopupIntent, +): Pick { + return withStateLock(() => { + const existing = loadAimlapiTopupState(intent) + if (existing) return existing + const claimed = { + paymentSessionId: randomUUID(), + resumeSessionToken: '', + } + saveAimlapiTopupState({ ...intent, ...claimed }) + return claimed + }) +} + export function clearAimlapiTopupState(intent: AimlapiTopupIntent): void { const current = loadAimlapiTopupState(intent) if (current) rmSync(statePath(), { force: true }) diff --git a/src/integrations/discoveryService.test.ts b/src/integrations/discoveryService.test.ts index 32316b9938..17acb1bc7f 100644 --- a/src/integrations/discoveryService.test.ts +++ b/src/integrations/discoveryService.test.ts @@ -469,17 +469,13 @@ describe('discoverModelsForRoute', () => { }) expect(result?.models.map((model: { apiName: string }) => model.apiName)).toEqual([ 'anthropic/claude-sonnet-5', - 'google/gemini-3.5-flash', - 'openai/gpt-5.5-2026-04-23', - 'qwen/qwen-3.7-max', - 'deepseek/deepseek-v4-pro', 'gpt-4o', 'gemini-2.5-pro', 'GLM-5.2', ]) - expect(result?.models.find((model: { apiName: string }) => model.apiName === 'gpt-4o')).toMatchObject({ - id: 'gpt-4o', - label: 'GPT-4o (OpenAI)', + expect(result?.models.find((model: { apiName: string }) => model.apiName === 'anthropic/claude-sonnet-5')).toMatchObject({ + id: 'aimlapi-claude-sonnet-5', + label: 'Claude Sonnet 5', }) expect(result?.models.find((model: { apiName: string }) => model.apiName === 'gemini-2.5-pro')).toMatchObject({ label: 'Gemini 2.5 Pro (Google)', @@ -543,14 +539,10 @@ describe('discoverModelsForRoute', () => { // Only `openai/chat-completions` entries survive discovery; the duplicate // gpt-3.5-turbo (responses/submit), embeddings, image, and anthropic - // endpoint types are dropped. The curated flagship fallback models ride - // along from the hybrid catalog. + // endpoint types are dropped. The curated Sonnet default rides along from + // the hybrid catalog. expect(result?.models.map((model: { apiName: string }) => model.apiName)).toEqual([ 'anthropic/claude-sonnet-5', - 'google/gemini-3.5-flash', - 'openai/gpt-5.5-2026-04-23', - 'qwen/qwen-3.7-max', - 'deepseek/deepseek-v4-pro', 'gpt-3.5-turbo', 'claude-opus-4-1-20250805', ]) diff --git a/src/integrations/gateways/aimlapi.ts b/src/integrations/gateways/aimlapi.ts index 16f90c3299..d47cad5dd8 100644 --- a/src/integrations/gateways/aimlapi.ts +++ b/src/integrations/gateways/aimlapi.ts @@ -115,11 +115,12 @@ export default defineGateway({ discoveryRefreshMode: 'startup', allowManualRefresh: true, models: [ - { id: 'aimlapi-claude-sonnet-5', apiName: 'anthropic/claude-sonnet-5', modelDescriptorId: 'claude-sonnet-5', label: 'Claude Sonnet 5' }, - { id: 'aimlapi-gemini-3.5-flash', apiName: 'google/gemini-3.5-flash', modelDescriptorId: 'gemini-3.5-flash', label: 'Gemini 3.5 Flash' }, - { id: 'aimlapi-gpt-5.5', apiName: 'openai/gpt-5.5-2026-04-23', modelDescriptorId: 'gpt-5.5', label: 'GPT-5.5' }, - { id: 'aimlapi-qwen-3.7-max', apiName: 'qwen/qwen-3.7-max', modelDescriptorId: 'qwen3.7-max', label: 'Qwen 3.7 Max' }, - { id: 'aimlapi-deepseek-v4', apiName: 'deepseek/deepseek-v4-pro', modelDescriptorId: 'deepseek-v4-pro', label: 'DeepSeek V4' }, + { + id: 'aimlapi-claude-sonnet-5', + apiName: 'anthropic/claude-sonnet-5', + label: 'Claude Sonnet 5', + modelDescriptorId: 'claude-sonnet-4-6', + }, ], }, usage: { supported: false }, diff --git a/src/integrations/index.ts b/src/integrations/index.ts index fb863f4077..1a50acbabb 100644 --- a/src/integrations/index.ts +++ b/src/integrations/index.ts @@ -141,6 +141,7 @@ export { isCloudflareBaseUrl, normalizeXiaomiMimoBaseUrl, resolveActiveRouteIdFromEnv, + resolveRouteCredentialValue, resolveRouteIdFromBaseUrl, routeSupportsApiFormatSelection, routeSupportsAuthHeaders, diff --git a/src/integrations/models/claude.ts b/src/integrations/models/claude.ts index 521ff82280..eb2d6a9581 100644 --- a/src/integrations/models/claude.ts +++ b/src/integrations/models/claude.ts @@ -1,24 +1,6 @@ import { defineModel } from '../define.js' export default [ - defineModel({ - id: 'claude-sonnet-5', - label: 'Claude Sonnet 5', - brandId: 'claude', - vendorId: 'anthropic', - classification: ['chat', 'reasoning', 'vision', 'coding'], - defaultModel: 'claude-sonnet-5', - capabilities: { - supportsVision: true, - supportsStreaming: true, - supportsFunctionCalling: true, - supportsJsonMode: true, - supportsReasoning: true, - supportsPreciseTokenCount: false, - }, - contextWindow: 1_000_000, - maxOutputTokens: 128_000, - }), defineModel({ id: 'claude-opus-4-8', label: 'Claude Opus 4.8', From 4fce554a0bc9d612603fb42db257296720745731 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Fri, 17 Jul 2026 03:31:19 +0500 Subject: [PATCH 06/17] fix(aimlapi): retain exchanged checkout receipt --- src/integrations/aimlapi/topup.test.ts | 24 +++++++++++++++++------- src/integrations/aimlapi/topup.ts | 3 --- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index 578b300860..8af5bdd5f8 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -123,7 +123,7 @@ test('CLI retries reuse the persisted checkout session and payment id', async () expect(() => readFileSync(join(configDirectory, 'aimlapi-topup.json'))).toThrow() }) -test('CLI clears an already-exchanged persisted checkout and points to key recovery', async () => { +test('CLI retains an already-exchanged checkout and blocks identical retries', async () => { const configDirectory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-cli-')) temporaryDirectories.push(configDirectory) setClaudeConfigHomeDirForTesting(configDirectory) @@ -144,6 +144,7 @@ test('CLI clears an already-exchanged persisted checkout and points to key recov resumeSessionToken: 'exchanged-session', }) + let sessionReads = 0 globalThis.fetch = mock(async (input: string | URL | Request) => { const url = String(input) if (url.endsWith('/v1/auth/account')) return Response.json({ action: 'sign-in' }) @@ -155,6 +156,7 @@ test('CLI clears an already-exchanged persisted checkout and points to key recov return Response.json({ key: 'key_test', id: 'created-key' }) } if (url.endsWith('/sessions/exchanged-session')) { + sessionReads += 1 return Response.json({ sessionToken: 'exchanged-session', status: 'exchanged', @@ -164,15 +166,23 @@ test('CLI clears an already-exchanged persisted checkout and points to key recov throw new Error(`Unexpected request: ${url}`) }) as unknown as typeof fetch - await expect( + const retry = (): Promise => runAimlapiTopup({ email: 'user@example.com', code: '123456', amountUsd: '25', noOpen: true, - }), - ).rejects.toThrow('Open https://aimlapi.com/app') - expect(() => readFileSync(join(configDirectory, 'aimlapi-topup.json'))).toThrow() + }) + + await expect(retry()).rejects.toThrow('issued key issued-key-id') + await expect(retry()).rejects.toThrow('issued key issued-key-id') + expect(sessionReads).toBe(2) + expect( + JSON.parse(readFileSync(join(configDirectory, 'aimlapi-topup.json'), 'utf8')), + ).toMatchObject({ + paymentSessionId: 'persisted-payment', + resumeSessionToken: 'exchanged-session', + }) }) test('topUpAimlapiByApiKey funds the key account without exchange', async () => { @@ -294,7 +304,7 @@ test('provisionAimlapiKey does not repeat an already completed exchange', async expect(calls).toEqual([ 'GET https://app.example.test/v3/partner-checkout/sessions/session', ]) - expect(sessions).toEqual(['']) + expect(sessions).toEqual([]) }) test('an in-progress exchange is observed without issuing a second exchange', async () => { @@ -323,7 +333,7 @@ test('an in-progress exchange is observed without issuing a second exchange', as }), ).rejects.toThrow('Session was already exchanged') expect(calls.every(call => call.startsWith('GET '))).toBe(true) - expect(sessions).toEqual(['session', '']) + expect(sessions).toEqual(['session']) }) test('email-session checkout carries the stable payment id', async () => { diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index 502c63eae4..29d87038d3 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -431,7 +431,6 @@ async function resolveTopupSession( } case 'exchanged': if (options.byKey) return { sessionToken: resume, phase: 'exchange' } - options.onSession?.('') throw alreadyExchangedError(session) default: options.onSession?.('') @@ -451,7 +450,6 @@ async function pollUntilExchangeSettled( try { const session = await client.getSession(sessionToken, signal) if (session.status === 'exchanged') { - onSession?.('') throw alreadyExchangedError(session) } if ( @@ -501,7 +499,6 @@ export async function pollUntilPaid( case 'exchanging': return session case 'exchanged': - onSession?.('') throw alreadyExchangedError(session) case 'cancelled': case 'expired': From 1d4cc80f3e4ec431640c8e6bebb2e3168ccee788 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Fri, 17 Jul 2026 03:52:16 +0500 Subject: [PATCH 07/17] fix(aimlapi): show ready copy after saved-key continue --- src/components/ProviderManager.test.tsx | 63 ++++++++++++---- src/components/ProviderManager.tsx | 39 ++++++++-- src/integrations/aimlapi/topup.test.ts | 17 ++++- src/integrations/aimlapi/topup.ts | 10 ++- src/integrations/aimlapi/topupState.test.ts | 45 ++++++++++-- src/integrations/aimlapi/topupState.ts | 79 ++++++++++++++++----- 6 files changed, 205 insertions(+), 48 deletions(-) diff --git a/src/components/ProviderManager.test.tsx b/src/components/ProviderManager.test.tsx index 8bf650d509..792a99fe21 100644 --- a/src/components/ProviderManager.test.tsx +++ b/src/components/ProviderManager.test.tsx @@ -1166,6 +1166,13 @@ test('ProviderManager offers and reuses an existing AIMLAPI profile', async () = 'aimlapi_existing', expect.objectContaining({ apiKey: 'saved-key' }), ) + // Continuing with a saved key never charges the account, so the done + // screen must report readiness rather than a phantom top-up. + const doneOutput = await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Everything is ready.'), + ) + expect(doneOutput).not.toContain('Top-up successful') + expect(doneOutput).not.toContain('credited to your account') } finally { await mounted.dispose() } @@ -1221,7 +1228,7 @@ test('ProviderManager uses OPENAI_API_KEY for an existing keyless AIMLAPI profil } }, 10_000) -test('ProviderManager first run recognizes the OPENAI_API_KEY fallback without persisting it', async () => { +test('ProviderManager does not send the OPENAI_API_KEY fallback to a custom AIMLAPI endpoint', async () => { delete process.env.AIMLAPI_API_KEY delete process.env.OPENAI_API_KEYS process.env.OPENAI_API_KEY = 'env-runtime-key' @@ -1251,20 +1258,47 @@ test('ProviderManager first run recognizes the OPENAI_API_KEY fallback without p frame.includes('Create provider profile') && frame.includes('Default model'), ) mounted.stdin.write('\r') - await waitForCondition(() => addProviderProfile.mock.calls.length > 0) - expect(addProviderProfile).toHaveBeenCalledWith( - expect.objectContaining({ - provider: 'aimlapi', - baseUrl: 'https://proxy.example.test/v1', - apiKey: '', - }), - expect.objectContaining({ makeActive: true }), + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Do you have aimlapi.com key?'), ) - expect(validateAimlapiApiKey).toHaveBeenCalledWith( - 'env-runtime-key', - expect.any(AbortSignal), - 'https://proxy.example.test/v1', + expect(validateAimlapiApiKey).not.toHaveBeenCalled() + expect(addProviderProfile).not.toHaveBeenCalled() + } finally { + await mounted.dispose() + } +}) + +test('ProviderManager manage flow does not reuse env credentials for a custom AIMLAPI endpoint', async () => { + delete process.env.AIMLAPI_API_KEY + delete process.env.OPENAI_API_KEYS + process.env.OPENAI_API_KEY = 'env-runtime-key' + process.env.AIMLAPI_INFERENCE_URL = 'https://proxy.example.test/v1' + const validateAimlapiApiKey = mock(async () => ({ + balance: 25, + lowBalance: false, + lowBalanceThreshold: 20, + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + validateAimlapiApiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Provider manager')) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Choose provider preset')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Do you have aimlapi.com key?'), ) + expect(validateAimlapiApiKey).not.toHaveBeenCalled() } finally { await mounted.dispose() } @@ -1424,6 +1458,9 @@ test('ProviderManager matches the AIMLAPI code and low-credit screen copy', asyn expect(codeOutput).not.toContain('We sent a 6-digit code') mounted.stdin.write('123456') await Bun.sleep(25) + const maskedCodeOutput = mounted.getOutput() + expect(maskedCodeOutput).not.toContain('123456') + expect(maskedCodeOutput).toContain('******') mounted.stdin.write('\r') const lowCreditOutput = await waitForFrameOutput(mounted.getOutput, frame => diff --git a/src/components/ProviderManager.tsx b/src/components/ProviderManager.tsx index f9ca4f789a..907a2b64d1 100644 --- a/src/components/ProviderManager.tsx +++ b/src/components/ProviderManager.tsx @@ -989,7 +989,14 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { const [, setIsAimlapiTopupRunning] = React.useState(false) const [isAimlapiKeyValidating, setIsAimlapiKeyValidating] = React.useState(false) const aimlapiAbortRef = React.useRef(null) - const aimlapiPersistedIntentRef = React.useRef(null) + const aimlapiPersistedIntentRef = React.useRef< + (AimlapiTopupIntent & { paymentSessionId: string }) | null + >(null) + // True only once a top-up payment actually completes. `aimlapiTopupByKey` + // marks that the flow is driven by a saved key, not that money changed hands, + // so the done screen must key off this instead to avoid showing the "Top-up + // successful" copy when the user merely continued with a saved key. + const aimlapiTopupPaidRef = React.useRef(false) function resetAimlapiCheckoutIntent(): void { if (aimlapiPersistedIntentRef.current) { @@ -1006,6 +1013,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setAimlapiIssuedKey('') setAimlapiIssuedKeyId('') setAimlapiTopupByKey(false) + aimlapiTopupPaidRef.current = false setAimlapiNewAccount(false) } @@ -1781,6 +1789,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setAimlapiIssuedKey('') setAimlapiIssuedKeyId('') setAimlapiTopupByKey(false) + aimlapiTopupPaidRef.current = false setAimlapiResumeSessionToken('') setAimlapiPaymentSessionId('') setAimlapiExistingProfileId(null) @@ -2581,7 +2590,11 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { routeId: 'aimlapi', baseUrl: nextDraft.baseUrl, })?.trim() - if (mode === 'first-run' && envKey) { + if ( + mode === 'first-run' && + envKey && + isCanonicalAimlapiInferenceBaseUrl(nextDraft.baseUrl) + ) { setAimlapiIssuedKey(envKey) setAimlapiExistingUsesEnv(true) void validateAndPersistAimlapiKey( @@ -2788,9 +2801,11 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { const isAimlapiProfile = (profile: ProviderProfile): boolean => profile.provider === 'aimlapi' || resolveRouteIdFromBaseUrl(profile.baseUrl) === 'aimlapi' + const inferenceBaseUrl = resolveEndpoints().inferenceBaseUrl + if (!isCanonicalAimlapiInferenceBaseUrl(inferenceBaseUrl)) return null const envKey = resolveRouteCredentialValue({ routeId: 'aimlapi', - baseUrl: resolveEndpoints().inferenceBaseUrl, + baseUrl: inferenceBaseUrl, })?.trim() const active = profiles.find(profile => profile.id === activeProfileId) const candidates = active @@ -2824,7 +2839,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { ? { apiKey: envKey, usesEnv: true, - inferenceBaseUrl: resolveEndpoints().inferenceBaseUrl, + inferenceBaseUrl, } : null } @@ -2843,7 +2858,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { deferNavigation: true, onSaved: () => { resetAimlapiCheckoutIntent() - setAimlapiDoneKind(aimlapiTopupByKey ? 'topup' : 'ready') + setAimlapiDoneKind(aimlapiTopupPaidRef.current ? 'topup' : 'ready') setErrorMessage(undefined) setScreen('aimlapi-done') }, @@ -2854,7 +2869,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { aimlapiIssuedKey, resolveEndpoints().inferenceBaseUrl, model, - aimlapiTopupByKey ? 'topup' : 'ready', + aimlapiTopupPaidRef.current ? 'topup' : 'ready', { preserveEnv: aimlapiExistingUsesEnv }, ) } @@ -2882,6 +2897,9 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setErrorMessage('The existing AI/ML API key is unavailable. Configure again.') return } + // Continuing with a saved key is not a payment; clear any stale paid flag + // from an earlier top-up so the done screen shows "Everything is ready." + aimlapiTopupPaidRef.current = false aimlapiAbortRef.current?.abort() const controller = new AbortController() aimlapiAbortRef.current = controller @@ -3107,7 +3125,10 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setScreen('aimlapi-topup-amount') return } - aimlapiPersistedIntentRef.current = intent + aimlapiPersistedIntentRef.current = { + ...intent, + paymentSessionId: checkoutState.paymentSessionId, + } setAimlapiPaymentSessionId(checkoutState.paymentSessionId) setAimlapiResumeSessionToken(checkoutState.resumeSessionToken) @@ -3165,6 +3186,9 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { }) if (controller.signal.aborted) return setIsAimlapiTopupRunning(false) + // A payment just cleared, so the done screen should report the top-up + // regardless of whether we route through the model picker first. + aimlapiTopupPaidRef.current = true if (aimlapiTopupByKey) { if (aimlapiExistingProfileId || aimlapiExistingUsesEnv) { setCursorOffset(provisioned.model.length) @@ -3337,6 +3361,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { onSubmit={verifyAimlapiSignInCode} focus={true} showCursor={true} + mask="*" placeholder={`6-digit code${figures.ellipsis}`} columns={inputColumns} cursorOffset={cursorOffset} diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index 8af5bdd5f8..98b55e8443 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -5,7 +5,7 @@ import { join } from 'node:path' import { setClaudeConfigHomeDirForTesting } from '../../utils/envUtils.js' import * as realTopupDependencies from './topupDependencies.js' -import { saveAimlapiTopupState } from './topupState.js' +import { claimAimlapiTopupState, saveAimlapiTopupState } from './topupState.js' import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' mock.module('./topupDependencies.js', () => ({ @@ -130,6 +130,17 @@ test('CLI retains an already-exchanged checkout and blocks identical retries', a process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' process.env.AIMLAPI_APP_URL = 'https://app.example.test' process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' + const persisted = claimAimlapiTopupState({ + email: 'user@example.com', + amountUsdMinor: 2500, + autoTopUp: false, + partnerId: 'part_62yQoGYDq4Yqnrj2R1iGrDNJ', + partnerName: 'Gitlawb', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.aimlapi.com/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://aimlapi.com/app', + }) saveAimlapiTopupState({ email: 'user@example.com', amountUsdMinor: 2500, @@ -140,7 +151,7 @@ test('CLI retains an already-exchanged checkout and blocks identical retries', a inferenceBaseUrl: 'https://api.aimlapi.com/v1', payBaseUrl: 'https://pay.example.test', verificationBaseUrl: 'https://aimlapi.com/app', - paymentSessionId: 'persisted-payment', + paymentSessionId: persisted.paymentSessionId, resumeSessionToken: 'exchanged-session', }) @@ -180,7 +191,7 @@ test('CLI retains an already-exchanged checkout and blocks identical retries', a expect( JSON.parse(readFileSync(join(configDirectory, 'aimlapi-topup.json'), 'utf8')), ).toMatchObject({ - paymentSessionId: 'persisted-payment', + paymentSessionId: persisted.paymentSessionId, resumeSessionToken: 'exchanged-session', }) }) diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index 29d87038d3..0f0d63a8cd 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -167,7 +167,10 @@ export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { if (!resumeSessionToken) { - clearAimlapiTopupState(intent) + clearAimlapiTopupState({ + ...intent, + paymentSessionId: checkoutState.paymentSessionId, + }) return } checkoutState.resumeSessionToken = resumeSessionToken @@ -206,7 +209,10 @@ export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { const directory = useTemporaryConfig() + const claimed = claimAimlapiTopupState(intent) saveAimlapiTopupState({ ...intent, - paymentSessionId: 'payment-id', + paymentSessionId: claimed.paymentSessionId, resumeSessionToken: 'session-token', }) expect(loadAimlapiTopupState(intent)).toEqual({ - paymentSessionId: 'payment-id', + paymentSessionId: claimed.paymentSessionId, resumeSessionToken: 'session-token', }) expect(loadAimlapiTopupState({ ...intent, amountUsdMinor: 3000 })).toBeNull() @@ -63,15 +64,20 @@ test('top-up state round-trips only for the same checkout intent', () => { test('top-up state is cleared only by its matching intent', () => { useTemporaryConfig() + const claimed = claimAimlapiTopupState(intent) saveAimlapiTopupState({ ...intent, - paymentSessionId: 'payment-id', + paymentSessionId: claimed.paymentSessionId, resumeSessionToken: 'session-token', }) - clearAimlapiTopupState({ ...intent, email: 'other@example.com' }) + clearAimlapiTopupState({ + ...intent, + email: 'other@example.com', + paymentSessionId: claimed.paymentSessionId, + }) expect(loadAimlapiTopupState(intent)).not.toBeNull() - clearAimlapiTopupState(intent) + clearAimlapiTopupState({ ...intent, paymentSessionId: claimed.paymentSessionId }) expect(loadAimlapiTopupState(intent)).toBeNull() }) @@ -83,3 +89,32 @@ test('claiming the same checkout intent reuses one payment id', () => { expect(first.paymentSessionId).toBeTruthy() expect(second).toEqual(first) }) + +test('stale writers cannot overwrite a newly claimed checkout', () => { + useTemporaryConfig() + const stale = claimAimlapiTopupState(intent) + clearAimlapiTopupState({ ...intent, paymentSessionId: stale.paymentSessionId }) + + const currentIntent = { ...intent, email: 'new@example.com' } + const current = claimAimlapiTopupState(currentIntent) + saveAimlapiTopupState({ + ...intent, + ...stale, + resumeSessionToken: 'stale-session', + }) + + expect(loadAimlapiTopupState(currentIntent)).toEqual(current) + expect(loadAimlapiTopupState(intent)).toBeNull() +}) + +test('stale clear cannot delete a replacement checkout', () => { + useTemporaryConfig() + const stale = claimAimlapiTopupState(intent) + clearAimlapiTopupState({ ...intent, paymentSessionId: stale.paymentSessionId }) + + const current = claimAimlapiTopupState(intent) + clearAimlapiTopupState({ ...intent, paymentSessionId: stale.paymentSessionId }) + + expect(current.paymentSessionId).not.toBe(stale.paymentSessionId) + expect(loadAimlapiTopupState(intent)).toEqual(current) +}) diff --git a/src/integrations/aimlapi/topupState.ts b/src/integrations/aimlapi/topupState.ts index aff567156f..b15595484f 100644 --- a/src/integrations/aimlapi/topupState.ts +++ b/src/integrations/aimlapi/topupState.ts @@ -38,6 +38,17 @@ function statePath(): string { const LOCK_RETRY_MS = 25 const LOCK_TIMEOUT_MS = 5_000 const LOCK_STALE_MS = 30_000 +const INTENT_KEYS: ReadonlyArray = [ + 'email', + 'amountUsdMinor', + 'autoTopUp', + 'partnerId', + 'partnerName', + 'appBaseUrl', + 'inferenceBaseUrl', + 'payBaseUrl', + 'verificationBaseUrl', +] function waitForLock(): void { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, LOCK_RETRY_MS) @@ -87,9 +98,7 @@ function matchesIntent( state: AimlapiPersistedTopup, intent: AimlapiTopupIntent, ): boolean { - return (Object.keys(intent) as Array).every( - key => state[key] === intent[key], - ) + return INTENT_KEYS.every(key => state[key] === intent[key]) } function isPersistedTopup(value: unknown): value is AimlapiPersistedTopup { @@ -112,22 +121,16 @@ function isPersistedTopup(value: unknown): value is AimlapiPersistedTopup { ) } -export function loadAimlapiTopupState( - intent: AimlapiTopupIntent, -): Pick | null { +function readAimlapiTopupStateUnlocked(): AimlapiPersistedTopup | null { try { const state: unknown = JSON.parse(readFileSync(statePath(), 'utf8')) - if (!isPersistedTopup(state) || !matchesIntent(state, intent)) return null - return { - paymentSessionId: state.paymentSessionId, - resumeSessionToken: state.resumeSessionToken, - } + return isPersistedTopup(state) ? state : null } catch { return null } } -export function saveAimlapiTopupState(state: AimlapiPersistedTopup): void { +function writeAimlapiTopupStateUnlocked(state: AimlapiPersistedTopup): void { const target = statePath() mkdirSync(dirname(target), { recursive: true }) const temporary = `${target}.${process.pid}.${randomUUID()}.tmp` @@ -144,22 +147,62 @@ export function saveAimlapiTopupState(state: AimlapiPersistedTopup): void { } } +export function loadAimlapiTopupState( + intent: AimlapiTopupIntent, +): Pick | null { + const state = readAimlapiTopupStateUnlocked() + if (!state || !matchesIntent(state, intent)) return null + return { + paymentSessionId: state.paymentSessionId, + resumeSessionToken: state.resumeSessionToken, + } +} + +export function saveAimlapiTopupState(state: AimlapiPersistedTopup): void { + withStateLock(() => { + const current = readAimlapiTopupStateUnlocked() + if ( + !current || + !matchesIntent(current, state) || + current.paymentSessionId !== state.paymentSessionId + ) { + return + } + writeAimlapiTopupStateUnlocked(state) + }) +} + export function claimAimlapiTopupState( intent: AimlapiTopupIntent, ): Pick { return withStateLock(() => { - const existing = loadAimlapiTopupState(intent) - if (existing) return existing + const existing = readAimlapiTopupStateUnlocked() + if (existing && matchesIntent(existing, intent)) { + return { + paymentSessionId: existing.paymentSessionId, + resumeSessionToken: existing.resumeSessionToken, + } + } const claimed = { paymentSessionId: randomUUID(), resumeSessionToken: '', } - saveAimlapiTopupState({ ...intent, ...claimed }) + writeAimlapiTopupStateUnlocked({ ...intent, ...claimed }) return claimed }) } -export function clearAimlapiTopupState(intent: AimlapiTopupIntent): void { - const current = loadAimlapiTopupState(intent) - if (current) rmSync(statePath(), { force: true }) +export function clearAimlapiTopupState( + expected: AimlapiTopupIntent & Pick, +): void { + withStateLock(() => { + const current = readAimlapiTopupStateUnlocked() + if ( + current && + matchesIntent(current, expected) && + current.paymentSessionId === expected.paymentSessionId + ) { + rmSync(statePath(), { force: true }) + } + }) } From b9c0fb6b070cb6603ec009287af29a9fa7567928 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Fri, 17 Jul 2026 22:30:32 +0500 Subject: [PATCH 08/17] fix(aimlapi): harden key forwarding, top-up settling, and checkout retries --- src/integrations/aimlapi/topup.test.ts | 75 ++++++++++++++++ src/integrations/aimlapi/topup.ts | 117 +++++++++++++++++++------ src/integrations/aimlapi/topupState.ts | 74 +++++++++++++--- src/utils/providerProfiles.test.ts | 8 +- src/utils/providerProfiles.ts | 22 +++-- 5 files changed, 248 insertions(+), 48 deletions(-) diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index 98b55e8443..514b8e323a 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -287,6 +287,81 @@ test('a pending resumed session is polled without paying again', async () => { ]) }) +test('a resumed by-key session still exchanging settles before success', async () => { + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + const calls: string[] = [] + let reads = 0 + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + calls.push(`${init?.method} ${String(input)}`) + reads += 1 + return Response.json({ + sessionToken: 'session', + status: reads === 1 ? 'exchanging' : 'exchanged', + }) + }) as unknown as typeof fetch + + const result = await topUpAimlapiByApiKey({ + apiKey: 'key_test', + paymentSessionId: 'payment-id', + resumeSessionToken: 'session', + amountUsd: '25', + noOpen: true, + }) + + expect(result.apiKey).toBe('key_test') + // The first GET resolves the resumed session (exchanging); the settle poll + // then waits for it to reach exchanged instead of reporting success early. + expect(calls).toEqual([ + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + 'GET https://app.example.test/v3/partner-checkout/sessions/session', + ]) +}) + +test('an invalid amount is rejected before any key is minted', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + calls.push(url) + if (url.endsWith('/v1/auth/account')) return Response.json({ action: 'sign-in' }) + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + await expect( + runAimlapiTopup({ + email: 'user@example.com', + code: '123456', + amountUsd: '5', + noOpen: true, + }), + ).rejects.toThrow('Minimum top-up is $20') + expect(calls.some(call => call.endsWith('/v1/keys'))).toBe(false) + expect(calls.some(call => call.endsWith('/sign-in/code'))).toBe(false) +}) + +test('an unsupported account action is rejected without provisioning', async () => { + const configDirectory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-cli-')) + temporaryDirectories.push(configDirectory) + setClaudeConfigHomeDirForTesting(configDirectory) + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + calls.push(url) + if (url.endsWith('/v1/auth/account')) return Response.json({ action: 'reset' }) + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + await expect( + runAimlapiTopup({ email: 'user@example.com', amountUsd: '25', noOpen: true }), + ).rejects.toThrow('unsupported account action') + expect(calls.some(call => call.endsWith('/passwordless'))).toBe(false) + expect(calls.some(call => call.endsWith('/v1/keys'))).toBe(false) +}) + test('provisionAimlapiKey does not repeat an already completed exchange', async () => { process.env.AIMLAPI_APP_URL = 'https://app.example.test' const calls: string[] = [] diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index 0f0d63a8cd..a110b1337c 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -129,27 +129,11 @@ export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise void, +): Promise { + const deadline = Date.now() + POLL_TIMEOUT_MS + while (Date.now() < deadline) { + if (signal?.aborted) throw abortError(signal) + try { + const session = await client.getSession(sessionToken, signal) + switch (session.status) { + case 'paid': + case 'exchanged': + return + case 'cancelled': + case 'expired': + case 'failed': + onSession?.('') + throw new Error(`Top-up ${session.status}. Re-run the top-up to try again.`) + default: + // pending_* / exchanging -> keep waiting for the balance to settle. + await sleep(POLL_INTERVAL_MS, signal) + } + } catch (error) { + if (signal?.aborted) throw abortError(signal) + if (isRetryableSessionApiError(error)) { + await sleep(POLL_INTERVAL_MS, signal) + continue + } + if (isTerminalSessionApiError(error)) onSession?.('') + throw error + } + } + throw new Error('Timed out waiting for the top-up to settle. Re-run once it clears.') +} + export async function pollUntilPaid( client: AimlapiClient, sessionToken: string, diff --git a/src/integrations/aimlapi/topupState.ts b/src/integrations/aimlapi/topupState.ts index b15595484f..df8d43ee0c 100644 --- a/src/integrations/aimlapi/topupState.ts +++ b/src/integrations/aimlapi/topupState.ts @@ -29,8 +29,19 @@ export type AimlapiTopupIntent = { export type AimlapiPersistedTopup = AimlapiTopupIntent & { paymentSessionId: string resumeSessionToken: string + /** + * Existing-account key issued for this intent, retained so an interrupted + * checkout resumes on the same credential instead of minting another key. + */ + apiKey?: string + apiKeyId?: string } +type AimlapiCheckoutState = Pick< + AimlapiPersistedTopup, + 'paymentSessionId' | 'resumeSessionToken' | 'apiKey' | 'apiKeyId' +> + function statePath(): string { return join(getClaudeConfigHomeDir(), 'aimlapi-topup.json') } @@ -59,26 +70,49 @@ function withStateLock(operation: () => T): T { const lockPath = `${target}.lock` mkdirSync(dirname(target), { recursive: true }) const deadline = Date.now() + LOCK_TIMEOUT_MS - let descriptor: number | undefined + // Ownership token written into the lock so recovery can tell this holder's + // lock apart from a replacement another process wrote after stealing a stale + // lock. + const token = `${process.pid}.${randomUUID()}` + let held = false - while (descriptor === undefined) { + while (!held) { try { - descriptor = openSync(lockPath, 'wx', 0o600) + const descriptor = openSync(lockPath, 'wx', 0o600) + try { + writeFileSync(descriptor, token, { encoding: 'utf8' }) + } finally { + closeSync(descriptor) + } + held = true } catch (error) { const code = typeof error === 'object' && error !== null && 'code' in error ? String(error.code) : undefined if (code !== 'EEXIST') throw error + let stale = false try { const lock = statSync(lockPath) - if (Date.now() - lock.mtimeMs > LOCK_STALE_MS) { - rmSync(lockPath, { force: true }) - continue - } + stale = Date.now() - lock.mtimeMs > LOCK_STALE_MS } catch { + // Lock vanished between open and stat; retry the create immediately. continue } + if (stale) { + // Steal atomically: renaming the stale lock away can succeed for only + // one racer, so a replacement lock a live holder just wrote is never + // removed by a second stealer. + try { + renameSync(lockPath, `${lockPath}.${token}.stale`) + rmSync(`${lockPath}.${token}.stale`, { force: true }) + continue + } catch { + // Another process already stole it, or a live holder keeps it open + // (Windows cannot rename an open file); fall through to the + // timeout-bounded wait. + } + } if (Date.now() >= deadline) { throw new Error('Timed out waiting for the AI/ML API checkout state lock.') } @@ -89,8 +123,16 @@ function withStateLock(operation: () => T): T { try { return operation() } finally { - closeSync(descriptor) - rmSync(lockPath, { force: true }) + // Only remove a lock this holder still owns. A stale-lock steal may have + // replaced ours with another process's lock; deleting that would admit a + // third process while the second still mutates the checkout state. + try { + if (readFileSync(lockPath, 'utf8') === token) { + rmSync(lockPath, { force: true }) + } + } catch { + // Lock already released or replaced by another owner. + } } } @@ -117,7 +159,9 @@ function isPersistedTopup(value: unknown): value is AimlapiPersistedTopup { typeof state.verificationBaseUrl === 'string' && typeof state.paymentSessionId === 'string' && Boolean(state.paymentSessionId.trim()) && - typeof state.resumeSessionToken === 'string' + typeof state.resumeSessionToken === 'string' && + (state.apiKey === undefined || typeof state.apiKey === 'string') && + (state.apiKeyId === undefined || typeof state.apiKeyId === 'string') ) } @@ -149,12 +193,14 @@ function writeAimlapiTopupStateUnlocked(state: AimlapiPersistedTopup): void { export function loadAimlapiTopupState( intent: AimlapiTopupIntent, -): Pick | null { +): AimlapiCheckoutState | null { const state = readAimlapiTopupStateUnlocked() if (!state || !matchesIntent(state, intent)) return null return { paymentSessionId: state.paymentSessionId, resumeSessionToken: state.resumeSessionToken, + apiKey: state.apiKey, + apiKeyId: state.apiKeyId, } } @@ -174,16 +220,18 @@ export function saveAimlapiTopupState(state: AimlapiPersistedTopup): void { export function claimAimlapiTopupState( intent: AimlapiTopupIntent, -): Pick { +): AimlapiCheckoutState { return withStateLock(() => { const existing = readAimlapiTopupStateUnlocked() if (existing && matchesIntent(existing, intent)) { return { paymentSessionId: existing.paymentSessionId, resumeSessionToken: existing.resumeSessionToken, + apiKey: existing.apiKey, + apiKeyId: existing.apiKeyId, } } - const claimed = { + const claimed: AimlapiCheckoutState = { paymentSessionId: randomUUID(), resumeSessionToken: '', } diff --git a/src/utils/providerProfiles.test.ts b/src/utils/providerProfiles.test.ts index 068010729a..7adce4a4a6 100644 --- a/src/utils/providerProfiles.test.ts +++ b/src/utils/providerProfiles.test.ts @@ -1010,7 +1010,7 @@ describe('applyProviderProfileToProcessEnv', () => { expect(getFreshAPIProvider()).toBe('openai') }, 20_000) - test('keyless custom AIMLAPI profile preserves route identity with ambient OpenAI key', async () => { + test('keyless custom AIMLAPI profile preserves route identity without forwarding the ambient key', async () => { const { applyProviderProfileToProcessEnv } = await importFreshProviderProfileModules() process.env.OPENAI_API_KEY = 'ambient-openai-key' @@ -1026,8 +1026,10 @@ describe('applyProviderProfileToProcessEnv', () => { expect(process.env.OPENAI_BASE_URL).toBe('https://proxy.example.com/v1') expect(process.env.OPENAI_MODEL).toBe('gpt-4o') - expect(process.env.OPENAI_API_KEY).toBe('ambient-openai-key') - expect(process.env.AIMLAPI_API_KEY).toBe('ambient-openai-key') + // The base URL is a user-controlled proxy, not the canonical inference + // host, so the canonical AIMLAPI credential must not be forwarded to it. + expect(process.env.OPENAI_API_KEY).toBeUndefined() + expect(process.env.AIMLAPI_API_KEY).toBeUndefined() expect(process.env.CLAUDE_CODE_PROVIDER_ROUTE_ID).toBe('aimlapi') }, 20_000) diff --git a/src/utils/providerProfiles.ts b/src/utils/providerProfiles.ts index edfc56c3d1..497e8bd034 100644 --- a/src/utils/providerProfiles.ts +++ b/src/utils/providerProfiles.ts @@ -33,6 +33,7 @@ import { type ProfileEnv, type ProviderProfile as ProviderProfileStartup, } from './providerProfile.js' +import { isCanonicalAimlapiInferenceBaseUrl } from '../integrations/aimlapi/config.js' import { refreshStartupDiscoveryForRoute } from '../integrations/discoveryService.js' import { getCatalogEntriesForRoute, @@ -994,14 +995,21 @@ export function applyProviderProfileToProcessEnv( } } if (isAimlapiProfile) { - const ambientAimlapiKey = - trimOrUndefined(process.env.AIMLAPI_API_KEY) ?? - trimOrUndefined(process.env.OPENAI_API_KEY) openAIProfileEnv.CLAUDE_CODE_PROVIDER_ROUTE_ID = 'aimlapi' - openAIProfileEnv.OPENAI_API_KEY = - openAIProfileEnv.OPENAI_API_KEY ?? ambientAimlapiKey - openAIProfileEnv.AIMLAPI_API_KEY = - openAIProfileEnv.AIMLAPI_API_KEY ?? ambientAimlapiKey + // The ambient AIMLAPI_API_KEY is the canonical aimlapi.com credential. + // Only forward it when the profile targets the canonical inference host; + // a keyless `aimlapi` profile can point at a user-controlled proxy, and + // injecting the credential there would leak it. This mirrors the + // guided-flow validation, which also gates on the canonical URL. + if (isCanonicalAimlapiInferenceBaseUrl(profile.baseUrl)) { + const ambientAimlapiKey = + trimOrUndefined(process.env.AIMLAPI_API_KEY) ?? + trimOrUndefined(process.env.OPENAI_API_KEY) + openAIProfileEnv.OPENAI_API_KEY = + openAIProfileEnv.OPENAI_API_KEY ?? ambientAimlapiKey + openAIProfileEnv.AIMLAPI_API_KEY = + openAIProfileEnv.AIMLAPI_API_KEY ?? ambientAimlapiKey + } } if (route.gatewayId === 'nvidia-nim') { openAIProfileEnv.NVIDIA_NIM = '1' From f9317ba4904f03d3443a39d5923c350f5942c8de Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Fri, 17 Jul 2026 22:56:53 +0500 Subject: [PATCH 09/17] fix(aimlapi): retain key on failed checkout, harden lock steal, fix env completion --- src/components/ProviderManager.tsx | 13 +++-- src/integrations/aimlapi/topup.test.ts | 59 +++++++++++++++++++ src/integrations/aimlapi/topup.ts | 14 +++++ src/integrations/aimlapi/topupState.ts | 80 +++++++++++++++++++++++--- 4 files changed, 154 insertions(+), 12 deletions(-) diff --git a/src/components/ProviderManager.tsx b/src/components/ProviderManager.tsx index 907a2b64d1..dc7c9ad4ad 100644 --- a/src/components/ProviderManager.tsx +++ b/src/components/ProviderManager.tsx @@ -2586,6 +2586,15 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { setErrorMessage(undefined) if (draftProvider === 'aimlapi') { + // An already-resolved existing credential (saved profile or an + // ambient env key adopted earlier, e.g. after a top-up) must + // complete through persistExistingAimlapi so the paid-completion + // path (aimlapiTopupPaidRef) is honored, instead of being + // re-detected into the plain "ready" flow below. + if (aimlapiExistingProfileId || aimlapiExistingUsesEnv) { + persistExistingAimlapi(nextDraft.model) + return + } const envKey = resolveRouteCredentialValue({ routeId: 'aimlapi', baseUrl: nextDraft.baseUrl, @@ -2605,10 +2614,6 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { ) return } - if (aimlapiExistingProfileId || aimlapiExistingUsesEnv) { - persistExistingAimlapi(nextDraft.model) - return - } if (mode === 'manage' && startExistingAimlapi(nextDraft)) { return } diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index 514b8e323a..c3555b2ec9 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -196,6 +196,65 @@ test('CLI retains an already-exchanged checkout and blocks identical retries', a }) }) +test('a failed payment retains the issued key for the next run', async () => { + const configDirectory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-cli-')) + temporaryDirectories.push(configDirectory) + setClaudeConfigHomeDirForTesting(configDirectory) + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_APP_URL = 'https://app.example.test' + process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + + let keyMints = 0 + let sessionStatus = 'expired' + globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { + const url = String(input) + if (url.endsWith('/v1/auth/account')) return Response.json({ action: 'sign-in' }) + if (url.endsWith('/sign-in/code')) return new Response(null, { status: 204 }) + if (url.endsWith('/code/verify')) return Response.json({ token: 'account-token', exp: 1 }) + if (url.endsWith('/v1/keys')) { + keyMints += 1 + return Response.json({ key: 'key_test', id: 'key_id' }) + } + if (url.endsWith('/v3/partner-checkout/sessions') && init?.method === 'POST') { + return Response.json({ sessionToken: 'checkout-session', status: 'pending_auth' }) + } + if (url.endsWith('/pay')) { + return Response.json({ + checkout: { providerSessionId: 'provider', payUrl: 'https://checkout.test/pay' }, + partnerCheckout: { sessionToken: 'checkout-session', status: 'pending_payment' }, + }) + } + if (url.endsWith('/v3/partner-checkout/sessions/checkout-session')) { + return Response.json({ sessionToken: 'checkout-session', status: sessionStatus }) + } + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + // First run: the payment expires. The issued key must survive the terminal reset. + await expect( + runAimlapiTopup({ email: 'user@example.com', code: '123456', amountUsd: '25', noOpen: true }), + ).rejects.toThrow('Payment expired') + + const afterFailure = JSON.parse( + readFileSync(join(configDirectory, 'aimlapi-topup.json'), 'utf8'), + ) as { apiKey?: string; resumeSessionToken: string } + expect(afterFailure.apiKey).toBe('key_test') + expect(afterFailure.resumeSessionToken).toBe('') + expect(keyMints).toBe(1) + + // Second run: the payment clears and the retained key is reused (not re-minted). + sessionStatus = 'paid' + await runAimlapiTopup({ + email: 'user@example.com', + code: '123456', + amountUsd: '25', + noOpen: true, + }) + expect(keyMints).toBe(1) + expect(() => readFileSync(join(configDirectory, 'aimlapi-topup.json'))).toThrow() +}) + test('topUpAimlapiByApiKey funds the key account without exchange', async () => { process.env.AIMLAPI_APP_URL = 'https://app.example.test' process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index a110b1337c..234bc1da17 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -19,6 +19,7 @@ import { openBrowser, promptText, saveProfileFile } from './topupDependencies.js import { claimAimlapiTopupState, clearAimlapiTopupState, + resetAimlapiCheckoutSession, saveAimlapiTopupState, type AimlapiTopupIntent, } from './topupState.js' @@ -151,6 +152,19 @@ export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { if (!resumeSessionToken) { + // A terminal checkout invalidates the payment session, but a minted + // existing-account key is still valid: retain it (with a fresh payment + // session) so the next run reuses the credential instead of issuing + // another. Fall back to a full clear when there is no key to keep. + if ( + checkoutState.apiKey && + resetAimlapiCheckoutSession({ + ...intent, + paymentSessionId: checkoutState.paymentSessionId, + }) + ) { + return + } clearAimlapiTopupState({ ...intent, paymentSessionId: checkoutState.paymentSessionId, diff --git a/src/integrations/aimlapi/topupState.ts b/src/integrations/aimlapi/topupState.ts index df8d43ee0c..337af82ae5 100644 --- a/src/integrations/aimlapi/topupState.ts +++ b/src/integrations/aimlapi/topupState.ts @@ -100,17 +100,45 @@ function withStateLock(operation: () => T): T { continue } if (stale) { - // Steal atomically: renaming the stale lock away can succeed for only - // one racer, so a replacement lock a live holder just wrote is never - // removed by a second stealer. + // Record the token we observed as stale so recovery can prove it is + // discarding the SAME lock and not a live replacement written between + // the staleness check and the steal. + let observedToken: string | undefined try { - renameSync(lockPath, `${lockPath}.${token}.stale`) - rmSync(`${lockPath}.${token}.stale`, { force: true }) + observedToken = readFileSync(lockPath, 'utf8') + } catch { + // Vanished already; retry the create immediately. continue + } + const stealPath = `${lockPath}.${token}.stale` + let stolen = false + try { + // Atomic: only one racer can rename a given inode away. + renameSync(lockPath, stealPath) + stolen = true } catch { - // Another process already stole it, or a live holder keeps it open - // (Windows cannot rename an open file); fall through to the - // timeout-bounded wait. + // Another racer already claimed it, or a live holder keeps it open + // (Windows cannot rename an open file); fall through to the wait. + } + if (stolen) { + let stolenToken: string | undefined + try { + stolenToken = readFileSync(stealPath, 'utf8') + } catch { + // Already gone; nothing to revalidate. + } + if (stolenToken === undefined || stolenToken === observedToken) { + // Exactly the stale lock we observed (or already gone): drop it. + rmSync(stealPath, { force: true }) + continue + } + // A live replacement slipped in and we renamed it away. Fail closed: + // put it back and wait rather than remove a lock we do not own. + try { + renameSync(stealPath, lockPath) + } catch { + rmSync(stealPath, { force: true }) + } } } if (Date.now() >= deadline) { @@ -240,6 +268,42 @@ export function claimAimlapiTopupState( }) } +/** + * A terminal checkout (cancelled/expired/failed, or a dead session) invalidates + * the payment session but not an already-issued existing-account key. Drop the + * dead session/payment identifiers and mint a fresh payment session while + * retaining the key, so the next run reuses the credential instead of minting + * another. Returns the refreshed checkout, or null when no matching keyed state + * exists (callers clear the state instead). + */ +export function resetAimlapiCheckoutSession( + expected: AimlapiTopupIntent & Pick, +): AimlapiCheckoutState | null { + return withStateLock(() => { + const current = readAimlapiTopupStateUnlocked() + if ( + !current || + !matchesIntent(current, expected) || + current.paymentSessionId !== expected.paymentSessionId || + !current.apiKey?.trim() + ) { + return null + } + const next: AimlapiPersistedTopup = { + ...current, + paymentSessionId: randomUUID(), + resumeSessionToken: '', + } + writeAimlapiTopupStateUnlocked(next) + return { + paymentSessionId: next.paymentSessionId, + resumeSessionToken: next.resumeSessionToken, + apiKey: next.apiKey, + apiKeyId: next.apiKeyId, + } + }) +} + export function clearAimlapiTopupState( expected: AimlapiTopupIntent & Pick, ): void { From 8bcf4d00b96b45f19798aa2e16d6d23c7973a327 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Fri, 17 Jul 2026 23:22:02 +0500 Subject: [PATCH 10/17] fix(aimlapi): guard undefined base URL, validate sessions, correct done screen and docs --- docs/aimlapi-setup.md | 10 ++--- src/components/ProviderManager.tsx | 37 ++++++++++------ src/integrations/aimlapi/client.test.ts | 21 +++++++++ src/integrations/aimlapi/client.ts | 59 ++++++++++++++++++------- src/integrations/aimlapi/topup.test.ts | 5 +++ src/utils/providerProfiles.test.ts | 22 +++++++++ src/utils/providerProfiles.ts | 6 ++- 7 files changed, 124 insertions(+), 36 deletions(-) diff --git a/docs/aimlapi-setup.md b/docs/aimlapi-setup.md index c0efc93124..ce95229ac0 100644 --- a/docs/aimlapi-setup.md +++ b/docs/aimlapi-setup.md @@ -13,13 +13,13 @@ None. You do not need to visit first - the guided top-up f ## Option 1 - Interactive (`/provider`) 1. Start OpenClaude and run `/provider`. -2. Choose **AI/ML API**. -3. If AI/ML API is already configured, choose one of: - - **Use existing configuration** - validate the saved key or `AIMLAPI_API_KEY`, check its balance, optionally top up a low balance, then choose a model. - - **Configure again** - enter the normal new-user or existing-key flow. +2. Choose **aimlapi.com**. +3. If aimlapi.com is already configured, choose one of: + - **Continue with your saved API key** - validate the saved key or `AIMLAPI_API_KEY`, check its balance, optionally top up a low balance, then choose a model. + - **Set up a new key or switch account** - enter the new-user or existing-key flow. 4. Otherwise choose how to get an API key: - **I am a new user** - enter your email. OpenClaude creates a passwordless account, lets you pick a top-up amount and automatic top-up preference, opens card checkout, then saves the issued key. - - **I already have an AI/ML API key** - paste a key from the dashboard. OpenClaude validates it, checks its balance, and offers an optional API-key top-up when the balance is low. + - **I already have aimlapi.com key** - paste a key from the dashboard. OpenClaude validates it, checks its balance, and offers an optional API-key top-up when the balance is low. For an email that already has an account, AI/ML API sends a 6-digit sign-in code. OpenClaude creates a new API key for that account, checks its balance, and only offers checkout when the balance is low. You can top up or save the key and skip funding for now. diff --git a/src/components/ProviderManager.tsx b/src/components/ProviderManager.tsx index dc7c9ad4ad..4cc7abd8e9 100644 --- a/src/components/ProviderManager.tsx +++ b/src/components/ProviderManager.tsx @@ -3471,23 +3471,32 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { } function renderAimlapiDone(): React.ReactNode { - const amountUsdMinor = parseAimlapiAmountUsd(aimlapiTopupAmountUsd) - const amountUsd = - amountUsdMinor % 100 === 0 - ? String(amountUsdMinor / 100) - : (amountUsdMinor / 100).toFixed(2) + // Only parse the amount for the top-up screen. When funding is skipped + // (e.g. after an invalid amount), aimlapiTopupAmountUsd may hold an unparsable + // value, and the "ready" screen never shows it — parsing it would throw. + let topUpBody: React.ReactNode = null + if (aimlapiDoneKind === 'topup') { + const amountUsdMinor = parseAimlapiAmountUsd(aimlapiTopupAmountUsd) + const amountUsd = + amountUsdMinor % 100 === 0 + ? String(amountUsdMinor / 100) + : (amountUsdMinor / 100).toFixed(2) + topUpBody = ( + <> + {AIMLAPI_MESSAGES.topUpSuccess(amountUsd)} + {aimlapiNewAccount ? ( + <> + + {AIMLAPI_MESSAGES.successMagicLink(aimlapiTopupEmail)} + + ) : null} + + ) + } return ( {aimlapiDoneKind === 'topup' ? ( - <> - {AIMLAPI_MESSAGES.topUpSuccess(amountUsd)} - {aimlapiNewAccount ? ( - <> - - {AIMLAPI_MESSAGES.successMagicLink(aimlapiTopupEmail)} - - ) : null} - + topUpBody ) : ( {AIMLAPI_MESSAGES.everythingRuns} )} diff --git a/src/integrations/aimlapi/client.test.ts b/src/integrations/aimlapi/client.test.ts index b394a6c64a..5e89c6698d 100644 --- a/src/integrations/aimlapi/client.test.ts +++ b/src/integrations/aimlapi/client.test.ts @@ -199,3 +199,24 @@ test('token-producing methods reject an empty token', async () => { 'did not return an auth token', ) }) + +test('session methods reject a malformed or empty success payload', async () => { + // A structurally-invalid 200 must surface as a non-terminal (status 200) + // error rather than a session with an unknown status, so callers never clear + // the retained payment identity or take an ambiguous retry on it. + const client = new AimlapiClient(endpoints) + + globalThis.fetch = mock(async () => jsonResponse({})) as unknown as typeof fetch + await expect(client.getSession('resume-token')).rejects.toMatchObject({ + name: 'AimlapiApiError', + status: 200, + }) + + globalThis.fetch = mock(async () => jsonResponse(null)) as unknown as typeof fetch + await expect(client.getSession('resume-token')).rejects.toThrow('invalid session') + + globalThis.fetch = mock(async () => + jsonResponse({ sessionToken: 'session', status: 'nonsense' }), + ) as unknown as typeof fetch + await expect(client.createSession({ partnerId: 'part_x' })).rejects.toThrow('invalid session') +}) diff --git a/src/integrations/aimlapi/client.ts b/src/integrations/aimlapi/client.ts index 66eea5fb6c..5401575df7 100644 --- a/src/integrations/aimlapi/client.ts +++ b/src/integrations/aimlapi/client.ts @@ -88,6 +88,28 @@ function redactRequestSecrets( return redacted } +const PARTNER_CHECKOUT_STATUSES: ReadonlySet = new Set([ + 'pending_auth', + 'pending_payment', + 'paid', + 'exchanging', + 'exchanged', + 'cancelled', + 'expired', + 'failed', +]) + +function isPartnerCheckoutSession(value: unknown): value is PartnerCheckoutSession { + if (typeof value !== 'object' || value === null) return false + const session = value as Record + return ( + typeof session.sessionToken === 'string' && + Boolean(session.sessionToken) && + typeof session.status === 'string' && + PARTNER_CHECKOUT_STATUSES.has(session.status) + ) +} + function isBalanceResult(value: unknown): value is BalanceResult { if (typeof value !== 'object' || value === null) return false const result = value as Record @@ -224,28 +246,35 @@ export class AimlapiClient { input: { partnerId: string; partnerName?: string | null; returnUrl?: string | null }, signal?: AbortSignal, ): Promise { - return this.request( - `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions`, - { - method: 'POST', - body: { - partnerId: input.partnerId, - ...(input.partnerName ? { partnerName: input.partnerName } : {}), - ...(input.returnUrl ? { returnUrl: input.returnUrl } : {}), - }, - signal, + const url = `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions` + const result = await this.request(url, { + method: 'POST', + body: { + partnerId: input.partnerId, + ...(input.partnerName ? { partnerName: input.partnerName } : {}), + ...(input.returnUrl ? { returnUrl: input.returnUrl } : {}), }, - ) + signal, + }) + if (!isPartnerCheckoutSession(result)) { + throw new AimlapiApiError(`POST ${requestLabel(url)} returned an invalid session`, 200, '') + } + return result } async getSession( sessionToken: string, signal?: AbortSignal, ): Promise { - return this.request( - `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}`, - { method: 'GET', signal }, - ) + const url = `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}` + const result = await this.request(url, { method: 'GET', signal }) + // A malformed/empty 200 must not read as an unknown status: that would let + // callers clear the retained payment identity or take an ambiguous retry. + // Surface it as a non-terminal error so retained state is preserved. + if (!isPartnerCheckoutSession(result)) { + throw new AimlapiApiError(`GET ${requestLabel(url)} returned an invalid session`, 200, '') + } + return result } async pay( diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index c3555b2ec9..49d4809a36 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -23,6 +23,11 @@ const originalEnv = { AIMLAPI_APP_URL: process.env.AIMLAPI_APP_URL, AIMLAPI_INFERENCE_URL: process.env.AIMLAPI_INFERENCE_URL, AIMLAPI_PAY_URL: process.env.AIMLAPI_PAY_URL, + AIMLAPI_PARTNER_ID: process.env.AIMLAPI_PARTNER_ID, + AIMLAPI_VERIFICATION_BASE_URL: process.env.AIMLAPI_VERIFICATION_BASE_URL, + AIMLAPI_RETURN_URL: process.env.AIMLAPI_RETURN_URL, + AIMLAPI_EMAIL: process.env.AIMLAPI_EMAIL, + AIMLAPI_CODE: process.env.AIMLAPI_CODE, } const temporaryDirectories: string[] = [] diff --git a/src/utils/providerProfiles.test.ts b/src/utils/providerProfiles.test.ts index 7adce4a4a6..1ad39d796f 100644 --- a/src/utils/providerProfiles.test.ts +++ b/src/utils/providerProfiles.test.ts @@ -1053,6 +1053,28 @@ describe('applyProviderProfileToProcessEnv', () => { expect(process.env.CLAUDE_CODE_PROVIDER_ROUTE_ID).toBe('aimlapi') }, 20_000) + test('keyless AIMLAPI profile without a base URL resolves the ambient key as canonical', async () => { + const { applyProviderProfileToProcessEnv } = + await importFreshProviderProfileModules() + process.env.AIMLAPI_API_KEY = 'ambient-aimlapi-key' + + // A missing base URL resolves to the canonical aimlapi default; the guard + // must treat it as canonical rather than crash on undefined.trim(). + applyProviderProfileToProcessEnv( + buildProfile({ + name: 'AI/ML API', + provider: 'aimlapi', + baseUrl: undefined, + model: 'gpt-4o', + apiKey: undefined, + }), + ) + + expect(process.env.AIMLAPI_API_KEY).toBe('ambient-aimlapi-key') + expect(process.env.OPENAI_API_KEY).toBe('ambient-aimlapi-key') + expect(process.env.CLAUDE_CODE_PROVIDER_ROUTE_ID).toBe('aimlapi') + }, 20_000) + test('openai profile on AI/ML API route mirrors AIMLAPI_API_KEY', async () => { const { applyProviderProfileToProcessEnv } = await importFreshProviderProfileModules() diff --git a/src/utils/providerProfiles.ts b/src/utils/providerProfiles.ts index 497e8bd034..92334a5539 100644 --- a/src/utils/providerProfiles.ts +++ b/src/utils/providerProfiles.ts @@ -1000,8 +1000,10 @@ export function applyProviderProfileToProcessEnv( // Only forward it when the profile targets the canonical inference host; // a keyless `aimlapi` profile can point at a user-controlled proxy, and // injecting the credential there would leak it. This mirrors the - // guided-flow validation, which also gates on the canonical URL. - if (isCanonicalAimlapiInferenceBaseUrl(profile.baseUrl)) { + // guided-flow validation, which also gates on the canonical URL. A missing + // base URL resolves to the aimlapi default (which is canonical), so treat + // it as canonical rather than passing undefined into the string helper. + if (!profile.baseUrl || isCanonicalAimlapiInferenceBaseUrl(profile.baseUrl)) { const ambientAimlapiKey = trimOrUndefined(process.env.AIMLAPI_API_KEY) ?? trimOrUndefined(process.env.OPENAI_API_KEY) From a291a4e63b05a0ea3d454e4ca379b80fc03a821e Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Fri, 17 Jul 2026 23:45:53 +0500 Subject: [PATCH 11/17] fix(aimlapi): gate guided provisioning to canonical endpoint, harden client responses --- src/components/ProviderManager.test.tsx | 41 +++++++++++++++++++++++++ src/components/ProviderManager.tsx | 9 ++++++ src/integrations/aimlapi/client.test.ts | 38 +++++++++++++++++++++-- src/integrations/aimlapi/client.ts | 15 ++++++++- src/integrations/aimlapi/messages.ts | 2 ++ src/integrations/aimlapi/topup.test.ts | 25 +++++++++++++++ src/integrations/aimlapi/topup.ts | 6 ++-- 7 files changed, 130 insertions(+), 6 deletions(-) diff --git a/src/components/ProviderManager.test.tsx b/src/components/ProviderManager.test.tsx index 792a99fe21..4bff4c964e 100644 --- a/src/components/ProviderManager.test.tsx +++ b/src/components/ProviderManager.test.tsx @@ -1268,6 +1268,47 @@ test('ProviderManager does not send the OPENAI_API_KEY fallback to a custom AIML } }) +test('ProviderManager refuses guided new-key creation on a custom AIMLAPI endpoint', async () => { + delete process.env.AIMLAPI_API_KEY + delete process.env.AIMLAPI_EMAIL + process.env.AIMLAPI_INFERENCE_URL = 'https://proxy.example.test/v1' + const beginAimlapiEmailOnboarding = mock(async () => ({ action: 'code-sent' as const })) + const provisionAimlapiKey = mock(async () => ({ + apiKey: 'issued', + apiKeyId: 'id', + baseUrl: 'https://proxy.example.test/v1', + model: 'anthropic/claude-sonnet-5', + })) + mockProviderManagerDependencies(() => undefined, async () => undefined, { + beginAimlapiEmailOnboarding, + provisionAimlapiKey, + }) + + const nonce = `${Date.now()}-${Math.random()}` + const { ProviderManager } = await import(`./ProviderManager.js?ts=${nonce}`) + const mounted = await mountProviderManager(ProviderManager, { mode: 'first-run' }) + try { + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('Set up provider')) + await navigateToPreset(mounted.stdin, 'aimlapi.com') + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Create provider profile') && frame.includes('Default model'), + ) + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => + frame.includes('Do you have aimlapi.com key?'), + ) + // Selecting "I am a new user" must be refused off the canonical endpoint, + // since guided provisioning would mint a production key against the proxy. + mounted.stdin.write('\r') + await waitForFrameOutput(mounted.getOutput, frame => frame.includes('production endpoint')) + expect(beginAimlapiEmailOnboarding).not.toHaveBeenCalled() + expect(provisionAimlapiKey).not.toHaveBeenCalled() + } finally { + await mounted.dispose() + } +}) + test('ProviderManager manage flow does not reuse env credentials for a custom AIMLAPI endpoint', async () => { delete process.env.AIMLAPI_API_KEY delete process.env.OPENAI_API_KEYS diff --git a/src/components/ProviderManager.tsx b/src/components/ProviderManager.tsx index 4cc7abd8e9..182345d549 100644 --- a/src/components/ProviderManager.tsx +++ b/src/components/ProviderManager.tsx @@ -3304,6 +3304,15 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { return } + // Guided provisioning mints a production-account key via production + // auth; it must never be written against a non-canonical inference + // endpoint. Pasting an existing key stays allowed for custom + // endpoints (handled by the 'manual' branch above). + if (!isCanonicalAimlapiInferenceBaseUrl(aimlapiInferenceBaseUrl)) { + setErrorMessage(AIMLAPI_MESSAGES.guidedNeedsCanonicalEndpoint) + return + } + resetAimlapiOnboardingIdentity() const envEmail = process.env.AIMLAPI_EMAIL?.trim() ?? '' setCursorOffset(envEmail.length) diff --git a/src/integrations/aimlapi/client.test.ts b/src/integrations/aimlapi/client.test.ts index 5e89c6698d..af5fc7fef7 100644 --- a/src/integrations/aimlapi/client.test.ts +++ b/src/integrations/aimlapi/client.test.ts @@ -206,17 +206,51 @@ test('session methods reject a malformed or empty success payload', async () => // the retained payment identity or take an ambiguous retry on it. const client = new AimlapiClient(endpoints) + // Empty object: passes the request-level object guard, rejected by the + // session shape check (no valid status). globalThis.fetch = mock(async () => jsonResponse({})) as unknown as typeof fetch await expect(client.getSession('resume-token')).rejects.toMatchObject({ name: 'AimlapiApiError', status: 200, }) + // null / non-object: rejected by the request-level guard. globalThis.fetch = mock(async () => jsonResponse(null)) as unknown as typeof fetch - await expect(client.getSession('resume-token')).rejects.toThrow('invalid session') + await expect(client.getSession('resume-token')).rejects.toMatchObject({ + name: 'AimlapiApiError', + status: 200, + }) + // Unknown status: object with a status outside the allowlist. globalThis.fetch = mock(async () => jsonResponse({ sessionToken: 'session', status: 'nonsense' }), ) as unknown as typeof fetch - await expect(client.createSession({ partnerId: 'part_x' })).rejects.toThrow('invalid session') + await expect(client.createSession({ partnerId: 'part_x' })).rejects.toMatchObject({ + name: 'AimlapiApiError', + status: 200, + }) +}) + +test('a request forwards the abort signal to fetch and rejects when cancelled', async () => { + const controller = new AbortController() + let forwardedSignal: AbortSignal | undefined + globalThis.fetch = mock(async (_input: string | URL | Request, init?: RequestInit) => { + forwardedSignal = init?.signal ?? undefined + // Model a transport that only settles when the request is aborted. + return await new Promise((_resolve, reject) => { + init?.signal?.addEventListener( + 'abort', + () => reject(new DOMException('The operation was aborted.', 'AbortError')), + { once: true }, + ) + }) + }) as unknown as typeof fetch + + const client = new AimlapiClient(endpoints) + const pending = client.getSession('resume-token', controller.signal) + controller.abort() + await expect(pending).rejects.toThrow() + // The signal reached the transport layer and observed the cancellation. + expect(forwardedSignal).toBeInstanceOf(AbortSignal) + expect(forwardedSignal?.aborted).toBe(true) }) diff --git a/src/integrations/aimlapi/client.ts b/src/integrations/aimlapi/client.ts index 5401575df7..f6ea6c9276 100644 --- a/src/integrations/aimlapi/client.ts +++ b/src/integrations/aimlapi/client.ts @@ -423,8 +423,9 @@ export class AimlapiClient { '', ) } + let parsed: unknown try { - return JSON.parse(text) as T + parsed = JSON.parse(text) } catch { throw new AimlapiApiError( `${options.method} ${label} returned non-JSON body`, @@ -432,5 +433,17 @@ export class AimlapiClient { text, ) } + // Every endpoint returns a JSON object. Reject null/non-object bodies here so + // no method dereferences a null/primitive success payload (which would throw + // a raw TypeError instead of a controlled, non-terminal error); endpoint + // guards below still validate structural completeness. + if (typeof parsed !== 'object' || parsed === null) { + throw new AimlapiApiError( + `${options.method} ${label} returned an unexpected body`, + response.status, + '', + ) + } + return parsed as T } } diff --git a/src/integrations/aimlapi/messages.ts b/src/integrations/aimlapi/messages.ts index 78f2fe8ff8..81465a611e 100644 --- a/src/integrations/aimlapi/messages.ts +++ b/src/integrations/aimlapi/messages.ts @@ -17,6 +17,8 @@ export const AIMLAPI_MESSAGES = { lowBalanceSkip: "I'll skip for now", topUpPrompt: 'Add credits (min $20).', amountRequired: 'Please enter a top-up amount.', + guidedNeedsCanonicalEndpoint: + 'Creating a new key requires the aimlapi.com production endpoint. Unset AIMLAPI_INFERENCE_URL, or paste an existing key to use a custom endpoint.', topUpBrowserFallback: 'If the browser did not open automatically please use this link to top up your account:', topUpFailed: 'Top up failed. Please try again.', diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index 49d4809a36..e31eb4756b 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -663,6 +663,31 @@ test('polling retains and retries the same session after a rate limit', async () expect(sessions).toEqual([]) }) +test('aborting during polling stops requests and preserves the retained session', async () => { + const controller = new AbortController() + let getCount = 0 + globalThis.fetch = mock(async () => { + getCount += 1 + controller.abort() + return Response.json({ sessionToken: 'session', status: 'pending_payment' }) + }) as unknown as typeof fetch + const client = new AimlapiClient({ + authBaseUrl: 'https://auth.example.test', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.example.test/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://front.example.test', + }) + const sessions: string[] = [] + + await expect( + pollUntilPaid(client, 'session', controller.signal, value => sessions.push(value)), + ).rejects.toThrow() + // Aborted before the next poll: exactly one GET, and the session is not cleared. + expect(getCount).toBe(1) + expect(sessions).toEqual([]) +}) + test('by-key billing stays on the endpoint that validated the key', async () => { process.env.AIMLAPI_APP_URL = 'https://app.example.test' process.env.AIMLAPI_INFERENCE_URL = 'https://override.example.test/v1' diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index 234bc1da17..9f9fa037c2 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -298,7 +298,7 @@ export async function provisionAimlapiKey( }, options.signal, ) - await announceCheckout(checkout.payUrl, options) + await announceCheckout(checkout?.payUrl, options) } let paidToken = sessionToken @@ -387,7 +387,7 @@ export async function topUpAimlapiByApiKey( }, options.signal, ) - await announceCheckout(checkout.payUrl, options) + await announceCheckout(checkout?.payUrl, options) } if (phase === 'pay' || phase === 'poll') { options.onStatus?.('waiting-payment') @@ -412,7 +412,7 @@ export async function topUpAimlapiByApiKey( } async function announceCheckout( - payUrl: string | null, + payUrl: string | null | undefined, options: Pick & { onStatus?: (status: AimlapiTopupStatus, detail?: string) => void }, From 83959c0ab3ecae1f1cd47370be9e5db7ab8f8ef1 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Sat, 18 Jul 2026 00:02:51 +0500 Subject: [PATCH 12/17] test(aimlapi): assert session errors via instanceof and status property --- src/integrations/aimlapi/client.test.ts | 25 ++++++++++++------------- 1 file changed, 12 insertions(+), 13 deletions(-) diff --git a/src/integrations/aimlapi/client.test.ts b/src/integrations/aimlapi/client.test.ts index af5fc7fef7..1c5a10b369 100644 --- a/src/integrations/aimlapi/client.test.ts +++ b/src/integrations/aimlapi/client.test.ts @@ -1,6 +1,6 @@ import { afterEach, expect, mock, test } from 'bun:test' -import { AimlapiClient } from './client.js' +import { AimlapiApiError, AimlapiClient } from './client.js' import type { AimlapiEndpoints } from './config.js' const originalFetch = globalThis.fetch @@ -209,26 +209,25 @@ test('session methods reject a malformed or empty success payload', async () => // Empty object: passes the request-level object guard, rejected by the // session shape check (no valid status). globalThis.fetch = mock(async () => jsonResponse({})) as unknown as typeof fetch - await expect(client.getSession('resume-token')).rejects.toMatchObject({ - name: 'AimlapiApiError', - status: 200, - }) + const emptyError = await client.getSession('resume-token').catch((error: unknown) => error) + expect(emptyError).toBeInstanceOf(AimlapiApiError) + expect(emptyError).toHaveProperty('status', 200) // null / non-object: rejected by the request-level guard. globalThis.fetch = mock(async () => jsonResponse(null)) as unknown as typeof fetch - await expect(client.getSession('resume-token')).rejects.toMatchObject({ - name: 'AimlapiApiError', - status: 200, - }) + const nullError = await client.getSession('resume-token').catch((error: unknown) => error) + expect(nullError).toBeInstanceOf(AimlapiApiError) + expect(nullError).toHaveProperty('status', 200) // Unknown status: object with a status outside the allowlist. globalThis.fetch = mock(async () => jsonResponse({ sessionToken: 'session', status: 'nonsense' }), ) as unknown as typeof fetch - await expect(client.createSession({ partnerId: 'part_x' })).rejects.toMatchObject({ - name: 'AimlapiApiError', - status: 200, - }) + const badStatusError = await client + .createSession({ partnerId: 'part_x' }) + .catch((error: unknown) => error) + expect(badStatusError).toBeInstanceOf(AimlapiApiError) + expect(badStatusError).toHaveProperty('status', 200) }) test('a request forwards the abort signal to fetch and rejects when cancelled', async () => { From c8cba1ca05e232dd56a3f95f9196abf160ff3a40 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Sat, 18 Jul 2026 00:10:53 +0500 Subject: [PATCH 13/17] fix(aimlapi): validate full session contract (id + partnerId) in shape guard --- src/integrations/aimlapi/client.ts | 9 ++++- src/integrations/aimlapi/topup.test.ts | 56 +++++++++++++++----------- 2 files changed, 40 insertions(+), 25 deletions(-) diff --git a/src/integrations/aimlapi/client.ts b/src/integrations/aimlapi/client.ts index f6ea6c9276..ce84afc7be 100644 --- a/src/integrations/aimlapi/client.ts +++ b/src/integrations/aimlapi/client.ts @@ -99,12 +99,17 @@ const PARTNER_CHECKOUT_STATUSES: ReadonlySet = new Set 0 +} + function isPartnerCheckoutSession(value: unknown): value is PartnerCheckoutSession { if (typeof value !== 'object' || value === null) return false const session = value as Record return ( - typeof session.sessionToken === 'string' && - Boolean(session.sessionToken) && + isNonEmptyString(session.id) && + isNonEmptyString(session.sessionToken) && + isNonEmptyString(session.partnerId) && typeof session.status === 'string' && PARTNER_CHECKOUT_STATUSES.has(session.status) ) diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index e31eb4756b..87a6df0b81 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -17,6 +17,16 @@ const { pollUntilPaid, provisionAimlapiKey, runAimlapiTopup, topUpAimlapiByApiKe await import('./topup.js') const { AimlapiClient } = await import('./client.js') +// createSession/getSession responses are validated against the full +// PartnerCheckoutSession contract, so mocks must carry id + partnerId too. +function sessionJson(session: Record): Response { + return Response.json({ + id: 'sess_test', + partnerId: 'part_62yQoGYDq4Yqnrj2R1iGrDNJ', + ...session, + }) +} + const originalFetch = globalThis.fetch const originalEnv = { AIMLAPI_AUTH_URL: process.env.AIMLAPI_AUTH_URL, @@ -94,14 +104,14 @@ test('CLI retries reuse the persisted checkout session and payment id', async () return Response.json({ key: 'key_test', id: 'key_id' }) } if (url.endsWith('/v3/partner-checkout/sessions') && init?.method === 'POST') { - return Response.json({ sessionToken: 'checkout-session', status: 'pending_auth' }) + return sessionJson({ sessionToken: 'checkout-session', status: 'pending_auth' }) } if (url.endsWith('/pay')) { payBodies.push(JSON.parse(String(init?.body)) as Record) throw new Error('ambiguous payment response') } if (url.endsWith('/v3/partner-checkout/sessions/checkout-session')) { - return Response.json({ sessionToken: 'checkout-session', status: 'paid' }) + return sessionJson({ sessionToken: 'checkout-session', status: 'paid' }) } throw new Error(`Unexpected request: ${url}`) }) as unknown as typeof fetch @@ -173,7 +183,7 @@ test('CLI retains an already-exchanged checkout and blocks identical retries', a } if (url.endsWith('/sessions/exchanged-session')) { sessionReads += 1 - return Response.json({ + return sessionJson({ sessionToken: 'exchanged-session', status: 'exchanged', issuedKeyId: 'issued-key-id', @@ -222,7 +232,7 @@ test('a failed payment retains the issued key for the next run', async () => { return Response.json({ key: 'key_test', id: 'key_id' }) } if (url.endsWith('/v3/partner-checkout/sessions') && init?.method === 'POST') { - return Response.json({ sessionToken: 'checkout-session', status: 'pending_auth' }) + return sessionJson({ sessionToken: 'checkout-session', status: 'pending_auth' }) } if (url.endsWith('/pay')) { return Response.json({ @@ -231,7 +241,7 @@ test('a failed payment retains the issued key for the next run', async () => { }) } if (url.endsWith('/v3/partner-checkout/sessions/checkout-session')) { - return Response.json({ sessionToken: 'checkout-session', status: sessionStatus }) + return sessionJson({ sessionToken: 'checkout-session', status: sessionStatus }) } throw new Error(`Unexpected request: ${url}`) }) as unknown as typeof fetch @@ -269,7 +279,7 @@ test('topUpAimlapiByApiKey funds the key account without exchange', async () => const url = String(input) calls.push(`${init?.method} ${url}`) if (url.endsWith('/v3/partner-checkout/sessions')) { - return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) } if (url.endsWith('/v2/billing/topup')) { return Response.json({ @@ -278,7 +288,7 @@ test('topUpAimlapiByApiKey funds the key account without exchange', async () => }) } if (url.endsWith('/v3/partner-checkout/sessions/session')) { - return Response.json({ sessionToken: 'session', status: 'paid' }) + return sessionJson({ sessionToken: 'session', status: 'paid' }) } return new Response('', { status: 404 }) }) as unknown as typeof fetch @@ -308,7 +318,7 @@ test('topUpAimlapiByApiKey resumes a paid session without charging again', async const calls: string[] = [] globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { calls.push(`${init?.method} ${String(input)}`) - return Response.json({ sessionToken: 'session', status: 'paid' }) + return sessionJson({ sessionToken: 'session', status: 'paid' }) }) as unknown as typeof fetch await topUpAimlapiByApiKey({ @@ -331,7 +341,7 @@ test('a pending resumed session is polled without paying again', async () => { globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { calls.push(`${init?.method} ${String(input)}`) reads += 1 - return Response.json({ + return sessionJson({ sessionToken: 'session', status: reads === 1 ? 'pending_payment' : 'paid', }) @@ -359,7 +369,7 @@ test('a resumed by-key session still exchanging settles before success', async ( globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { calls.push(`${init?.method} ${String(input)}`) reads += 1 - return Response.json({ + return sessionJson({ sessionToken: 'session', status: reads === 1 ? 'exchanging' : 'exchanged', }) @@ -431,7 +441,7 @@ test('provisionAimlapiKey does not repeat an already completed exchange', async const calls: string[] = [] globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { calls.push(`${init?.method} ${String(input)}`) - return Response.json({ + return sessionJson({ sessionToken: 'session', status: 'exchanged', issuedKeyId: 'key_recoverable', @@ -465,7 +475,7 @@ test('an in-progress exchange is observed without issuing a second exchange', as globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { calls.push(`${init?.method} ${String(input)}`) reads += 1 - return Response.json({ + return sessionJson({ sessionToken: 'session', status: reads === 1 ? 'exchanging' : 'exchanged', }) @@ -493,7 +503,7 @@ test('email-session checkout carries the stable payment id', async () => { globalThis.fetch = mock(async (input: string | URL | Request, init?: RequestInit) => { const url = String(input) if (url.endsWith('/v3/partner-checkout/sessions')) { - return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) } if (url.endsWith('/pay')) { payBody = JSON.parse(String(init?.body)) as Record @@ -502,7 +512,7 @@ test('email-session checkout carries the stable payment id', async () => { partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, }) } - return Response.json({ sessionToken: 'session', status: 'paid' }) + return sessionJson({ sessionToken: 'session', status: 'paid' }) }) as unknown as typeof fetch await provisionAimlapiKey({ @@ -522,7 +532,7 @@ test('checkout URL must be an absolute credential-free HTTPS URL', async () => { globalThis.fetch = mock(async (input: string | URL | Request) => { const url = String(input) if (url.endsWith('/v3/partner-checkout/sessions')) { - return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) } return Response.json({ checkout: { providerSessionId: 'provider', payUrl: 'file:///tmp/checkout' }, @@ -563,7 +573,7 @@ test('dead sessions observed while polling are cleared immediately', async () => globalThis.fetch = mock(async (input: string | URL | Request) => { const url = String(input) if (url.endsWith('/v3/partner-checkout/sessions')) { - return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) } if (url.endsWith('/v2/billing/topup')) { return Response.json({ @@ -571,7 +581,7 @@ test('dead sessions observed while polling are cleared immediately', async () => partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, }) } - return Response.json({ sessionToken: 'session', status: 'expired' }) + return sessionJson({ sessionToken: 'session', status: 'expired' }) }) as unknown as typeof fetch const sessions: string[] = [] @@ -593,7 +603,7 @@ test('terminal API errors observed while polling clear retained checkout state', globalThis.fetch = mock(async (input: string | URL | Request) => { const url = String(input) if (url.endsWith('/v3/partner-checkout/sessions')) { - return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) } if (url.endsWith('/v2/billing/topup')) { return Response.json({ @@ -623,7 +633,7 @@ test('polling retries a transient transport failure', async () => { globalThis.fetch = mock(async () => { attempts += 1 if (attempts === 1) throw new TypeError('temporary connection reset') - return Response.json({ sessionToken: 'session', status: 'paid' }) + return sessionJson({ sessionToken: 'session', status: 'paid' }) }) as unknown as typeof fetch const client = new AimlapiClient({ authBaseUrl: 'https://auth.example.test', @@ -645,7 +655,7 @@ test('polling retains and retries the same session after a rate limit', async () globalThis.fetch = mock(async () => { attempts += 1 if (attempts === 1) return new Response('rate limited', { status: 429 }) - return Response.json({ sessionToken: 'session', status: 'paid' }) + return sessionJson({ sessionToken: 'session', status: 'paid' }) }) as unknown as typeof fetch const client = new AimlapiClient({ authBaseUrl: 'https://auth.example.test', @@ -669,7 +679,7 @@ test('aborting during polling stops requests and preserves the retained session' globalThis.fetch = mock(async () => { getCount += 1 controller.abort() - return Response.json({ sessionToken: 'session', status: 'pending_payment' }) + return sessionJson({ sessionToken: 'session', status: 'pending_payment' }) }) as unknown as typeof fetch const client = new AimlapiClient({ authBaseUrl: 'https://auth.example.test', @@ -696,7 +706,7 @@ test('by-key billing stays on the endpoint that validated the key', async () => const url = String(input) calls.push(url) if (url.endsWith('/v3/partner-checkout/sessions')) { - return Response.json({ sessionToken: 'session', status: 'pending_auth' }) + return sessionJson({ sessionToken: 'session', status: 'pending_auth' }) } if (url.endsWith('/v2/billing/topup')) { return Response.json({ @@ -704,7 +714,7 @@ test('by-key billing stays on the endpoint that validated the key', async () => partnerCheckout: { sessionToken: 'session', status: 'pending_payment' }, }) } - return Response.json({ sessionToken: 'session', status: 'paid' }) + return sessionJson({ sessionToken: 'session', status: 'paid' }) }) as unknown as typeof fetch await topUpAimlapiByApiKey({ From 25ddf62fc1e6e1baf912e1bb5181117df6348175 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Sat, 18 Jul 2026 00:49:16 +0500 Subject: [PATCH 14/17] test(aimlapi): relocate abort coverage next to the reviewed session/polling blocks --- src/integrations/aimlapi/client.test.ts | 48 ++++++++++++------------ src/integrations/aimlapi/topup.test.ts | 50 ++++++++++++------------- 2 files changed, 49 insertions(+), 49 deletions(-) diff --git a/src/integrations/aimlapi/client.test.ts b/src/integrations/aimlapi/client.test.ts index 1c5a10b369..ac1f79e6c8 100644 --- a/src/integrations/aimlapi/client.test.ts +++ b/src/integrations/aimlapi/client.test.ts @@ -200,6 +200,30 @@ test('token-producing methods reject an empty token', async () => { ) }) +test('a request forwards the abort signal to fetch and rejects when cancelled', async () => { + const controller = new AbortController() + let forwardedSignal: AbortSignal | undefined + globalThis.fetch = mock(async (_input: string | URL | Request, init?: RequestInit) => { + forwardedSignal = init?.signal ?? undefined + // Model a transport that only settles when the request is aborted. + return await new Promise((_resolve, reject) => { + init?.signal?.addEventListener( + 'abort', + () => reject(new DOMException('The operation was aborted.', 'AbortError')), + { once: true }, + ) + }) + }) as unknown as typeof fetch + + const client = new AimlapiClient(endpoints) + const pending = client.getSession('resume-token', controller.signal) + controller.abort() + await expect(pending).rejects.toThrow() + // The signal reached the transport layer and observed the cancellation. + expect(forwardedSignal).toBeInstanceOf(AbortSignal) + expect(forwardedSignal?.aborted).toBe(true) +}) + test('session methods reject a malformed or empty success payload', async () => { // A structurally-invalid 200 must surface as a non-terminal (status 200) // error rather than a session with an unknown status, so callers never clear @@ -229,27 +253,3 @@ test('session methods reject a malformed or empty success payload', async () => expect(badStatusError).toBeInstanceOf(AimlapiApiError) expect(badStatusError).toHaveProperty('status', 200) }) - -test('a request forwards the abort signal to fetch and rejects when cancelled', async () => { - const controller = new AbortController() - let forwardedSignal: AbortSignal | undefined - globalThis.fetch = mock(async (_input: string | URL | Request, init?: RequestInit) => { - forwardedSignal = init?.signal ?? undefined - // Model a transport that only settles when the request is aborted. - return await new Promise((_resolve, reject) => { - init?.signal?.addEventListener( - 'abort', - () => reject(new DOMException('The operation was aborted.', 'AbortError')), - { once: true }, - ) - }) - }) as unknown as typeof fetch - - const client = new AimlapiClient(endpoints) - const pending = client.getSession('resume-token', controller.signal) - controller.abort() - await expect(pending).rejects.toThrow() - // The signal reached the transport layer and observed the cancellation. - expect(forwardedSignal).toBeInstanceOf(AbortSignal) - expect(forwardedSignal?.aborted).toBe(true) -}) diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index 87a6df0b81..80fdc51586 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -597,6 +597,31 @@ test('dead sessions observed while polling are cleared immediately', async () => expect(sessions).toEqual(['session', '']) }) +test('aborting during polling stops requests and preserves the retained session', async () => { + const controller = new AbortController() + let getCount = 0 + globalThis.fetch = mock(async () => { + getCount += 1 + controller.abort() + return sessionJson({ sessionToken: 'session', status: 'pending_payment' }) + }) as unknown as typeof fetch + const client = new AimlapiClient({ + authBaseUrl: 'https://auth.example.test', + appBaseUrl: 'https://app.example.test', + inferenceBaseUrl: 'https://api.example.test/v1', + payBaseUrl: 'https://pay.example.test', + verificationBaseUrl: 'https://front.example.test', + }) + const sessions: string[] = [] + + await expect( + pollUntilPaid(client, 'session', controller.signal, value => sessions.push(value)), + ).rejects.toThrow() + // Aborted before the next poll: exactly one GET, and the session is not cleared. + expect(getCount).toBe(1) + expect(sessions).toEqual([]) +}) + test('terminal API errors observed while polling clear retained checkout state', async () => { process.env.AIMLAPI_APP_URL = 'https://app.example.test' process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' @@ -673,31 +698,6 @@ test('polling retains and retries the same session after a rate limit', async () expect(sessions).toEqual([]) }) -test('aborting during polling stops requests and preserves the retained session', async () => { - const controller = new AbortController() - let getCount = 0 - globalThis.fetch = mock(async () => { - getCount += 1 - controller.abort() - return sessionJson({ sessionToken: 'session', status: 'pending_payment' }) - }) as unknown as typeof fetch - const client = new AimlapiClient({ - authBaseUrl: 'https://auth.example.test', - appBaseUrl: 'https://app.example.test', - inferenceBaseUrl: 'https://api.example.test/v1', - payBaseUrl: 'https://pay.example.test', - verificationBaseUrl: 'https://front.example.test', - }) - const sessions: string[] = [] - - await expect( - pollUntilPaid(client, 'session', controller.signal, value => sessions.push(value)), - ).rejects.toThrow() - // Aborted before the next poll: exactly one GET, and the session is not cleared. - expect(getCount).toBe(1) - expect(sessions).toEqual([]) -}) - test('by-key billing stays on the endpoint that validated the key', async () => { process.env.AIMLAPI_APP_URL = 'https://app.example.test' process.env.AIMLAPI_INFERENCE_URL = 'https://override.example.test/v1' From 11372cc8bc3a031d2aa6b8f20a6cd61b3ceaa7c1 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Sat, 18 Jul 2026 01:48:42 +0500 Subject: [PATCH 15/17] fix(aimlapi): address reviewer P1/P2 findings (revert model, guards, recovery) - Revert the unrelated Sonnet 5 default/catalog/docs change back to gpt-4o (the catalog entry was also mis-wired to the claude-sonnet-4-6 descriptor); restore the matching test expectations - Gate the CLI guided top-up on the canonical inference endpoint, mirroring the provider-manager gate, so a freshly minted key is never sent to a proxy - Persist the provisioned key as a `settled` recoverable state before the profile write and resume that step on retry, so an interrupted new-account exchange no longer strands the paid key - announceCheckout: surface the validated checkout URL before opening the browser (and tolerate a launcher failure) so a headless host can still pay - client: endpoint-specific response validation for account/auth/key/pay/ exchange so a wrong-typed 2xx payload yields a controlled error, not a raw TypeError after state-changing operations --- docs/aimlapi-setup.md | 8 +- src/cli/aimlapiCommand.test.ts | 2 +- src/components/ProviderManager.test.tsx | 22 +++--- src/integrations/aimlapi/client.ts | 94 ++++++++++++++++------- src/integrations/aimlapi/config.ts | 2 +- src/integrations/aimlapi/topup.test.ts | 3 +- src/integrations/aimlapi/topup.ts | 94 ++++++++++++++++------- src/integrations/aimlapi/topupState.ts | 14 +++- src/integrations/discoveryService.test.ts | 13 ++-- src/integrations/gateways/aimlapi.ts | 10 +-- src/integrations/routeMetadata.test.ts | 4 +- src/integrations/runtimeMetadata.test.ts | 4 +- src/services/api/client.test.ts | 2 +- src/utils/providerProfiles.test.ts | 2 +- 14 files changed, 182 insertions(+), 92 deletions(-) diff --git a/docs/aimlapi-setup.md b/docs/aimlapi-setup.md index ce95229ac0..38c89e5325 100644 --- a/docs/aimlapi-setup.md +++ b/docs/aimlapi-setup.md @@ -4,7 +4,7 @@ OpenClaude connects to [AI/ML API](https://aimlapi.com) through its OpenAI-compa ## Overview -AI/ML API is an aggregating gateway that exposes many chat models behind a single OpenAI-compatible API. OpenClaude ships a first-class `AI/ML API` provider preset: it uses `AIMLAPI_API_KEY`, sends the OpenClaude attribution headers, and discovers chat-capable models from the public `/models` catalog. It defaults to `anthropic/claude-sonnet-5`. +AI/ML API is an aggregating gateway that exposes many chat models behind a single OpenAI-compatible API. OpenClaude ships a first-class `AI/ML API` provider preset: it uses `AIMLAPI_API_KEY`, sends the OpenClaude attribution headers, and discovers chat-capable models from the public `/models` catalog. It defaults to `gpt-4o`. ## Prerequisites @@ -27,7 +27,7 @@ When `AIMLAPI_API_KEY` supplies the credential, OpenClaude uses its runtime valu Checkout progress is retained while the provider flow remains open. Retrying an ambiguous payment or exchange failure resumes the original partner session instead of creating a second checkout. -The base URL (`https://api.aimlapi.com/v1`) and default model (`anthropic/claude-sonnet-5`) are filled in automatically. Switch models any time with `/model`; only chat-capable models from the AI/ML API catalog are listed. +The base URL (`https://api.aimlapi.com/v1`) and default model (`gpt-4o`) are filled in automatically. Switch models any time with `/model`; only chat-capable models from the AI/ML API catalog are listed. ## Option 2 - CLI (`openclaude aimlapi topup`) @@ -41,7 +41,7 @@ openclaude aimlapi topup --email you@example.com --amount 25 - `--amount`: top-up amount in USD (min 20, max 10000; defaults to 25). - Checkout always uses card payment; there is no separate payment-method step. - `--auto-top-up`: enroll the account in automatic top-up at checkout. -- `--model`: default model id written into the provider profile (defaults to `anthropic/claude-sonnet-5`). +- `--model`: default model id written into the provider profile (defaults to `gpt-4o`). - `--no-open`: print the payment URL instead of auto-opening a browser. The issued key is written into OpenClaude's provider profile automatically once payment clears. @@ -60,7 +60,7 @@ To configure the OpenAI-compatible route explicitly: export CLAUDE_CODE_USE_OPENAI=1 export AIMLAPI_API_KEY="your-aimlapi-key" export OPENAI_BASE_URL="https://api.aimlapi.com/v1" -export OPENAI_MODEL="anthropic/claude-sonnet-5" +export OPENAI_MODEL="gpt-4o" ``` `OPENAI_API_KEY` also works as a fallback credential for the route. diff --git a/src/cli/aimlapiCommand.test.ts b/src/cli/aimlapiCommand.test.ts index d712ed2931..33c0200b68 100644 --- a/src/cli/aimlapiCommand.test.ts +++ b/src/cli/aimlapiCommand.test.ts @@ -26,7 +26,7 @@ test('aimlapi topup forwards the passwordless CLI contract', async () => { code: '123456', amountUsd: undefined, autoTopUp: true, - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', partnerId: undefined, noOpen: true, }) diff --git a/src/components/ProviderManager.test.tsx b/src/components/ProviderManager.test.tsx index 4bff4c964e..8fc7ce5e3a 100644 --- a/src/components/ProviderManager.test.tsx +++ b/src/components/ProviderManager.test.tsx @@ -273,7 +273,7 @@ function mockProviderProfilesModule(options?: { provider: 'aimlapi', name: 'aimlapi.com', baseUrl: 'https://api.aimlapi.com/v1', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', apiKey: '', requiresApiKey: true, } @@ -1047,7 +1047,7 @@ test('ProviderManager saves AI/ML API preset with OpenAI-compatible defaults', a ) expect(modelOutput).toContain('aimlapi.com') - expect(modelOutput).toContain('anthropic/claude-sonnet-5') + expect(modelOutput).toContain('gpt-4o') expect(modelOutput).not.toContain('Provider name') expect(modelOutput).not.toContain('Base URL') @@ -1093,7 +1093,7 @@ test('ProviderManager saves AI/ML API preset with OpenAI-compatible defaults', a provider: 'aimlapi', name: 'aimlapi.com', baseUrl: 'https://api.aimlapi.com/v1', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', apiKey: 'aimlapi-test-key', apiFormat: 'chat_completions', }), @@ -1187,7 +1187,7 @@ test('ProviderManager uses OPENAI_API_KEY for an existing keyless AIMLAPI profil provider: 'aimlapi', name: 'aimlapi.com', baseUrl: 'https://api.aimlapi.com/v1', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', apiKey: undefined, apiFormat: 'chat_completions', } @@ -1277,7 +1277,7 @@ test('ProviderManager refuses guided new-key creation on a custom AIMLAPI endpoi apiKey: 'issued', apiKeyId: 'id', baseUrl: 'https://proxy.example.test/v1', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', })) mockProviderManagerDependencies(() => undefined, async () => undefined, { beginAimlapiEmailOnboarding, @@ -1523,7 +1523,7 @@ test('ProviderManager rejects an empty AIMLAPI top-up amount instead of charging apiKey: 'unexpected', apiKeyId: 'unexpected', baseUrl: 'https://api.aimlapi.com/v1', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', })) mockProviderManagerDependencies(() => undefined, async () => undefined, { provisionAimlapiKey, @@ -1580,7 +1580,7 @@ test('ProviderManager drops a retained checkout when the onboarding email change apiKey: 'issued-for-second-account', apiKeyId: 'key_second', baseUrl: 'https://api.aimlapi.com/v1', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', } }) mockProviderManagerDependencies(() => undefined, async () => undefined, { @@ -1651,7 +1651,7 @@ test('ProviderManager cancellation returns a live checkout to the resumable amou apiKey: 'issued-after-resume', apiKeyId: 'key_after_resume', baseUrl: 'https://api.aimlapi.com/v1', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', } }) mockProviderManagerDependencies(() => undefined, async () => undefined, { @@ -1720,7 +1720,7 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => apiKey: 'aimlapi-issued-key', apiKeyId: 'key_test', baseUrl: 'https://api.aimlapi.com/v1', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', } }) const claimAimlapiTopupState = mock(() => ({ @@ -1817,7 +1817,7 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => expect(provisionAimlapiKey).toHaveBeenCalledWith( expect.objectContaining({ amountUsd: '25', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', sessionToken: 'session_test', paymentSessionId: 'persisted-payment-id', resumeSessionToken: 'persisted-checkout-session', @@ -1831,7 +1831,7 @@ test('ProviderManager can top up AI/ML API and save the issued key', async () => provider: 'aimlapi', name: 'aimlapi.com', baseUrl: 'https://api.aimlapi.com/v1', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', apiKey: 'aimlapi-issued-key', apiFormat: 'chat_completions', }), diff --git a/src/integrations/aimlapi/client.ts b/src/integrations/aimlapi/client.ts index ce84afc7be..8de290cc31 100644 --- a/src/integrations/aimlapi/client.ts +++ b/src/integrations/aimlapi/client.ts @@ -99,8 +99,32 @@ const PARTNER_CHECKOUT_STATUSES: ReadonlySet = new Set { + return typeof value === 'object' && value !== null +} + function isNonEmptyString(value: unknown): value is string { - return typeof value === 'string' && value.length > 0 + return typeof value === 'string' && value.trim().length > 0 +} + +function isAccountCheckResult(value: unknown): value is AccountCheckResult { + return isRecord(value) && typeof value.action === 'string' +} + +function isAuthResult(value: unknown): value is AuthResult { + return isRecord(value) && isNonEmptyString(value.token) +} + +function isCreatedKey(value: unknown): value is CreatedKey { + return isRecord(value) && isNonEmptyString(value.key) +} + +function isExchangeResult(value: unknown): value is ExchangeResult { + return isRecord(value) && isNonEmptyString(value.apiKey) +} + +function isPayResult(value: unknown): value is PayResult { + return isRecord(value) && isRecord(value.checkout) } function isPartnerCheckoutSession(value: unknown): value is PartnerCheckoutSession { @@ -176,11 +200,16 @@ export class AimlapiClient { constructor(private readonly endpoints: AimlapiEndpoints) {} async checkAccount(email: string, signal?: AbortSignal): Promise { - return this.request(`${this.endpoints.authBaseUrl}/v1/auth/account`, { + const url = `${this.endpoints.authBaseUrl}/v1/auth/account` + const result = await this.request(url, { method: 'PATCH', body: { email }, signal, }) + if (!isAccountCheckResult(result)) { + throw new AimlapiApiError(`PATCH ${requestLabel(url)} returned an invalid account response`, 200, '') + } + return result } async sendSignInCode(email: string, signal?: AbortSignal): Promise { @@ -197,20 +226,20 @@ export class AimlapiClient { code: string, signal?: AbortSignal, ): Promise { - const result = await this.request( + const result = await this.request( `${this.endpoints.authBaseUrl}/v1/auth/sign-in/code/verify`, { method: 'POST', body: { email, code }, signal }, ) - if (!result.token?.trim()) throw new Error('AI/ML API did not return an auth token.') + if (!isAuthResult(result)) throw new Error('AI/ML API did not return an auth token.') return result } async createPasswordlessAccount(email: string, signal?: AbortSignal): Promise { - const result = await this.request( + const result = await this.request( `${this.endpoints.authBaseUrl}/v1/auth/account/passwordless`, { method: 'POST', body: { email }, signal }, ) - if (!result.token?.trim()) throw new Error('AI/ML API did not return an auth token.') + if (!isAuthResult(result)) throw new Error('AI/ML API did not return an auth token.') return result } @@ -219,13 +248,13 @@ export class AimlapiClient { name: string, signal?: AbortSignal, ): Promise { - const result = await this.request(`${this.endpoints.appBaseUrl}/v1/keys`, { + const result = await this.request(`${this.endpoints.appBaseUrl}/v1/keys`, { method: 'POST', bearer, body: name.trim() ? { name: name.trim() } : {}, signal, }) - if (!result.key?.trim()) { + if (!isCreatedKey(result)) { throw new Error('AI/ML API did not return an API key.') } return result @@ -294,22 +323,24 @@ export class AimlapiClient { }, signal?: AbortSignal, ): Promise { - return this.request( - `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}/pay`, - { - method: 'POST', - bearer, - body: { - amountUsdMinor: input.amountUsdMinor, - paymentSessionId: input.paymentSessionId, - method: 'card', - ...(input.successUrl ? { successUrl: input.successUrl } : {}), - ...(input.cancelUrl ? { cancelUrl: input.cancelUrl } : {}), - ...(input.autoTopUp ? { autoTopUp: true } : {}), - }, - signal, + const url = `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}/pay` + const result = await this.request(url, { + method: 'POST', + bearer, + body: { + amountUsdMinor: input.amountUsdMinor, + paymentSessionId: input.paymentSessionId, + method: 'card', + ...(input.successUrl ? { successUrl: input.successUrl } : {}), + ...(input.cancelUrl ? { cancelUrl: input.cancelUrl } : {}), + ...(input.autoTopUp ? { autoTopUp: true } : {}), }, - ) + signal, + }) + if (!isPayResult(result)) { + throw new AimlapiApiError(`POST ${requestLabel(url)} returned an invalid checkout`, 200, '') + } + return result } async topUpByKey( @@ -328,7 +359,8 @@ export class AimlapiClient { .trim() .replace(/\/+$/, '') .replace(/\/v1$/i, '') - return this.request(`${inferenceBase}/v2/billing/topup`, { + const url = `${inferenceBase}/v2/billing/topup` + const result = await this.request(url, { method: 'POST', bearer: apiKey, body: { @@ -341,6 +373,10 @@ export class AimlapiClient { }, signal, }) + if (!isPayResult(result)) { + throw new AimlapiApiError(`POST ${requestLabel(url)} returned an invalid checkout`, 200, '') + } + return result } async exchange( @@ -348,10 +384,12 @@ export class AimlapiClient { sessionToken: string, signal?: AbortSignal, ): Promise { - return this.request( - `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}/exchange`, - { method: 'POST', bearer, signal }, - ) + const url = `${this.endpoints.appBaseUrl}/v3/partner-checkout/sessions/${encodeURIComponent(sessionToken)}/exchange` + const result = await this.request(url, { method: 'POST', bearer, signal }) + if (!isExchangeResult(result)) { + throw new AimlapiApiError(`POST ${requestLabel(url)} returned an invalid exchange response`, 200, '') + } + return result } private async request( diff --git a/src/integrations/aimlapi/config.ts b/src/integrations/aimlapi/config.ts index a590938366..57005db820 100644 --- a/src/integrations/aimlapi/config.ts +++ b/src/integrations/aimlapi/config.ts @@ -42,7 +42,7 @@ export const DEFAULT_PARTNER_NAME = 'Gitlawb' export const PARTNER_HEADER_NAME = 'X-AIMLAPI-Partner-ID' /** Default model id written into the profile - override with `--model`. */ -export const DEFAULT_MODEL = 'anthropic/claude-sonnet-5' +export const DEFAULT_MODEL = 'gpt-4o' export const DEFAULT_RETURN_URL = 'https://aimlapi.com/app' /** Top-up bounds enforced by the backend DTO (USD minor units / cents). */ diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index 80fdc51586..59140da151 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -218,7 +218,8 @@ test('a failed payment retains the issued key for the next run', async () => { process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' process.env.AIMLAPI_APP_URL = 'https://app.example.test' process.env.AIMLAPI_PAY_URL = 'https://pay.example.test' - process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + // Keep the canonical inference URL so the guided-provisioning gate allows the + // run; the flow uses the app/auth/pay hosts for its requests. let keyMints = 0 let sessionStatus = 'expired' diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index 9f9fa037c2..1e91313c68 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -12,6 +12,7 @@ import { buildPartnerReturnUrl, DEFAULT_MODEL, DEFAULT_PARTNER_NAME, + isCanonicalAimlapiInferenceBaseUrl, resolveEndpoints, resolvePartnerId, } from './config.js' @@ -128,13 +129,22 @@ export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { + const profilePath = saveProfileFile({ + profile: 'openai', + env: { + OPENAI_BASE_URL: provisioned.baseUrl, + OPENAI_API_KEY: provisioned.apiKey, + AIMLAPI_API_KEY: provisioned.apiKey, + OPENAI_MODEL: provisioned.model, + CLAUDE_CODE_PROVIDER_ROUTE_ID: 'aimlapi', + }, + createdAt: new Date().toISOString(), + }) + clearAimlapiTopupState({ ...intent, paymentSessionId: checkoutState.paymentSessionId }) + console.log(chalk.green('\n [OK] Balance topped up and provider configured.')) + console.log(` key ${chalk.dim(maskKey(provisioned.apiKey))} (id ${provisioned.apiKeyId})`) + console.log(` base URL ${chalk.dim(provisioned.baseUrl)}`) + console.log(` model ${chalk.dim(provisioned.model)}`) + console.log(` profile ${chalk.dim(profilePath)}`) + } + + // Resume: a prior run provisioned the key but was interrupted before the + // profile write. Finish that last step with the retained key instead of + // re-provisioning a now-exchanged (otherwise stranded) session. + if (checkoutState.settled && checkoutState.apiKey) { + finishProfile({ + apiKey: checkoutState.apiKey, + apiKeyId: checkoutState.apiKeyId ?? '', + baseUrl: endpoints.inferenceBaseUrl, + model: options.model?.trim() || DEFAULT_MODEL, + }) + return + } + + const account = await client.checkAccount(email, options.signal) const persistSession = (resumeSessionToken: string): void => { if (!resumeSessionToken) { // A terminal checkout invalidates the payment session, but a minted @@ -234,27 +279,15 @@ export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise function statePath(): string { @@ -189,7 +196,8 @@ function isPersistedTopup(value: unknown): value is AimlapiPersistedTopup { Boolean(state.paymentSessionId.trim()) && typeof state.resumeSessionToken === 'string' && (state.apiKey === undefined || typeof state.apiKey === 'string') && - (state.apiKeyId === undefined || typeof state.apiKeyId === 'string') + (state.apiKeyId === undefined || typeof state.apiKeyId === 'string') && + (state.settled === undefined || typeof state.settled === 'boolean') ) } @@ -229,6 +237,7 @@ export function loadAimlapiTopupState( resumeSessionToken: state.resumeSessionToken, apiKey: state.apiKey, apiKeyId: state.apiKeyId, + settled: state.settled, } } @@ -257,6 +266,7 @@ export function claimAimlapiTopupState( resumeSessionToken: existing.resumeSessionToken, apiKey: existing.apiKey, apiKeyId: existing.apiKeyId, + settled: existing.settled, } } const claimed: AimlapiCheckoutState = { diff --git a/src/integrations/discoveryService.test.ts b/src/integrations/discoveryService.test.ts index 17acb1bc7f..bb56f6c9d5 100644 --- a/src/integrations/discoveryService.test.ts +++ b/src/integrations/discoveryService.test.ts @@ -468,14 +468,13 @@ describe('discoverModelsForRoute', () => { 'X-Title': 'OpenClaude', }) expect(result?.models.map((model: { apiName: string }) => model.apiName)).toEqual([ - 'anthropic/claude-sonnet-5', 'gpt-4o', 'gemini-2.5-pro', 'GLM-5.2', ]) - expect(result?.models.find((model: { apiName: string }) => model.apiName === 'anthropic/claude-sonnet-5')).toMatchObject({ - id: 'aimlapi-claude-sonnet-5', - label: 'Claude Sonnet 5', + expect(result?.models.find((model: { apiName: string }) => model.apiName === 'gpt-4o')).toMatchObject({ + id: 'aimlapi-gpt-4o', + label: 'GPT-4o', }) expect(result?.models.find((model: { apiName: string }) => model.apiName === 'gemini-2.5-pro')).toMatchObject({ label: 'Gemini 2.5 Pro (Google)', @@ -539,10 +538,10 @@ describe('discoverModelsForRoute', () => { // Only `openai/chat-completions` entries survive discovery; the duplicate // gpt-3.5-turbo (responses/submit), embeddings, image, and anthropic - // endpoint types are dropped. The curated Sonnet default rides along from - // the hybrid catalog. + // endpoint types are dropped. The curated `gpt-4o` rides along from the + // hybrid catalog. expect(result?.models.map((model: { apiName: string }) => model.apiName)).toEqual([ - 'anthropic/claude-sonnet-5', + 'gpt-4o', 'gpt-3.5-turbo', 'claude-opus-4-1-20250805', ]) diff --git a/src/integrations/gateways/aimlapi.ts b/src/integrations/gateways/aimlapi.ts index d47cad5dd8..df97d57063 100644 --- a/src/integrations/gateways/aimlapi.ts +++ b/src/integrations/gateways/aimlapi.ts @@ -61,7 +61,7 @@ export default defineGateway({ label: 'aimlapi.com', category: 'aggregating', defaultBaseUrl: 'https://api.aimlapi.com/v1', - defaultModel: 'anthropic/claude-sonnet-5', + defaultModel: 'gpt-4o', supportsModelRouting: true, setup: { requiresAuth: true, @@ -116,10 +116,10 @@ export default defineGateway({ allowManualRefresh: true, models: [ { - id: 'aimlapi-claude-sonnet-5', - apiName: 'anthropic/claude-sonnet-5', - label: 'Claude Sonnet 5', - modelDescriptorId: 'claude-sonnet-4-6', + id: 'aimlapi-gpt-4o', + apiName: 'gpt-4o', + label: 'GPT-4o', + modelDescriptorId: 'gpt-4o', }, ], }, diff --git a/src/integrations/routeMetadata.test.ts b/src/integrations/routeMetadata.test.ts index 40b88c04b9..75517d45f6 100644 --- a/src/integrations/routeMetadata.test.ts +++ b/src/integrations/routeMetadata.test.ts @@ -277,7 +277,7 @@ test('Venice route metadata uses official OpenAI-compatible defaults', () => { test('AI/ML API route metadata uses official OpenAI-compatible defaults', () => { expect(getRouteDefaultBaseUrl('aimlapi')).toBe('https://api.aimlapi.com/v1') - expect(getRouteDefaultModel('aimlapi')).toBe('anthropic/claude-sonnet-5') + expect(getRouteDefaultModel('aimlapi')).toBe('gpt-4o') expect(resolveRouteIdFromBaseUrl('https://api.aimlapi.com/v1')).toBe('aimlapi') expect(resolveRouteIdFromBaseUrl('https://api.aimlapi.com/v1/chat/completions')).toBe('aimlapi') }) @@ -556,7 +556,7 @@ test.each([ ['OpenRouter', 'https://openrouter.ai/api/v1', 'openai/gpt-5-mini', 'openrouter'], ['DeepSeek', 'https://api.deepseek.com/v1', 'deepseek-v4-pro', 'deepseek'], ['Hicap', 'https://api.hicap.ai/v1', 'claude-opus-4.8', 'hicap'], - ['aimlapi.com', 'https://api.aimlapi.com/v1', 'anthropic/claude-sonnet-5', 'aimlapi'], + ['aimlapi.com', 'https://api.aimlapi.com/v1', 'gpt-4o', 'aimlapi'], ['Xiaomi MiMo', 'https://api.xiaomimimo.com/v1', 'mimo-v2.5-pro', 'xiaomi-mimo'], ['Venice', 'https://api.venice.ai/api/v1', 'venice-uncensored', 'venice'], ])( diff --git a/src/integrations/runtimeMetadata.test.ts b/src/integrations/runtimeMetadata.test.ts index 388558d6d3..b6dccb314c 100644 --- a/src/integrations/runtimeMetadata.test.ts +++ b/src/integrations/runtimeMetadata.test.ts @@ -170,7 +170,7 @@ describe('AIMLAPI runtime attribution', () => { const canonical = resolveOpenAIShimRuntimeContext({ activeProfileProvider: 'aimlapi', baseUrl: 'https://api.aimlapi.com/v1', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', }) expect(canonical.openaiShimConfig.headers?.['X-AIMLAPI-Partner-ID']).toBe( 'part_runtime_override', @@ -179,7 +179,7 @@ describe('AIMLAPI runtime attribution', () => { const proxy = resolveOpenAIShimRuntimeContext({ activeProfileProvider: 'aimlapi', baseUrl: 'https://proxy.example.test/v1', - model: 'anthropic/claude-sonnet-5', + model: 'gpt-4o', }) expect(proxy.openaiShimConfig.headers?.['X-AIMLAPI-Partner-ID']).toBeUndefined() expect(proxy.openaiShimConfig.headers?.['X-AIMLAPI-Integration-Repo']).toBeUndefined() diff --git a/src/services/api/client.test.ts b/src/services/api/client.test.ts index c75700cfeb..9f5a776105 100644 --- a/src/services/api/client.test.ts +++ b/src/services/api/client.test.ts @@ -814,7 +814,7 @@ test('routes env-only AI/ML API requests through the OpenAI-compatible shim desp expect(capturedBody?.model).toBe('gpt-4o') expect(process.env.CLAUDE_CODE_USE_OPENAI).toBe('1') expect(process.env.OPENAI_BASE_URL).toBe('https://api.aimlapi.com/v1') - expect(process.env.OPENAI_MODEL).toBe('anthropic/claude-sonnet-5') + expect(process.env.OPENAI_MODEL).toBe('gpt-4o') expect(process.env.OPENAI_API_KEY).toBe('aimlapi-test-key') expect(response).toMatchObject({ role: 'assistant', diff --git a/src/utils/providerProfiles.test.ts b/src/utils/providerProfiles.test.ts index 1ad39d796f..ae967cf338 100644 --- a/src/utils/providerProfiles.test.ts +++ b/src/utils/providerProfiles.test.ts @@ -2449,7 +2449,7 @@ describe('getProviderPresetDefaults', () => { expect(defaults.provider).toBe('aimlapi') expect(defaults.name).toBe('aimlapi.com') expect(defaults.baseUrl).toBe('https://api.aimlapi.com/v1') - expect(defaults.model).toBe('anthropic/claude-sonnet-5') + expect(defaults.model).toBe('gpt-4o') expect(defaults.apiKey).toBe('aimlapi-live-key') expect(defaults.requiresApiKey).toBe(true) }) From 6cc4f45e15691cfc8fc605be69ca673e57bf6b84 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Sat, 18 Jul 2026 02:18:13 +0500 Subject: [PATCH 16/17] fix(aimlapi): reuse sign-in key in the UI; require key ids; persist provisioned model - Provider-manager: cache the existing-account key minted at code sign-in by email and reuse it (loadAimlapiSignInKey/saveAimlapiSignInKey) so closing before amount entry or restarting a checkout no longer mints another key; completeAimlapiCodeSignIn accepts a supplied key; clear the cache on success - client: isCreatedKey/isExchangeResult now require the id/apiKeyId identifiers so a key-only 200 cannot yield an incomplete settled receipt - topupState/topup: persist the provisioned model in the settled receipt and prefer it on resume, so a retry with a different --model cannot silently reconfigure the recovered profile - tests: sign-in key round-trip, key-reuse sign-in, CLI canonical gate, settled resume (incl. model preservation), and wrong-typed/partial response guards --- src/components/ProviderManager.test.tsx | 6 ++ src/components/ProviderManager.tsx | 12 +++ src/components/providerManagerAimlapi.ts | 15 ++++ src/integrations/aimlapi/client.test.ts | 41 ++++++++++ src/integrations/aimlapi/client.ts | 4 +- src/integrations/aimlapi/onboarding.test.ts | 28 +++++++ src/integrations/aimlapi/onboarding.ts | 21 ++++-- src/integrations/aimlapi/topup.test.ts | 67 +++++++++++++++- src/integrations/aimlapi/topup.ts | 11 ++- src/integrations/aimlapi/topupState.test.ts | 21 ++++++ src/integrations/aimlapi/topupState.ts | 84 ++++++++++++++++++++- 11 files changed, 296 insertions(+), 14 deletions(-) diff --git a/src/components/ProviderManager.test.tsx b/src/components/ProviderManager.test.tsx index 8fc7ce5e3a..845cf091a1 100644 --- a/src/components/ProviderManager.test.tsx +++ b/src/components/ProviderManager.test.tsx @@ -356,6 +356,9 @@ function mockProviderManagerDependencies( claimAimlapiTopupState?: (...args: any[]) => unknown clearAimlapiTopupState?: (...args: any[]) => unknown saveAimlapiTopupState?: (...args: any[]) => unknown + loadAimlapiSignInKey?: (...args: any[]) => unknown + saveAimlapiSignInKey?: (...args: any[]) => unknown + clearAimlapiSignInKey?: (...args: any[]) => unknown useCodexOAuthFlow?: (options: { onAuthenticated: ( tokens: { @@ -535,6 +538,9 @@ function mockProviderManagerDependencies( ((state: Record) => { persistedAimlapiTopup = state }), + loadAimlapiSignInKey: options?.loadAimlapiSignInKey ?? (() => null), + saveAimlapiSignInKey: options?.saveAimlapiSignInKey ?? (() => {}), + clearAimlapiSignInKey: options?.clearAimlapiSignInKey ?? (() => {}), parseAimlapiAmountUsd: (value: string | undefined) => { const amount = Number(value || 25) if (!Number.isFinite(amount) || amount < 20 || amount > 10000) { diff --git a/src/components/ProviderManager.tsx b/src/components/ProviderManager.tsx index 182345d549..801d2dbf49 100644 --- a/src/components/ProviderManager.tsx +++ b/src/components/ProviderManager.tsx @@ -61,6 +61,9 @@ import { claimAimlapiTopupState, clearAimlapiTopupState, saveAimlapiTopupState, + loadAimlapiSignInKey, + saveAimlapiSignInKey, + clearAimlapiSignInKey, type AimlapiTopupIntent, type AimlapiTopupStatus, } from './providerManagerAimlapi.js' @@ -2863,6 +2866,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { deferNavigation: true, onSaved: () => { resetAimlapiCheckoutIntent() + clearAimlapiSignInKey() setAimlapiDoneKind(aimlapiTopupPaidRef.current ? 'topup' : 'ready') setErrorMessage(undefined) setScreen('aimlapi-done') @@ -2961,6 +2965,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { deferNavigation: true, onSaved: () => { resetAimlapiCheckoutIntent() + clearAimlapiSignInKey() setAimlapiDoneKind(doneKind) setErrorMessage(undefined) setScreen('aimlapi-done') @@ -3041,12 +3046,19 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { void (async () => { try { + // Reuse a key already minted for this email (e.g. after closing before + // amount entry or restarting a checkout) instead of creating another. + const retainedSignInKey = loadAimlapiSignInKey(aimlapiTopupEmail) const result = await completeAimlapiCodeSignIn( aimlapiTopupEmail, trimmedCode, controller.signal, aimlapiInferenceBaseUrl, + retainedSignInKey ?? undefined, ) + // Persist immediately so an abort/restart before the checkout completes + // recovers this key rather than minting a second one. + saveAimlapiSignInKey(aimlapiTopupEmail, result.apiKey, result.apiKeyId) setAimlapiSessionToken(result.sessionToken) setAimlapiIssuedKey(result.apiKey) setAimlapiIssuedKeyId(result.apiKeyId) diff --git a/src/components/providerManagerAimlapi.ts b/src/components/providerManagerAimlapi.ts index 7cb31f95ce..7fafd6f006 100644 --- a/src/components/providerManagerAimlapi.ts +++ b/src/components/providerManagerAimlapi.ts @@ -11,6 +11,9 @@ import { claimAimlapiTopupState as claimAimlapiTopupStateImpl, clearAimlapiTopupState as clearAimlapiTopupStateImpl, saveAimlapiTopupState as saveAimlapiTopupStateImpl, + loadAimlapiSignInKey as loadAimlapiSignInKeyImpl, + saveAimlapiSignInKey as saveAimlapiSignInKeyImpl, + clearAimlapiSignInKey as clearAimlapiSignInKeyImpl, } from '../integrations/aimlapi/topupState.js' import type { AimlapiPersistedTopup, @@ -55,3 +58,15 @@ export const clearAimlapiTopupState: typeof clearAimlapiTopupStateImpl = intent export const saveAimlapiTopupState: typeof saveAimlapiTopupStateImpl = state => saveAimlapiTopupStateImpl(state) + +export const loadAimlapiSignInKey: typeof loadAimlapiSignInKeyImpl = email => + loadAimlapiSignInKeyImpl(email) + +export const saveAimlapiSignInKey: typeof saveAimlapiSignInKeyImpl = ( + email, + apiKey, + apiKeyId, +) => saveAimlapiSignInKeyImpl(email, apiKey, apiKeyId) + +export const clearAimlapiSignInKey: typeof clearAimlapiSignInKeyImpl = () => + clearAimlapiSignInKeyImpl() diff --git a/src/integrations/aimlapi/client.test.ts b/src/integrations/aimlapi/client.test.ts index ac1f79e6c8..24029bab11 100644 --- a/src/integrations/aimlapi/client.test.ts +++ b/src/integrations/aimlapi/client.test.ts @@ -253,3 +253,44 @@ test('session methods reject a malformed or empty success payload', async () => expect(badStatusError).toBeInstanceOf(AimlapiApiError) expect(badStatusError).toHaveProperty('status', 200) }) + +test('typed methods reject wrong-typed success fields without a raw TypeError', async () => { + const client = new AimlapiClient(endpoints) + + // A 2xx payload with a numeric token/key/apiKey must not reach .trim(). + globalThis.fetch = mock(async () => jsonResponse({ token: 1 })) as unknown as typeof fetch + await expect(client.verifySignInCode('user@example.com', '123456')).rejects.toThrow( + 'did not return an auth token', + ) + await expect(client.createPasswordlessAccount('user@example.com')).rejects.toThrow( + 'did not return an auth token', + ) + + globalThis.fetch = mock(async () => jsonResponse({ key: 1 })) as unknown as typeof fetch + await expect(client.createKey('bearer', 'OpenClaude CLI')).rejects.toThrow( + 'did not return an API key', + ) + // Key without its required id is an incomplete receipt and must be rejected. + globalThis.fetch = mock(async () => jsonResponse({ key: 'k_only' })) as unknown as typeof fetch + await expect(client.createKey('bearer', 'OpenClaude CLI')).rejects.toThrow( + 'did not return an API key', + ) + + globalThis.fetch = mock(async () => jsonResponse({ apiKey: 1 })) as unknown as typeof fetch + const exchangeError = await client.exchange('bearer', 'session').catch((e: unknown) => e) + expect(exchangeError).toBeInstanceOf(AimlapiApiError) + expect(exchangeError).toHaveProperty('status', 200) + + // apiKey without its required apiKeyId is an incomplete exchange receipt. + globalThis.fetch = mock(async () => + jsonResponse({ apiKey: 'k_only' }), + ) as unknown as typeof fetch + const partialExchange = await client.exchange('bearer', 'session').catch((e: unknown) => e) + expect(partialExchange).toBeInstanceOf(AimlapiApiError) + expect(partialExchange).toHaveProperty('status', 200) + + globalThis.fetch = mock(async () => jsonResponse({ action: 1 })) as unknown as typeof fetch + const accountError = await client.checkAccount('user@example.com').catch((e: unknown) => e) + expect(accountError).toBeInstanceOf(AimlapiApiError) + expect(accountError).toHaveProperty('status', 200) +}) diff --git a/src/integrations/aimlapi/client.ts b/src/integrations/aimlapi/client.ts index 8de290cc31..845f2a93cf 100644 --- a/src/integrations/aimlapi/client.ts +++ b/src/integrations/aimlapi/client.ts @@ -116,11 +116,11 @@ function isAuthResult(value: unknown): value is AuthResult { } function isCreatedKey(value: unknown): value is CreatedKey { - return isRecord(value) && isNonEmptyString(value.key) + return isRecord(value) && isNonEmptyString(value.key) && isNonEmptyString(value.id) } function isExchangeResult(value: unknown): value is ExchangeResult { - return isRecord(value) && isNonEmptyString(value.apiKey) + return isRecord(value) && isNonEmptyString(value.apiKey) && isNonEmptyString(value.apiKeyId) } function isPayResult(value: unknown): value is PayResult { diff --git a/src/integrations/aimlapi/onboarding.test.ts b/src/integrations/aimlapi/onboarding.test.ts index 1dd4853dc1..ff977bb7c3 100644 --- a/src/integrations/aimlapi/onboarding.test.ts +++ b/src/integrations/aimlapi/onboarding.test.ts @@ -136,3 +136,31 @@ test('unknown account actions are rejected instead of signing up', async () => { 'unsupported account action', ) }) + +test('completeAimlapiCodeSignIn reuses a supplied key instead of minting a new one', async () => { + process.env.AIMLAPI_AUTH_URL = 'https://auth.example.test' + process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' + const calls: string[] = [] + globalThis.fetch = mock(async (input: string | URL | Request) => { + const url = String(input) + calls.push(url) + if (url.endsWith('/code/verify')) return response({ token: 'bearer', exp: 1 }) + if (url.endsWith('/billing/balance')) { + return response({ balance: 100, lowBalance: false, lowBalanceThreshold: 20 }) + } + throw new Error(`Unexpected request: ${url}`) + }) as unknown as typeof fetch + + const result = await completeAimlapiCodeSignIn( + 'user@example.com', + '123456', + undefined, + 'https://api.example.test/v1', + { apiKey: 'existing-key', apiKeyId: 'existing-id' }, + ) + + expect(result.apiKey).toBe('existing-key') + expect(result.apiKeyId).toBe('existing-id') + // No key was minted; only verify + balance were called. + expect(calls.some(call => call.endsWith('/v1/keys'))).toBe(false) +}) diff --git a/src/integrations/aimlapi/onboarding.ts b/src/integrations/aimlapi/onboarding.ts index 3342ba6d58..5c652c45c9 100644 --- a/src/integrations/aimlapi/onboarding.ts +++ b/src/integrations/aimlapi/onboarding.ts @@ -52,16 +52,25 @@ export async function completeAimlapiCodeSignIn( code: string, signal?: AbortSignal, inferenceBaseUrl?: string, + existingKey?: { apiKey: string; apiKeyId: string }, ): Promise { const client = clientForInferenceBaseUrl(inferenceBaseUrl) const auth = await client.verifySignInCode(email, code, signal) - const created = await client.createKey(auth.token, 'OpenClaude CLI', signal) + let apiKey = existingKey?.apiKey?.trim() ?? '' + let apiKeyId = existingKey?.apiKeyId ?? '' + if (!apiKey) { + // Reuse a previously issued key when one is supplied so a restart does not + // mint a second key for the same account. + const created = await client.createKey(auth.token, 'OpenClaude CLI', signal) + apiKey = created.key + apiKeyId = created.id + } try { - const balance = await client.getBalance(created.key, signal) + const balance = await client.getBalance(apiKey, signal) return { sessionToken: auth.token, - apiKey: created.key, - apiKeyId: created.id, + apiKey, + apiKeyId, balanceStatus: 'confirmed', lowBalance: balance.lowBalance, } @@ -70,8 +79,8 @@ export async function completeAimlapiCodeSignIn( // The key is already issued; a balance read failure must not discard it. return { sessionToken: auth.token, - apiKey: created.key, - apiKeyId: created.id, + apiKey, + apiKeyId, balanceStatus: 'unknown', balanceError: error instanceof Error ? error.message : String(error), } diff --git a/src/integrations/aimlapi/topup.test.ts b/src/integrations/aimlapi/topup.test.ts index 59140da151..e70ab16fff 100644 --- a/src/integrations/aimlapi/topup.test.ts +++ b/src/integrations/aimlapi/topup.test.ts @@ -8,9 +8,13 @@ import * as realTopupDependencies from './topupDependencies.js' import { claimAimlapiTopupState, saveAimlapiTopupState } from './topupState.js' import { isValidAimlapiEmail, parseAimlapiAmountUsd } from './validation.js' +let lastSavedProfileEnv: Record | undefined mock.module('./topupDependencies.js', () => ({ openBrowser: async () => {}, - saveProfileFile: () => 'profile.json', + saveProfileFile: (arg: { env: Record }) => { + lastSavedProfileEnv = arg.env + return 'profile.json' + }, promptText: async () => '', })) const { pollUntilPaid, provisionAimlapiKey, runAimlapiTopup, topUpAimlapiByApiKey } = @@ -47,6 +51,7 @@ afterAll(() => { afterEach(() => { globalThis.fetch = originalFetch + lastSavedProfileEnv = undefined setClaudeConfigHomeDirForTesting(undefined) for (const directory of temporaryDirectories.splice(0)) { rmSync(directory, { force: true, recursive: true }) @@ -271,6 +276,66 @@ test('a failed payment retains the issued key for the next run', async () => { expect(() => readFileSync(join(configDirectory, 'aimlapi-topup.json'))).toThrow() }) +test('the CLI refuses guided top-up on a non-canonical inference endpoint', async () => { + process.env.AIMLAPI_INFERENCE_URL = 'https://proxy.example.test/v1' + let fetched = false + globalThis.fetch = mock(async () => { + fetched = true + return Response.json({}) + }) as unknown as typeof fetch + + await expect( + runAimlapiTopup({ email: 'user@example.com', amountUsd: '25', noOpen: true }), + ).rejects.toThrow('production endpoint') + // Rejected before any account lookup or key mint. + expect(fetched).toBe(false) +}) + +test('a settled interrupted run resumes the profile write without re-provisioning', async () => { + const configDirectory = mkdtempSync(join(tmpdir(), 'openclaude-aimlapi-cli-')) + temporaryDirectories.push(configDirectory) + setClaudeConfigHomeDirForTesting(configDirectory) + const intent = { + email: 'user@example.com', + amountUsdMinor: 2500, + autoTopUp: false, + partnerId: 'part_62yQoGYDq4Yqnrj2R1iGrDNJ', + partnerName: 'Gitlawb', + appBaseUrl: 'https://app.aimlapi.com', + inferenceBaseUrl: 'https://api.aimlapi.com/v1', + payBaseUrl: 'https://pay.aimlapi.com', + verificationBaseUrl: 'https://aimlapi.com/app', + } + const claimed = claimAimlapiTopupState(intent) + saveAimlapiTopupState({ + ...intent, + paymentSessionId: claimed.paymentSessionId, + resumeSessionToken: 'checkout-session', + apiKey: 'exchanged-key', + apiKeyId: 'exchanged-id', + // Original run provisioned a non-default model. + model: 'anthropic/claude-opus-4-8', + settled: true, + }) + + let fetched = false + globalThis.fetch = mock(async () => { + fetched = true + return Response.json({}) + }) as unknown as typeof fetch + + // Retry without --model: the default would be gpt-4o, but the settled receipt + // must win. + await runAimlapiTopup({ email: 'user@example.com', amountUsd: '25', noOpen: true }) + + // The retained settled key finished the write — no account check/provisioning, + // the persisted model is preserved, and the checkout state is cleared. + expect(fetched).toBe(false) + expect(lastSavedProfileEnv?.OPENAI_API_KEY).toBe('exchanged-key') + expect(lastSavedProfileEnv?.OPENAI_MODEL).toBe('anthropic/claude-opus-4-8') + expect(() => readFileSync(join(configDirectory, 'aimlapi-topup.json'))).toThrow() +}) + test('topUpAimlapiByApiKey funds the key account without exchange', async () => { process.env.AIMLAPI_APP_URL = 'https://app.example.test' process.env.AIMLAPI_INFERENCE_URL = 'https://api.example.test/v1' diff --git a/src/integrations/aimlapi/topup.ts b/src/integrations/aimlapi/topup.ts index 1e91313c68..7538015ba4 100644 --- a/src/integrations/aimlapi/topup.ts +++ b/src/integrations/aimlapi/topup.ts @@ -189,7 +189,9 @@ export async function runAimlapiTopup(options: AimlapiTopupOptions): Promise { expect(current.paymentSessionId).not.toBe(stale.paymentSessionId) expect(loadAimlapiTopupState(intent)).toEqual(current) }) + +test('sign-in key cache round-trips by normalized email and clears', () => { + useTemporaryConfig() + + expect(loadAimlapiSignInKey('User@Example.com')).toBeNull() + + saveAimlapiSignInKey('User@Example.com', 'k_signin', 'id_signin') + // Lookup is case/whitespace-insensitive on the email. + expect(loadAimlapiSignInKey('user@example.com')).toEqual({ + apiKey: 'k_signin', + apiKeyId: 'id_signin', + }) + // A different email must not read this key. + expect(loadAimlapiSignInKey('other@example.com')).toBeNull() + + clearAimlapiSignInKey() + expect(loadAimlapiSignInKey('user@example.com')).toBeNull() +}) diff --git a/src/integrations/aimlapi/topupState.ts b/src/integrations/aimlapi/topupState.ts index b8b458aba7..51110d4803 100644 --- a/src/integrations/aimlapi/topupState.ts +++ b/src/integrations/aimlapi/topupState.ts @@ -35,6 +35,12 @@ export type AimlapiPersistedTopup = AimlapiTopupIntent & { */ apiKey?: string apiKeyId?: string + /** + * Model chosen for this provisioning; retained with the settled receipt so a + * resumed profile write configures the original model instead of recomputing + * it from (possibly different) retry arguments. + */ + model?: string /** * Set once payment/exchange has completed and `apiKey` is the final * provisioned credential. The next run then resumes the profile write with @@ -46,7 +52,12 @@ export type AimlapiPersistedTopup = AimlapiTopupIntent & { type AimlapiCheckoutState = Pick< AimlapiPersistedTopup, - 'paymentSessionId' | 'resumeSessionToken' | 'apiKey' | 'apiKeyId' | 'settled' + | 'paymentSessionId' + | 'resumeSessionToken' + | 'apiKey' + | 'apiKeyId' + | 'model' + | 'settled' > function statePath(): string { @@ -197,6 +208,7 @@ function isPersistedTopup(value: unknown): value is AimlapiPersistedTopup { typeof state.resumeSessionToken === 'string' && (state.apiKey === undefined || typeof state.apiKey === 'string') && (state.apiKeyId === undefined || typeof state.apiKeyId === 'string') && + (state.model === undefined || typeof state.model === 'string') && (state.settled === undefined || typeof state.settled === 'boolean') ) } @@ -237,6 +249,7 @@ export function loadAimlapiTopupState( resumeSessionToken: state.resumeSessionToken, apiKey: state.apiKey, apiKeyId: state.apiKeyId, + model: state.model, settled: state.settled, } } @@ -266,6 +279,7 @@ export function claimAimlapiTopupState( resumeSessionToken: existing.resumeSessionToken, apiKey: existing.apiKey, apiKeyId: existing.apiKeyId, + model: existing.model, settled: existing.settled, } } @@ -328,3 +342,71 @@ export function clearAimlapiTopupState( } }) } + +// --- Sign-in key cache ------------------------------------------------------ +// The guided provider-manager mints an existing-account key at code sign-in, +// before the top-up amount (and therefore the full checkout intent) is known. +// This lightweight per-email cache retains that key so a restart before/without +// completing the checkout reuses it instead of minting another one. + +type AimlapiSignInKey = { email: string; apiKey: string; apiKeyId: string } + +function signInKeyPath(): string { + return join(getClaudeConfigHomeDir(), 'aimlapi-signin-key.json') +} + +function normalizeEmail(email: string): string { + return email.trim().toLowerCase() +} + +export function loadAimlapiSignInKey( + email: string, +): { apiKey: string; apiKeyId: string } | null { + try { + const raw: unknown = JSON.parse(readFileSync(signInKeyPath(), 'utf8')) + if ( + typeof raw === 'object' && + raw !== null && + typeof (raw as Record).email === 'string' && + (raw as AimlapiSignInKey).email === normalizeEmail(email) && + typeof (raw as Record).apiKey === 'string' && + (raw as AimlapiSignInKey).apiKey.trim() + ) { + const record = raw as AimlapiSignInKey + return { + apiKey: record.apiKey, + apiKeyId: typeof record.apiKeyId === 'string' ? record.apiKeyId : '', + } + } + } catch { + // Missing/corrupt cache: mint a fresh key. + } + return null +} + +export function saveAimlapiSignInKey( + email: string, + apiKey: string, + apiKeyId: string, +): void { + if (!apiKey.trim()) return + const target = signInKeyPath() + mkdirSync(dirname(target), { recursive: true }) + const temporary = `${target}.${process.pid}.${randomUUID()}.tmp` + const record: AimlapiSignInKey = { email: normalizeEmail(email), apiKey, apiKeyId } + try { + writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { + encoding: 'utf8', + flag: 'wx', + mode: 0o600, + }) + chmodSync(temporary, 0o600) + renameSync(temporary, target) + } finally { + rmSync(temporary, { force: true }) + } +} + +export function clearAimlapiSignInKey(): void { + rmSync(signInKeyPath(), { force: true }) +} From d3abefd05a5190844ded0f8d54776084edc1f5c7 Mon Sep 17 00:00:00 2001 From: Lookoff123 Date: Sat, 18 Jul 2026 02:39:45 +0500 Subject: [PATCH 17/17] fix(aimlapi): harden sign-in key cache integrity Require a non-empty apiKeyId on both load and save of the sign-in key cache so an incomplete receipt can no longer bypass createKey and propagate an empty identifier through onboarding. Make clearAimlapiSignInKey ownership-aware: it now takes the owning email and apiKeyId and deletes under the state lock only when the cached record still matches, so a stale completion cannot remove a newer key another concurrent flow cached for a different email. --- src/components/ProviderManager.tsx | 4 +- src/components/providerManagerAimlapi.ts | 6 +- src/integrations/aimlapi/topupState.test.ts | 54 +++++++++++- src/integrations/aimlapi/topupState.ts | 93 +++++++++++++-------- 4 files changed, 115 insertions(+), 42 deletions(-) diff --git a/src/components/ProviderManager.tsx b/src/components/ProviderManager.tsx index 801d2dbf49..2e4cc9142d 100644 --- a/src/components/ProviderManager.tsx +++ b/src/components/ProviderManager.tsx @@ -2866,7 +2866,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { deferNavigation: true, onSaved: () => { resetAimlapiCheckoutIntent() - clearAimlapiSignInKey() + clearAimlapiSignInKey(aimlapiTopupEmail, aimlapiIssuedKeyId) setAimlapiDoneKind(aimlapiTopupPaidRef.current ? 'topup' : 'ready') setErrorMessage(undefined) setScreen('aimlapi-done') @@ -2965,7 +2965,7 @@ export function ProviderManager({ mode, onDone }: Props): React.ReactNode { deferNavigation: true, onSaved: () => { resetAimlapiCheckoutIntent() - clearAimlapiSignInKey() + clearAimlapiSignInKey(aimlapiTopupEmail, aimlapiIssuedKeyId) setAimlapiDoneKind(doneKind) setErrorMessage(undefined) setScreen('aimlapi-done') diff --git a/src/components/providerManagerAimlapi.ts b/src/components/providerManagerAimlapi.ts index 7fafd6f006..56c68a6dee 100644 --- a/src/components/providerManagerAimlapi.ts +++ b/src/components/providerManagerAimlapi.ts @@ -68,5 +68,7 @@ export const saveAimlapiSignInKey: typeof saveAimlapiSignInKeyImpl = ( apiKeyId, ) => saveAimlapiSignInKeyImpl(email, apiKey, apiKeyId) -export const clearAimlapiSignInKey: typeof clearAimlapiSignInKeyImpl = () => - clearAimlapiSignInKeyImpl() +export const clearAimlapiSignInKey: typeof clearAimlapiSignInKeyImpl = ( + email, + apiKeyId, +) => clearAimlapiSignInKeyImpl(email, apiKeyId) diff --git a/src/integrations/aimlapi/topupState.test.ts b/src/integrations/aimlapi/topupState.test.ts index 77c2f4d178..334649828e 100644 --- a/src/integrations/aimlapi/topupState.test.ts +++ b/src/integrations/aimlapi/topupState.test.ts @@ -1,5 +1,12 @@ import { afterEach, expect, test } from 'bun:test' -import { mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs' +import { + existsSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' @@ -136,6 +143,49 @@ test('sign-in key cache round-trips by normalized email and clears', () => { // A different email must not read this key. expect(loadAimlapiSignInKey('other@example.com')).toBeNull() - clearAimlapiSignInKey() + clearAimlapiSignInKey('user@example.com', 'id_signin') + expect(loadAimlapiSignInKey('user@example.com')).toBeNull() +}) + +test('sign-in key cache rejects records missing the key identifier', () => { + const directory = useTemporaryConfig() + const cachePath = join(directory, 'aimlapi-signin-key.json') + + // A persisted record without a usable apiKeyId cannot bypass createKey. + writeFileSync( + cachePath, + JSON.stringify({ email: 'user@example.com', apiKey: 'k_signin', apiKeyId: '' }), + ) + expect(loadAimlapiSignInKey('user@example.com')).toBeNull() + + writeFileSync( + cachePath, + JSON.stringify({ email: 'user@example.com', apiKey: 'k_signin' }), + ) + expect(loadAimlapiSignInKey('user@example.com')).toBeNull() + + // The save guard refuses to persist an incomplete receipt in the first place. + rmSync(cachePath, { force: true }) + saveAimlapiSignInKey('user@example.com', 'k_signin', ' ') expect(loadAimlapiSignInKey('user@example.com')).toBeNull() + expect(existsSync(cachePath)).toBe(false) +}) + +test('sign-in key clear leaves a newer cached record intact', () => { + useTemporaryConfig() + saveAimlapiSignInKey('user@example.com', 'k_signin', 'id_signin') + + // A concurrent flow replaced the cache with a newer key for another email. + saveAimlapiSignInKey('other@example.com', 'k_other', 'id_other') + + // The stale completion for the original email/id must not delete it. + clearAimlapiSignInKey('user@example.com', 'id_signin') + expect(loadAimlapiSignInKey('other@example.com')).toEqual({ + apiKey: 'k_other', + apiKeyId: 'id_other', + }) + + // The owning flow still clears its own record. + clearAimlapiSignInKey('other@example.com', 'id_other') + expect(loadAimlapiSignInKey('other@example.com')).toBeNull() }) diff --git a/src/integrations/aimlapi/topupState.ts b/src/integrations/aimlapi/topupState.ts index 51110d4803..1d419bf8d9 100644 --- a/src/integrations/aimlapi/topupState.ts +++ b/src/integrations/aimlapi/topupState.ts @@ -83,8 +83,7 @@ function waitForLock(): void { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, LOCK_RETRY_MS) } -function withStateLock(operation: () => T): T { - const target = statePath() +function withStateLock(operation: () => T, target: string = statePath()): T { const lockPath = `${target}.lock` mkdirSync(dirname(target), { recursive: true }) const deadline = Date.now() + LOCK_TIMEOUT_MS @@ -359,29 +358,37 @@ function normalizeEmail(email: string): string { return email.trim().toLowerCase() } -export function loadAimlapiSignInKey( - email: string, -): { apiKey: string; apiKeyId: string } | null { +// A cached receipt is only useful if it can bypass createKey, which needs both +// the key and its identifier; treat a record missing either as absent so the +// flow mints a fresh, complete credential rather than propagating an empty id. +function isSignInKey(value: unknown): value is AimlapiSignInKey { + if (typeof value !== 'object' || value === null) return false + const record = value as Record + return ( + typeof record.email === 'string' && + typeof record.apiKey === 'string' && + Boolean(record.apiKey.trim()) && + typeof record.apiKeyId === 'string' && + Boolean(record.apiKeyId.trim()) + ) +} + +function readSignInKeyUnlocked(): AimlapiSignInKey | null { try { const raw: unknown = JSON.parse(readFileSync(signInKeyPath(), 'utf8')) - if ( - typeof raw === 'object' && - raw !== null && - typeof (raw as Record).email === 'string' && - (raw as AimlapiSignInKey).email === normalizeEmail(email) && - typeof (raw as Record).apiKey === 'string' && - (raw as AimlapiSignInKey).apiKey.trim() - ) { - const record = raw as AimlapiSignInKey - return { - apiKey: record.apiKey, - apiKeyId: typeof record.apiKeyId === 'string' ? record.apiKeyId : '', - } - } + return isSignInKey(raw) ? raw : null } catch { // Missing/corrupt cache: mint a fresh key. + return null } - return null +} + +export function loadAimlapiSignInKey( + email: string, +): { apiKey: string; apiKeyId: string } | null { + const record = readSignInKeyUnlocked() + if (!record || record.email !== normalizeEmail(email)) return null + return { apiKey: record.apiKey, apiKeyId: record.apiKeyId } } export function saveAimlapiSignInKey( @@ -389,24 +396,38 @@ export function saveAimlapiSignInKey( apiKey: string, apiKeyId: string, ): void { - if (!apiKey.trim()) return + if (!apiKey.trim() || !apiKeyId.trim()) return const target = signInKeyPath() - mkdirSync(dirname(target), { recursive: true }) - const temporary = `${target}.${process.pid}.${randomUUID()}.tmp` const record: AimlapiSignInKey = { email: normalizeEmail(email), apiKey, apiKeyId } - try { - writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { - encoding: 'utf8', - flag: 'wx', - mode: 0o600, - }) - chmodSync(temporary, 0o600) - renameSync(temporary, target) - } finally { - rmSync(temporary, { force: true }) - } + withStateLock(() => { + const temporary = `${target}.${process.pid}.${randomUUID()}.tmp` + try { + writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\n`, { + encoding: 'utf8', + flag: 'wx', + mode: 0o600, + }) + chmodSync(temporary, 0o600) + renameSync(temporary, target) + } finally { + rmSync(temporary, { force: true }) + } + }, target) } -export function clearAimlapiSignInKey(): void { - rmSync(signInKeyPath(), { force: true }) +// Delete the cache only when it still holds the record this flow saved. A stale +// completion must not remove a newer key another concurrent flow cached for a +// different email, which would force that flow to mint a redundant key. +export function clearAimlapiSignInKey(email: string, apiKeyId: string): void { + const target = signInKeyPath() + withStateLock(() => { + const record = readSignInKeyUnlocked() + if ( + record && + record.email === normalizeEmail(email) && + record.apiKeyId === apiKeyId + ) { + rmSync(target, { force: true }) + } + }, target) }