From 59fbad1ac63097572befadc02170cb2ccb640afe Mon Sep 17 00:00:00 2001 From: aiirvizionz Date: Thu, 23 Jul 2026 12:08:39 -0600 Subject: [PATCH] fix(ai-perceptron): require clean api base urls --- packages/ai/perceptron/src/index.test.ts | 18 +++++++++++++++++- packages/ai/perceptron/src/index.ts | 22 +++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/packages/ai/perceptron/src/index.test.ts b/packages/ai/perceptron/src/index.test.ts index a808dcac..306a0338 100644 --- a/packages/ai/perceptron/src/index.test.ts +++ b/packages/ai/perceptron/src/index.test.ts @@ -108,7 +108,7 @@ describe('Perceptron chat completions generation', () => { }, }, }, - { baseUrl: 'https://perceptron.test/v1' } + { baseUrl: 'https://perceptron.test/v1/' } ); expect(fetchMock).toHaveBeenCalledWith( @@ -127,6 +127,22 @@ describe('Perceptron chat completions generation', () => { ); }); + it.each([ + ['missing scheme', 'perceptron.test/v1'], + ['ftp scheme', 'ftp://perceptron.test/v1'], + ['credentials', 'https://user:pass@perceptron.test/v1'], + ['query string', 'https://perceptron.test/v1?token=secret'], + ['fragment', 'https://perceptron.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( + /Perceptron 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/perceptron/src/index.ts b/packages/ai/perceptron/src/index.ts index 2188cf32..ea8d90f9 100644 --- a/packages/ai/perceptron/src/index.ts +++ b/packages/ai/perceptron/src/index.ts @@ -29,7 +29,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}`, @@ -90,3 +91,22 @@ interface PerceptronChatResponse { completion_tokens?: number; }; } + +function cleanBaseUrl(value: string): string { + let url: URL; + try { + url = new URL(value); + } catch { + throw new Error('Perceptron baseUrl must be a valid URL'); + } + + if (url.protocol !== 'https:' && url.protocol !== 'http:') { + throw new Error('Perceptron baseUrl must use http or https'); + } + + if (url.username || url.password || url.search || url.hash) { + throw new Error('Perceptron baseUrl must be a clean API base without credentials, query, or hash'); + } + + return url.toString().replace(/\/+$/, ''); +}