Skip to content

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

feat: use custom keys for playground (#2139)

Hassieb Pakzadd1c1e60eca1a
diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.ts
index 1fefd630b9..de7524087a 100644
--- a/packages/shared/prisma/seed.ts
+++ b/packages/shared/prisma/seed.ts
@@ -12,6 +12,7 @@ import { chunk } from "lodash";
import { v4 } from "uuid";
import { ModelUsageUnit } from "../src";
import { getDisplaySecretKey, hashSecretKey } from "../src/server/auth";
+import { encrypt } from "../src/encryption";
const LOAD_TRACE_VOLUME = 10_000;
@@ -165,6 +166,24 @@ async function main() {
await uploadObjects(traces, observations, scores, sessions, events);
+ // If openai key is in environment, add it to the projects LLM API keys
+ const OPENAI_API_KEY = process.env.OPENAI_API_KEY;
+
+ if (OPENAI_API_KEY) {
+ await prisma.llmApiKeys.create({
+ data: {
+ projectId: project1.id,
+ secretKey: encrypt(OPENAI_API_KEY),
+ displaySecretKey: getDisplaySecretKey(OPENAI_API_KEY),
+ provider: "openai",
+ },
+ });
+ } else {
+ console.warn(
+ "No OPENAI_API_KEY found in environment. Skipping seeding LLM API key."
+ );
+ }
+
// add eval objects
const evalTemplate = await prisma.evalTemplate.upsert({
where: {
diff --git a/web/src/app/api/chatCompletion/route.ts b/web/src/app/api/chatCompletion/route.ts
new file mode 100644
index 0000000000..6acf98aca9
--- /dev/null
+++ b/web/src/app/api/chatCompletion/route.ts
@@ -0,0 +1,6 @@
+import chatCompletionHandler from "@/src/ee/features/playground/server/chatCompletionHandler";
+
+export const dynamic = "force-dynamic";
+export const maxDuration = 60;
+
+export const POST = chatCompletionHandler;
diff --git a/web/src/components/ModelParameters/LLMApiKeyComponent.tsx b/web/src/components/ModelParameters/LLMApiKeyComponent.tsx
new file mode 100644
index 0000000000..0ac49cc2f4
--- /dev/null
+++ b/web/src/components/ModelParameters/LLMApiKeyComponent.tsx
@@ -0,0 +1,77 @@
+import Link from "next/link";
+
+import { Label } from "@/src/components/ui/label";
+import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
+import { api } from "@/src/utils/api";
+import { supportedModels, type UIModelParams } from "@langfuse/shared";
+import { ArrowTopRightIcon } from "@radix-ui/react-icons";
+
+export const LLMApiKeyComponent = (p: {
+ projectId: string;
+ modelParams: UIModelParams;
+}) => {
+ const hasAccess = useHasAccess({
+ projectId: p.projectId,
+ scope: "llmApiKeys:read",
+ });
+
+ if (!hasAccess) {
+ return (
+ <div>
+ <Label className="text-xs font-semibold">API key</Label>
+ <p className="text-sm text-muted-foreground">
+ LLM API Key only visible to Owner and Admin roles.
+ </p>
+ </div>
+ );
+ }
+
+ const apiKeys = api.llmApiKey.all.useQuery({
+ projectId: p.projectId,
+ });
+
+ if (apiKeys.isLoading) {
+ return (
+ <div>
+ <Label className="text-xs font-semibold">API key</Label>
+ <p className="text-sm text-muted-foreground">Loading...</p>
+ </div>
+ );
+ }
+
+ const model = p.modelParams.model.value;
+ const modelProvider = Object.entries(supportedModels).find((providerData) =>
+ (providerData[1] as any as string[]).includes(model),
+ )?.[0];
+
+ const apiKey = apiKeys.data?.data.find((k) => k.provider === modelProvider);
+
+ return (
+ <div className="space-y-2 text-xs">
+ <Label className="text-xs font-semibold">API key</Label>
+ <div>
+ {apiKey ? (
+ <span className="mr-2 rounded-sm bg-input p-1 text-xs">
+ {apiKey.displaySecretKey}
+ </span>
+ ) : undefined}
+ </div>
+ {/* Custom form message to include a link to the already existing prompt */}
+ {!apiKey ? (
+ <div className="flex flex-col font-medium text-destructive">
+ {`No LLM API key found for provider ${modelProvider}.`}
+
+ <Link
+ href={`/project/${p.projectId}/settings`}
+ className="flex flex-row"
+ >
+ Create a new LLM API key here. <ArrowTopRightIcon />
+ </Link>
+ </div>
+ ) : undefined}
+ <p className="text-muted-foreground">
+ The LLM API key is used for each execution and will incur costs.
+ </p>
+ </div>
+ );
+};
diff --git a/web/src/components/ModelParameters.tsx b/web/src/components/ModelParameters/index.tsx
similarity index 95%
rename from web/src/components/ModelParameters.tsx
rename to web/src/components/ModelParameters/index.tsx
index fa80a9946c..2c8b26ee4b 100644
--- a/web/src/components/ModelParameters.tsx
+++ b/web/src/components/ModelParameters/index.tsx
@@ -8,6 +8,7 @@ import {
} from "@/src/components/ui/select";
import { Slider } from "@/src/components/ui/slider";
import { Switch } from "@/src/components/ui/switch";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
import { cn } from "@/src/utils/tailwind";
import {
ModelProvider,
@@ -15,6 +16,8 @@ import {
type UIModelParams,
} from "@langfuse/shared";
+import { LLMApiKeyComponent } from "./LLMApiKeyComponent";
+
export type ModelParamsContext = {
modelParams: UIModelParams;
availableModels?: UIModelParams[];
@@ -33,10 +36,14 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
setModelParamEnabled,
formDisabled = false,
}) => {
+ const projectId = useProjectIdFromURL();
+
+ if (!projectId) return null;
+
return (
<div className="flex flex-col space-y-4">
<p className="font-semibold">Model</p>
- <div className="space-y-6">
+ <div className="space-y-4">
<ModelParamsSelect
title="Provider"
modelParamsKey="provider"
@@ -104,6 +111,7 @@ export const ModelParameters: React.FC<ModelParamsContext> = ({
tooltip="An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered. We generally recommend altering this or temperature but not both."
updateModelParam={updateModelParamValue}
/>
+ <LLMApiKeyComponent {...{ projectId, modelParams }} />
</div>
</div>
);
diff --git a/web/src/ee/features/evals/components/template-form.tsx b/web/src/ee/features/evals/components/template-form.tsx
index a58afcd18a..e95b21140b 100644
--- a/web/src/ee/features/evals/components/template-form.tsx
+++ b/web/src/ee/features/evals/components/template-form.tsx
@@ -33,8 +33,6 @@ import {
type ModelParams,
} from "@langfuse/shared";
import { PromptDescription } from "@/src/features/prompts/components/prompt-description";
-import Link from "next/dist/client/link";
-import { ArrowTopRightIcon } from "@radix-ui/react-icons";
import {
Select,
SelectContent,
@@ -43,8 +41,6 @@ import {
SelectValue,
} from "@/src/components/ui/select";
import { TEMPLATES } from "@/src/ee/features/evals/components/templates";
-import { Label } from "@/src/components/ui/label";
-import { useHasAccess } from "@/src/features/rbac/utils/checkAccess";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
import { getFinalModelParams } from "@/src/ee/utils/getFinalModelParams";
@@ -439,10 +435,6 @@ export const InnerEvalTemplateForm = (props: {
availableModels={[...evalLLMModels]}
formDisabled={!props.isEditing}
/>
- <LLMApiKeyComponent
- projectId={props.projectId}
- modelParams={modelParams}
- />
</div>
</div>
@@ -465,78 +457,6 @@ export const InnerEvalTemplateForm = (props: {
);
};
-export const LLMApiKeyComponent = (p: {
- projectId: string;
- modelParams: UIModelParams;
-}) => {
- const hasAccess = useHasAccess({
- projectId: p.projectId,
- scope: "llmApiKeys:read",
- });
-
- if (!hasAccess) {
- return (
- <div>
- <Label>API key</Label>
- <p className="text-sm text-muted-foreground">
- LLM API Key only visible to Owner and Admin roles.
- </p>
- </div>
- );
- }
-
- const apiKeys = api.llmApiKey.all.useQuery({
- projectId: p.projectId,
- });
-
- if (apiKeys.isLoading) {
- return (
- <div>
- <Label>API key</Label>
- <p className="text-sm text-muted-foreground">Loading...</p>
- </div>
- );
- }
-
- const getModelProvider = (model: string) => {
- return evalLLMModels.find((m) => m.model.value === model)?.provider.value;
- };
-
- const getApiKeyForModel = (model: string) => {
- const modelProvider = getModelProvider(model);
- return apiKeys.data?.data.find((k) => k.provider === modelProvider);
- };
-
- return (
- <div>
- <Label>API key</Label>
- <div>
- {getApiKeyForModel(p.modelParams.model.value) ? (
- <span className="mr-2 rounded-sm bg-input p-1 text-xs">
- {getApiKeyForModel(p.modelParams.model.value)?.displaySecretKey}
- </span>
- ) : undefined}
- </div>
- {/* Custom form message to include a link to the already existing prompt */}
- {!getApiKeyForModel(p.modelParams.model.value) ? (
- <div className="flex flex-col text-sm font-medium text-destructive">
- {"No LLM API key found."}
-
- <Link
- href={`/project/${p.projectId}/settings`}
- className="flex flex-row"
- >
- Create a new API key here. <ArrowTopRightIcon />
- </Link>
- </div>
- ) : undefined}
- <p className="text-sm text-muted-foreground">
- The API key is used for each evaluation and will incur costs.
- </p>
- </div>
- );
-};
-
function getModelParamsWithEnabledFlag(
evalPreFill?: EvalTemplateFormPreFill,
): UIModelParams {
diff --git a/web/src/ee/features/playground/page/context/index.tsx b/web/src/ee/features/playground/page/context/index.tsx
index c318360929..dd8d291d30 100644
--- a/web/src/ee/features/playground/page/context/index.tsx
+++ b/web/src/ee/features/playground/page/context/index.tsx
@@ -14,6 +14,7 @@ import useCommandEnter from "@/src/ee/features/playground/page/hooks/useCommandE
import usePlaygroundCache from "@/src/ee/features/playground/page/hooks/usePlaygroundCache";
import { getFinalModelParams } from "@/src/ee/utils/getFinalModelParams";
import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";
+import useProjectIdFromURL from "@/src/hooks/useProjectIdFromURL";
import { extractVariables } from "@/src/utils/string";
import {
ChatMessageRole,
@@ -57,6 +58,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
children,
}) => {
const capture = usePostHogClientCapture();
+ const projectId = useProjectIdFromURL();
const { playgroundCache, setPlaygroundCache } = usePlaygroundCache();
const [promptVariables, setPromptVariables] = useState<PromptVariable[]>([]);
const [output, setOutput] = useState("");
@@ -172,6 +174,7 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
}
const completionStream = getChatCompletionStream(
+ projectId,
finalMessages,
modelParams,
);
@@ -263,10 +266,17 @@ export const PlaygroundProvider: React.FC<PropsWithChildren> = ({
};
async function* getChatCompletionStream(
+ projectId: string | undefined,
messages: ChatMessageWithId[],
modelParams: UIModelParams,
) {
+ if (!projectId) {
+ console.error("Project ID is not set");
+ return;
+ }
+
const body = JSON.stringify({
+ projectId,
messages,
modelParams: getFinalModelParams(modelParams),
});
diff --git a/web/src/ee/features/playground/page/playground.tsx b/web/src/ee/features/playground/page/playground.tsx
index 1acd09d43e..09ec7e1067 100644
--- a/web/src/ee/features/playground/page/playground.tsx
+++ b/web/src/ee/features/playground/page/playground.tsx
@@ -16,7 +16,7 @@ export default function Playground() {
<div className="basis-[55%] ">
<ModelParameters {...playgroundContext} />
</div>
- <div className="basis-[45%] overflow-auto">
+ <div className="mt-4 basis-[45%] overflow-auto">
<Variables />
</div>
</div>
diff --git a/web/src/ee/features/playground/server/authorizeRequest.ts b/web/src/ee/features/playground/server/authorizeRequest.ts
new file mode 100644
index 0000000000..2aa006bde5
--- /dev/null
+++ b/web/src/ee/features/playground/server/authorizeRequest.ts
@@ -0,0 +1,26 @@
+import { getServerSession } from "next-auth";
+
+import { getIsCloudEnvironment } from "@/src/ee/utils/getIsCloudEnvironment";
+import { getAuthOptions } from "@/src/server/auth";
+import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";
+import { ApiError, ForbiddenError, UnauthorizedError } from "@langfuse/shared";
+
+export type AuthorizeRequestResult = {
+ userId: string;
+};
+
+export const authorizeRequestOrThrow = async (
+ projectId: string,
+): Promise<AuthorizeRequestResult> => {
+ if (!getIsCloudEnvironment())
+ throw new ApiError("This endpoint is available in Langfuse cloud only.");
+
+ const authOptions = await getAuthOptions();
+ const session = await getServerSession(authOptions);
+ if (!session?.user) throw new UnauthorizedError("Unauthenticated");
+
+ if (!isProjectMemberOrAdmin(session.user, projectId))
+ throw new ForbiddenError("User is not a member of this project");
+
+ return { userId: session.user.id };
+};
diff --git a/web/src/ee/features/playground/server/chatCompletionHandler.ts b/web/src/ee/features/playground/server/chatCompletionHandler.ts
index fc8c38edd2..f7fe958611 100644
--- a/web/src/ee/features/playground/server/chatCompletionHandler.ts
+++ b/web/src/ee/features/playground/server/chatCompletionHandler.ts
@@ -1,75 +1,60 @@
import { StreamingTextResponse } from "ai";
-import { getToken } from "next-auth/jwt";
-import { type NextRequest, NextResponse } from "next/server";
+import { NextResponse, type NextRequest } from "next/server";
-import { fetchLLMCompletion } from "@langfuse/shared";
-
-import { PosthogCallbackHandler } from "./analytics/posthogCallback";
import {
- validateChatCompletionBody,
- type ValidatedChatCompletionBody,
-} from "./validateChatCompletionBody";
-import { getCookieName } from "@/src/server/utils/cookies";
-import { env } from "@/src/env.mjs";
-import { getIsCloudEnvironment } from "@/src/ee/utils/getIsCloudEnvironment";
-
-export default async function chatCompletionHandler(req: NextRequest) {
- if (!getIsCloudEnvironment()) {
- return NextResponse.json(
- { message: "This endpoint is available in Langfuse cloud only." },
- { status: 501 },
- );
- }
-
- const token = await getToken({
- req,
- cookieName: getCookieName("next-auth.session-token"),
- secret: env.NEXTAUTH_SECRET,
- });
-
- if (!token || !token.sub)
- // sub is the user id
- return NextResponse.json({ message: "Unauthenticated" }, { status: 401 });
+ BaseError,
+ ValidationError,
+ fetchLLMCompletion,
+} from "@langfuse/shared";
- if (req.method !== "POST")
- return NextResponse.json(
- { message: "Method not allowed" },
- { status: 405 },
- );
+import { PosthogCallbackHandler } from "./analytics/posthogCallback";
+import { authorizeRequestOrThrow } from "./authorizeRequest";
+import { validateChatCompletionBody } from "./validateChatCompletionBody";
- let body: ValidatedChatCompletionBody;
+import { prisma } from "@langfuse/shared/src/db";
+import { decrypt } from "@langfuse/shared/encryption";
+export default async function chatCompletionHandler(req: NextRequest) {
try {
- body = validateChatCompletionBody(await req.json());
- } catch (err) {
- console.error(err);
+ const body = validateChatCompletionBody(await req.json());
+ const { userId } = await authorizeRequestOrThrow(body.projectId);
+
+ const { messages, modelParams } = body;
- return NextResponse.json(
- {
- message: "Invalid request body",
- error: err,
+ const LLMApiKey = await prisma.llmApiKeys.findFirst({
+ where: {
+ projectId: body.projectId,
+ provider: modelParams.provider,
},
- { status: 400 },
- );
- }
+ });
+
+ if (!LLMApiKey)
+ throw new ValidationError(
+ `No ${modelParams.provider} API key found in project. Please add one in the project settings.`,
+ );
- try {
- const { messages, modelParams } = body;
const stream = await fetchLLMCompletion({
messages,
modelParams,
streaming: true,
- callbacks: [new PosthogCallbackHandler("playground", body, token.sub)],
- apiKey:
- modelParams.provider === "openai"
- ? env.OPENAI_API_KEY
- : env.ANTHROPIC_API_KEY,
+ callbacks: [new PosthogCallbackHandler("playground", body, userId)],
+ apiKey: decrypt(LLMApiKey.secretKey),
});
return new StreamingTextResponse(stream);
} catch (err) {
console.error(err);
+ if (err instanceof BaseError) {
+ return NextResponse.json(
+ {
+ error: err.name,
+ message: err.message,
+ },
+ { status: err.httpCode },
+ );
+ }
+
if (err instanceof Error) {
return NextResponse.json(
{
diff --git a/web/src/ee/features/playground/server/validateChatCompletionBody.ts b/web/src/ee/features/playground/server/validateChatCompletionBody.ts
index a6ff68bf7c..6a8b51d24e 100644
--- a/web/src/ee/features/playground/server/validateChatCompletionBody.ts
+++ b/web/src/ee/features/playground/server/validateChatCompletionBody.ts
@@ -32,6 +32,7 @@ const MessageSchema = z.object({
id: z.string().optional(),
});
export const ChatCompletionBodySchema = z.object({
+ projectId: z.string(),
messages: z.array(MessageSchema),
modelParams: ModelParamsSchema,
});
diff --git a/web/src/features/email/lib/project-invitation.ts b/web/src/features/email/lib/project-invitation.ts
index f1eaf87bf1..7c416909fb 100644
--- a/web/src/features/email/lib/project-invitation.ts
+++ b/web/src/features/email/lib/project-invitation.ts
@@ -11,7 +11,7 @@ const langfuseUrls = {
STAGING: "https://staging.langfuse.com",
};
-const authUrl =
+const getAuthURL = () =>
env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "US" ||
env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "EU" ||
env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION === "STAGING"
@@ -40,7 +40,7 @@ export const sendProjectInvitation = async (
invitedByUserEmail: inviterEmail,
projectName: projectName,
recieverEmail: to,
- inviteLink: authUrl,
+ inviteLink: getAuthURL(),
langfuseCloudRegion: env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION,
}),
);
diff --git a/web/src/features/llm-api-key/types.ts b/web/src/features/llm-api-key/types.ts
index 561fe7eac8..074ac617f9 100644
--- a/web/src/features/llm-api-key/types.ts
+++ b/web/src/features/llm-api-key/types.ts
@@ -1,13 +1,8 @@
import { z } from "zod";
import { ModelProvider } from "@langfuse/shared";
-export const ZodModelProvider = z.enum([
- ModelProvider.Anthropic,
- ModelProvider.OpenAI,
-]);
-
export const CreateLlmApiKey = z.object({
projectId: z.string(),
secretKey: z.string().min(1),
- provider: z.literal(ModelProvider.OpenAI),
+ provider: z.nativeEnum(ModelProvider),
});
diff --git a/web/src/features/public-api/components/LLMApiKeyList.tsx b/web/src/features/public-api/components/LLMApiKeyList.tsx
index bc6aa7b424..54c0a1b989 100644
--- a/web/src/features/public-api/components/LLMApiKeyList.tsx
+++ b/web/src/features/public-api/components/LLMApiKeyList.tsx
@@ -175,7 +175,7 @@ function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {
const formSchema = z.object({
secretKey: z.string().min(1),
- provider: z.literal(ModelProvider.OpenAI),
+ provider: z.nativeEnum(ModelProvider),
});
export function CreateLlmApiKeyComponent(props: {
@@ -277,7 +277,7 @@ export function CreateLlmApiKeyComponent(props: {
<Select
defaultValue={field.value}
onValueChange={(value) =>
- field.onChange(value as ModelProvider[number])
+ field.onChange(value as ModelProvider)
}
>
<FormControl>
@@ -286,13 +286,7 @@ export function CreateLlmApiKeyComponent(props: {
</SelectTrigger>
</FormControl>
<SelectContent>
- {Array.from(
- new Set(
- evalLLMModels.map(
- (models) => models.provider.value,
- ),
- ),
- ).map((provider) => (
+ {Object.values(ModelProvider).map((provider) => (
<SelectItem value={provider} key={provider}>
{provider}
</SelectItem>
diff --git a/web/src/pages/api/chatCompletion.ts b/web/src/pages/api/chatCompletion.ts
deleted file mode 100644
index 600152cb84..0000000000
--- a/web/src/pages/api/chatCompletion.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import chatCompletionHandler from "@/src/ee/features/playground/server/chatCompletionHandler";
-
-export const runtime = "edge";
-
-export default chatCompletionHandler;
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index b8c3ad20ee..d30ab7c06a 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -79,6 +79,7 @@ import superjson from "superjson";
import { ZodError } from "zod";
import { setUpSuperjson } from "@/src/utils/superjson";
import { DB } from "@/src/server/db";
+import { isProjectMemberOrAdmin } from "@/src/server/utils/checkProjectMembershipOrAdmin";
setUpSuperjson();
@@ -177,7 +178,7 @@ const enforceUserIsAuthedAndProjectMember = t.middleware(
({ id }) => id === projectId,
);
- if (!sessionProject && ctx.session.user.admin !== true)
+ if (!sessionProject && !isProjectMemberOrAdmin(ctx.session.user, projectId))
throw new TRPCError({
code: "UNAUTHORIZED",
message: "User is not a member of this project",
@@ -242,7 +243,11 @@ const enforceTraceAccess = t.middleware(async ({ ctx, rawInput, next }) => {
({ id }) => id === trace.projectId,
);
- if (!trace.public && !sessionProject && ctx.session?.user?.admin !== true)
+ if (
+ !trace.public &&
+ !sessionProject &&
+ !isProjectMemberOrAdmin(ctx.session?.user, trace.projectId)
+ )
throw new TRPCError({
code: "UNAUTHORIZED",
message:
diff --git a/web/src/server/auth.ts b/web/src/server/auth.ts
index 409dc89465..ba99f4cb82 100644
--- a/web/src/server/auth.ts
+++ b/web/src/server/auth.ts
@@ -22,7 +22,7 @@ import Auth0Provider from "next-auth/providers/auth0";
import CognitoProvider from "next-auth/providers/cognito";
import AzureADProvider from "next-auth/providers/azure-ad";
import { type Provider } from "next-auth/providers/index";
-import { getCookieName, cookieOptions } from "./utils/cookies";
+import { getCookieName, getCookieOptions } from "./utils/cookies";
import {
getSsoAuthProviderIdForDomain,
loadSsoProviders,
@@ -330,27 +330,27 @@ export async function getAuthOptions(): Promise<NextAuthOptions> {
cookies: {
sessionToken: {
name: getCookieName("next-auth.session-token"),
- options: cookieOptions,
+ options: getCookieOptions(),
},
csrfToken: {
name: getCookieName("next-auth.csrf-token"),
- options: cookieOptions,
+ options: getCookieOptions(),
},
callbackUrl: {
name: getCookieName("next-auth.callback-url"),
- options: cookieOptions,
+ options: getCookieOptions(),
},
state: {
name: getCookieName("next-auth.state"),
- options: cookieOptions,
+ options: getCookieOptions(),
},
nonce: {
name: getCookieName("next-auth.nonce"),
- options: cookieOptions,
+ options: getCookieOptions(),
},
pkceCodeVerifier: {
name: getCookieName("next-auth.pkce.code_verifier"),
- options: cookieOptions,
+ options: getCookieOptions(),
},
},
events: {
diff --git a/web/src/server/utils/checkProjectMembershipOrAdmin.ts b/web/src/server/utils/checkProjectMembershipOrAdmin.ts
new file mode 100644
index 0000000000..7aebf1c0e3
--- /dev/null
+++ b/web/src/server/utils/checkProjectMembershipOrAdmin.ts
@@ -0,0 +1,15 @@
+import { type User } from "next-auth";
+
+export const isProjectMemberOrAdmin = (
+ user: User | null | undefined,
+ projectId: string,
+): boolean => {
+ if (!user) return false;
+
+ const isAdmin = user.admin === true;
+ const isProjectMember = user.projects.some(
+ (project) => project.id === projectId,
+ );
+
+ return isProjectMember || isAdmin;
+};
diff --git a/web/src/server/utils/cookies.ts b/web/src/server/utils/cookies.ts
index caef83700f..5c3f48df03 100644
--- a/web/src/server/utils/cookies.ts
+++ b/web/src/server/utils/cookies.ts
@@ -1,20 +1,20 @@
import { env } from "@/src/env.mjs";
// Use secure cookies on https hostnames, exception for Vercel which sets NEXTAUTH_URL without the protocol
-const shouldSecureCookies =
+const shouldSecureCookies = () =>
env.NEXTAUTH_URL.startsWith("https://") || process.env.VERCEL === "1";
-export const cookieOptions = {
+export const getCookieOptions = () => ({
domain: env.NEXTAUTH_COOKIE_DOMAIN ?? undefined,
httpOnly: true,
sameSite: "lax" as const,
path: "/",
- secure: shouldSecureCookies,
-};
+ secure: shouldSecureCookies(),
+});
export const getCookieName = (name: string) =>
[
- shouldSecureCookies ? "__Secure-" : "",
+ shouldSecureCookies() ? "__Secure-" : "",
name,
env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
? `.${env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION}`