Skip to content

7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.

TypeScript

fix(cloudflare): verify account-scoped tokens via /accounts/{id}/tokens/verify (#297) (#298)

Tashfeene94b2c96cdf6
diff --git a/server/src/__tests__/providers/cloudflare.test.ts b/server/src/__tests__/providers/cloudflare.test.ts
index 8ae457e3..a36d6580 100644
--- a/server/src/__tests__/providers/cloudflare.test.ts
+++ b/server/src/__tests__/providers/cloudflare.test.ts
@@ -54,6 +54,66 @@ describe('CloudflareProvider', () => {
).rejects.toThrow(/account_id:api_token/);
});
+ describe('validateKey', () => {
+ it('validates via /user/tokens/verify when the token is user-scoped', async () => {
+ const calls: string[] = [];
+ vi.spyOn(global, 'fetch').mockImplementation(async (url) => {
+ calls.push(url as string);
+ return {
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ success: true, result: { status: 'active' } }),
+ } as any;
+ });
+
+ expect(await provider.validateKey('acc123:tok')).toBe(true);
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toBe('https://api.cloudflare.com/client/v4/user/tokens/verify');
+ });
+
+ it('falls back to the account-scoped endpoint when /user 403s (#297)', async () => {
+ const calls: string[] = [];
+ vi.spyOn(global, 'fetch').mockImplementation(async (url) => {
+ calls.push(url as string);
+ if ((url as string).includes('/user/tokens/verify')) {
+ return { ok: false, status: 403, json: () => Promise.resolve({}) } as any;
+ }
+ return {
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ success: true, result: { status: 'active' } }),
+ } as any;
+ });
+
+ expect(await provider.validateKey('acc123:tok')).toBe(true);
+ expect(calls).toHaveLength(2);
+ expect(calls[1]).toBe('https://api.cloudflare.com/client/v4/accounts/acc123/tokens/verify');
+ });
+
+ it('returns false only when both scopes reject the token', async () => {
+ vi.spyOn(global, 'fetch').mockImplementation(async () => {
+ return { ok: false, status: 403, json: () => Promise.resolve({}) } as any;
+ });
+
+ expect(await provider.validateKey('acc123:tok')).toBe(false);
+ });
+
+ it('returns false when the account scope reports an inactive token', async () => {
+ vi.spyOn(global, 'fetch').mockImplementation(async (url) => {
+ if ((url as string).includes('/user/tokens/verify')) {
+ return { ok: false, status: 403, json: () => Promise.resolve({}) } as any;
+ }
+ return {
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ success: true, result: { status: 'disabled' } }),
+ } as any;
+ });
+
+ expect(await provider.validateKey('acc123:tok')).toBe(false);
+ });
+ });
+
it('should convert null assistant content to empty string (CF rejects null)', async () => {
let capturedBody: any = null;
vi.spyOn(global, 'fetch').mockImplementation(async (_url, init) => {
diff --git a/server/src/providers/cloudflare.ts b/server/src/providers/cloudflare.ts
index 0a9074ff..94f0a0b0 100644
--- a/server/src/providers/cloudflare.ts
+++ b/server/src/providers/cloudflare.ts
@@ -105,13 +105,36 @@ export class CloudflareProvider extends BaseProvider {
async validateKey(apiKey: string): Promise<boolean> {
// Transport errors propagate — health.ts marks status='error' without
// counting toward auto-disable. Only confirmed bad/inactive tokens disable.
- const { token } = this.parseKey(apiKey);
- const res = await this.fetchWithTimeout(
+ const { accountId, token } = this.parseKey(apiKey);
+
+ // Account-scoped Workers AI tokens 403 on /user/tokens/verify; they can only
+ // self-verify via /accounts/{id}/tokens/verify. User-scoped tokens are the
+ // opposite. Try the self-verify endpoint first, then fall back to the
+ // account-scoped one before treating an auth failure as a bad key. (#297)
+ const userResult = await this.verifyAt(
'https://api.cloudflare.com/client/v4/user/tokens/verify',
+ token,
+ );
+ if (userResult !== 'auth-failed') return userResult;
+
+ const accountResult = await this.verifyAt(
+ `https://api.cloudflare.com/client/v4/accounts/${accountId}/tokens/verify`,
+ token,
+ );
+ if (accountResult === 'auth-failed') return false;
+ return accountResult;
+ }
+
+ // Hits a Cloudflare token-verify endpoint. Returns true/false for a definitive
+ // active/inactive verdict, or 'auth-failed' when the token lacks access to
+ // THIS endpoint (401/403) so the caller can try the other scope.
+ private async verifyAt(url: string, token: string): Promise<boolean | 'auth-failed'> {
+ const res = await this.fetchWithTimeout(
+ url,
{ method: 'GET', headers: { 'Authorization': `Bearer ${token}` } },
10000,
);
- if (res.status === 401 || res.status === 403) return false;
+ if (res.status === 401 || res.status === 403) return 'auth-failed';
if (!res.ok) return true; // unexpected non-2xx that isn't auth — don't disable
const data = await res.json() as any;
return data.success === true && data.result?.status === 'active';