From d9dd2d81bec21e00ae6ae30fb06fa508977d8c57 Mon Sep 17 00:00:00 2001 From: dreamhunter2333 Date: Sat, 7 Feb 2026 22:15:25 +0800 Subject: [PATCH] Make /v1/models auth optional --- src/providers/models.ts | 46 ++++++++++++++++++++++++++++++----------- 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/src/providers/models.ts b/src/providers/models.ts index 8390e54..d0369e7 100644 --- a/src/providers/models.ts +++ b/src/providers/models.ts @@ -48,6 +48,35 @@ const fetchChannelsForToken = async ( ).bind(...channelKeys).all(); } +const fetchAllChannels = async (c: Context) => { + return await c.env.DB.prepare( + `SELECT key, value FROM channel_config` + ).all(); +} + +const fetchChannelsForRequest = async ( + c: Context, + apiKey: string | null +) => { + if (!apiKey) { + return { + channelsResult: await fetchAllChannels(c), + }; + } + + const tokenInfo = await fetchTokenData(c, apiKey); + if (!tokenInfo) { + return { + errorResponse: c.text("Invalid API key", 401), + }; + } + + const { tokenData } = tokenInfo; + return { + channelsResult: await fetchChannelsForToken(c, tokenData), + }; +} + export class ModelsEndpoint extends OpenAPIRoute { schema = { tags: ['OpenAI Proxy'], @@ -80,20 +109,13 @@ export class ModelsEndpoint extends OpenAPIRoute { async handle(c: Context) { const apiKey = getApiKeyFromHeaders(c); - if (!apiKey) { - return c.text("Authorization header or x-api-key not found", 401); + const { channelsResult, errorResponse } = await fetchChannelsForRequest(c, apiKey); + + if (errorResponse) { + return errorResponse; } - const tokenInfo = await fetchTokenData(c, apiKey); - if (!tokenInfo) { - return c.text("Invalid API key", 401); - } - - const { tokenData } = tokenInfo; - - const channelsResult = await fetchChannelsForToken(c, tokenData); - - if (!channelsResult.results || channelsResult.results.length === 0) { + if (!channelsResult || !channelsResult.results || channelsResult.results.length === 0) { return c.json({ object: "list", data: [],