🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix: use secure cookies for chatCompletion endpoint in prod environment (#1482)
Hassieb Pakzad06fdc336278f
diff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex a21a8f9547..d04af430c1 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -1,9 +1,3 @@-import {- type ChatMessage,- ChatMessageRole,- type ModelParams,- ModelProvider,-} from "./types";import { ChatAnthropic } from "@langchain/anthropic";import {AIMessage,@@ -14,8 +8,16 @@ import {BytesOutputParser,StringOutputParser,} from "@langchain/core/output_parsers";+import { IterableReadableStream } from "@langchain/core/utils/stream";import { ChatOpenAI } from "@langchain/openai";+import {+ ChatMessage,+ ChatMessageRole,+ ModelParams,+ ModelProvider,+} from "./types";+type LLMCompletionParams = {messages: ChatMessage[];modelParams: ModelParams;@@ -29,7 +31,7 @@ export async function fetchLLMCompletion(params: LLMCompletionParams & {streaming: true;}-): Promise<ReadableStream<Uint8Array>>;+): Promise<IterableReadableStream<Uint8Array>>;export async function fetchLLMCompletion(params: LLMCompletionParams & {@@ -39,7 +41,7 @@ export async function fetchLLMCompletion(export async function fetchLLMCompletion(params: FetchLLMCompletionParams-): Promise<string | ReadableStream<Uint8Array>> {+): Promise<string | IterableReadableStream<Uint8Array>> {const { messages, modelParams, streaming } = params;const finalMessages = messages.map((message) => {if (message.role === ChatMessageRole.User)diff --git a/web/src/features/playground/server/chatCompletionHandler.ts b/web/src/features/playground/server/chatCompletionHandler.tsindex d103b5e954..0b553af7e8 100644--- a/web/src/features/playground/server/chatCompletionHandler.ts+++ b/web/src/features/playground/server/chatCompletionHandler.ts@@ -3,13 +3,20 @@ import { getToken } from "next-auth/jwt";import { type NextRequest, NextResponse } from "next/server";import { fetchLLMCompletion } from "@langfuse/shared/src/server/llm/fetchLLMCompletion";+import {- type ValidatedChatCompletionBody,validateChatCompletionBody,+ type ValidatedChatCompletionBody,} from "./validateChatCompletionBody";+import { getCookieName } from "@/src/server/utils/cookies";export default async function chatCompletionHandler(req: NextRequest) {- if (!(await getToken({ req })))+ const token = await getToken({+ req,+ cookieName: getCookieName("next-auth.session-token"),+ });++ if (!token)return NextResponse.json({ message: "Unauthenticated" }, { status: 401 });if (req.method !== "POST")diff --git a/web/src/server/auth.ts b/web/src/server/auth.tsindex 63793c6710..d67e9c78d4 100644--- a/web/src/server/auth.ts+++ b/web/src/server/auth.ts@@ -19,27 +19,7 @@ import GoogleProvider from "next-auth/providers/google";import GitHubProvider from "next-auth/providers/github";import AzureADProvider from "next-auth/providers/azure-ad";import { type Provider } from "next-auth/providers/index";--// Use secure cookies on https hostnames, exception for Vercel which sets NEXTAUTH_URL without the protocol-const useSecureCookies =- env.NEXTAUTH_URL.startsWith("https://") || process.env.VERCEL === "1";--const cookieOptions = {- domain: env.NEXTAUTH_COOKIE_DOMAIN ?? undefined,- httpOnly: true,- sameSite: "lax",- path: "/",- secure: useSecureCookies,-};--const cookieName = (name: string) =>- [- useSecureCookies ? "__Secure-" : "",- name,- env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION- ? `.${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}`- : "",- ].join("");+import { getCookieName, cookieOptions } from "./utils/cookies";const providers: Provider[] = [CredentialsProvider({@@ -223,27 +203,27 @@ export const authOptions: NextAuthOptions = {},cookies: {sessionToken: {- name: cookieName("next-auth.session-token"),+ name: getCookieName("next-auth.session-token"),options: cookieOptions,},csrfToken: {- name: cookieName("next-auth.csrf-token"),+ name: getCookieName("next-auth.csrf-token"),options: cookieOptions,},callbackUrl: {- name: cookieName("next-auth.callback-url"),+ name: getCookieName("next-auth.callback-url"),options: cookieOptions,},state: {- name: cookieName("next-auth.state"),+ name: getCookieName("next-auth.state"),options: cookieOptions,},nonce: {- name: cookieName("next-auth.nonce"),+ name: getCookieName("next-auth.nonce"),options: cookieOptions,},pkceCodeVerifier: {- name: cookieName("next-auth.pkce.code_verifier"),+ name: getCookieName("next-auth.pkce.code_verifier"),options: cookieOptions,},},diff --git a/web/src/server/utils/cookies.ts b/web/src/server/utils/cookies.tsnew file mode 100644index 0000000000..848296ebdf--- /dev/null+++ b/web/src/server/utils/cookies.ts@@ -0,0 +1,22 @@+import { env } from "@/src/env.mjs";++// Use secure cookies on https hostnames, exception for Vercel which sets NEXTAUTH_URL without the protocol+const shouldSecureCookies =+ env.NEXTAUTH_URL.startsWith("https://") || process.env.VERCEL === "1";++export const cookieOptions = {+ domain: env.NEXTAUTH_COOKIE_DOMAIN ?? undefined,+ httpOnly: true,+ sameSite: "lax",+ path: "/",+ secure: shouldSecureCookies,+};++export const getCookieName = (name: string) =>+ [+ shouldSecureCookies ? "__Secure-" : "",+ name,+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION+ ? `.${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}`+ : "",+ ].join("");diff --git a/web/tsconfig.json b/web/tsconfig.jsonindex afcd24dd75..0c431eeefc 100644--- a/web/tsconfig.json+++ b/web/tsconfig.json@@ -10,10 +10,16 @@}],"paths": {- "@/*": ["./*"]- }+ "@/*": [+ "./*"+ ]+ },+ "strictNullChecks": true},- "exclude": ["node_modules", "sdk"],+ "exclude": [+ "node_modules",+ "sdk"+ ],"include": ["src","next-env.d.ts",