diff --git a/packages/ai/moonshot/src/index.test.ts b/packages/ai/moonshot/src/index.test.ts index 91ea1547..cc2a9ab9 100644 --- a/packages/ai/moonshot/src/index.test.ts +++ b/packages/ai/moonshot/src/index.test.ts @@ -54,14 +54,14 @@ describe('Moonshot OpenAI-compatible generation', () => { temperature: 0.2, extra: { thinking: { type: 'disabled' } }, }, - {} + { baseUrl: 'https://moonshot.test/v1/' } ); expect(fetchMock).toHaveBeenCalledOnce(); const call = fetchMock.mock.calls[0]; expect(call).toBeDefined(); const [url, request] = call!; - expect(url).toBe('https://api.moonshot.ai/v1/chat/completions'); + expect(url).toBe('https://moonshot.test/v1/chat/completions'); expect(request.headers.authorization).toBe('Bearer test-key'); expect(JSON.parse(request.body)).toEqual({ model: 'kimi-k2.5', @@ -81,6 +81,22 @@ describe('Moonshot OpenAI-compatible generation', () => { }); }); + it.each([ + ['missing scheme', 'moonshot.test/v1'], + ['ftp scheme', 'ftp://moonshot.test/v1'], + ['credentials', 'https://user:pass@moonshot.test/v1'], + ['query string', 'https://moonshot.test/v1?token=secret'], + ['fragment', 'https://moonshot.test/v1#chat'], + ])('rejects unclean custom baseUrl values: %s', async (_label, baseUrl) => { + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + + await expect(adapter.generate(ctx(), 'hello', {}, { baseUrl })).rejects.toThrow( + /Moonshot baseUrl/ + ); + expect(fetchMock).not.toHaveBeenCalled(); + }); + it('includes status and response body excerpt on errors', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, diff --git a/packages/ai/moonshot/src/index.ts b/packages/ai/moonshot/src/index.ts index 7a46ca75..f3f89892 100644 --- a/packages/ai/moonshot/src/index.ts +++ b/packages/ai/moonshot/src/index.ts @@ -24,7 +24,8 @@ export default defineAi({ if (opts.system) messages.push({ role: 'system', content: opts.system }); messages.push({ role: 'user', content: prompt }); - const res = await fetch(`${config.baseUrl ?? DEFAULT_BASE}/chat/completions`, { + const baseUrl = cleanBaseUrl(config.baseUrl ?? DEFAULT_BASE); + const res = await fetch(`${baseUrl}/chat/completions`, { method: 'POST', headers: { authorization: `Bearer ${apiKey}`, @@ -81,3 +82,22 @@ interface MoonshotChatResponse { completion_tokens?: number; }; } + +function cleanBaseUrl(value: string): string { + let url: URL; + try { + url = new URL(value); + } catch { + throw new Error('Moonshot baseUrl must be a valid URL'); + } + + if (url.protocol !== 'https:' && url.protocol !== 'http:') { + throw new Error('Moonshot baseUrl must use http or https'); + } + + if (url.username || url.password || url.search || url.hash) { + throw new Error('Moonshot baseUrl must be a clean API base without credentials, query, or hash'); + } + + return url.toString().replace(/\/+$/, ''); +}