Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(llm): harden LLM connection fetches (#13797)

Tobias Wochinger2048fee518b0
diff --git a/packages/shared/package.json b/packages/shared/package.json
index 128745ec93..fbb3017b27 100644
--- a/packages/shared/package.json
+++ b/packages/shared/package.json
@@ -97,9 +97,8 @@
"@google-cloud/storage": "^7.19.0",
"@langchain/anthropic": "^1.3.26",
"@langchain/aws": "^1.3.4",
- "@langchain/core": "^1.1.39",
- "@langchain/google-genai": "^2.1.26",
- "@langchain/google-vertexai": "^2.1.26",
+ "@langchain/core": "^1.1.48",
+ "@langchain/google": "^0.1.11",
"@langchain/openai": "^1.4.2",
"@opentelemetry/api": ">=1.0.0 <1.10.0",
"@prisma/client": "^6.19.3",
@@ -117,6 +116,7 @@
"dd-trace": "5.97.0",
"decimal.js": "^10.4.3",
"exponential-backoff": "^3.1.2",
+ "google-auth-library": "^10.6.2",
"ioredis": "^5.10.1",
"ipaddr.js": "^2.2.0",
"jsonpath-plus": "10.3.0",
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.ts
index e5e8edbd7c..0ce9e79954 100644
--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts
+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts
@@ -1,12 +1,13 @@
import { type ZodType, z } from "zod";
import { ChatAnthropic, ChatAnthropicInput } from "@langchain/anthropic";
-import { ChatVertexAI } from "@langchain/google-vertexai";
+import { ChatGoogle } from "@langchain/google";
import { ChatBedrockConverse } from "@langchain/aws";
-import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
import {
AIMessage,
+ AIMessageChunk,
BaseMessage,
+ ContentBlock,
HumanMessage,
SystemMessage,
ToolMessage,
@@ -51,13 +52,19 @@ import {
} from "./utils";
import { logger } from "../logger";
import { LLMCompletionError } from "./errors";
+import {
+ createSecureGoogleAIStudioApiClient,
+ createSecureVertexAIApiClient,
+} from "./googleSecureApiClient";
+import { createSecureLlmFetch } from "./secureLlmFetch";
export type CompletionWithReasoning = { text: string; reasoning?: string };
-type AIMessageContent = AIMessage["content"];
-type AIMessageContentBlock = Exclude<AIMessageContent, string>[number];
type SplitAIMessageContent = {
text: string;
- contentWithoutThinking: AIMessageContent;
+ // Standard `ContentBlock` shape exposed by `AIMessage#contentBlocks`, stripped
+ // of `tool_call` and `reasoning` blocks. A plain string is preserved when the
+ // upstream message carried plain-string content.
+ contentWithoutThinking: string | Array<ContentBlock.Standard>;
reasoning?: string;
};
@@ -67,20 +74,34 @@ const NON_RETRYABLE_LLM_ERROR_PATTERNS = [
"Unterminated string in JSON at position",
"TypeError",
"reached the end of its life",
+ // secureLlmFetch validation failures: synchronous, status-less errors that
+ // would otherwise default to 500 + retryable and burn the eval-retry budget
+ // on permanent config or redirect-target failures.
+ "Only HTTP and HTTPS protocols are allowed",
+ "Only HTTPS base URLs are allowed",
+ "Blocked hostname detected",
+ "Blocked IP address detected",
+ "Redirect validation failed",
+ "Maximum redirects",
+ "Circular redirect detected",
] as const;
const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
+const AZURE_OPENAI_API_KEY_HEADER = "api-key";
+const ANTHROPIC_API_KEY_HEADER = "x-api-key";
+
+// Adapters whose models can return separate reasoning content. We route their
+// responses through `AIMessage#contentBlocks`, which normalizes provider-specific
+// shapes (Bedrock `reasoning_content`, Gemini `{ thought: true }` text parts, etc.)
+// into the documented `{ type: "reasoning", reasoning: string }` standard block.
+const ADAPTERS_WITH_REASONING_SUPPORT = new Set<LLMAdapter>([
+ LLMAdapter.Bedrock,
+ LLMAdapter.VertexAI,
+ LLMAdapter.GoogleAIStudio,
+]);
-// Maps adapters to the content block types that represent "thinking".
-// Used to extract reasoning separately and strip thinking parts from parsed output.
-const THINKING_BLOCK_TYPES: Partial<Record<LLMAdapter, Set<string>>> = {
- [LLMAdapter.Bedrock]: new Set(["reasoning_content"]),
- [LLMAdapter.VertexAI]: new Set(["reasoning"]),
- [LLMAdapter.GoogleAIStudio]: new Set(["reasoning"]),
-};
-
-function getThinkingBlockTypes(adapter: LLMAdapter): Set<string> | undefined {
- return THINKING_BLOCK_TYPES[adapter];
+function adapterSupportsReasoning(adapter: LLMAdapter): boolean {
+ return ADAPTERS_WITH_REASONING_SUPPORT.has(adapter);
}
const PROVIDERS_WITH_REQUIRED_USER_MESSAGE = [
@@ -312,13 +333,17 @@ export async function fetchLLMCompletion(
const proxyUrl = env.HTTPS_PROXY;
const proxyDispatcher = proxyUrl ? new ProxyAgent(proxyUrl) : undefined;
const timeoutMs = env.LANGFUSE_FETCH_LLM_COMPLETION_TIMEOUT_MS;
+ const secureLlmFetch = (
+ logContext: string,
+ additionalSensitiveHeaders?: string[],
+ ) =>
+ createSecureLlmFetch({
+ logContext,
+ additionalSensitiveHeaders,
+ dispatcher: proxyDispatcher,
+ });
- let chatModel:
- | ChatOpenAI
- | ChatAnthropic
- | ChatBedrockConverse
- | ChatVertexAI
- | ChatGoogleGenerativeAI;
+ let chatModel: ChatOpenAI | ChatAnthropic | ChatBedrockConverse | ChatGoogle;
if (modelParams.adapter === LLMAdapter.Anthropic) {
const isClaude45Family =
modelParams.model?.includes("claude-sonnet-4-5") ||
@@ -337,9 +362,9 @@ export async function fetchLLMCompletion(
maxRetries,
defaultHeaders: extraHeaders,
timeout: timeoutMs,
- ...(proxyDispatcher && {
- fetchOptions: { dispatcher: proxyDispatcher },
- }),
+ fetch: secureLlmFetch("Anthropic LLM base URL", [
+ ANTHROPIC_API_KEY_HEADER,
+ ]),
},
temperature: modelParams.temperature,
topP: modelParams.top_p,
@@ -390,9 +415,7 @@ export async function fetchLLMCompletion(
baseURL: processedBaseURL,
timeout: timeoutMs,
defaultHeaders: extraHeaders,
- ...(proxyDispatcher && {
- fetchOptions: { dispatcher: proxyDispatcher },
- }),
+ fetch: secureLlmFetch("OpenAI LLM base URL"),
},
modelKwargs: modelParams.providerOptions,
timeout: timeoutMs,
@@ -412,9 +435,9 @@ export async function fetchLLMCompletion(
configuration: {
timeout: timeoutMs,
defaultHeaders: extraHeaders,
- ...(proxyDispatcher && {
- fetchOptions: { dispatcher: proxyDispatcher },
- }),
+ fetch: secureLlmFetch("Azure OpenAI LLM base URL", [
+ AZURE_OPENAI_API_KEY_HEADER,
+ ]),
},
modelKwargs: modelParams.providerOptions,
});
@@ -472,7 +495,7 @@ export async function fetchLLMCompletion(
// Requests time out after 60 seconds for both public and private endpoints by default
// Reference: https://cloud.google.com/vertex-ai/docs/predictions/get-online-predictions#send-request
- chatModel = new ChatVertexAI({
+ chatModel = new ChatGoogle({
model: modelParams.model,
temperature: modelParams.temperature,
maxOutputTokens: modelParams.max_tokens,
@@ -480,7 +503,11 @@ export async function fetchLLMCompletion(
callbacks: finalCallbacks,
maxRetries,
location,
- authOptions,
+ vertexai: true,
+ apiClient: createSecureVertexAIApiClient({
+ authOptions,
+ dispatcher: proxyDispatcher,
+ }),
...(modelParams.maxReasoningTokens !== undefined && {
maxReasoningTokens: modelParams.maxReasoningTokens,
}),
@@ -491,20 +518,20 @@ export async function fetchLLMCompletion(
modelParams.providerOptions,
);
- chatModel = new ChatGoogleGenerativeAI({
+ chatModel = new ChatGoogle({
model: modelParams.model,
- baseUrl: baseURL ?? undefined,
temperature: modelParams.temperature,
maxOutputTokens: modelParams.max_tokens,
topP: modelParams.top_p,
callbacks: finalCallbacks,
maxRetries,
apiKey,
- ...(googleProviderOptions
- ? {
- thinkingConfig: googleProviderOptions as any, // Typecast as thinkingLevel is intentionally looser typed
- }
- : {}),
+ apiClient: createSecureGoogleAIStudioApiClient({
+ apiKey,
+ baseURL,
+ dispatcher: proxyDispatcher,
+ }),
+ ...((googleProviderOptions as any) ?? {}), // Typecast as thinkingLevel is intentionally looser typed
});
} else {
const _exhaustiveCheck: never = modelParams.adapter;
@@ -533,7 +560,7 @@ export async function fetchLLMCompletion(
}
: runConfig;
- const thinkingTypes = getThinkingBlockTypes(modelParams.adapter);
+ const supportsReasoning = adapterSupportsReasoning(modelParams.adapter);
try {
// Important: await all generations in the try block as otherwise `processTracedEvents` will run too early in finally block
@@ -541,10 +568,9 @@ export async function fetchLLMCompletion(
// Thinking-capable adapters may produce reasoning blocks that corrupt JSON schema
// parsing. Force function calling so the parser reads from tool_calls instead.
const structuredOutputSchema = params.structuredOutputSchema;
- const structuredOutputConfig =
- thinkingTypes != null
- ? { method: "functionCalling" as const }
- : undefined;
+ const structuredOutputConfig = supportsReasoning
+ ? { method: "functionCalling" as const }
+ : undefined;
const structuredOutput = await executeWithRuntimeTimeout({
enabled: runtimeTimeoutEnabled,
@@ -578,28 +604,20 @@ export async function fetchLLMCompletion(
.invoke(finalMessages, runConfigWithTimeout),
});
- if (thinkingTypes != null && Array.isArray(result.content)) {
- const { contentWithoutThinking, reasoning } = splitAIMessageContent(
- result.content,
- thinkingTypes,
- );
- const parsed = ToolCallResponseSchema.safeParse({
- content: contentWithoutThinking,
- tool_calls: result.tool_calls,
- });
- if (!parsed.success)
- throw Error("Failed to parse LLM tool call result");
-
- return {
- ...parsed.data,
- ...(reasoning ? { reasoning } : {}),
- };
- }
-
- const parsed = ToolCallResponseSchema.safeParse(result);
+ // Always normalize through `splitAIMessage` so we feed the schema the
+ // standard `contentBlocks` shape regardless of provider, instead of the
+ // raw, provider-specific message content.
+ const { contentWithoutThinking, reasoning } = splitAIMessage(result);
+ const parsed = ToolCallResponseSchema.safeParse({
+ content: contentWithoutThinking,
+ tool_calls: result.tool_calls,
+ });
if (!parsed.success) throw Error("Failed to parse LLM tool call result");
- return parsed.data;
+ return {
+ ...parsed.data,
+ ...(reasoning ? { reasoning } : {}),
+ };
}
if (streaming)
@@ -609,23 +627,20 @@ export async function fetchLLMCompletion(
abortController: runtimeTimeoutController,
operation: () =>
chatModel
- .pipe(createBytesOutputParser(thinkingTypes))
+ .pipe(createBytesOutputParser(supportsReasoning))
.stream(finalMessages, runConfigWithTimeout),
});
// content with thinking blocks can't be handled by StringOutputParser
// Invoke model directly and extract text + reasoning separately.
- if (thinkingTypes != null) {
+ if (supportsReasoning) {
const aiMessage = await executeWithRuntimeTimeout({
enabled: runtimeTimeoutEnabled,
timeoutMs,
abortController: runtimeTimeoutController,
operation: () => chatModel.invoke(finalMessages, runConfigWithTimeout),
});
- const completion = extractCompletionWithReasoning(
- aiMessage,
- thinkingTypes,
- );
+ const completion = extractCompletionWithReasoning(aiMessage);
// Bedrock only returns reasoning blocks for selected models. Preserve the
// historical plain-string shape when the response contains no reasoning.
@@ -658,12 +673,17 @@ export async function fetchLLMCompletion(
(e as any)?.$metadata?.httpStatusCode ??
500;
const rawMessage = e instanceof Error ? e.message : String(e);
- const message = extractCleanErrorMessage(rawMessage);
-
- // Check for non-retryable error patterns in message
- const hasNonRetryablePattern = NON_RETRYABLE_LLM_ERROR_PATTERNS.some(
- (pattern) => message.includes(pattern),
- );
+ // Anthropic/OpenAI/Azure SDKs wrap synchronous fetch errors as
+ // `APIConnectionError { message: "Connection error.", cause: original }`,
+ // hiding the actual secureLlmFetch validation reason. Walk the `.cause`
+ // chain for both retryability classification and the user-visible message
+ // so operators see "Blocked hostname detected" / "Redirect validation
+ // failed ..." instead of the unhelpful wrapper text.
+ const nonRetryableCauseMessage = findNonRetryableCauseMessage(e);
+ const message =
+ nonRetryableCauseMessage ?? extractCleanErrorMessage(rawMessage);
+
+ const hasNonRetryablePattern = nonRetryableCauseMessage !== undefined;
// Determine retryability:
// - 429 (rate limit): retryable with custom delay
@@ -703,12 +723,8 @@ export async function fetchLLMCompletion(
function extractCompletionWithReasoning(
message: AIMessage,
- thinkingBlockTypes: Set<string>,
): CompletionWithReasoning {
- const { text, reasoning } = splitAIMessageContent(
- message.content,
- thinkingBlockTypes,
- );
+ const { text, reasoning } = splitAIMessage(message);
return {
text,
@@ -717,53 +733,56 @@ function extractCompletionWithReasoning(
}
function createBytesOutputParser(
- thinkingBlockTypes: Set<string> | undefined,
+ filterReasoningBlocks: boolean,
): BytesOutputParser {
- return thinkingBlockTypes != null
- ? new ThinkingBlockFilteringBytesOutputParser(thinkingBlockTypes)
+ return filterReasoningBlocks
+ ? new ReasoningStrippingBytesOutputParser()
: new BytesOutputParser();
}
-class ThinkingBlockFilteringBytesOutputParser extends BytesOutputParser {
- constructor(private readonly thinkingBlockTypes: Set<string>) {
- super();
- }
-
- protected _baseMessageContentToString(
- content: Exclude<AIMessageContent, string>,
- ): string {
- return splitAIMessageContent(content, this.thinkingBlockTypes).text;
+class ReasoningStrippingBytesOutputParser extends BytesOutputParser {
+ // Override `_baseMessageToString` (not `_baseMessageContentToString`) so we
+ // have the whole AIMessage(Chunk) and can read `contentBlocks`, which the
+ // langchain provider translator normalizes into standard blocks. Streaming
+ // yields AIMessageChunk instances, so we check both predicates explicitly.
+ protected _baseMessageToString(message: BaseMessage): string {
+ if (AIMessage.isInstance(message) || AIMessageChunk.isInstance(message)) {
+ return splitAIMessage(message).text;
+ }
+ return typeof message.content === "string"
+ ? message.content
+ : super._baseMessageToString(message);
}
}
-function splitAIMessageContent(
- content: AIMessageContent,
- thinkingBlockTypes: Set<string>,
+// Reads the standard `contentBlocks` view of an AIMessage(Chunk) and splits it
+// into displayable text, reasoning, and a content array stripped of reasoning
+// and tool_call blocks (tool calls live on `message.tool_calls`).
+function splitAIMessage(
+ message: AIMessage | AIMessageChunk,
): SplitAIMessageContent {
- if (typeof content === "string") {
- return { text: content, contentWithoutThinking: content };
- }
-
- if (!Array.isArray(content)) {
- return { text: String(content), contentWithoutThinking: content };
+ if (typeof message.content === "string") {
+ return { text: message.content, contentWithoutThinking: message.content };
}
const textParts: string[] = [];
const reasoningParts: string[] = [];
- const contentWithoutThinking: AIMessageContentBlock[] = [];
-
- for (const block of content) {
- if (typeof block === "string") {
- textParts.push(block);
- contentWithoutThinking.push(block as AIMessageContentBlock);
- } else if (thinkingBlockTypes.has(block.type)) {
- const reasoning = extractReasoningBlockText(block);
- if (typeof reasoning === "string") reasoningParts.push(reasoning);
- } else {
- const text = extractTextBlockText(block);
- if (typeof text === "string") textParts.push(text);
- contentWithoutThinking.push(block);
+ const contentWithoutThinking: Array<ContentBlock.Standard> = [];
+
+ for (const block of message.contentBlocks) {
+ if (block.type === "reasoning") {
+ if (typeof block.reasoning === "string")
+ reasoningParts.push(block.reasoning);
+ continue;
+ }
+ if (block.type === "tool_call") {
+ // Already represented in `message.tool_calls`; omit to avoid duplicates.
+ continue;
}
+ if (block.type === "text" && typeof block.text === "string") {
+ textParts.push(block.text);
+ }
+ contentWithoutThinking.push(block);
}
return {
@@ -775,19 +794,6 @@ function splitAIMessageContent(
};
}
-function extractTextBlockText(block: AIMessageContentBlock) {
- return (block as any).text ?? (block as any).reasoning;
-}
-
-function extractReasoningBlockText(block: AIMessageContentBlock) {
- const reasoningText = (block as any).reasoningText;
-
- if (typeof reasoningText === "string") return reasoningText;
- if (typeof reasoningText?.text === "string") return reasoningText.text;
-
- return extractTextBlockText(block);
-}
-
/**
* Process baseURL template for OpenAI adapter only.
* Replaces {model} placeholder with actual model name.
@@ -807,6 +813,28 @@ function processOpenAIBaseURL(params: {
return url.replace("{model}", modelName);
}
+function findNonRetryableCauseMessage(error: unknown): string | undefined {
+ const visited = new Set<unknown>();
+ for (
+ let current: unknown = error;
+ current;
+ current = (current as any).cause
+ ) {
+ if (visited.has(current)) break;
+ visited.add(current);
+ if (!(current instanceof Error)) continue;
+ const message = extractCleanErrorMessage(current.message);
+ if (
+ NON_RETRYABLE_LLM_ERROR_PATTERNS.some((pattern) =>
+ message.includes(pattern),
+ )
+ ) {
+ return message;
+ }
+ }
+ return undefined;
+}
+
function extractCleanErrorMessage(rawMessage: string): string {
// Try to parse JSON error format (common in Google/Vertex AI errors)
// Example: '[{"error":{"code":404,"message":"Model not found..."}}]'
diff --git a/packages/shared/src/server/llm/googleSecureApiClient.ts b/packages/shared/src/server/llm/googleSecureApiClient.ts
new file mode 100644
index 0000000000..5042ade01b
--- /dev/null
+++ b/packages/shared/src/server/llm/googleSecureApiClient.ts
@@ -0,0 +1,144 @@
+import { type OutboundUrlValidationWhitelist } from "../outbound-url";
+import { type ChatGoogleParams } from "@langchain/google";
+import { GoogleAuth, type GoogleAuthOptions } from "google-auth-library";
+import { llmBaseUrlWhitelistFromEnv } from "./baseUrlValidation";
+import { fetchSecureLlmUrl } from "./secureLlmFetch";
+
+const GOOGLE_AI_STUDIO_ORIGIN = "https://generativelanguage.googleapis.com";
+const GOOGLE_API_KEY_HEADER = "X-Goog-Api-Key";
+const VERTEX_AI_AUTH_HEADER = "authorization";
+const VERTEX_AI_AUTH_SCOPES = [
+ "https://www.googleapis.com/auth/cloud-platform",
+];
+
+type GoogleApiClient = NonNullable<ChatGoogleParams["apiClient"]>;
+
+type SecureGoogleAIStudioApiClientParams = {
+ apiKey: string;
+ baseURL?: string | null;
+ whitelist?: OutboundUrlValidationWhitelist;
+ dispatcher?: unknown;
+};
+
+type SecureVertexAIApiClientParams = {
+ authOptions?: GoogleAuthOptions;
+ whitelist?: OutboundUrlValidationWhitelist;
+ dispatcher?: unknown;
+};
+
+export function createSecureGoogleAIStudioApiClient({
+ apiKey,
+ baseURL,
+ whitelist = llmBaseUrlWhitelistFromEnv(),
+ dispatcher,
+}: SecureGoogleAIStudioApiClientParams): GoogleApiClient {
+ return {
+ hasApiKey: () => true,
+ getProjectId: async () => "unknown-project-id",
+ fetch: async (request: Request) => {
+ const url = rewriteGoogleAIStudioUrl(request.url, baseURL);
+
+ const headers = new Headers(request.headers);
+ headers.set(GOOGLE_API_KEY_HEADER, apiKey);
+
+ return fetchGoogleLlmRequest({
+ url,
+ request,
+ headers,
+ whitelist,
+ logContext: "Google AI Studio LLM base URL",
+ additionalSensitiveHeaders: [GOOGLE_API_KEY_HEADER],
+ dispatcher,
+ });
+ },
+ };
+}
+
+export function createSecureVertexAIApiClient({
+ authOptions,
+ whitelist = llmBaseUrlWhitelistFromEnv(),
+ dispatcher,
+}: SecureVertexAIApiClientParams): GoogleApiClient {
+ const googleAuth = new GoogleAuth({
+ ...authOptions,
+ scopes: authOptions?.scopes ?? VERTEX_AI_AUTH_SCOPES,
+ });
+
+ return {
+ hasApiKey: () => false,
+ getProjectId: () => googleAuth.getProjectId(),
+ fetch: async (request: Request) => {
+ const headers = new Headers(request.headers);
+ (await googleAuth.getRequestHeaders(request.url)).forEach(
+ (value, key) => {
+ if (value !== null) headers.set(key, value);
+ },
+ );
+
+ return fetchGoogleLlmRequest({
+ url: request.url,
+ request,
+ headers,
+ whitelist,
+ logContext: "Vertex AI LLM endpoint",
+ additionalSensitiveHeaders: [VERTEX_AI_AUTH_HEADER],
+ dispatcher,
+ });
+ },
+ };
+}
+
+export function rewriteGoogleAIStudioUrl(
+ requestUrl: string,
+ baseURL?: string | null,
+): string {
+ if (!baseURL) return requestUrl;
+
+ const parsedRequestUrl = new URL(requestUrl);
+
+ if (parsedRequestUrl.origin !== GOOGLE_AI_STUDIO_ORIGIN) {
+ return requestUrl;
+ }
+
+ // Match the previous @google/generative-ai baseUrl behavior: append the
+ // generated Google path to the configured baseURL as-is.
+ return `${baseURL}${parsedRequestUrl.pathname}${parsedRequestUrl.search}`;
+}
+
+async function fetchGoogleLlmRequest({
+ url,
+ request,
+ headers,
+ whitelist,
+ logContext,
+ additionalSensitiveHeaders,
+ dispatcher,
+}: {
+ url: string;
+ request: Request;
+ headers: Headers;
+ whitelist: OutboundUrlValidationWhitelist;
+ logContext: string;
+ additionalSensitiveHeaders?: string[];
+ dispatcher?: unknown;
+}): Promise<Response> {
+ const body = ["GET", "HEAD"].includes(request.method)
+ ? undefined
+ : await request.text();
+
+ return fetchSecureLlmUrl(
+ url,
+ {
+ method: request.method,
+ headers,
+ body,
+ signal: request.signal,
+ },
+ {
+ whitelist,
+ logContext,
+ additionalSensitiveHeaders,
+ dispatcher,
+ },
+ );
+}
diff --git a/packages/shared/src/server/llm/secureLlmFetch.ts b/packages/shared/src/server/llm/secureLlmFetch.ts
new file mode 100644
index 0000000000..ef8d8438b0
--- /dev/null
+++ b/packages/shared/src/server/llm/secureLlmFetch.ts
@@ -0,0 +1,94 @@
+import {
+ fetchWithSecureRedirects,
+ type OutboundUrlValidationWhitelist,
+ type RequestInitWithDispatcher,
+} from "../outbound-url";
+import {
+ llmBaseUrlWhitelistFromEnv,
+ validateLlmConnectionBaseURL,
+} from "./baseUrlValidation";
+
+const MAX_LLM_REDIRECTS = 10;
+
+type SecureLlmFetchParams = {
+ whitelist?: OutboundUrlValidationWhitelist;
+ logContext: string;
+ additionalSensitiveHeaders?: string[];
+ dispatcher?: unknown;
+};
+
+export function createSecureLlmFetch({
+ whitelist = llmBaseUrlWhitelistFromEnv(),
+ logContext,
+ additionalSensitiveHeaders,
+ dispatcher,
+}: SecureLlmFetchParams): typeof fetch {
+ return async (input, init) => {
+ const { url, options } = await normalizeFetchInput(input, init);
+
+ return fetchSecureLlmUrl(url, options, {
+ whitelist,
+ logContext,
+ additionalSensitiveHeaders,
+ dispatcher,
+ });
+ };
+}
+
+export async function fetchSecureLlmUrl(
+ url: string,
+ options: RequestInit,
+ {
+ whitelist = llmBaseUrlWhitelistFromEnv(),
+ logContext,
+ additionalSensitiveHeaders,
+ dispatcher,
+ }: SecureLlmFetchParams,
+): Promise<Response> {
+ await validateLlmConnectionBaseURL(url, whitelist);
+ const optionsWithoutDispatcher = stripCallerDispatcher(options);
+ // If we have a proxy dispatcher (HTTPS_PROXY), attach it here so the
+ // outbound connection traverses the operator's proxy. Otherwise
+ // fetchWithSecureRedirects will inject the secure-lookup dispatcher.
+ const fetchOptions: RequestInit = dispatcher
+ ? ({ ...optionsWithoutDispatcher, dispatcher } as RequestInit)
+ : optionsWithoutDispatcher;
+
+ const { response } = await fetchWithSecureRedirects(url, fetchOptions, {
+ maxRedirects: MAX_LLM_REDIRECTS,
+ additionalSensitiveHeaders,
+ redirectValidation: {
+ validateUrl: validateLlmConnectionBaseURL,
+ whitelist,
+ logContext,
+ },
+ });
+
+ return response;
+}
+
+function stripCallerDispatcher(options: RequestInit): RequestInit {
+ const fetchOptions = { ...options } as RequestInitWithDispatcher;
+ delete fetchOptions.dispatcher;
+ return fetchOptions;
+}
+
+async function normalizeFetchInput(
+ input: Parameters<typeof fetch>[0],
+ init?: RequestInit,
+): Promise<{ url: string; options: RequestInit }> {
+ const request = new Request(input, init);
+
+ return {
+ url: request.url,
+ options: {
+ ...init,
+ method: request.method,
+ headers: request.headers,
+ body: ["GET", "HEAD"].includes(request.method)
+ ? undefined
+ : await request.text(),
+ signal: request.signal,
+ },
+ };
+}
diff --git a/packages/shared/src/server/llm/types.ts b/packages/shared/src/server/llm/types.ts
index 5c7d7aedac..952a292aa8 100644
--- a/packages/shared/src/server/llm/types.ts
+++ b/packages/shared/src/server/llm/types.ts
@@ -48,26 +48,6 @@ export const LLMToolDefinitionSchema = z.object({
});
export type LLMToolDefinition = z.infer<typeof LLMToolDefinitionSchema>;
-const AnthropicMessageContentWithToolUse = z.union([
- z.object({
- type: z.literal("text"),
- text: z.string(),
- }),
- z.object({
- type: z.literal("tool_use"),
- id: z.string(),
- name: z.string(),
- input: z.unknown(),
- }),
-]);
-
-const GoogleAIStudioMessageContentWithToolUse = z.object({
- functionCall: z.object({
- name: z.string(),
- args: z.unknown(),
- }),
-});
-
export const LLMToolCallSchema = z.object({
name: z.string(),
id: z.string(),
@@ -114,12 +94,18 @@ export const OpenAIResponseFormatSchema = z.object({
}),
});
+// Standard ContentBlock shape per @langchain/core. fetchLLMCompletion routes
+// every provider through `AIMessage#contentBlocks`, so every element in the
+// array variant carries a `type` discriminator and the well-known fields for
+// that type (e.g. `text` for "text", `value` for "non_standard").
+const StandardContentBlockSchema = z
+ .object({
+ type: z.string(),
+ })
+ .loose();
+
export const ToolCallResponseSchema = z.object({
- content: z.union([
- z.string(),
- z.array(AnthropicMessageContentWithToolUse),
- z.array(GoogleAIStudioMessageContentWithToolUse),
- ]),
+ content: z.union([z.string(), z.array(StandardContentBlockSchema)]),
tool_calls: z.array(LLMToolCallSchema),
});
export type ToolCallResponse = z.infer<typeof ToolCallResponseSchema>;
diff --git a/packages/shared/src/server/outbound-url/connection.ts b/packages/shared/src/server/outbound-url/connection.ts
index 68af4620ff..605bac7881 100644
--- a/packages/shared/src/server/outbound-url/connection.ts
+++ b/packages/shared/src/server/outbound-url/connection.ts
@@ -18,6 +18,7 @@ const DEFAULT_OUTBOUND_URL_VALIDATION_WHITELIST: OutboundUrlValidationWhitelist
ips: [],
ip_ranges: [],
};
+export type RequestInitWithDispatcher = RequestInit & { dispatcher?: unknown };
export interface OutboundUrlConnectionValidationOptions {
whitelist?: OutboundUrlValidationWhitelist;
@@ -34,6 +35,14 @@ export function addSecureOutboundConnectionValidation(
options: RequestInit,
validationOptions: OutboundUrlConnectionValidationOptions,
): RequestInit {
+ if ((options as RequestInitWithDispatcher).dispatcher) {
+ // A dispatcher is already attached (today: HTTPS_PROXY routing via
+ // secureLlmFetch). Forward proxies own DNS resolution at the proxy hop,
+ // so a connect.lookup hook on our Agent would not see the target host
+ // anyway. Pre-fetch URL validation and redirect validation still run.
+ return options;
+ }
+
return {
...options,
dispatcher: getSecureOutboundDispatcher(validationOptions),
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 76a95b3eea..b646ed7373 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -193,22 +193,19 @@ importers:
version: 7.19.0
'@langchain/anthropic':
specifier: ^1.3.26
- version: 1.3.26(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
+ version: 1.3.26(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
'@langchain/aws':
specifier: ^1.3.4
- version: 1.3.4(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
+ version: 1.3.4(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
'@langchain/core':
- specifier: ^1.1.39
- version: 1.1.39(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
- '@langchain/google-genai':
- specifier: ^2.1.26
- version: 2.1.26(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
- '@langchain/google-vertexai':
- specifier: ^2.1.26
- version: 2.1.26(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
+ specifier: ^1.1.48
+ version: 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ '@langchain/google':
+ specifier: ^0.1.11
+ version: 0.1.11(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
'@langchain/openai':
specifier: ^1.4.2
'@opentelemetry/api':
specifier: '>=1.0.0 <1.10.0'
version: 1.9.0
@@ -257,6 +254,9 @@ importers:
exponential-backoff:
specifier: ^3.1.2
version: 3.1.2
+ google-auth-library:
+ specifier: ^10.6.2
+ version: 10.6.2
ioredis:
specifier: ^5.10.1
version: 5.10.1
@@ -268,10 +268,10 @@ importers:
version: 10.3.0
langchain:
specifier: ^1.3.0
langfuse-langchain:
specifier: 3.38.20
lodash:
specifier: ^4.18.1
version: 4.18.1
@@ -421,8 +421,8 @@ importers:
specifier: ^5.2.2
'@langchain/core':
- specifier: ^1.1.39
- version: 1.1.39(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ specifier: ^1.1.48
+ version: 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
'@langfuse/ee':
specifier: workspace:*
version: link:../ee
@@ -656,7 +656,7 @@ importers:
version: 10.3.0
langchain:
specifier: ^1.3.0
langfuse:
specifier: 3.38.4
version: 3.38.4
@@ -1046,6 +1046,9 @@ importers:
eslint:
specifier: ^9.39.2
version: 9.39.4([email protected])
+ google-auth-library:
+ specifier: ^10.6.2
+ version: 10.6.2
msw:
specifier: ^2.6.5
version: 2.6.5(@types/[email protected])([email protected])
@@ -2057,10 +2060,6 @@ packages:
resolution: {integrity: sha512-n2FjE7NAOYyshogdc7KQOl/VZb4sneqPjWouSyia9CMDdMhRX5+RIbqalNmC7LOLzuLAN89VlF2HvG8na9G+zQ==}
engines: {node: '>=14'}
- '@google/[email protected]':
- resolution: {integrity: sha512-MqO+MLfM6kjxcKoy0p1wRzG3b4ZZXtPI+z2IE26UogS2Cm/XHO+7gGRBh6gcJsOiIVoH93UwKvW4HdgiOZCy9Q==}
- engines: {node: '>=18.0.0'}
-
'@graphql-typed-document-node/[email protected]':
resolution: {integrity: sha512-mB9oAsNCm9aM3/SOv4YtBMqZbYj10R7dkq8byBqxGY/ncFwhf2oQzMV+LCRlWoDSEBJ3COiR1yeDvMtsoOsuFQ==}
peerDependencies:
@@ -2471,29 +2470,15 @@ packages:
peerDependencies:
'@langchain/core': ^1.0.0
- '@langchain/[email protected]':
- resolution: {integrity: sha512-DP9c7TREy6iA7HnywstmUAsNyJNYTFpRg2yBfQ+6H0l1HnvQzei9GsQ36GeOLxgRaD3vm9K8urCcawSC7yQpCw==}
- engines: {node: '>=20'}
-
- '@langchain/[email protected]':
- resolution: {integrity: sha512-5zTVwsEz2TwM8nBe1YtFjkP2okK2/QwpNebm/t9OJ9wXxXJQa2dQ9jz9LQNjRy9e0BQEkHrMFUD/71XSSiXW/A==}
- engines: {node: '>=20'}
- peerDependencies:
- '@langchain/core': ^1.1.33
-
- '@langchain/[email protected]':
- resolution: {integrity: sha512-frfMVKuiGAmNH6NY8X+YGU57215z8IXcbcpkAv2uZsrzbHmytI09/a6B7vPtl/MEb5VcCpUOZyFn+Ytesoztaw==}
+ '@langchain/[email protected]':
+ resolution: {integrity: sha512-fQU6Guyb1pwc2fEplmA8FPbKfOMAofjnyJzExevro0FxEiuGHE18Ov/ZHmT9trWCDTZRI9eW1VIc6aChxV8pAQ==}
engines: {node: '>=20'}
- '@langchain/[email protected]':
- resolution: {integrity: sha512-202ZBVEIXxKhNbDzktLKSffb9pNfrYBGPV7j54nvAR0uqfoh5reRlX8wmOZEDflojvX/GHc69jTOsc0eZKgRsA==}
+ '@langchain/[email protected]':
+ resolution: {integrity: sha512-c7E77jfRGGg8j2F/OGEfzsTBsA7UbzctnaqDHC9GHQdXosfTuAgsae2Z8wjp7DY4ikjCBk8kKEtKo2AjFEfgKw==}
engines: {node: '>=20'}
peerDependencies:
- '@langchain/core': ^1.1.33
-
- '@langchain/[email protected]':
- resolution: {integrity: sha512-gjA6qVgt9kS/zM0bsPhJWWTsWHL83hk/Mag8UEPC+snP3RSNndScamc/aJempn34KmOp4Y8EPnxrsLxh7fBGBA==}
- engines: {node: '>=20'}
+ '@langchain/core': ^1.0.0
'@langchain/[email protected]':
resolution: {integrity: sha512-HM0cJLRpIsSlWBQ/xuDC67l52SqZ62Bh2Y61DX+Xorqwoh5e1KxYvfCD7GnSTbWWhjBOutvnR0vPhu4orFkZfw==}
@@ -6139,10 +6124,6 @@ packages:
resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-blhOL/WNR+Km1RI/LCVAvA73xplXA7ZbjzI4YkMK9pa6T/P3F2GxjNpEkyw5repTw9IvkyrjyHpwjnhZ5FOvYQ==}
@@ -6630,10 +6611,6 @@ packages:
supports-color:
optional: true
- resolution: {integrity: sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==}
- engines: {node: '>=0.10.0'}
-
resolution: {integrity: sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg==}
@@ -7357,8 +7334,8 @@ packages:
resolution: {integrity: sha512-LDODD4TMYx7XXdpwxAVRAIAuB0bzv0s+ywFonY46k126qzQHT9ygyoa9tncmOiQmmDrik65UYsEkv3lbfqQ3yQ==}
engines: {node: '>=14'}
- resolution: {integrity: sha512-YGGyuEdVIjqxkxVH1pUTMY/XtmmsApXrCVv5EU25iX6inEPbV+VakJfLealkBtJN69AQmh1eGOdCl9Sm1UP6XQ==}
+ resolution: {integrity: sha512-bTIgTsM2bWn3XklZISBTQX7ZSddGW+IO3bMdGaemHZ3tbqExMENHLx6kKZ/KlejgrMtj8q7wBItt51yegqalrA==}
engines: {node: '>=18'}
@@ -7460,8 +7437,8 @@ packages:
resolution: {integrity: sha512-uHJgbwAMwNFf5mLst7IWLNg14x1CkeqglJb/K3doi4dw6q2IvAAmM/Y81kevy83wP+Sst+nutFTYOGg3d1lsxg==}
- resolution: {integrity: sha512-7ABviyMOlX5hIVD60YOfHw4/CxOfBhyduaYB+wbFWCWoni4N7SLcV46hrVRktuBbZjFC9ONyqamZITN7q3n32w==}
+ resolution: {integrity: sha512-e27Z6EThmVNNvtYASwQxose/G57rkRuaRbQyxM2bvYLLX/GqWZ5chWq2EBoUchJbCc57eC9ArzO5wMsEmWftCw==}
engines: {node: '>=18'}
@@ -7491,10 +7468,6 @@ packages:
resolution: {integrity: sha512-pCcEwRi+TKpMlxAQObHDQ56KawURgyAf6jtIY046fJ5tIv3zDe/LEIubckAO8fj6JnAxLdmWkUfNyulQ2iKdEw==}
engines: {node: '>=14.0.0'}
- resolution: {integrity: sha512-+CqsMbHPiSTdtSO14O51eMNlrp9N79gmeqmXeouJOhfucAedHw9noVe/n5uJk3tbKE6a+6ZCQg3RPhVhHByAIw==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg==}
@@ -8137,6 +8110,26 @@ packages:
ws:
optional: true
+ resolution: {integrity: sha512-Wjk90UjNoY5cBHMlNAC/eZx5clI8jnjBOBW8uJu8+MWBtx0QesNjsUiLtjI+I3UnrpxFFpDqGXcnhBjH654Mqg==}
+ peerDependencies:
+ '@opentelemetry/api': '*'
+ '@opentelemetry/exporter-trace-otlp-proto': '*'
+ '@opentelemetry/sdk-trace-base': '*'
+ openai: '*'
+ ws: '>=7'
+ peerDependenciesMeta:
+ '@opentelemetry/api':
+ optional: true
+ '@opentelemetry/exporter-trace-otlp-proto':
+ optional: true
+ '@opentelemetry/sdk-trace-base':
+ optional: true
+ openai:
+ optional: true
+ ws:
+ optional: true
+
resolution: {integrity: sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==}
@@ -8958,8 +8951,8 @@ packages:
resolution: {integrity: sha512-RwFpb72c/BhQLEXIZ5K2e+AhgNVmIejGlTgiB9MzZ0e93GRvqZ7uSi0dvRF7/XIXDeNkra2fNHBxTyPDGySpjQ==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-ktsDOALzTYTWWF1PbkNVg2rOt+HaOaMWJMUnt7T3qf5tvZ1L8dBW3tObzprBcXNMKkwj+yFSLqHso0x+UFcJXw==}
+ resolution: {integrity: sha512-7NED7xhQ74Ngp4JP/2e0VZHp7vSWfJfqeiR92jPgxsz6m0Se4P03YoTKa9dDXyZ3r6P616gUXttrB6nnHYKang==}
engines: {node: '>=20'}
@@ -9650,10 +9643,6 @@ packages:
resolution: {integrity: sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==}
engines: {iojs: '>=1.0.0', node: '>=0.10.0'}
- resolution: {integrity: sha512-l0OE8wL34P4nJH/H2ffoaniAokM2qSmrtXHmlpvYr5AVVX8msAyW0l8NVJFDxlSK4u3Uh/f41cQheDVdnYijwQ==}
- hasBin: true
-
resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==}
@@ -11044,7 +11033,7 @@ snapshots:
'@aws-crypto/sha256-browser': 5.2.0
'@aws-crypto/sha256-js': 5.2.0
'@aws-sdk/core': 3.974.8
- '@aws-sdk/credential-provider-node': 3.972.39
+ '@aws-sdk/credential-provider-node': 3.972.40
'@aws-sdk/middleware-host-header': 3.972.10
'@aws-sdk/middleware-logger': 3.972.10
'@aws-sdk/middleware-recursion-detection': 3.972.11
@@ -11091,7 +11080,7 @@ snapshots:
'@aws-crypto/sha256-browser': 5.2.0
'@aws-crypto/sha256-js': 5.2.0
'@aws-sdk/core': 3.974.8
- '@aws-sdk/credential-provider-node': 3.972.39
+ '@aws-sdk/credential-provider-node': 3.972.40
'@aws-sdk/eventstream-handler-node': 3.972.11
'@aws-sdk/middleware-eventstream': 3.972.8
'@aws-sdk/middleware-host-header': 3.972.10
@@ -11189,7 +11178,7 @@ snapshots:
'@aws-crypto/sha256-browser': 5.2.0
'@aws-crypto/sha256-js': 5.2.0
'@aws-sdk/core': 3.974.8
- '@aws-sdk/credential-provider-node': 3.972.39
+ '@aws-sdk/credential-provider-node': 3.972.40
'@aws-sdk/middleware-host-header': 3.972.10
'@aws-sdk/middleware-logger': 3.972.10
'@aws-sdk/middleware-recursion-detection': 3.972.11
@@ -12613,8 +12602,6 @@ snapshots:
- encoding
- supports-color
- '@google/[email protected]': {}
-
'@graphql-typed-document-node/[email protected]([email protected])':
dependencies:
graphql: 16.13.2
@@ -12947,34 +12934,30 @@ snapshots:
dependencies:
jsep: 1.4.0
dependencies:
'@anthropic-ai/sdk': 0.74.0([email protected])
- '@langchain/core': 1.1.39(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
zod: 4.3.6
dependencies:
'@aws-sdk/client-bedrock-agent-runtime': 3.1024.0
'@aws-sdk/client-bedrock-runtime': 3.1013.0
'@aws-sdk/client-kendra': 3.1013.0
- '@aws-sdk/credential-provider-node': 3.972.39
- '@langchain/core': 1.1.39(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ '@aws-sdk/credential-provider-node': 3.972.40
+ '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
transitivePeerDependencies:
- aws-crt
dependencies:
'@cfworker/json-schema': 4.1.1
'@standard-schema/spec': 1.1.0
- ansi-styles: 5.2.0
- camelcase: 6.3.0
- decamelize: 1.2.0
js-tiktoken: 1.0.21
- langsmith: 0.6.0(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ langsmith: 0.7.1(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
mustache: 4.2.0
p-queue: 6.6.2
- uuid: 11.1.1
zod: 4.3.6
transitivePeerDependencies:
- '@opentelemetry/api'
@@ -12983,53 +12966,36 @@ snapshots:
- openai
- ws
- dependencies:
- '@langchain/core': 1.1.39(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
- uuid: 10.0.0
-
- dependencies:
- '@langchain/google-common': 2.1.26(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
- google-auth-library: 10.5.0
- transitivePeerDependencies:
- - '@langchain/core'
- - supports-color
-
dependencies:
- '@google/generative-ai': 0.24.1
- '@langchain/core': 1.1.39(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
- uuid: 11.1.1
-
- dependencies:
- '@langchain/google-gauth': 2.1.26(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
+ '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ eventsource-parser: 3.0.8
+ google-auth-library: 10.6.2
+ jose: 6.2.3
transitivePeerDependencies:
- - '@langchain/core'
- supports-color
dependencies:
- '@langchain/core': 1.1.39(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
uuid: 10.0.0
dependencies:
'@types/json-schema': 7.0.15
- p-queue: 9.1.2
+ p-queue: 9.3.0
p-retry: 7.1.1
uuid: 13.0.0
optionalDependencies:
- '@langchain/core': 1.1.39(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
react: 19.2.4
react-dom: 19.2.4([email protected])
dependencies:
- '@langchain/core': 1.1.39(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
- '@langchain/langgraph-checkpoint': 1.0.1(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
+ '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ '@langchain/langgraph-checkpoint': 1.0.1(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
'@standard-schema/spec': 1.1.0
uuid: 10.0.0
zod: 4.3.6
@@ -13041,9 +13007,9 @@ snapshots:
- svelte
- vue
dependencies:
- '@langchain/core': 1.1.39(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
js-tiktoken: 1.0.21
zod: 4.3.6
@@ -16952,8 +16918,6 @@ snapshots:
-
@@ -17462,8 +17426,6 @@ snapshots:
dependencies:
ms: 2.1.3
-
@@ -18389,12 +18351,11 @@ snapshots:
- encoding
- supports-color
dependencies:
extend: 3.0.2
https-proxy-agent: 7.0.6
node-fetch: 3.3.2
- rimraf: 5.0.10
transitivePeerDependencies:
- supports-color
@@ -18409,7 +18370,7 @@ snapshots:
dependencies:
- gaxios: 7.1.3
+ gaxios: 7.1.4
google-logging-utils: 1.1.3
json-bigint: 1.0.0
transitivePeerDependencies:
@@ -18517,14 +18478,13 @@ snapshots:
dependencies:
base64-js: 1.5.1
ecdsa-sig-formatter: 1.0.11
- gaxios: 7.1.3
+ gaxios: 7.1.4
gcp-metadata: 8.1.2
google-logging-utils: 1.1.3
- gtoken: 8.0.0
jws: 4.0.1
transitivePeerDependencies:
- supports-color
@@ -18559,13 +18519,6 @@ snapshots:
- encoding
- supports-color
- dependencies:
- gaxios: 7.1.3
- jws: 4.0.1
- transitivePeerDependencies:
- - supports-color
-
@@ -19228,11 +19181,11 @@ snapshots:
dependencies:
- '@langchain/core': 1.1.39(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
- '@langchain/langgraph-checkpoint': 1.0.1(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
+ '@langchain/core': 1.1.48(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
+ '@langchain/langgraph-checkpoint': 1.0.1(@langchain/[email protected](@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected]))
langsmith: 0.6.0(@opentelemetry/[email protected])(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected]([email protected])([email protected]))([email protected])
uuid: 11.1.1
zod: 4.3.6
@@ -19252,9 +19205,9 @@ snapshots:
dependencies:
mustache: 4.2.0
dependencies:
langfuse: 3.38.20
langfuse-core: 3.38.20
@@ -19276,6 +19229,16 @@ snapshots:
ws: 8.20.1
+ dependencies:
+ p-queue: 6.6.2
+ optionalDependencies:
+ '@opentelemetry/api': 1.9.0
+ '@opentelemetry/exporter-trace-otlp-proto': 0.218.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.7.1(@opentelemetry/[email protected])
+ ws: 8.20.1
+
@@ -20309,7 +20272,7 @@ snapshots:
eventemitter3: 4.0.7
p-timeout: 3.2.0
dependencies:
eventemitter3: 5.0.4
p-timeout: 7.0.1
@@ -21050,10 +21013,6 @@ snapshots:
- dependencies:
- glob: 10.5.0
-
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 20f8fc9486..f3ac399fd5 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -8,7 +8,7 @@ packages:
minimumReleaseAge: 7200
# the exclusions are temporary so that we can set the 5 day limit without downgrading packages.
# this list is version-specific
-# minimumReleaseAgeExclude:
+minimumReleaseAgeExclude: []
allowBuilds:
"@prisma/client": true
"@prisma/engines": true
diff --git a/web/package.json b/web/package.json
index e5d76493ce..0780631ae5 100644
--- a/web/package.json
+++ b/web/package.json
@@ -49,7 +49,7 @@
"@ferrucc-io/emoji-picker": "^0.0.47",
"@heroicons/react": "^2.2.0",
"@hookform/resolvers": "^5.2.2",
- "@langchain/core": "^1.1.39",
+ "@langchain/core": "^1.1.48",
"@langfuse/ee": "workspace:*",
"@langfuse/shared": "workspace:*",
"@lezer/highlight": "^1.2.3",
diff --git a/worker/package.json b/worker/package.json
index 748fe0439e..b3cbfba863 100644
--- a/worker/package.json
+++ b/worker/package.json
@@ -79,6 +79,7 @@
"@typescript/native-preview": "7.0.0-dev.20260122.3",
"@vitest/coverage-v8": "^4.1.4",
"eslint": "^9.39.2",
+ "google-auth-library": "^10.6.2",
"msw": "^2.6.5",
"prettier": "^3.8.3",
"ts-node": "^10.9.2",
diff --git a/worker/src/__tests__/fetchLLMCompletionReasoning.test.ts b/worker/src/__tests__/fetchLLMCompletionReasoning.test.ts
index d75dc49e30..fc1406d594 100644
--- a/worker/src/__tests__/fetchLLMCompletionReasoning.test.ts
+++ b/worker/src/__tests__/fetchLLMCompletionReasoning.test.ts
@@ -1,4 +1,33 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ AIMessage,
+ AIMessageChunk,
+} from "../../../packages/shared/node_modules/@langchain/core/messages";
+
+// Real AIMessage(Chunk) instances are required because the production code
+// reads `message.contentBlocks`, which is a class getter that dispatches to
+// `@langchain/core`'s registered translator based on `response_metadata.model_provider`.
+// Plain object mocks bypass the translator and would leave raw
+// `reasoning_content` blocks unstripped.
+function bedrockAIMessage(params: {
+ content: AIMessage["content"];
+ tool_calls?: AIMessage["tool_calls"];
+}): AIMessage {
+ return new AIMessage({
+ content: params.content,
+ tool_calls: params.tool_calls,
+ response_metadata: { model_provider: "bedrock-converse" },
+ });
+}
+
+function bedrockAIMessageChunk(params: {
+ content: AIMessage["content"];
+}): AIMessageChunk {
+ return new AIMessageChunk({
+ content: params.content,
+ response_metadata: { model_provider: "bedrock-converse" },
+ });
+}
const invokeMock = vi.fn();
const streamMock = vi.fn();
@@ -89,9 +118,7 @@ describe("fetchLLMCompletion Bedrock reasoning blocks", () => {
});
it("preserves plain string completions when Bedrock returns no reasoning", async () => {
- invokeMock.mockResolvedValue({
- content: "4",
- });
+ invokeMock.mockResolvedValue(bedrockAIMessage({ content: "4" }));
const completion = await fetchLLMCompletion({
streaming: false,
@@ -121,15 +148,17 @@ describe("fetchLLMCompletion Bedrock reasoning blocks", () => {
});
it("returns Bedrock GPT OSS reasoning separately from text", async () => {
- invokeMock.mockResolvedValue({
- content: [
- {
- type: "reasoning_content",
- reasoningText: { text: "Compute the arithmetic." },
- },
- { type: "text", text: "4" },
- ],
- });
+ invokeMock.mockResolvedValue(
+ bedrockAIMessage({
+ content: [
+ {
+ type: "reasoning_content",
+ reasoningText: "Compute the arithmetic.",
+ },
+ { type: "text", text: "4" },
+ ],
+ }),
+ );
const completion = await fetchLLMCompletion({
streaming: false,
@@ -162,22 +191,24 @@ describe("fetchLLMCompletion Bedrock reasoning blocks", () => {
});
it("strips Bedrock reasoning blocks before parsing tool calls", async () => {
- bindToolsInvokeMock.mockResolvedValue({
- content: [
- {
- type: "reasoning_content",
- reasoningText: { text: "Need the weather tool." },
- },
- { type: "text", text: "" },
- ],
- tool_calls: [
- {
- id: "tool-use-1",
- name: "get_weather",
- args: { location: "Paris" },
- },
- ],
- });
+ bindToolsInvokeMock.mockResolvedValue(
+ bedrockAIMessage({
+ content: [
+ {
+ type: "reasoning_content",
+ reasoningText: "Need the weather tool.",
+ },
+ { type: "text", text: "" },
+ ],
+ tool_calls: [
+ {
+ id: "tool-use-1",
+ name: "get_weather",
+ args: { location: "Paris" },
+ },
+ ],
+ }),
+ );
const completion = await fetchLLMCompletion({
streaming: false,
@@ -231,17 +262,17 @@ describe("fetchLLMCompletion Bedrock reasoning blocks", () => {
it("filters Bedrock reasoning blocks out of streaming output", async () => {
streamMock.mockImplementation(async function* () {
- yield {
+ yield bedrockAIMessageChunk({
content: [
{
type: "reasoning_content",
- reasoningText: { text: "Do not show this in the playground." },
+ reasoningText: "Do not show this in the playground.",
},
],
- };
- yield {
+ });
+ yield bedrockAIMessageChunk({
content: [{ type: "text", text: "Hello!" }],
- };
+ });
} as any);
const stream = await fetchLLMCompletion({
diff --git a/worker/src/__tests__/fetchLLMCompletionTimeout.test.ts b/worker/src/__tests__/fetchLLMCompletionTimeout.test.ts
index e1641a8aef..af2fd145ce 100644
--- a/worker/src/__tests__/fetchLLMCompletionTimeout.test.ts
+++ b/worker/src/__tests__/fetchLLMCompletionTimeout.test.ts
@@ -1,9 +1,10 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { AIMessage } from "../../../packages/shared/node_modules/@langchain/core/messages";
const invokeMock = vi.fn();
const streamMock = vi.fn();
const bedrockInvokeMock = vi.fn();
-const chatVertexAIConstructorMock = vi.fn().mockImplementation(function () {
+const chatGoogleConstructorMock = vi.fn().mockImplementation(function () {
return {
invoke: invokeMock,
pipe: vi.fn().mockReturnValue({
@@ -68,13 +69,16 @@ describe("fetchLLMCompletion runtime timeouts", () => {
vi.useFakeTimers();
invokeMock.mockReset();
streamMock.mockReset();
- chatVertexAIConstructorMock.mockClear();
+ chatGoogleConstructorMock.mockClear();
vi.resetModules();
originalCloudRegion = process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
- vi.doMock("@langchain/google-vertexai", () => ({
- ChatVertexAI: chatVertexAIConstructorMock,
- }));
+ vi.doMock(
+ "../../../packages/shared/node_modules/@langchain/google",
+ () => ({
+ ChatGoogle: chatGoogleConstructorMock,
+ }),
+ );
vi.doMock("../../../packages/shared/src/server/llm/errors", () => ({
LLMCompletionError: MockLLMCompletionError,
}));
@@ -174,6 +178,47 @@ describe("fetchLLMCompletion runtime timeouts", () => {
await vi.runOnlyPendingTimersAsync();
await completionRejection;
});
+
+ it("passes Google AI Studio thinking provider options as ChatGoogle top-level fields", async () => {
+ invokeMock.mockResolvedValue(new AIMessage("4"));
+
+ await fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "What is 2+2? Answer only with the number.",
+ type: "public-api-created",
+ },
+ ],
+ modelParams: {
+ provider: "google-ai-studio",
+ adapter: "google-ai-studio",
+ model: "gemini-2.5-flash",
+ temperature: 0,
+ max_tokens: 10,
+ providerOptions: {
+ thinkingBudget: 1024,
+ thinkingLevel: "high",
+ },
+ },
+ llmConnection: {
+ secretKey: encrypt("google-api-key"),
+ },
+ });
+
+ expect(chatGoogleConstructorMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ thinkingBudget: 1024,
+ thinkingLevel: "high",
+ }),
+ );
+ expect(chatGoogleConstructorMock).not.toHaveBeenCalledWith(
+ expect.objectContaining({
+ thinkingConfig: expect.anything(),
+ }),
+ );
+ });
});
describe("fetchLLMCompletion end of model lifetime", () => {
diff --git a/worker/src/__tests__/googleSecureApiClient.test.ts b/worker/src/__tests__/googleSecureApiClient.test.ts
new file mode 100644
index 0000000000..cccfbfceec
--- /dev/null
+++ b/worker/src/__tests__/googleSecureApiClient.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, test } from "vitest";
+import { rewriteGoogleAIStudioUrl } from "../../../packages/shared/src/server/llm/googleSecureApiClient";
+
+// Real Google Vertex AI and AI Studio request paths are exercised end-to-end
+// in llmConnections.test.ts against live APIs. This file keeps the pure
+// URL-rewrite unit cases that the live tests can't easily express.
+
+describe("rewriteGoogleAIStudioUrl", () => {
+ test.each([
+ {
+ name: "custom base URL",
+ requestUrl:
+ "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent",
+ baseURL: "https://example.com/google",
+ expectedUrl:
+ "https://example.com/google/v1beta/models/gemini-2.5-flash:generateContent",
+ },
+ {
+ name: "opaque custom base URL prefix",
+ requestUrl:
+ "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
+ baseURL:
+ "https://86c599932057.ngrok.app?url=https://generativelanguage.googleapis.com",
+ expectedUrl:
+ "https://86c599932057.ngrok.app?url=https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse",
+ },
+ {
+ name: "non-Google URL",
+ requestUrl: "https://other.example.com/v1beta/models/model:generate",
+ baseURL: "https://example.com/google",
+ expectedUrl: "https://other.example.com/v1beta/models/model:generate",
+ },
+ {
+ name: "unset base URL",
+ requestUrl:
+ "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent",
+ baseURL: undefined,
+ expectedUrl:
+ "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent",
+ },
+ ])("rewrites $name", ({ requestUrl, baseURL, expectedUrl }) => {
+ expect(rewriteGoogleAIStudioUrl(requestUrl, baseURL)).toBe(expectedUrl);
+ });
+});
diff --git a/worker/src/__tests__/helpers/localLlmServer.ts b/worker/src/__tests__/helpers/localLlmServer.ts
new file mode 100644
index 0000000000..77740a5489
--- /dev/null
+++ b/worker/src/__tests__/helpers/localLlmServer.ts
@@ -0,0 +1,59 @@
+import {
+ createServer,
+ type IncomingMessage,
+ type ServerResponse,
+} from "node:http";
+import type { AddressInfo } from "node:net";
+
+export type RecordedRequest = {
+ method: string;
+ url: string;
+ headers: Record<string, string | string[] | undefined>;
+ body: string;
+};
+
+export type LocalLlmServerHandler = (
+ req: IncomingMessage,
+ body: string,
+ res: ServerResponse,
+) => void;
+
+export type LocalLlmServer = {
+ url: string;
+ host: string;
+ requests: RecordedRequest[];
+ close: () => Promise<void>;
+};
+
+export async function startLocalLlmServer(
+ handler: LocalLlmServerHandler,
+): Promise<LocalLlmServer> {
+ const requests: RecordedRequest[] = [];
+ const server = createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on("data", (chunk: Buffer) => chunks.push(chunk));
+ req.on("end", () => {
+ const body = Buffer.concat(chunks).toString("utf-8");
+ requests.push({
+ method: req.method ?? "",
+ url: req.url ?? "",
+ headers: req.headers,
+ body,
+ });
+ handler(req, body, res);
+ });
+ });
+
+ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const port = (server.address() as AddressInfo).port;
+
+ return {
+ url: `http://127.0.0.1:${port}`,
+ host: "127.0.0.1",
+ requests,
+ close: () =>
+ new Promise<void>((resolve, reject) =>
+ server.close((err) => (err ? reject(err) : resolve())),
+ ),
+ };
+}
diff --git a/worker/src/__tests__/secureLlmFetch.test.ts b/worker/src/__tests__/secureLlmFetch.test.ts
new file mode 100644
index 0000000000..d92ce1fd8d
--- /dev/null
+++ b/worker/src/__tests__/secureLlmFetch.test.ts
@@ -0,0 +1,230 @@
+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
+import { encrypt } from "../../../packages/shared/src/encryption";
+import { env } from "../../../packages/shared/src/env";
+import {
+ ChatMessageType,
+ LLMAdapter,
+} from "../../../packages/shared/src/server/llm/types";
+import { fetchLLMCompletion } from "../../../packages/shared/src/server/llm/fetchLLMCompletion";
+import {
+ createSecureLlmFetch,
+ fetchSecureLlmUrl,
+} from "../../../packages/shared/src/server/llm/secureLlmFetch";
+import { RedirectValidationError } from "../../../packages/shared/src/server/outbound-url";
+import {
+ startLocalLlmServer,
+ type LocalLlmServer,
+} from "./helpers/localLlmServer";
+
+// These tests replace the previous mock-heavy unit tests for the secure LLM
+// fetch path. The happy-path wiring is now proven against a real local HTTP
+// server (so a regression in the SDK -> secureLlmFetch handoff is caught
+// without provider credentials), and the security-boundary cases use the
+// validator directly to avoid coupling to provider SDK error wrapping.
+// Production end-to-end coverage continues to live in llmConnections.test.ts.
+
+const OPENAI_RESPONSE_BODY = JSON.stringify({
+ id: "chatcmpl-test",
+ object: "chat.completion",
+ created: 1,
+ model: "gpt-4o-mini",
+ choices: [
+ {
+ index: 0,
+ message: { role: "assistant", content: "4" },
+ finish_reason: "stop",
+ },
+ ],
+});
+
+describe("secure LLM fetch", () => {
+ const originalWhitelistedHosts = env.LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST;
+ // env is the zod-validated object: read from process.env at module load and
+ // not refreshed afterward. Mutating process.env later is a no-op for the
+ // code under test, so we mutate `env.*` directly and restore in afterEach.
+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ const servers: LocalLlmServer[] = [];
+
+ beforeEach(() => {
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;
+ env.LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST = ["127.0.0.1"];
+ });
+
+ afterEach(async () => {
+ vi.restoreAllMocks();
+ await Promise.all(servers.splice(0).map((s) => s.close()));
+ env.LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST = originalWhitelistedHosts;
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
+ });
+
+ async function spinUp(handler: Parameters<typeof startLocalLlmServer>[0]) {
+ const server = await startLocalLlmServer(handler);
+ servers.push(server);
+ return server;
+ }
+
+ describe("end-to-end SDK wiring", () => {
+ // Allow ample headroom for first-run module import + SDK warmup; the
+ // actual request to 127.0.0.1 is sub-second.
+ test(
+ "OpenAI SDK routes through secureLlmFetch and reaches the configured base URL",
+ { timeout: 30_000 },
+ async () => {
+ const server = await spinUp((_req, _body, res) => {
+ res.setHeader("content-type", "application/json");
+ res.end(OPENAI_RESPONSE_BODY);
+ });
+
+ const completion = await fetchLLMCompletion({
+ streaming: false,
+ messages: [
+ {
+ role: "user",
+ content: "What is 2+2? Answer only with the number.",
+ type: ChatMessageType.PublicAPICreated,
+ },
+ ],
+ modelParams: {
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ model: "gpt-4o-mini",
+ temperature: 0,
+ max_tokens: 10,
+ },
+ llmConnection: {
+ secretKey: encrypt("openai-api-key"),
+ baseURL: `${server.url}/v1`,
+ },
+ });
+
+ expect(completion).toBe("4");
+ expect(server.requests).toHaveLength(1);
+ const [request] = server.requests;
+ expect(request.method).toBe("POST");
+ expect(request.url).toBe("/v1/chat/completions");
+ expect(request.headers.authorization).toBe("Bearer openai-api-key");
+ // Body is buffered (not streamed) so redirect retry stays possible.
+ expect(JSON.parse(request.body)).toMatchObject({
+ model: "gpt-4o-mini",
+ });
+ },
+ );
+ });
+
+ describe("SSRF protection", () => {
+ test("ignores caller-supplied dispatchers so connection validation can install its own", async () => {
+ const leakedDispatcher = { name: "sdk-dispatcher" };
+ const fetchSpy = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue(new Response("ok"));
+
+ await expect(
+ fetchSecureLlmUrl(
+ "https://example.com/v1/chat/completions",
+ {
+ method: "POST",
+ dispatcher: leakedDispatcher,
+ } as RequestInit & { dispatcher: unknown },
+ {
+ logContext: "Test LLM endpoint",
+ whitelist: { hosts: ["example.com"], ips: [], ip_ranges: [] },
+ },
+ ),
+ ).resolves.toBeInstanceOf(Response);
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [, fetchOptions] = fetchSpy.mock.calls[0] as Parameters<
+ typeof fetch
+ >;
+ expect(
+ (fetchOptions as { dispatcher?: unknown }).dispatcher,
+ ).toBeDefined();
+ expect((fetchOptions as { dispatcher?: unknown }).dispatcher).not.toBe(
+ leakedDispatcher,
+ );
+ });
+
+ test("rejects link-local metadata hostnames before opening a socket", async () => {
+ env.LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST = [];
+
+ await expect(
+ fetchSecureLlmUrl(
+ // Cloud metadata IPs are in the static hostname deny list, so this
+ // throws "Blocked hostname detected" before any DNS or IP check.
+ "http://169.254.169.254/v1/chat/completions",
+ { method: "POST" },
+ { logContext: "Test LLM endpoint" },
+ ),
+ ).rejects.toThrow(/Blocked hostname detected/);
+ });
+
+ test("rejects HTTP base URLs when running on Langfuse Cloud", async () => {
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "US";
+
+ await expect(
+ fetchSecureLlmUrl(
+ "http://example.com/v1/chat/completions",
+ { method: "POST" },
+ { logContext: "Test LLM endpoint" },
+ ),
+ ).rejects.toThrow(/Only HTTPS base URLs are allowed/);
+ });
+ });
+
+ describe("redirect validation", () => {
+ test("rejects redirects pointing at a blocked target", async () => {
+ const server = await spinUp((_req, _body, res) => {
+ res.statusCode = 302;
+ res.setHeader("location", "http://169.254.169.254/v1/chat/completions");
+ res.end();
+ });
+
+ const secureFetch = createSecureLlmFetch({
+ logContext: "Test LLM endpoint",
+ });
+
+ await expect(
+ secureFetch(`${server.url}/v1/chat/completions`, {
+ method: "POST",
+ headers: { authorization: "Bearer leakable-token" },
+ body: JSON.stringify({ messages: [] }),
+ }),
+ ).rejects.toBeInstanceOf(RedirectValidationError);
+ });
+
+ test("strips additional sensitive headers on cross-origin redirects", async () => {
+ const target = await spinUp((_req, _body, res) => {
+ res.setHeader("content-type", "application/json");
+ res.end(OPENAI_RESPONSE_BODY);
+ });
+ const redirector = await spinUp((_req, _body, res) => {
+ res.statusCode = 302;
+ res.setHeader("location", `${target.url}/v1/chat/completions`);
+ res.end();
+ });
+
+ const secureFetch = createSecureLlmFetch({
+ logContext: "Test LLM endpoint",
+ additionalSensitiveHeaders: ["x-api-key"],
+ });
+
+ await secureFetch(`${redirector.url}/v1/chat/completions`, {
+ method: "POST",
+ headers: {
+ authorization: "Bearer leakable-token",
+ "x-api-key": "leakable-key",
+ "x-non-sensitive": "keep-me",
+ },
+ body: JSON.stringify({ messages: [] }),
+ });
+
+ expect(target.requests).toHaveLength(1);
+ const forwarded = target.requests[0];
+ // Default + caller-provided sensitive headers are stripped across origins.
+ expect(forwarded.headers.authorization).toBeUndefined();
+ expect(forwarded.headers["x-api-key"]).toBeUndefined();
+ // Non-sensitive headers survive the redirect.
+ expect(forwarded.headers["x-non-sensitive"]).toBe("keep-me");
+ });
+ });
+});