|
| 1 | +import { |
| 2 | + BYOK_OPENROUTER_ENV_VAR, |
| 3 | + BYOK_OPENROUTER_HEADER, |
| 4 | +} from '@codebuff/common/constants/byok' |
| 5 | +import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test' |
| 6 | +import { streamText } from 'ai' |
| 7 | +import { z } from 'zod' |
| 8 | + |
| 9 | +import { promptAiSdk, promptAiSdkStream, promptAiSdkStructured } from '../llm' |
| 10 | +import { getModelForRequest } from '../model-provider' |
| 11 | + |
| 12 | +const originalKey = process.env[BYOK_OPENROUTER_ENV_VAR] |
| 13 | +const legacyKey = 'legacy-openrouter-key-canary' |
| 14 | +const content = '{"answer":"ok"}' |
| 15 | +const logger = { debug() {}, info() {}, warn() {}, error() {} } |
| 16 | + |
| 17 | +beforeEach(() => { |
| 18 | + process.env[BYOK_OPENROUTER_ENV_VAR] = legacyKey |
| 19 | +}) |
| 20 | + |
| 21 | +afterEach(() => { |
| 22 | + if (originalKey === undefined) delete process.env[BYOK_OPENROUTER_ENV_VAR] |
| 23 | + else process.env[BYOK_OPENROUTER_ENV_VAR] = originalKey |
| 24 | +}) |
| 25 | + |
| 26 | +describe('Freebuff provider credentials', () => { |
| 27 | + test('an explicitly selected BYOK connection still uses its selected key and endpoint', async () => { |
| 28 | + const requests: Array<{ url: string; headers: Headers }> = [] |
| 29 | + const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation( |
| 30 | + (async (input, init) => { |
| 31 | + requests.push({ |
| 32 | + url: String(input), |
| 33 | + headers: new Headers(init?.headers), |
| 34 | + }) |
| 35 | + return new Response( |
| 36 | + 'data: {"choices":[{"delta":{"content":"ok"},"finish_reason":"stop"}]}\n\ndata: [DONE]\n\n', |
| 37 | + { headers: { 'content-type': 'text/event-stream' } }, |
| 38 | + ) |
| 39 | + }) as typeof fetch, |
| 40 | + ) |
| 41 | + try { |
| 42 | + const response = streamText({ |
| 43 | + model: getModelForRequest({ |
| 44 | + apiKey: 'freebuff-login-token', |
| 45 | + model: 'ignored/model', |
| 46 | + costMode: 'free', |
| 47 | + byok: { |
| 48 | + id: 'connection', |
| 49 | + revision: 1, |
| 50 | + name: 'My provider', |
| 51 | + provider: 'openai-compatible', |
| 52 | + baseUrl: 'https://provider.example/v1', |
| 53 | + model: 'selected/model', |
| 54 | + apiKey: 'explicit-provider-key', |
| 55 | + credentialRef: 'connection:connection', |
| 56 | + createdAt: 'x', |
| 57 | + updatedAt: 'x', |
| 58 | + }, |
| 59 | + }), |
| 60 | + messages: [{ role: 'user', content: 'hello' }], |
| 61 | + }) |
| 62 | + expect(await response.text).toBe('ok') |
| 63 | + expect(requests).toHaveLength(1) |
| 64 | + expect(requests[0]!.url).toBe( |
| 65 | + 'https://provider.example/v1/chat/completions', |
| 66 | + ) |
| 67 | + expect(requests[0]!.headers.get('authorization')).toBe( |
| 68 | + 'Bearer explicit-provider-key', |
| 69 | + ) |
| 70 | + expect(requests[0]!.headers.get(BYOK_OPENROUTER_HEADER)).toBeNull() |
| 71 | + } finally { |
| 72 | + fetchSpy.mockRestore() |
| 73 | + } |
| 74 | + }) |
| 75 | + |
| 76 | + for (const kind of ['stream', 'text', 'structured'] as const) { |
| 77 | + test.each(['free', 'normal'])( |
| 78 | + `${kind}: provider key selection for %s mode`, |
| 79 | + async (costMode) => { |
| 80 | + const requests: Array<{ url: string; headers: Headers; body: string }> = |
| 81 | + [] |
| 82 | + const fetchSpy = spyOn(globalThis, 'fetch').mockImplementation( |
| 83 | + (async (input, init) => { |
| 84 | + const body = String(init?.body) |
| 85 | + requests.push({ |
| 86 | + url: String(input), |
| 87 | + headers: new Headers(init?.headers), |
| 88 | + body, |
| 89 | + }) |
| 90 | + if (JSON.parse(body).stream) { |
| 91 | + return new Response( |
| 92 | + `data: ${JSON.stringify({ choices: [{ delta: { content }, finish_reason: 'stop' }] })}\n\ndata: [DONE]\n\n`, |
| 93 | + { headers: { 'content-type': 'text/event-stream' } }, |
| 94 | + ) |
| 95 | + } |
| 96 | + return Response.json({ |
| 97 | + id: 'completion', |
| 98 | + model: 'openai/gpt-6.1-sol', |
| 99 | + choices: [ |
| 100 | + { |
| 101 | + message: { role: 'assistant', content }, |
| 102 | + finish_reason: 'stop', |
| 103 | + }, |
| 104 | + ], |
| 105 | + usage: { |
| 106 | + prompt_tokens: 1, |
| 107 | + completion_tokens: 1, |
| 108 | + total_tokens: 2, |
| 109 | + }, |
| 110 | + }) |
| 111 | + }) as typeof fetch, |
| 112 | + ) |
| 113 | + try { |
| 114 | + const params = { |
| 115 | + apiKey: 'freebuff-login-token', |
| 116 | + model: 'openai/gpt-6.1-sol', |
| 117 | + costMode, |
| 118 | + runId: 'run', |
| 119 | + clientSessionId: 'session', |
| 120 | + fingerprintId: 'fingerprint', |
| 121 | + userInputId: 'input', |
| 122 | + userId: 'user', |
| 123 | + messages: [ |
| 124 | + { |
| 125 | + role: 'user' as const, |
| 126 | + content: [{ type: 'text' as const, text: 'hello' }], |
| 127 | + }, |
| 128 | + ], |
| 129 | + includeCacheControl: false, |
| 130 | + sendAction() {}, |
| 131 | + trackEvent() {}, |
| 132 | + logger, |
| 133 | + signal: new AbortController().signal, |
| 134 | + } |
| 135 | + if (kind === 'stream') { |
| 136 | + for await (const _chunk of promptAiSdkStream(params)) { |
| 137 | + // Drain the real SDK stream so its request reaches the fetch boundary. |
| 138 | + } |
| 139 | + } else if (kind === 'structured') { |
| 140 | + await promptAiSdkStructured({ |
| 141 | + ...params, |
| 142 | + schema: z.object({ answer: z.string() }), |
| 143 | + }) |
| 144 | + } else { |
| 145 | + await promptAiSdk(params) |
| 146 | + } |
| 147 | + expect(requests).toHaveLength(1) |
| 148 | + const request = requests[0]! |
| 149 | + expect(new URL(request.url).pathname).toBe('/api/v1/chat/completions') |
| 150 | + expect(request.headers.get('authorization')).toBe( |
| 151 | + 'Bearer freebuff-login-token', |
| 152 | + ) |
| 153 | + expect(JSON.parse(request.body).codebuff_metadata.cost_mode).toBe( |
| 154 | + costMode, |
| 155 | + ) |
| 156 | + expect(request.headers.get(BYOK_OPENROUTER_HEADER)).toBe( |
| 157 | + costMode === 'free' ? null : legacyKey, |
| 158 | + ) |
| 159 | + expect(request.body).not.toContain(legacyKey) |
| 160 | + } finally { |
| 161 | + fetchSpy.mockRestore() |
| 162 | + } |
| 163 | + }, |
| 164 | + ) |
| 165 | + } |
| 166 | +}) |
0 commit comments