Skip to content

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

feat(trace): send web callouts from a trace & session (#13731)

Nimarc6f9aff77c46
diff --git a/.env.dev.example b/.env.dev.example
index 165dd0fb65..df573bd5c3 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -70,6 +70,7 @@ NEXT_PUBLIC_LANGFUSE_CLOUD_REGION="DEV"
# Langfuse experimental features
LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES="false"
+LANGFUSE_ENABLE_WEB_CALLOUTS="true"
# Salt for API key hashing
SALT="salt"
diff --git a/.env.prod.example b/.env.prod.example
index 9c833cf816..79e47b0981 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -54,6 +54,7 @@ OTEL_SERVICE_NAME="langfuse"
# Enable experimental features, optional
# LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES=false
+# LANGFUSE_ENABLE_WEB_CALLOUTS=false
# Auth, optional configuration
# AUTH_DOMAINS_WITH_SSO_ENFORCEMENT=domain1.com,domain2.com
diff --git a/packages/shared/prisma/migrations/20260610000000_add_web_callout_endpoints/migration.sql b/packages/shared/prisma/migrations/20260610000000_add_web_callout_endpoints/migration.sql
new file mode 100644
index 0000000000..fe1a9f7065
--- /dev/null
+++ b/packages/shared/prisma/migrations/20260610000000_add_web_callout_endpoints/migration.sql
@@ -0,0 +1,24 @@
+-- CreateTable
+CREATE TABLE "web_callout_endpoints" (
+ "id" TEXT NOT NULL,
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updated_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "project_id" TEXT NOT NULL,
+ "name" TEXT NOT NULL DEFAULT 'Default',
+ "url" TEXT NOT NULL,
+ "enabled" BOOLEAN NOT NULL DEFAULT true,
+ "toast_message" TEXT NOT NULL DEFAULT 'Callout sent',
+ "request_headers" TEXT,
+ "request_header_keys" TEXT[] NOT NULL DEFAULT '{}'::TEXT[],
+
+ CONSTRAINT "web_callout_endpoints_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "web_callout_endpoints_project_id_idx" ON "web_callout_endpoints"("project_id");
+
+-- CreateIndex
+CREATE INDEX "web_callout_endpoints_project_id_enabled_idx" ON "web_callout_endpoints"("project_id", "enabled");
+
+-- AddForeignKey
+ALTER TABLE "web_callout_endpoints" ADD CONSTRAINT "web_callout_endpoints_project_id_fkey" FOREIGN KEY ("project_id") REFERENCES "projects"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prisma
index 67c0492021..3e613dce9b 100644
--- a/packages/shared/prisma/schema.prisma
+++ b/packages/shared/prisma/schema.prisma
@@ -141,6 +141,7 @@ model Project {
PosthogIntegration PosthogIntegration[]
MixpanelIntegration MixpanelIntegration[]
BlobStorageIntegration BlobStorageIntegration[]
+ webCalloutEndpoints WebCalloutEndpoint[]
scoreConfig ScoreConfig[]
BatchExport BatchExport[]
BatchAction BatchAction[]
@@ -1241,6 +1242,26 @@ model BlobStorageIntegration {
@@map("blob_storage_integrations")
}
+model WebCalloutEndpoint {
+ id String @id @default(cuid())
+ createdAt DateTime @default(now()) @map("created_at")
+ updatedAt DateTime @default(now()) @updatedAt @map("updated_at")
+
+ projectId String @map("project_id")
+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)
+
+ name String @default("Default")
+ url String
+ enabled Boolean @default(true)
+ toastMessage String @default("Callout sent") @map("toast_message")
+ requestHeaders String? @map("request_headers")
+ requestHeaderKeys String[] @default([]) @map("request_header_keys")
+
+ @@index([projectId])
+ @@index([projectId, enabled])
+ @@map("web_callout_endpoints")
+}
+
enum BlobStorageIntegrationFileType {
JSON
CSV
diff --git a/packages/shared/src/server/webhooks/validation.ts b/packages/shared/src/server/webhooks/validation.ts
index ae6b482ef9..1aa0daa5ae 100644
--- a/packages/shared/src/server/webhooks/validation.ts
+++ b/packages/shared/src/server/webhooks/validation.ts
@@ -10,6 +10,11 @@ export type WebhookValidationWhitelist = OutboundUrlValidationWhitelist;
export { resolveHost };
export const WEBHOOK_URL_VALIDATION_LOG_CONTEXT = "Webhook";
+const DEFAULT_WEBHOOK_ALLOWED_PORTS = ["443", "80"] as const;
+
+export type WebhookUrlValidationOptions = {
+ allowedPorts?: readonly string[] | "any";
+};
export function whitelistFromEnv(): WebhookValidationWhitelist {
return {
@@ -30,6 +35,7 @@ export function whitelistFromEnv(): WebhookValidationWhitelist {
export async function validateWebhookURL(
urlString: string,
whitelist: WebhookValidationWhitelist = whitelistFromEnv(),
+ options: WebhookUrlValidationOptions = {},
): Promise<void> {
const url = parseOutboundUrl(urlString);
@@ -37,7 +43,8 @@ export async function validateWebhookURL(
throw new Error("Only HTTP and HTTPS protocols are allowed");
}
- if (url.port && !["443", "80"].includes(url.port)) {
+ const allowedPorts = options.allowedPorts ?? DEFAULT_WEBHOOK_ALLOWED_PORTS;
+ if (url.port && allowedPorts !== "any" && !allowedPorts.includes(url.port)) {
throw new Error("Only ports 80 and 443 are allowed");
}
diff --git a/web/src/__tests__/server/web-callouts-trpc.servertest.ts b/web/src/__tests__/server/web-callouts-trpc.servertest.ts
new file mode 100644
index 0000000000..7d959cea9e
--- /dev/null
+++ b/web/src/__tests__/server/web-callouts-trpc.servertest.ts
@@ -0,0 +1,934 @@
+import type { Session } from "next-auth";
+import type { Mock } from "vitest";
+
+import { env } from "@/src/env.mjs";
+import { appRouter } from "@/src/server/api/root";
+import { createInnerTRPCContext } from "@/src/server/api/trpc";
+import { decrypt } from "@langfuse/shared/encryption";
+import {
+ fetchWithSecureRedirects,
+ getObservationById,
+ getObservationByIdFromEventsTable,
+ getTraceById,
+ getTraceByIdFromEventsTable,
+ getTracesIdentifierForSession,
+ getTracesIdentifierForSessionFromEvents,
+ validateWebhookURL,
+} from "@langfuse/shared/src/server";
+
+vi.mock("@langfuse/shared/encryption", async () => {
+ const actual = await vi.importActual("@langfuse/shared/encryption");
+ return {
+ ...actual,
+ encrypt: vi.fn((value: string) => `encrypted:${value}`),
+ decrypt: vi.fn((value: string) =>
+ value.startsWith("encrypted:") ? value.slice("encrypted:".length) : value,
+ ),
+ };
+});
+
+vi.mock("@langfuse/shared/src/server", async () => {
+ const actual = await vi.importActual("@langfuse/shared/src/server");
+ return {
+ ...actual,
+ fetchWithSecureRedirects: vi.fn(),
+ getObservationById: vi.fn(),
+ getObservationByIdFromEventsTable: vi.fn(),
+ getTraceById: vi.fn(),
+ getTraceByIdFromEventsTable: vi.fn(),
+ getTracesIdentifierForSession: vi.fn(),
+ getTracesIdentifierForSessionFromEvents: vi.fn(),
+ validateWebhookURL: vi.fn(),
+ };
+});
+
+const buildSession = ({
+ orgId,
+ projectId,
+ projectRole = "ADMIN",
+}: {
+ orgId: string;
+ projectId: string;
+ projectRole?: "ADMIN" | "MEMBER" | "NONE" | "OWNER" | "VIEWER";
+}): Session => ({
+ expires: "1",
+ user: {
+ id: "user-1",
+ name: "Demo User",
+ canCreateOrganizations: true,
+ organizations: [
+ {
+ id: orgId,
+ name: "Test Organization",
+ role: "OWNER",
+ plan: "cloud:hobby",
+ cloudConfig: undefined,
+ metadata: {},
+ projects: [
+ {
+ id: projectId,
+ role: projectRole,
+ name: "Test Project",
+ deletedAt: null,
+ retentionDays: null,
+ metadata: {},
+ },
+ ],
+ },
+ ],
+ featureFlags: {
+ templateFlag: true,
+ excludeClickhouseRead: false,
+ },
+ admin: false,
+ v4BetaEnabled: false,
+ },
+ environment: {} as any,
+});
+
+type StoredEndpoint = {
+ id: string;
+ createdAt: Date;
+ updatedAt: Date;
+ projectId: string;
+ name: string;
+ url: string;
+ enabled: boolean;
+ toastMessage: string;
+ requestHeaders: unknown;
+ requestHeaderKeys: string[];
+};
+
+type StoredEndpointWhere = Partial<
+ Pick<StoredEndpoint, "enabled" | "id" | "projectId">
+>;
+type AppRouterCaller = ReturnType<typeof appRouter.createCaller>;
+type WebCalloutUpsertInput = Parameters<
+ AppRouterCaller["webCallouts"]["upsert"]
+>[0];
+
+const createPrismaStub = () => {
+ const endpoints: StoredEndpoint[] = [];
+ const sessions = new Set<string>();
+ let endpointCounter = 0;
+
+ const matchesWhere = (endpoint: StoredEndpoint, where: StoredEndpointWhere) =>
+ (where.id === undefined || endpoint.id === where.id) &&
+ (where.projectId === undefined || endpoint.projectId === where.projectId) &&
+ (where.enabled === undefined || endpoint.enabled === where.enabled);
+
+ const applySelect = (
+ endpoint: StoredEndpoint,
+ select?: Partial<Record<keyof StoredEndpoint, boolean>>,
+ ) => {
+ if (!select) return endpoint;
+
+ return Object.fromEntries(
+ Object.entries(select)
+ .filter(([, enabled]) => enabled)
+ .map(([field]) => [field, endpoint[field as keyof StoredEndpoint]]),
+ );
+ };
+
+ const prismaStub = {
+ webCalloutEndpoint: {
+ create: vi.fn(
+ async ({
+ data,
+ }: {
+ data: Omit<StoredEndpoint, "createdAt" | "id" | "updatedAt">;
+ }) => {
+ const endpoint = {
+ id: `endpoint-${++endpointCounter}`,
+ createdAt: new Date(),
+ updatedAt: new Date(),
+ ...data,
+ };
+ endpoints.push(endpoint);
+ return endpoint;
+ },
+ ),
+ delete: vi.fn(async ({ where }: { where: { id: string } }) => {
+ const index = endpoints.findIndex(
+ (endpoint) => endpoint.id === where.id,
+ );
+ if (index === -1) {
+ throw new Error("Endpoint not found");
+ }
+ return endpoints.splice(index, 1)[0];
+ }),
+ findFirst: vi.fn(
+ async ({
+ select,
+ where,
+ }: {
+ select?: Partial<Record<keyof StoredEndpoint, boolean>>;
+ where: StoredEndpointWhere;
+ }) => {
+ const endpoint = endpoints.find((candidate) =>
+ matchesWhere(candidate, where),
+ );
+
+ if (!endpoint) {
+ return null;
+ }
+
+ return applySelect(endpoint, select);
+ },
+ ),
+ findMany: vi.fn(async ({ where }: { where: StoredEndpointWhere }) =>
+ endpoints.filter((endpoint) => matchesWhere(endpoint, where)),
+ ),
+ findUnique: vi.fn(
+ async ({ where }: { where: { id?: string; projectId?: string } }) => {
+ const endpoint = endpoints.find((candidate) =>
+ matchesWhere(candidate, where),
+ );
+ return endpoint ?? null;
+ },
+ ),
+ update: vi.fn(
+ async ({
+ data,
+ where,
+ }: {
+ data: Partial<StoredEndpoint>;
+ where: { id: string };
+ }) => {
+ const endpoint = endpoints.find(
+ (candidate) => candidate.id === where.id,
+ );
+ if (!endpoint) {
+ throw new Error("Endpoint not found");
+ }
+
+ Object.assign(endpoint, data, { updatedAt: new Date() });
+ return endpoint;
+ },
+ ),
+ },
+ auditLog: {
+ create: vi.fn(),
+ },
+ traceSession: {
+ findFirst: vi.fn(
+ async ({
+ select,
+ where,
+ }: {
+ select?: Record<string, boolean>;
+ where: { id: string; projectId: string };
+ }) => {
+ if (!sessions.has(`${where.projectId}:${where.id}`)) {
+ return null;
+ }
+
+ if (select) {
+ return Object.fromEntries(
+ Object.entries(select)
+ .filter(([, enabled]) => enabled)
+ .map(([field]) => [field, field === "id" ? where.id : true]),
+ );
+ }
+
+ return { id: where.id, projectId: where.projectId };
+ },
+ ),
+ },
+ };
+
+ return {
+ endpoints,
+ prisma: prismaStub,
+ sessions,
+ };
+};
+
+const prepare = async ({
+ projectRole = "ADMIN",
+}: {
+ projectRole?: "ADMIN" | "MEMBER" | "NONE" | "OWNER" | "VIEWER";
+} = {}) => {
+ const orgId = "org-1";
+ const projectId = "project-1";
+ const prismaStub = createPrismaStub();
+
+ const ctx = createInnerTRPCContext({
+ session: buildSession({ orgId, projectId, projectRole }),
+ headers: {},
+ });
+
+ return {
+ caller: appRouter.createCaller({
+ ...ctx,
+ prisma: prismaStub.prisma as any,
+ }),
+ orgId,
+ projectId,
+ prismaStub,
+ };
+};
+
+const createEndpoint = async (
+ caller: AppRouterCaller,
+ projectId: string,
+ overrides: Partial<WebCalloutUpsertInput> = {},
+) =>
+ caller.webCallouts.upsert({
+ projectId,
+ name: "Default",
+ url: "https://example.com/callout",
+ enabled: true,
+ toastMessage: "Sent to app",
+ requestHeaders: {},
+ ...overrides,
+ });
+
+const mockSuccessfulTargetValidation = ({
+ traceSessionId = null,
+ observationSessionId = null,
+}: {
+ traceSessionId?: string | null;
+ observationSessionId?: string | null;
+} = {}) => {
+ (getTraceById as Mock).mockImplementation(async ({ traceId }) => ({
+ id: traceId,
+ sessionId: traceSessionId,
+ }));
+ (getObservationById as Mock).mockImplementation(async ({ id, traceId }) => ({
+ id,
+ traceId,
+ sessionId: observationSessionId,
+ }));
+};
+
+describe("webCallouts router", () => {
+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+ const originalNodeEnv = env.NODE_ENV;
+ const originalWebCalloutsEnabled = env.LANGFUSE_ENABLE_WEB_CALLOUTS;
+
+ beforeEach(() => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;
+ (env as any).LANGFUSE_ENABLE_WEB_CALLOUTS = "true";
+ (validateWebhookURL as Mock).mockResolvedValue(undefined);
+ (fetchWithSecureRedirects as Mock).mockResolvedValue({
+ response: { ok: true, status: 204 },
+ redirectChain: [],
+ finalUrl: "https://example.com/callout",
+ });
+ mockSuccessfulTargetValidation();
+ (getTraceByIdFromEventsTable as Mock).mockResolvedValue(undefined);
+ (getObservationByIdFromEventsTable as Mock).mockResolvedValue(undefined);
+ (getTracesIdentifierForSession as Mock).mockResolvedValue([]);
+ (getTracesIdentifierForSessionFromEvents as Mock).mockResolvedValue([]);
+ });
+
+ afterEach(() => {
+ (env as any).NODE_ENV = originalNodeEnv;
+ (env as any).LANGFUSE_ENABLE_WEB_CALLOUTS = originalWebCalloutsEnabled;
+ vi.useRealTimers();
+ vi.clearAllMocks();
+ });
+
+ afterAll(() => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
+ });
+
+ it("creates a safe endpoint and exposes only minimal invoke metadata", async () => {
+ const { caller, prismaStub, projectId } = await prepare();
+
+ const endpoint = await createEndpoint(caller, projectId, {
+ requestHeaders: {
+ Authorization: "Bearer secret-token",
+ "X-Env": "prod",
+ },
+ });
+
+ expect(endpoint.requestHeaderKeys).toEqual(["Authorization", "X-Env"]);
+ expect("requestHeaders" in endpoint).toBe(false);
+
+ const stored = prismaStub.endpoints.find(
+ (candidate) => candidate.id === endpoint.id,
+ );
+ expect(stored?.requestHeaders).toBe(
+ 'encrypted:{"Authorization":"Bearer secret-token","X-Env":"prod"}',
+ );
+ expect(stored?.requestHeaderKeys).toEqual(["Authorization", "X-Env"]);
+
+ const endpoints = await caller.webCallouts.all({ projectId });
+ expect(endpoints).toHaveLength(1);
+ expect("requestHeaders" in endpoints[0]).toBe(false);
+ expect(endpoints[0]?.requestHeaderKeys).toEqual(["Authorization", "X-Env"]);
+
+ const enabled = await caller.webCallouts.enabled({ projectId });
+ expect(enabled).toEqual({
+ enabled: true,
+ id: endpoint.id,
+ name: "Default",
+ toastMessage: "Sent to app",
+ });
+ expect(enabled).not.toHaveProperty("url");
+ expect(enabled).not.toHaveProperty("requestHeaders");
+ expect(enabled).not.toHaveProperty("requestHeaderKeys");
+ });
+
+ it("hides metadata and blocks backend work when disabled by environment", async () => {
+ const { caller, projectId } = await prepare();
+
+ await createEndpoint(caller, projectId);
+ vi.clearAllMocks();
+ (env as any).LANGFUSE_ENABLE_WEB_CALLOUTS = "false";
+
+ await expect(
+ caller.webCallouts.availability({ projectId }),
+ ).resolves.toEqual({ enabled: false });
+ await expect(caller.webCallouts.enabled({ projectId })).resolves.toEqual({
+ enabled: false,
+ id: null,
+ name: null,
+ toastMessage: null,
+ });
+ await expect(caller.webCallouts.all({ projectId })).rejects.toMatchObject({
+ code: "NOT_FOUND",
+ message: "Web callouts are not enabled.",
+ });
+ await expect(
+ caller.webCallouts.invoke({
+ projectId,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ }),
+ ).rejects.toMatchObject({
+ code: "NOT_FOUND",
+ message: "Web callouts are not enabled.",
+ });
+ expect(fetchWithSecureRedirects).not.toHaveBeenCalled();
+ });
+
+ it("allows callout URLs on custom ports", async () => {
+ const { caller, projectId } = await prepare();
+
+ const endpoint = await createEndpoint(caller, projectId, {
+ url: "https://example.com:8443/callout",
+ toastMessage: "Callout sent",
+ });
+
+ expect(endpoint.url).toBe("https://example.com:8443/callout");
+ expect(validateWebhookURL).toHaveBeenCalledWith(
+ "https://example.com:8443/callout",
+ expect.any(Object),
+ { allowedPorts: "any" },
+ );
+ });
+
+ it("allows loopback callout targets in local development", async () => {
+ (env as any).NODE_ENV = "development";
+ const { caller, projectId } = await prepare();
+
+ await createEndpoint(caller, projectId, {
+ url: "http://127.0.0.1:4047/api/langfuse-trace",
+ toastMessage: "Callout sent",
+ });
+
+ expect(validateWebhookURL).toHaveBeenCalledWith(
+ "http://127.0.0.1:4047/api/langfuse-trace",
+ expect.objectContaining({
+ hosts: expect.arrayContaining(["localhost", "127.0.0.1", "[::1]"]),
+ ips: expect.arrayContaining(["127.0.0.1", "::1"]),
+ ip_ranges: expect.arrayContaining(["127.0.0.0/8", "::1/128"]),
+ }),
+ { allowedPorts: "any" },
+ );
+ });
+
+ it("enforces max one endpoint per project", async () => {
+ const { caller, prismaStub, projectId } = await prepare();
+
+ await createEndpoint(caller, projectId);
+
+ await expect(
+ createEndpoint(caller, projectId, {
+ name: "Second",
+ url: "https://example.com/other",
+ }),
+ ).rejects.toMatchObject({ code: "CONFLICT" });
+ expect(prismaStub.endpoints).toHaveLength(1);
+ expect(prismaStub.prisma.webCalloutEndpoint.create).toHaveBeenCalledTimes(
+ 1,
+ );
+ });
+
+ it("rejects unsafe header names", async () => {
+ const { caller, projectId } = await prepare();
+
+ await expect(
+ createEndpoint(caller, projectId, {
+ requestHeaders: {
+ "Content-Type": "text/plain",
+ },
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ });
+
+ it("stores authentication headers encrypted", async () => {
+ const { caller, projectId } = await prepare();
+
+ const endpoint = await createEndpoint(caller, projectId, {
+ requestHeaders: {
+ Authorization: "Bearer secret-token",
+ },
+ });
+
+ expect(endpoint.requestHeaderKeys).toEqual(["Authorization"]);
+ });
+
+ it("limits configured request headers", async () => {
+ const { caller, projectId } = await prepare();
+
+ await expect(
+ createEndpoint(caller, projectId, {
+ requestHeaders: Object.fromEntries(
+ Array.from({ length: 21 }, (_, index) => [
+ `X-Test-${index}`,
+ "value",
+ ]),
+ ),
+ }),
+ ).rejects.toMatchObject({
+ code: "BAD_REQUEST",
+ message: "At most 20 request headers can be configured.",
+ });
+
+ await expect(
+ createEndpoint(caller, projectId, {
+ requestHeaders: {
+ "X-Large": "a".repeat(4097),
+ },
+ }),
+ ).rejects.toMatchObject({
+ code: "BAD_REQUEST",
+ message: 'Header "X-Large" value must be at most 4096 bytes.',
+ });
+ });
+
+ it("keeps setup management gated by integrations access", async () => {
+ const { caller, orgId, prismaStub, projectId } = await prepare();
+ await createEndpoint(caller, projectId);
+
+ const viewerCtx = createInnerTRPCContext({
+ session: buildSession({ orgId, projectId, projectRole: "VIEWER" }),
+ headers: {},
+ });
+ const viewerCaller = appRouter.createCaller({
+ ...viewerCtx,
+ prisma: prismaStub.prisma as any,
+ });
+
+ await expect(
+ viewerCaller.webCallouts.all({ projectId }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+
+ await expect(
+ viewerCaller.webCallouts.upsert({
+ projectId,
+ name: "Viewer update",
+ url: "https://example.com/viewer",
+ enabled: true,
+ toastMessage: "Sent",
+ requestHeaders: {},
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ });
+
+ it("allows project viewers to resolve invoke metadata and invoke callouts", async () => {
+ const { caller, orgId, prismaStub, projectId } = await prepare();
+ const endpoint = await createEndpoint(caller, projectId);
+
+ const viewerCtx = createInnerTRPCContext({
+ session: buildSession({ orgId, projectId, projectRole: "VIEWER" }),
+ headers: {},
+ });
+ const viewerCaller = appRouter.createCaller({
+ ...viewerCtx,
+ prisma: prismaStub.prisma as any,
+ });
+
+ await expect(
+ viewerCaller.webCallouts.enabled({ projectId }),
+ ).resolves.toEqual({
+ enabled: true,
+ id: endpoint.id,
+ name: "Default",
+ toastMessage: "Sent to app",
+ });
+
+ await expect(
+ viewerCaller.webCallouts.invoke({
+ projectId,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ }),
+ ).resolves.toEqual({ success: true, status: 204 });
+ });
+
+ it("rejects callout metadata and invoke access for project none role", async () => {
+ const { caller, orgId, prismaStub, projectId } = await prepare();
+ await createEndpoint(caller, projectId);
+
+ const noneCtx = createInnerTRPCContext({
+ session: buildSession({ orgId, projectId, projectRole: "NONE" }),
+ headers: {},
+ });
+ const noneCaller = appRouter.createCaller({
+ ...noneCtx,
+ prisma: prismaStub.prisma as any,
+ });
+
+ await expect(
+ noneCaller.webCallouts.enabled({ projectId }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+
+ await expect(
+ noneCaller.webCallouts.invoke({
+ projectId,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ }),
+ ).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(fetchWithSecureRedirects).not.toHaveBeenCalled();
+ });
+
+ it("invokes the backend endpoint with decrypted headers and id-only payload", async () => {
+ const { caller, prismaStub, projectId } = await prepare();
+ const responseBody = { cancel: vi.fn().mockResolvedValue(undefined) };
+ (fetchWithSecureRedirects as Mock).mockResolvedValueOnce({
+ response: { ok: true, status: 204, body: responseBody },
+ redirectChain: [],
+ finalUrl: "https://example.com/callout",
+ });
+ prismaStub.sessions.add(`${projectId}:session-1`);
+ mockSuccessfulTargetValidation({
+ traceSessionId: "session-1",
+ observationSessionId: "session-1",
+ });
+ await createEndpoint(caller, projectId, {
+ requestHeaders: {
+ Authorization: "Bearer secret-token",
+ "X-Env": "prod",
+ },
+ });
+
+ await expect(
+ caller.webCallouts.invoke({
+ projectId,
+ traceId: "trace-1",
+ observationId: "observation-1",
+ sessionId: "session-1",
+ }),
+ ).resolves.toEqual({ success: true, status: 204 });
+
+ expect(fetchWithSecureRedirects).toHaveBeenCalledTimes(1);
+ const [url, request, redirectOptions] = (fetchWithSecureRedirects as Mock)
+ .mock.calls[0];
+ expect(url).toBe("https://example.com/callout");
+ expect(request.method).toBe("POST");
+ expect(JSON.parse(request.body)).toEqual({
+ version: 1,
+ items: [
+ {
+ projectId,
+ traceId: "trace-1",
+ observationId: "observation-1",
+ sessionId: "session-1",
+ },
+ ],
+ });
+ expect(request.headers.get("Authorization")).toBe("Bearer secret-token");
+ expect(request.headers.get("X-Env")).toBe("prod");
+ expect(request.headers.get("Content-Type")).toBe("application/json");
+ expect(responseBody.cancel).toHaveBeenCalledTimes(1);
+ expect(redirectOptions).toMatchObject({
+ maxRedirects: 10,
+ additionalSensitiveHeaders: ["Authorization", "X-Env"],
+ redirectValidation: {
+ logContext: "Web callout",
+ },
+ });
+ expect(redirectOptions.redirectValidation.validateUrl).toEqual(
+ expect.any(Function),
+ );
+ });
+
+ it("preserves blank existing request header values on update", async () => {
+ const { caller, prismaStub, projectId } = await prepare();
+ const endpoint = await createEndpoint(caller, projectId, {
+ requestHeaders: {
+ Authorization: "Bearer secret-token",
+ "X-Env": "prod",
+ },
+ });
+
+ await caller.webCallouts.upsert({
+ projectId,
+ id: endpoint.id,
+ name: "Default",
+ url: "https://example.com/callout",
+ enabled: true,
+ toastMessage: "Sent to app",
+ requestHeaders: {
+ Authorization: "",
+ "X-New": "new-value",
+ },
+ });
+
+ const stored = prismaStub.endpoints.find(
+ (candidate) => candidate.id === endpoint.id,
+ );
+ expect(stored?.requestHeaders).toBe(
+ 'encrypted:{"Authorization":"Bearer secret-token","X-New":"new-value"}',
+ );
+ expect(stored?.requestHeaderKeys).toEqual(["Authorization", "X-New"]);
+ });
+
+ it("rejects blank values for new or renamed request headers", async () => {
+ const { caller, prismaStub, projectId } = await prepare();
+ const endpoint = await createEndpoint(caller, projectId, {
+ requestHeaders: {
+ Authorization: "Bearer secret-token",
+ },
+ });
+
+ await expect(
+ caller.webCallouts.upsert({
+ projectId,
+ id: endpoint.id,
+ name: "Default",
+ url: "https://example.com/callout",
+ enabled: true,
+ toastMessage: "Sent to app",
+ requestHeaders: {
+ "X-Auth": "",
+ },
+ }),
+ ).rejects.toMatchObject({
+ code: "BAD_REQUEST",
+ message:
+ 'Header "X-Auth" value is required when adding or renaming a header.',
+ });
+
+ const stored = prismaStub.endpoints.find(
+ (candidate) => candidate.id === endpoint.id,
+ );
+ expect(stored?.requestHeaders).toBe(
+ 'encrypted:{"Authorization":"Bearer secret-token"}',
+ );
+ expect(stored?.requestHeaderKeys).toEqual(["Authorization"]);
+ });
+
+ it("clears request headers when all configured keys are removed", async () => {
+ const { caller, prismaStub, projectId } = await prepare();
+ const endpoint = await createEndpoint(caller, projectId, {
+ requestHeaders: {
+ Authorization: "Bearer secret-token",
+ },
+ });
+
+ await caller.webCallouts.upsert({
+ projectId,
+ id: endpoint.id,
+ name: "Default",
+ url: "https://example.com/callout",
+ enabled: true,
+ toastMessage: "Sent to app",
+ requestHeaders: {},
+ });
+
+ const stored = prismaStub.endpoints.find(
+ (candidate) => candidate.id === endpoint.id,
+ );
+ expect(stored?.requestHeaders).toBeNull();
+ expect(stored?.requestHeaderKeys).toEqual([]);
+ });
+
+ it("can clear request headers without decrypting existing values", async () => {
+ const { caller, prismaStub, projectId } = await prepare();
+ const endpoint = await createEndpoint(caller, projectId, {
+ requestHeaders: {
+ Authorization: "Bearer secret-token",
+ },
+ });
+
+ await caller.webCallouts.upsert({
+ projectId,
+ id: endpoint.id,
+ name: "Default",
+ url: "https://example.com/callout",
+ enabled: true,
+ toastMessage: "Sent to app",
+ requestHeaders: {},
+ });
+
+ const stored = prismaStub.endpoints.find(
+ (candidate) => candidate.id === endpoint.id,
+ );
+ expect(stored?.requestHeaders).toBeNull();
+ expect(stored?.requestHeaderKeys).toEqual([]);
+ expect(decrypt).not.toHaveBeenCalled();
+ });
+
+ it("does not invoke when configured headers cannot be decrypted", async () => {
+ const { caller, projectId } = await prepare();
+ await createEndpoint(caller, projectId, {
+ requestHeaders: {
+ Authorization: "Bearer secret-token",
+ },
+ });
+ (decrypt as Mock).mockImplementationOnce(() => {
+ throw new Error("bad decrypt");
+ });
+
+ await expect(
+ caller.webCallouts.invoke({
+ projectId,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ }),
+ ).rejects.toMatchObject({
+ code: "BAD_REQUEST",
+ message:
+ "Failed to decrypt web callout headers. Please update the web callout configuration.",
+ });
+ expect(fetchWithSecureRedirects).not.toHaveBeenCalled();
+ });
+
+ it("supports session-only callouts", async () => {
+ const { caller, prismaStub, projectId } = await prepare();
+ prismaStub.sessions.add(`${projectId}:session-1`);
+ await createEndpoint(caller, projectId);
+
+ await caller.webCallouts.invoke({
+ projectId,
+ traceId: null,
+ observationId: null,
+ sessionId: "session-1",
+ });
+
+ const [, request] = (fetchWithSecureRedirects as Mock).mock.calls[0];
+ expect(JSON.parse(request.body)).toEqual({
+ version: 1,
+ items: [
+ {
+ projectId,
+ traceId: null,
+ observationId: null,
+ sessionId: "session-1",
+ },
+ ],
+ });
+ });
+
+ it("rejects invoke requests without a trace or session id", async () => {
+ const { caller, projectId } = await prepare();
+ await createEndpoint(caller, projectId);
+
+ await expect(
+ caller.webCallouts.invoke({
+ projectId,
+ traceId: null,
+ observationId: null,
+ sessionId: null,
+ }),
+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });
+ expect(fetchWithSecureRedirects).not.toHaveBeenCalled();
+ });
+
+ it("does not invoke when a trace without session is paired with a session id", async () => {
+ const { caller, prismaStub, projectId } = await prepare();
+ prismaStub.sessions.add(`${projectId}:session-1`);
+ await createEndpoint(caller, projectId);
+
+ await expect(
+ caller.webCallouts.invoke({
+ projectId,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: "session-1",
+ }),
+ ).rejects.toMatchObject({
+ code: "BAD_REQUEST",
+ message: "Trace does not belong to the provided session.",
+ });
+ expect(fetchWithSecureRedirects).not.toHaveBeenCalled();
+ });
+
+ it("does not invoke when the trace does not belong to the project", async () => {
+ const { caller, projectId } = await prepare();
+ await createEndpoint(caller, projectId);
+ (getTraceById as Mock).mockResolvedValueOnce(undefined);
+
+ await expect(
+ caller.webCallouts.invoke({
+ projectId,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ }),
+ ).rejects.toMatchObject({ code: "NOT_FOUND" });
+ expect(fetchWithSecureRedirects).not.toHaveBeenCalled();
+ });
+
+ it("surfaces non-2xx backend responses", async () => {
+ const { caller, projectId } = await prepare();
+ await createEndpoint(caller, projectId);
+ (fetchWithSecureRedirects as Mock).mockResolvedValueOnce({
+ response: { ok: false, status: 404 },
+ redirectChain: [],
+ finalUrl: "https://example.com/callout",
+ });
+
+ await expect(
+ caller.webCallouts.invoke({
+ projectId,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ }),
+ ).rejects.toMatchObject({
+ code: "BAD_REQUEST",
+ message: "Web callout endpoint returned HTTP 404.",
+ });
+ });
+
+ it("uses the fixed server timeout for backend calls", async () => {
+ vi.useFakeTimers();
+ const { caller, projectId } = await prepare();
+ await createEndpoint(caller, projectId);
+ (fetchWithSecureRedirects as Mock).mockImplementationOnce(
+ async (_url, request: RequestInit) =>
+ new Promise((_, reject) => {
+ request.signal?.addEventListener("abort", () =>
+ reject(new Error("aborted")),
+ );
+ }),
+ );
+
+ const invoke = caller.webCallouts.invoke({
+ projectId,
+ traceId: "trace-1",
+ observationId: null,
+ sessionId: null,
+ });
+ const expectation = expect(invoke).rejects.toMatchObject({
+ code: "BAD_REQUEST",
+ message: "Web callout timed out after 5 seconds.",
+ });
+
+ await vi.advanceTimersByTimeAsync(5_000);
+
+ await expectation;
+ });
+});
diff --git a/web/src/components/session/index.tsx b/web/src/components/session/index.tsx
index d1562c7052..7a19e5737a 100644
--- a/web/src/components/session/index.tsx
+++ b/web/src/components/session/index.tsx
@@ -35,6 +35,7 @@ import {
TableViewPresetTableName,
} from "@langfuse/shared";
import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
+import { WebCalloutButton } from "@/src/features/web-callouts/components/WebCalloutMenuItem";
import { TablePeekViewTraceDetail } from "@/src/components/table/peek/peek-trace-detail";
import { usePeekNavigation } from "@/src/components/table/peek/hooks/usePeekNavigation";
import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";
@@ -378,6 +379,12 @@ export const SessionPage: React.FC<{
listKey="sessions"
/>
)}
+ <WebCalloutButton
+ projectId={projectId}
+ traceId={null}
+ observationId={null}
+ sessionId={sessionId}
+ />
<Button
variant="outline"
size="icon"
@@ -949,6 +956,12 @@ export const SessionEventsPage: React.FC<{
listKey="sessions"
/>
)}
+ <WebCalloutButton
+ projectId={projectId}
+ traceId={null}
+ observationId={null}
+ sessionId={sessionId}
+ />
<CommentDrawerButton
key="comment"
variant="outline"
diff --git a/web/src/components/trace/components/ObservationDetailView/ObservationDetailViewHeader.tsx b/web/src/components/trace/components/ObservationDetailView/ObservationDetailViewHeader.tsx
index 8f2e16cd68..61cb6d0a5c 100644
--- a/web/src/components/trace/components/ObservationDetailView/ObservationDetailViewHeader.tsx
+++ b/web/src/components/trace/components/ObservationDetailView/ObservationDetailViewHeader.tsx
@@ -115,6 +115,11 @@ export const ObservationDetailViewHeader = memo(
observationType={observation.type}
projectId={projectId}
spanName={observation.name ?? ""}
+ webCallout={{
+ traceId,
+ observationId: observation.id,
+ sessionId: observation.sessionId ?? null,
+ }}
/>
</div>
{/* Action buttons */}
diff --git a/web/src/components/trace/components/TraceDetailView/TraceDetailViewHeader.tsx b/web/src/components/trace/components/TraceDetailView/TraceDetailViewHeader.tsx
index 3c3ef4cd0a..aefa38389c 100644
--- a/web/src/components/trace/components/TraceDetailView/TraceDetailViewHeader.tsx
+++ b/web/src/components/trace/components/TraceDetailView/TraceDetailViewHeader.tsx
@@ -2,7 +2,7 @@
* TraceDetailViewHeader - Extracted header component for TraceDetailView
*
* Contains:
- * - Title row with ItemBadge, trace name, CopyIdsPopover
+ * - Title row with ItemBadge, trace name, options menu
* - Action buttons (Dataset, Annotate, Queue, Comments)
* - Metadata badges (timestamp, latency, session, user, environment, release, version, cost, usage)
*
@@ -21,7 +21,7 @@ import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes"
import { type ObservationReturnTypeWithMetadata } from "@/src/server/api/routers/traces";
import { ItemBadge } from "@/src/components/ItemBadge";
import { LocalIsoDate } from "@/src/components/LocalIsoDate";
-import { CopyIdsPopover } from "@/src/components/trace/components/_shared/CopyIdsPopover";
+import { DetailHeaderActionsMenu } from "@/src/components/trace/components/_shared/DetailHeaderActionsMenu";
import { NewDatasetItemFromExistingObject } from "@/src/features/datasets/components/NewDatasetItemFromExistingObject";
import { AnnotateDrawer } from "@/src/features/scores/components/AnnotateDrawer";
import { CreateNewAnnotationQueueItem } from "@/src/features/annotation-queues/components/CreateNewAnnotationQueueItem";
@@ -93,7 +93,14 @@ export const TraceDetailViewHeader = memo(function TraceDetailViewHeader({
<span className="line-clamp-2 min-w-0 font-medium break-all md:break-normal md:wrap-break-word">
{trace.name || trace.id}
</span>
- <CopyIdsPopover idItems={[{ id: trace.id, name: "Trace ID" }]} />
+ <DetailHeaderActionsMenu
+ idItems={[{ id: trace.id, name: "Trace ID" }]}
+ projectId={projectId}
+ webCallout={{
+ traceId: trace.id,
+ sessionId: trace.sessionId ?? null,
+ }}
+ />
</div>
{/* Action buttons */}
<div className="flex h-full flex-wrap content-start items-start justify-start gap-0.5 @2xl:mr-1 @2xl:justify-end">
diff --git a/web/src/components/trace/components/_shared/DetailHeaderActionsMenu.tsx b/web/src/components/trace/components/_shared/DetailHeaderActionsMenu.tsx
index 632640699b..547feccd9f 100644
--- a/web/src/components/trace/components/_shared/DetailHeaderActionsMenu.tsx
+++ b/web/src/components/trace/components/_shared/DetailHeaderActionsMenu.tsx
@@ -15,6 +15,7 @@ import {
} from "@/src/features/events/lib/eventsTablePaths";
import { copyTextToClipboard } from "@/src/utils/clipboard";
import { type ObservationType } from "@langfuse/shared";
+import { WebCalloutMenuItem } from "@/src/features/web-callouts/components/WebCalloutMenuItem";
type IdItem = {
name: string;
@@ -26,6 +27,11 @@ type DetailHeaderActionsMenuProps = {
observationType?: ObservationType;
projectId: string;
spanName?: string;
+ webCallout?: {
+ traceId: string | null;
+ observationId?: string | null;
+ sessionId?: string | null;
+ };
};
export function DetailHeaderActionsMenu({
@@ -33,6 +39,7 @@ export function DetailHeaderActionsMenu({
observationType,
projectId,
spanName,
+ webCallout,
}: DetailHeaderActionsMenuProps) {
const router = useRouter();
const [copiedId, setCopiedId] = useState<string | null>(null);
@@ -77,6 +84,17 @@ export function DetailHeaderActionsMenu({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start">
+ {webCallout && (
+ <>
+ <WebCalloutMenuItem
+ projectId={projectId}
+ traceId={webCallout.traceId}
+ observationId={webCallout.observationId}
+ sessionId={webCallout.sessionId}
+ withSeparator
+ />
+ </>
+ )}
{(href || typeHref) && (
<>
{href && (
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
index db3d27c7ec..a3d02fd8ee 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
@@ -2,6 +2,7 @@
import { Loader2, Wrench } from "lucide-react";
import { Streamdown } from "streamdown";
+import { getSafeLinkUrl } from "@/src/components/ui/safe-url";
import { cn } from "@/src/utils/tailwind";
import { useMemo } from "react";
@@ -239,11 +240,23 @@ function MessageText({
h6: ({ children }) => <h6>{children}</h6>,
p: ({ children }) => <p>{children}</p>,
- a: ({ children, href }) => (
- <a href={href} target="_blank" rel="noopener noreferrer">
- {children}
- </a>
- ),
+ a: ({ children, href }) => {
+ const safeHref = getSafeLinkUrl(href);
+
+ if (!safeHref) {
+ return (
+ <span className="text-muted-foreground underline">
+ {children}
+ </span>
+ );
+ }
+
+ return (
+ <a href={safeHref} target="_blank" rel="noopener noreferrer">
+ {children}
+ </a>
+ );
+ },
hr: ({ children }) => <hr>{children}</hr>,
ul: ({ children }) => <ul>{children}</ul>,
ol: ({ children }) => <ol>{children}</ol>,
diff --git a/web/src/env.mjs b/web/src/env.mjs
index 8478b9db19..15b4e1528b 100644
--- a/web/src/env.mjs
+++ b/web/src/env.mjs
@@ -67,6 +67,7 @@ export const env = createEnv({
LANGFUSE_ADMIN_ACCESS_WEBHOOK: z.url().optional(),
// Add `.min(1) on ID and SECRET if you want to make sure they're not empty
LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES: z.enum(["true", "false"]).optional(),
+ LANGFUSE_ENABLE_WEB_CALLOUTS: z.enum(["true", "false"]).default("false"),
SALT: z.string({
error: (issue) =>
issue.input === undefined
@@ -508,6 +509,7 @@ export const env = createEnv({
NEXT_PUBLIC_SIGN_UP_DISABLED: process.env.NEXT_PUBLIC_SIGN_UP_DISABLED,
LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES:
process.env.LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES,
+ LANGFUSE_ENABLE_WEB_CALLOUTS: process.env.LANGFUSE_ENABLE_WEB_CALLOUTS,
AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID,
AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY,
LANGFUSE_AWS_BEDROCK_REGION: process.env.LANGFUSE_AWS_BEDROCK_REGION,
diff --git a/web/src/features/audit-logs/auditLog.ts b/web/src/features/audit-logs/auditLog.ts
index 1bdbf536a5..dcda765c30 100644
--- a/web/src/features/audit-logs/auditLog.ts
+++ b/web/src/features/audit-logs/auditLog.ts
@@ -33,6 +33,7 @@ export type AuditableResource =
| "blobStorageIntegration"
| "posthogIntegration"
| "mixpanelIntegration"
+ | "webCalloutEndpoint"
| "llmApiKey"
| "llmTool"
| "llmSchema"
diff --git a/web/src/features/web-callouts/components/WebCalloutMenuItem.tsx b/web/src/features/web-callouts/components/WebCalloutMenuItem.tsx
new file mode 100644
index 0000000000..832071f5d1
--- /dev/null
+++ b/web/src/features/web-callouts/components/WebCalloutMenuItem.tsx
@@ -0,0 +1,151 @@
+import { Webhook } from "lucide-react";
+
+import { Button } from "@/src/components/ui/button";
+import {
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+} from "@/src/components/ui/dropdown-menu";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { api } from "@/src/utils/api";
+
+type WebCalloutTarget = {
+ projectId: string;
+ traceId: string | null;
+ observationId?: string | null;
+ sessionId?: string | null;
+};
+
+function useWebCalloutAction(props: WebCalloutTarget) {
+ const endpoint = api.webCallouts.enabled.useQuery(
+ { projectId: props.projectId },
+ {
+ staleTime: 60_000,
+ },
+ );
+ const invokeMutation = api.webCallouts.invoke.useMutation({
+ onSuccess: () => {
+ const callout = endpoint.data;
+ if (!callout?.enabled) return;
+
+ showSuccessToast({
+ title: callout.toastMessage,
+ description: callout.name,
+ });
+ },
+ onError: (error) => {
+ showErrorToast("Web callout failed", error.message);
+ },
+ });
+
+ const invokeCallout = async () => {
+ const callout = endpoint.data;
+
+ if (!callout?.enabled) {
+ return;
+ }
+
+ await invokeMutation.mutateAsync({
+ projectId: props.projectId,
+ traceId: props.traceId,
+ observationId: props.observationId ?? null,
+ sessionId: props.sessionId ?? null,
+ });
+ };
+
+ return {
+ endpointName: endpoint.data?.name ?? "Web callout",
+ isLoading: invokeMutation.isPending,
+ isVisible: endpoint.data?.enabled === true,
+ invokeCallout,
+ };
+}
+
+export function WebCalloutMenuItem({
+ projectId,
+ traceId,
+ observationId,
+ sessionId,
+ withSeparator,
+}: WebCalloutTarget & {
+ withSeparator?: boolean;
+}) {
+ const action = useWebCalloutAction({
+ projectId,
+ traceId,
+ observationId,
+ sessionId,
+ });
+
+ if (!action.isVisible) {
+ return null;
+ }
+
+ return (
+ <>
+ <DropdownMenuItem
+ className="text-xs"
+ disabled={action.isLoading}
+ onSelect={(event) => {
+ event.preventDefault();
+ action.invokeCallout().catch(() => undefined);
+ }}
+ >
+ <Webhook className="mr-2 h-4 w-4" />
+ <span
+ className="max-w-[260px] min-w-0 truncate"
+ title={action.endpointName}
+ >
+ <span>Call </span>
+ <span className="font-semibold">{action.endpointName}</span>
+ </span>
+ </DropdownMenuItem>
+ {withSeparator && <DropdownMenuSeparator />}
+ </>
+ );
+}
+
+export function WebCalloutButton({
+ projectId,
+ traceId,
+ observationId,
+ sessionId,
+}: WebCalloutTarget) {
+ const action = useWebCalloutAction({
+ projectId,
+ traceId,
+ observationId,
+ sessionId,
+ });
+
+ if (!action.isVisible) {
+ return null;
+ }
+
+ const label = `Call ${action.endpointName}`;
+
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ aria-label={label}
+ title={label}
+ variant="outline"
+ size="icon"
+ loading={action.isLoading}
+ onClick={() => {
+ action.invokeCallout().catch(() => undefined);
+ }}
+ >
+ <Webhook className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{label}</TooltipContent>
+ </Tooltip>
+ );
+}
diff --git a/web/src/features/web-callouts/components/WebCalloutSettingsPage.tsx b/web/src/features/web-callouts/components/WebCalloutSettingsPage.tsx
new file mode 100644
index 0000000000..758167dec5
--- /dev/null
+++ b/web/src/features/web-callouts/components/WebCalloutSettingsPage.tsx
@@ -0,0 +1,696 @@
+import { zodResolver } from "@hookform/resolvers/zod";
+import { Pencil, Plus, Trash2, Webhook, X } from "lucide-react";
+import type { ReactNode } from "react";
+import { useEffect, useState } from "react";
+import { useFieldArray, useForm } from "react-hook-form";
+import { z } from "zod";
+
+import { ActionButton } from "@/src/components/ActionButton";
+import Header from "@/src/components/layouts/header";
+import { StatusBadge } from "@/src/components/layouts/status-badge";
+import { Alert, AlertDescription, AlertTitle } from "@/src/components/ui/alert";
+import { Button } from "@/src/components/ui/button";
+import { Card } from "@/src/components/ui/card";
+import {
+ Dialog,
+ DialogBody,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/src/components/ui/dialog";
+import {
+ Form,
+ FormControl,
+ FormDescription,
+ FormField,
+ FormItem,
+ FormLabel,
+ FormMessage,
+} from "@/src/components/ui/form";
+import { Input } from "@/src/components/ui/input";
+import { Switch } from "@/src/components/ui/switch";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from "@/src/components/ui/table";
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@/src/components/ui/tooltip";
+import { showErrorToast } from "@/src/features/notifications/showErrorToast";
+import { showSuccessToast } from "@/src/features/notifications/showSuccessToast";
+import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ WEB_CALLOUT_BLOCKED_HEADER_NAMES,
+ WEB_CALLOUT_HEADER_NAME_PATTERN,
+} from "@/src/features/web-callouts/headerRules";
+import { api, type RouterOutputs } from "@/src/utils/api";
+
+type WebCalloutEndpoint = RouterOutputs["webCallouts"]["all"][number];
+
+const webCalloutFormSchema = z
+ .object({
+ id: z.string().optional(),
+ name: z.string().trim().min(1).max(100),
+ url: z.url(),
+ enabled: z.boolean(),
+ toastMessage: z.string().trim().min(1).max(200),
+ headers: z.array(
+ z.object({
+ name: z.string(),
+ value: z.string(),
+ }),
+ ),
+ })
+ .superRefine((data, ctx) => {
+ const seenHeaderNames = new Set<string>();
+
+ data.headers.forEach((header, index) => {
+ const name = header.name.trim();
+
+ if (!name) {
+ return;
+ }
+
+ const lowerName = name.toLowerCase();
+
+ if (!WEB_CALLOUT_HEADER_NAME_PATTERN.test(name)) {
+ ctx.addIssue({
+ code: "custom",
+ message: "Invalid header name.",
+ path: ["headers", index, "name"],
+ });
+ }
+
+ if (WEB_CALLOUT_BLOCKED_HEADER_NAMES.has(lowerName)) {
+ ctx.addIssue({
+ code: "custom",
+ message: "This header is set by Langfuse and cannot be customized.",
+ path: ["headers", index, "name"],
+ });
+ }
+
+ if (seenHeaderNames.has(lowerName)) {
+ ctx.addIssue({
+ code: "custom",
+ message: "Header names must be unique.",
+ path: ["headers", index, "name"],
+ });
+ }
+
+ seenHeaderNames.add(lowerName);
+ });
+ });
+
+type WebCalloutFormValues = z.infer<typeof webCalloutFormSchema>;
+
+export function WebCalloutSettingsPage(props: { projectId: string }) {
+ const [dialogOpen, setDialogOpen] = useState(false);
+ const [editingEndpoint, setEditingEndpoint] =
+ useState<WebCalloutEndpoint | null>(null);
+
+ const hasAccess = useHasProjectAccess({
+ projectId: props.projectId,
+ scope: "integrations:CRUD",
+ });
+
+ const endpoints = api.webCallouts.all.useQuery(
+ { projectId: props.projectId },
+ { enabled: hasAccess },
+ );
+ const utils = api.useUtils();
+
+ const deleteMutation = api.webCallouts.delete.useMutation({
+ onSuccess: async () => {
+ await utils.webCallouts.invalidate();
+ showSuccessToast({
+ title: "Callout endpoint deleted",
+ description: "The endpoint was removed from this project.",
+ });
+ },
+ onError: (error) => {
+ showErrorToast("Failed to delete callout endpoint", error.message);
+ },
+ });
+
+ if (!hasAccess) {
+ return (
+ <div>
+ <Header title="Web Callouts" />
+ <Alert>
+ <AlertTitle>Access Denied</AlertTitle>
+ <AlertDescription>
+ You do not have permission to manage integrations for this project.
+ </AlertDescription>
+ </Alert>
+ </div>
+ );
+ }
+
+ const configuredEndpoint = endpoints.data?.[0];
+ const canCreateEndpoint = !configuredEndpoint;
+
+ const openCreateDialog = () => {
+ setEditingEndpoint(null);
+ setDialogOpen(true);
+ };
+
+ const openEditDialog = (endpoint: WebCalloutEndpoint) => {
+ setEditingEndpoint(endpoint);
+ setDialogOpen(true);
+ };
+
+ return (
+ <div>
+ <div className="mb-4 flex items-center justify-between gap-2">
+ <Header title="Web Callouts" />
+ <WebCalloutEndpointDialog
+ projectId={props.projectId}
+ endpoint={editingEndpoint}
+ open={dialogOpen}
+ onOpenChange={(open) => {
+ setDialogOpen(open);
+ if (!open) {
+ setEditingEndpoint(null);
+ }
+ }}
+ trigger={
+ <Button
+ disabled={!canCreateEndpoint || endpoints.isLoading}
+ onClick={openCreateDialog}
+ >
+ <Plus className="mr-1 h-4 w-4" />
+ Add endpoint
+ </Button>
+ }
+ />
+ </div>
+
+ <p className="text-primary mb-4 text-sm">
+ Configure a project-level callout endpoint for trace, observation, and
+ session detail actions. Langfuse sends a backend POST with ids only.
+ </p>
+
+ <Card className="overflow-auto">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead className="text-primary">Endpoint</TableHead>
+ <TableHead className="text-primary">Behavior</TableHead>
+ <TableHead className="text-primary">Headers</TableHead>
+ <TableHead className="text-primary">Status</TableHead>
+ <TableHead />
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {endpoints.data?.length === 0 ? (
+ <TableRow>
+ <TableCell
+ density="comfortable"
+ colSpan={5}
+ className="text-muted-foreground text-center"
+ >
+ No callout endpoint configured.
+ </TableCell>
+ </TableRow>
+ ) : (
+ endpoints.data?.map((endpoint) => (
+ <TableRow key={endpoint.id}>
+ <TableCell
+ density="comfortable"
+ className="max-w-xl font-mono break-all"
+ >
+ {endpoint.url}
+ </TableCell>
+ <TableCell density="comfortable">
+ <BehaviorSummary endpoint={endpoint} />
+ </TableCell>
+ <TableCell density="comfortable">
+ <HeaderList endpoint={endpoint} />
+ </TableCell>
+ <TableCell density="comfortable">
+ <StatusBadge
+ type={endpoint.enabled ? "active" : "disabled"}
+ />
+ </TableCell>
+ <TableCell density="comfortable" className="text-right">
+ <div className="flex justify-end gap-1">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={() => openEditDialog(endpoint)}
+ >
+ <Pencil className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Edit endpoint</TooltipContent>
+ </Tooltip>
+ <DeleteEndpointButton
+ endpoint={endpoint}
+ onDelete={(id) => {
+ deleteMutation.mutate({
+ projectId: props.projectId,
+ id,
+ });
+ }}
+ loading={deleteMutation.isPending}
+ />
+ </div>
+ </TableCell>
+ </TableRow>
+ ))
+ )}
+ </TableBody>
+ </Table>
+ </Card>
+ </div>
+ );
+}
+
+function HeaderList(props: { endpoint: WebCalloutEndpoint }) {
+ const headers = props.endpoint.requestHeaderKeys;
+
+ if (headers.length === 0) {
+ return <span className="text-muted-foreground">None</span>;
+ }
+
+ return (
+ <div className="flex flex-wrap gap-1">
+ {headers.map((name) => (
+ <code key={name}>{name}</code>
+ ))}
+ </div>
+ );
+}
+
+function BehaviorSummary(props: { endpoint: WebCalloutEndpoint }) {
+ return (
+ <div className="space-y-1 text-sm">
+ <div className="max-w-xs truncate" title={props.endpoint.toastMessage}>
+ {props.endpoint.toastMessage}
+ </div>
+ <div className="text-muted-foreground">5s backend timeout</div>
+ </div>
+ );
+}
+
+function WebCalloutEndpointDialog(props: {
+ projectId: string;
+ endpoint: WebCalloutEndpoint | null;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ trigger: ReactNode;
+}) {
+ const utils = api.useUtils();
+ const upsertMutation = api.webCallouts.upsert.useMutation({
+ onSuccess: async () => {
+ await utils.webCallouts.invalidate();
+ showSuccessToast({
+ title: props.endpoint
+ ? "Callout endpoint updated"
+ : "Callout endpoint created",
+ description: "Web callout configuration was saved.",
+ });
+ props.onOpenChange(false);
+ },
+ onError: (error) => {
+ showErrorToast("Failed to save callout endpoint", error.message);
+ },
+ });
+
+ const form = useForm<WebCalloutFormValues>({
+ resolver: zodResolver(webCalloutFormSchema),
+ defaultValues: endpointToFormValues(props.endpoint),
+ });
+
+ const { fields, append, remove } = useFieldArray({
+ control: form.control,
+ name: "headers",
+ });
+
+ useEffect(() => {
+ if (props.open) {
+ form.reset(endpointToFormValues(props.endpoint));
+ }
+ }, [form, props.endpoint, props.open]);
+
+ const onSubmit = (values: WebCalloutFormValues) => {
+ upsertMutation.mutate({
+ projectId: props.projectId,
+ id: values.id,
+ name: values.name,
+ url: values.url,
+ enabled: values.enabled,
+ toastMessage: values.toastMessage,
+ requestHeaders: formValuesToRequestHeaders(values),
+ });
+ };
+
+ return (
+ <Dialog open={props.open} onOpenChange={props.onOpenChange}>
+ <DialogTrigger asChild>{props.trigger}</DialogTrigger>
+ <DialogContent size="lg">
+ <DialogHeader>
+ <DialogTitle>
+ {props.endpoint ? "Edit Callout Endpoint" : "Add Callout Endpoint"}
+ </DialogTitle>
+ <DialogDescription>
+ Langfuse sends a backend JSON POST when a user clicks a web callout
+ action.
+ </DialogDescription>
+ </DialogHeader>
+
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)}>
+ <DialogBody>
+ <Alert>
+ <AlertTitle>Backend request requirements</AlertTitle>
+ <AlertDescription className="space-y-3">
+ <p>
+ Langfuse sends this request from its backend. Your endpoint
+ must accept <code>POST</code> requests with{" "}
+ <code>Content-Type: application/json</code> and return HTTP
+ 2xx within 5 seconds.
+ </p>
+ <p>
+ Header values are encrypted at rest and sent only from the
+ backend. They are not exposed to the user&apos;s browser.
+ </p>
+ <p>
+ Every configured header is sent with each callout request.
+ If the URL uses <code>http://</code>, those headers are sent
+ without transport encryption; use HTTPS for production.
+ </p>
+ </AlertDescription>
+ </Alert>
+
+ <FormField
+ control={form.control}
+ name="name"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Name</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="url"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Endpoint URL</FormLabel>
+ <FormControl>
+ <Input
+ placeholder="https://example.com/langfuse/callout"
+ {...field}
+ />
+ </FormControl>
+ <FormDescription>
+ HTTP or HTTPS URL. Custom ports are allowed. The endpoint
+ is called from the Langfuse backend.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="enabled"
+ render={({ field }) => (
+ <FormItem className="flex items-center justify-between rounded-md border p-3">
+ <div>
+ <FormLabel>Enabled</FormLabel>
+ <FormDescription>
+ Shows the callout action in trace, observation, and
+ session detail headers.
+ </FormDescription>
+ </div>
+ <FormControl>
+ <Switch
+ checked={field.value}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ )}
+ />
+
+ <FormField
+ control={form.control}
+ name="toastMessage"
+ render={({ field }) => (
+ <FormItem>
+ <FormLabel>Toast message</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormDescription>
+ Shown after the backend callout succeeds.
+ </FormDescription>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+
+ <div>
+ <FormLabel>Headers</FormLabel>
+ <FormDescription className="mb-2">
+ Optional headers added to the backend POST. Content-Type is
+ set automatically. Leave values empty for existing header
+ names to keep encrypted values.
+ </FormDescription>
+ <div className="space-y-2">
+ {fields.map((field, index) => {
+ const currentHeaderName = form.watch(
+ `headers.${index}.name`,
+ );
+ const preservesExistingValue = hasExistingHeaderName(
+ props.endpoint,
+ currentHeaderName,
+ );
+
+ return (
+ <div
+ key={field.id}
+ className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)_auto] items-start gap-2"
+ >
+ <FormField
+ control={form.control}
+ name={`headers.${index}.name`}
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Input placeholder="Header name" {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <FormField
+ control={form.control}
+ name={`headers.${index}.value`}
+ render={({ field }) => (
+ <FormItem>
+ <FormControl>
+ <Input
+ placeholder={
+ preservesExistingValue
+ ? "***"
+ : "Header value"
+ }
+ type="password"
+ {...field}
+ />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )}
+ />
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => remove(index)}
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Remove header</TooltipContent>
+ </Tooltip>
+ </div>
+ );
+ })}
+ </div>
+ <Button
+ type="button"
+ variant="outline"
+ className="mt-2"
+ onClick={() =>
+ append({
+ name: "",
+ value: "",
+ })
+ }
+ >
+ <Plus className="mr-1 h-4 w-4" />
+ Add header
+ </Button>
+ </div>
+ </DialogBody>
+
+ <DialogFooter>
+ <Button
+ type="button"
+ variant="ghost"
+ onClick={() => props.onOpenChange(false)}
+ >
+ Cancel
+ </Button>
+ <Button type="submit" loading={upsertMutation.isPending}>
+ Save endpoint
+ </Button>
+ </DialogFooter>
+ </form>
+ </Form>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function DeleteEndpointButton(props: {
+ endpoint: WebCalloutEndpoint;
+ onDelete: (id: string) => void;
+ loading: boolean;
+}) {
+ const [open, setOpen] = useState(false);
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <DialogTrigger asChild>
+ <Button variant="ghost" size="icon">
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </DialogTrigger>
+ </TooltipTrigger>
+ <TooltipContent>Delete endpoint</TooltipContent>
+ </Tooltip>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Delete Callout Endpoint</DialogTitle>
+ <DialogDescription>
+ This removes the configured endpoint and hides the web callout
+ action.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <Button variant="ghost" onClick={() => setOpen(false)}>
+ Cancel
+ </Button>
+ <Button
+ variant="destructive"
+ loading={props.loading}
+ onClick={() => {
+ props.onDelete(props.endpoint.id);
+ setOpen(false);
+ }}
+ >
+ Delete endpoint
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+const endpointToFormValues = (
+ endpoint: WebCalloutEndpoint | null,
+): WebCalloutFormValues => ({
+ id: endpoint?.id,
+ name: endpoint?.name ?? "Default",
+ url: endpoint?.url ?? "",
+ enabled: endpoint?.enabled ?? true,
+ toastMessage: endpoint?.toastMessage ?? "Callout sent",
+ headers: (endpoint?.requestHeaderKeys ?? []).map((name) => ({
+ name,
+ value: "",
+ })),
+});
+
+const formValuesToRequestHeaders = (
+ values: WebCalloutFormValues,
+): Record<string, string> =>
+ Object.fromEntries(
+ values.headers
+ .filter((header) => header.name.trim())
+ .map((header) => [header.name.trim(), header.value.trim()]),
+ );
+
+const hasExistingHeaderName = (
+ endpoint: WebCalloutEndpoint | null,
+ name: string,
+) => {
+ const normalizedName = name.trim().toLowerCase();
+ if (!normalizedName) {
+ return false;
+ }
+
+ return (
+ endpoint?.requestHeaderKeys.some(
+ (headerName) => headerName.toLowerCase() === normalizedName,
+ ) ?? false
+ );
+};
+
+export function WebCalloutIntegrationCard(props: {
+ projectId: string;
+ hasAccess: boolean;
+}) {
+ const availability = api.webCallouts.availability.useQuery(
+ { projectId: props.projectId },
+ { staleTime: 60_000 },
+ );
+
+ if (availability.data?.enabled !== true) {
+ return null;
+ }
+
+ return (
+ <Card className="p-3">
+ <div className="mb-4 flex items-center gap-2">
+ <Webhook className="text-foreground h-5 w-5" />
+ <span className="font-semibold">Web Callouts</span>
+ </div>
+ <p className="text-primary mb-4 text-sm">
+ Send backend callouts from trace, observation, and session detail views
+ to your own application.
+ </p>
+ <ActionButton
+ variant="secondary"
+ hasAccess={props.hasAccess}
+ href={`/project/${props.projectId}/settings/integrations/web-callouts`}
+ >
+ Configure
+ </ActionButton>
+ </Card>
+ );
+}
diff --git a/web/src/features/web-callouts/headerRules.ts b/web/src/features/web-callouts/headerRules.ts
new file mode 100644
index 0000000000..95d41f05b4
--- /dev/null
+++ b/web/src/features/web-callouts/headerRules.ts
@@ -0,0 +1,8 @@
+export const WEB_CALLOUT_BLOCKED_HEADER_NAMES = new Set([
+ "content-length",
+ "content-type",
+ "cookie",
+ "host",
+]);
+
+export const WEB_CALLOUT_HEADER_NAME_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
diff --git a/web/src/features/web-callouts/server/featureFlag.ts b/web/src/features/web-callouts/server/featureFlag.ts
new file mode 100644
index 0000000000..edb5722790
--- /dev/null
+++ b/web/src/features/web-callouts/server/featureFlag.ts
@@ -0,0 +1,15 @@
+import { TRPCError } from "@trpc/server";
+
+import { env } from "@/src/env.mjs";
+
+export const isWebCalloutsEnabled = () =>
+ env.LANGFUSE_ENABLE_WEB_CALLOUTS === "true";
+
+export const throwIfWebCalloutsDisabled = () => {
+ if (!isWebCalloutsEnabled()) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Web callouts are not enabled.",
+ });
+ }
+};
diff --git a/web/src/features/web-callouts/server/headers.ts b/web/src/features/web-callouts/server/headers.ts
new file mode 100644
index 0000000000..d71f6d5ba5
--- /dev/null
+++ b/web/src/features/web-callouts/server/headers.ts
@@ -0,0 +1,167 @@
+import { TRPCError } from "@trpc/server";
+import { z } from "zod";
+
+import { type WebCalloutHeaders } from "@/src/features/web-callouts/types";
+import {
+ WEB_CALLOUT_BLOCKED_HEADER_NAMES,
+ WEB_CALLOUT_HEADER_NAME_PATTERN,
+} from "@/src/features/web-callouts/headerRules";
+import { decrypt, encrypt } from "@langfuse/shared/encryption";
+
+const WEB_CALLOUT_MAX_HEADER_COUNT = 20;
+const WEB_CALLOUT_MAX_HEADER_NAME_BYTES = 128;
+const WEB_CALLOUT_MAX_HEADER_VALUE_BYTES = 4 * 1024;
+const WEB_CALLOUT_MAX_TOTAL_HEADER_BYTES = 8 * 1024;
+const WebCalloutEncryptedHeadersSchema = z.record(z.string(), z.string());
+
+export type StoredWebCalloutHeaders = {
+ requestHeaders: string | null;
+ requestHeaderKeys: string[];
+};
+
+export const processHeadersForStorage = ({
+ inputHeaders,
+ existingHeaders,
+}: {
+ inputHeaders: WebCalloutHeaders;
+ existingHeaders: WebCalloutHeaders;
+}): StoredWebCalloutHeaders => {
+ const requestHeaders: WebCalloutHeaders = {};
+ const normalizedHeaderNames = new Set<string>();
+
+ for (const [rawName, rawValue] of Object.entries(inputHeaders)) {
+ const name = rawName.trim();
+ const value = rawValue.trim();
+
+ if (!name) {
+ continue;
+ }
+
+ validateHeaderName(name);
+ const normalizedName = name.toLowerCase();
+
+ if (normalizedHeaderNames.has(normalizedName)) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Header "${name}" is configured more than once.`,
+ });
+ }
+ normalizedHeaderNames.add(normalizedName);
+
+ if (value) {
+ requestHeaders[name] = value;
+ continue;
+ }
+
+ const existingValue = findExistingHeaderValue(name, existingHeaders);
+ if (existingValue !== undefined) {
+ requestHeaders[name] = existingValue;
+ continue;
+ }
+
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Header "${name}" value is required when adding or renaming a header.`,
+ });
+ }
+
+ assertHeaderLimits(requestHeaders);
+
+ const requestHeaderKeys = Object.keys(requestHeaders);
+
+ return {
+ requestHeaders:
+ requestHeaderKeys.length > 0
+ ? encrypt(JSON.stringify(requestHeaders))
+ : null,
+ requestHeaderKeys,
+ };
+};
+
+export const decryptWebCalloutHeaders = (
+ storedHeaders: string | null | undefined,
+): WebCalloutHeaders => {
+ if (!storedHeaders) {
+ return {};
+ }
+
+ try {
+ return WebCalloutEncryptedHeadersSchema.parse(
+ JSON.parse(decrypt(storedHeaders)),
+ );
+ } catch {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ "Failed to decrypt web callout headers. Please update the web callout configuration.",
+ });
+ }
+};
+
+const findExistingHeaderValue = (
+ name: string,
+ existingHeaders: WebCalloutHeaders,
+) => {
+ const existingName = Object.keys(existingHeaders).find(
+ (headerName) => headerName.toLowerCase() === name.toLowerCase(),
+ );
+
+ return existingName ? existingHeaders[existingName] : undefined;
+};
+
+const assertHeaderLimits = (headers: WebCalloutHeaders) => {
+ const entries = Object.entries(headers);
+ if (entries.length > WEB_CALLOUT_MAX_HEADER_COUNT) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `At most ${WEB_CALLOUT_MAX_HEADER_COUNT} request headers can be configured.`,
+ });
+ }
+
+ let totalHeaderBytes = 0;
+
+ for (const [name, value] of entries) {
+ const nameBytes = Buffer.byteLength(name, "utf8");
+ if (nameBytes > WEB_CALLOUT_MAX_HEADER_NAME_BYTES) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Header "${name}" name must be at most ${WEB_CALLOUT_MAX_HEADER_NAME_BYTES} bytes.`,
+ });
+ }
+
+ const valueBytes = Buffer.byteLength(value, "utf8");
+ if (valueBytes > WEB_CALLOUT_MAX_HEADER_VALUE_BYTES) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Header "${name}" value must be at most ${WEB_CALLOUT_MAX_HEADER_VALUE_BYTES} bytes.`,
+ });
+ }
+
+ totalHeaderBytes += nameBytes + valueBytes;
+ }
+
+ if (totalHeaderBytes > WEB_CALLOUT_MAX_TOTAL_HEADER_BYTES) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Request headers must be at most ${WEB_CALLOUT_MAX_TOTAL_HEADER_BYTES} bytes total.`,
+ });
+ }
+};
+
+const validateHeaderName = (name: string) => {
+ const lowerName = name.toLowerCase();
+
+ if (!WEB_CALLOUT_HEADER_NAME_PATTERN.test(name)) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Header "${name}" has an invalid name.`,
+ });
+ }
+
+ if (WEB_CALLOUT_BLOCKED_HEADER_NAMES.has(lowerName)) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Header "${name}" cannot be configured manually.`,
+ });
+ }
+};
diff --git a/web/src/features/web-callouts/server/router.ts b/web/src/features/web-callouts/server/router.ts
new file mode 100644
index 0000000000..0ee94272f3
--- /dev/null
+++ b/web/src/features/web-callouts/server/router.ts
@@ -0,0 +1,176 @@
+import { z } from "zod";
+import { TRPCError } from "@trpc/server";
+
+import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";
+import {
+ WebCalloutEndpointUpsertInputSchema,
+ WebCalloutInvokeInputSchema,
+} from "@/src/features/web-callouts/types";
+import {
+ invokeWebCalloutEndpoint,
+ toEnabledWebCallout,
+ toSafeWebCalloutEndpoint,
+ upsertWebCalloutEndpoint,
+} from "@/src/features/web-callouts/server/service";
+import {
+ isWebCalloutsEnabled,
+ throwIfWebCalloutsDisabled,
+} from "@/src/features/web-callouts/server/featureFlag";
+import {
+ createTRPCRouter,
+ protectedProjectProcedure,
+} from "@/src/server/api/trpc";
+
+export const webCalloutsRouter = createTRPCRouter({
+ availability: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "project:read",
+ });
+
+ return { enabled: isWebCalloutsEnabled() };
+ }),
+
+ all: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "integrations:CRUD",
+ });
+ throwIfWebCalloutsDisabled();
+
+ const endpoints = await ctx.prisma.webCalloutEndpoint.findMany({
+ where: { projectId: input.projectId },
+ orderBy: { createdAt: "asc" },
+ });
+
+ return endpoints.map(toSafeWebCalloutEndpoint);
+ }),
+
+ enabled: protectedProjectProcedure
+ .input(z.object({ projectId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "project:read",
+ });
+
+ if (!isWebCalloutsEnabled()) {
+ return toEnabledWebCallout(null);
+ }
+
+ const endpoint = await ctx.prisma.webCalloutEndpoint.findFirst({
+ where: { projectId: input.projectId, enabled: true },
+ orderBy: { createdAt: "asc" },
+ });
+
+ return toEnabledWebCallout(endpoint);
+ }),
+
+ upsert: protectedProjectProcedure
+ .input(WebCalloutEndpointUpsertInputSchema)
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "integrations:CRUD",
+ });
+ throwIfWebCalloutsDisabled();
+
+ const before = input.id
+ ? await ctx.prisma.webCalloutEndpoint
+ .findFirst({
+ where: { id: input.id, projectId: input.projectId },
+ })
+ .then((endpoint) =>
+ endpoint ? toSafeWebCalloutEndpoint(endpoint) : null,
+ )
+ : null;
+
+ const endpoint = await upsertWebCalloutEndpoint({
+ prisma: ctx.prisma,
+ projectId: input.projectId,
+ input,
+ });
+
+ await auditLog(
+ {
+ session: ctx.session,
+ action: before ? "update" : "create",
+ resourceType: "webCalloutEndpoint",
+ resourceId: endpoint.id,
+ before,
+ after: endpoint,
+ },
+ ctx.prisma,
+ );
+
+ return endpoint;
+ }),
+
+ delete: protectedProjectProcedure
+ .input(z.object({ projectId: z.string(), id: z.string() }))
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "integrations:CRUD",
+ });
+ throwIfWebCalloutsDisabled();
+
+ const endpoint = await ctx.prisma.webCalloutEndpoint.findFirst({
+ where: {
+ id: input.id,
+ projectId: input.projectId,
+ },
+ });
+
+ if (!endpoint) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Web callout endpoint not found",
+ });
+ }
+
+ const safeEndpoint = toSafeWebCalloutEndpoint(endpoint);
+
+ await ctx.prisma.webCalloutEndpoint.delete({
+ where: { id: input.id },
+ });
+
+ await auditLog(
+ {
+ session: ctx.session,
+ action: "delete",
+ resourceType: "webCalloutEndpoint",
+ resourceId: input.id,
+ before: safeEndpoint,
+ },
+ ctx.prisma,
+ );
+ }),
+
+ invoke: protectedProjectProcedure
+ .input(WebCalloutInvokeInputSchema)
+ .mutation(async ({ input, ctx }) => {
+ throwIfNoProjectAccess({
+ session: ctx.session,
+ projectId: input.projectId,
+ scope: "project:read",
+ });
+ throwIfWebCalloutsDisabled();
+
+ return invokeWebCalloutEndpoint({
+ prisma: ctx.prisma,
+ input,
+ useEventsTable: ctx.session.user.v4BetaEnabled === true,
+ });
+ }),
+});
diff --git a/web/src/features/web-callouts/server/service.ts b/web/src/features/web-callouts/server/service.ts
new file mode 100644
index 0000000000..a9ec54f4df
--- /dev/null
+++ b/web/src/features/web-callouts/server/service.ts
@@ -0,0 +1,275 @@
+import { TRPCError } from "@trpc/server";
+
+import {
+ type WebCalloutEndpointInput,
+ type WebCalloutInvokeInput,
+ type WebCalloutPayload,
+} from "@/src/features/web-callouts/types";
+import {
+ decryptWebCalloutHeaders,
+ processHeadersForStorage,
+} from "@/src/features/web-callouts/server/headers";
+import { assertTargetBelongsToProject } from "@/src/features/web-callouts/server/targetValidation";
+import {
+ assertValidCalloutUrl,
+ validateWebCalloutUrl,
+ webCalloutWhitelist,
+} from "@/src/features/web-callouts/server/urlValidation";
+import { fetchWithSecureRedirects, logger } from "@langfuse/shared/src/server";
+import {
+ type PrismaClient,
+ type WebCalloutEndpoint,
+} from "@langfuse/shared/src/db";
+
+export const WEB_CALLOUT_TIMEOUT_MS = 5_000;
+const WEB_CALLOUT_MAX_REDIRECTS = 10;
+
+type StoredEndpoint = WebCalloutEndpoint;
+
+export type SafeWebCalloutEndpoint = Omit<StoredEndpoint, "requestHeaders">;
+
+export const toSafeWebCalloutEndpoint = (
+ endpoint: StoredEndpoint,
+): SafeWebCalloutEndpoint => {
+ const { requestHeaders: _requestHeaders, ...safeEndpoint } = endpoint;
+ return safeEndpoint;
+};
+
+export type EnabledWebCallout =
+ | {
+ enabled: false;
+ id: null;
+ name: null;
+ toastMessage: null;
+ }
+ | {
+ enabled: true;
+ id: string;
+ name: string;
+ toastMessage: string;
+ };
+
+export const toEnabledWebCallout = (
+ endpoint: StoredEndpoint | null | undefined,
+): EnabledWebCallout => {
+ if (!endpoint?.enabled) {
+ return {
+ enabled: false,
+ id: null,
+ name: null,
+ toastMessage: null,
+ };
+ }
+
+ return {
+ enabled: true,
+ id: endpoint.id,
+ name: endpoint.name,
+ toastMessage: endpoint.toastMessage,
+ };
+};
+
+export const upsertWebCalloutEndpoint = async ({
+ prisma,
+ projectId,
+ input,
+}: {
+ prisma: PrismaClient;
+ projectId: string;
+ input: WebCalloutEndpointInput;
+}) => {
+ await assertValidCalloutUrl(input.url);
+
+ const existingEndpoint = input.id
+ ? await prisma.webCalloutEndpoint.findFirst({
+ where: { id: input.id, projectId },
+ })
+ : await prisma.webCalloutEndpoint.findFirst({
+ where: { projectId },
+ orderBy: { createdAt: "asc" },
+ });
+
+ if (input.id && !existingEndpoint) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Web callout endpoint not found",
+ });
+ }
+
+ if (!input.id && existingEndpoint) {
+ throw new TRPCError({
+ code: "CONFLICT",
+ message: "Only one web callout endpoint can be configured per project.",
+ });
+ }
+
+ const shouldMergeExistingHeaders =
+ Object.keys(input.requestHeaders).length > 0;
+ const headers = processHeadersForStorage({
+ inputHeaders: input.requestHeaders,
+ existingHeaders:
+ existingEndpoint && shouldMergeExistingHeaders
+ ? decryptWebCalloutHeaders(existingEndpoint.requestHeaders)
+ : {},
+ });
+
+ const data = {
+ name: input.name,
+ url: input.url,
+ enabled: input.enabled,
+ toastMessage: input.toastMessage,
+ requestHeaders: headers.requestHeaders,
+ requestHeaderKeys: headers.requestHeaderKeys,
+ };
+
+ const endpoint = input.id
+ ? await prisma.webCalloutEndpoint.update({
+ where: { id: input.id },
+ data,
+ })
+ : await prisma.webCalloutEndpoint.create({
+ data: {
+ ...data,
+ projectId,
+ },
+ });
+
+ return toSafeWebCalloutEndpoint(endpoint);
+};
+
+export const invokeWebCalloutEndpoint = async ({
+ prisma,
+ input,
+ useEventsTable,
+}: {
+ prisma: PrismaClient;
+ input: WebCalloutInvokeInput;
+ useEventsTable: boolean;
+}) => {
+ const endpoint = await prisma.webCalloutEndpoint.findFirst({
+ where: {
+ projectId: input.projectId,
+ enabled: true,
+ },
+ orderBy: { createdAt: "asc" },
+ });
+
+ if (!endpoint) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "No enabled web callout is configured.",
+ });
+ }
+
+ await assertTargetBelongsToProject({
+ prisma,
+ input,
+ useEventsTable,
+ });
+ await assertValidCalloutUrl(endpoint.url);
+
+ const payload: WebCalloutPayload = {
+ version: 1,
+ items: [
+ {
+ projectId: input.projectId,
+ traceId: input.traceId,
+ observationId: input.observationId,
+ sessionId: input.sessionId,
+ },
+ ],
+ };
+ const body = JSON.stringify(payload);
+ const decryptedHeaders = decryptWebCalloutHeaders(endpoint.requestHeaders);
+ const outboundHeaders = new Headers();
+ outboundHeaders.set("Content-Type", "application/json");
+ outboundHeaders.set("User-Agent", "Langfuse/1.0");
+
+ for (const [name, value] of Object.entries(decryptedHeaders)) {
+ outboundHeaders.set(name, value);
+ }
+
+ const abortController = new AbortController();
+ const timeout = setTimeout(
+ () => abortController.abort(),
+ WEB_CALLOUT_TIMEOUT_MS,
+ );
+
+ try {
+ const { response } = await fetchWithSecureRedirects(
+ endpoint.url,
+ {
+ method: "POST",
+ body,
+ headers: outboundHeaders,
+ signal: abortController.signal,
+ },
+ {
+ maxRedirects: WEB_CALLOUT_MAX_REDIRECTS,
+ additionalSensitiveHeaders: Object.keys(decryptedHeaders),
+ redirectValidation: {
+ validateUrl: validateWebCalloutUrl,
+ whitelist: webCalloutWhitelist(),
+ logContext: "Web callout",
+ },
+ },
+ );
+ await discardResponseBody(response);
+
+ if (!response.ok) {
+ logger.warn("Web callout returned non-2xx status", {
+ projectId: input.projectId,
+ endpointId: endpoint.id,
+ status: response.status,
+ });
+
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: `Web callout endpoint returned HTTP ${response.status}.`,
+ });
+ }
+
+ return {
+ success: true as const,
+ status: response.status,
+ };
+ } catch (error) {
+ if (error instanceof TRPCError) {
+ throw error;
+ }
+
+ logger.warn("Web callout request failed", {
+ projectId: input.projectId,
+ endpointId: endpoint.id,
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+
+ if (abortController.signal.aborted) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Web callout timed out after 5 seconds.",
+ });
+ }
+
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Web callout request failed.",
+ });
+ } finally {
+ clearTimeout(timeout);
+ }
+};
+
+const discardResponseBody = async (response: Response) => {
+ if (!response.body) {
+ return;
+ }
+
+ try {
+ await response.body.cancel();
+ } catch (error) {
+ logger.warn("Failed to discard web callout response body", {
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ }
+};
diff --git a/web/src/features/web-callouts/server/targetValidation.ts b/web/src/features/web-callouts/server/targetValidation.ts
new file mode 100644
index 0000000000..94de00e5a0
--- /dev/null
+++ b/web/src/features/web-callouts/server/targetValidation.ts
@@ -0,0 +1,353 @@
+import { TRPCError } from "@trpc/server";
+
+import { env } from "@/src/env.mjs";
+import { type WebCalloutInvokeInput } from "@/src/features/web-callouts/types";
+import { type PrismaClient } from "@langfuse/shared/src/db";
+import {
+ getObservationById,
+ getObservationByIdFromEventsTable,
+ getTraceById,
+ getTraceByIdFromEventsTable,
+ getTracesIdentifierForSession,
+ getTracesIdentifierForSessionFromEvents,
+ logger,
+} from "@langfuse/shared/src/server";
+
+export const assertTargetBelongsToProject = async ({
+ prisma,
+ input,
+ useEventsTable,
+}: {
+ prisma: PrismaClient;
+ input: WebCalloutInvokeInput;
+ useEventsTable: boolean;
+}) => {
+ if (!input.traceId && !input.sessionId) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Trace or session id is required.",
+ });
+ }
+
+ const trace = input.traceId
+ ? await getTraceForProject({
+ traceId: input.traceId,
+ projectId: input.projectId,
+ useEventsTable,
+ })
+ : null;
+
+ if (input.traceId && !trace) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Trace not found in project.",
+ });
+ }
+
+ if (input.observationId) {
+ if (!input.traceId) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Observation callouts require a trace id.",
+ });
+ }
+
+ const observation = await getObservationForProject({
+ observationId: input.observationId,
+ traceId: input.traceId,
+ projectId: input.projectId,
+ useEventsTable,
+ });
+
+ if (!observation) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Observation not found in project.",
+ });
+ }
+ }
+
+ if (input.sessionId) {
+ if (trace && trace.sessionId !== input.sessionId) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message: "Trace does not belong to the provided session.",
+ });
+ }
+
+ const sessionExists = await sessionBelongsToProject({
+ prisma,
+ projectId: input.projectId,
+ sessionId: input.sessionId,
+ useEventsTable,
+ });
+
+ if (!sessionExists) {
+ throw new TRPCError({
+ code: "NOT_FOUND",
+ message: "Session not found in project.",
+ });
+ }
+ }
+};
+
+const getTraceForProject = async ({
+ traceId,
+ projectId,
+ useEventsTable,
+}: {
+ traceId: string;
+ projectId: string;
+ useEventsTable: boolean;
+}) => {
+ if (useEventsTable) {
+ const trace = await tryGetTraceFromEvents({ traceId, projectId });
+ if (trace) return trace;
+ }
+
+ const trace = await tryGetTrace({ traceId, projectId });
+ if (trace) return trace;
+
+ if (shouldTryEventsTableFallback(useEventsTable)) {
+ return tryGetTraceFromEvents({ traceId, projectId });
+ }
+
+ return undefined;
+};
+
+const getObservationForProject = async ({
+ observationId,
+ traceId,
+ projectId,
+ useEventsTable,
+}: {
+ observationId: string;
+ traceId: string;
+ projectId: string;
+ useEventsTable: boolean;
+}) => {
+ if (useEventsTable) {
+ const observation = await tryGetObservationFromEvents({
+ observationId,
+ traceId,
+ projectId,
+ });
+ if (observation) return observation;
+ }
+
+ const observation = await tryGetObservation({
+ observationId,
+ traceId,
+ projectId,
+ });
+ if (observation) return observation;
+
+ if (shouldTryEventsTableFallback(useEventsTable)) {
+ return tryGetObservationFromEvents({ observationId, traceId, projectId });
+ }
+
+ return undefined;
+};
+
+const tryGetTrace = async ({
+ traceId,
+ projectId,
+}: {
+ traceId: string;
+ projectId: string;
+}) => {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Per customer requirement, web callouts should also work on v3.
+ return await getTraceById({
+ traceId,
+ projectId,
+ excludeInputOutput: true,
+ excludeMetadata: true,
+ clickhouseFeatureTag: "web-callouts",
+ });
+ } catch (error) {
+ logger.warn("Failed to validate web callout trace via traces table", {
+ projectId,
+ traceId,
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ return undefined;
+ }
+};
+
+const tryGetTraceFromEvents = async ({
+ traceId,
+ projectId,
+}: {
+ traceId: string;
+ projectId: string;
+}) => {
+ try {
+ return await getTraceByIdFromEventsTable({
+ traceId,
+ projectId,
+ renderingProps: {
+ truncated: true,
+ shouldJsonParse: false,
+ },
+ clickhouseFeatureTag: "web-callouts",
+ });
+ } catch (error) {
+ logger.warn("Failed to validate web callout trace via events table", {
+ projectId,
+ traceId,
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ return undefined;
+ }
+};
+
+const tryGetObservation = async ({
+ observationId,
+ traceId,
+ projectId,
+}: {
+ observationId: string;
+ traceId: string;
+ projectId: string;
+}) => {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Per customer requirement, web callouts should also work on v3.
+ return await getObservationById({
+ id: observationId,
+ projectId,
+ traceId,
+ fetchWithInputOutput: false,
+ renderingProps: {
+ truncated: true,
+ shouldJsonParse: false,
+ },
+ });
+ } catch {
+ return undefined;
+ }
+};
+
+const tryGetObservationFromEvents = async ({
+ observationId,
+ traceId,
+ projectId,
+}: {
+ observationId: string;
+ traceId: string;
+ projectId: string;
+}) => {
+ try {
+ return await getObservationByIdFromEventsTable({
+ id: observationId,
+ projectId,
+ traceId,
+ fetchWithInputOutput: false,
+ renderingProps: {
+ truncated: true,
+ shouldJsonParse: false,
+ },
+ });
+ } catch (error) {
+ logger.warn("Failed to validate web callout observation via events table", {
+ projectId,
+ observationId,
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ return undefined;
+ }
+};
+
+const sessionBelongsToProject = async ({
+ prisma,
+ projectId,
+ sessionId,
+ useEventsTable,
+}: {
+ prisma: PrismaClient;
+ projectId: string;
+ sessionId: string;
+ useEventsTable: boolean;
+}) => {
+ const postgresSession = await prisma.traceSession.findFirst({
+ where: {
+ id: sessionId,
+ projectId,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (postgresSession) {
+ return true;
+ }
+
+ const traces = useEventsTable
+ ? await tryGetTracesIdentifierForSessionFromEvents({
+ projectId,
+ sessionId,
+ })
+ : await tryGetTracesIdentifierForSession({
+ projectId,
+ sessionId,
+ });
+
+ if (traces.length > 0) {
+ return true;
+ }
+
+ if (shouldTryEventsTableFallback(useEventsTable)) {
+ const eventTraces = await tryGetTracesIdentifierForSessionFromEvents({
+ projectId,
+ sessionId,
+ });
+ return eventTraces.length > 0;
+ }
+
+ return false;
+};
+
+const tryGetTracesIdentifierForSession = async ({
+ projectId,
+ sessionId,
+}: {
+ projectId: string;
+ sessionId: string;
+}) => {
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-deprecated -- Per customer requirement, web callouts should also work on v3.
+ return await getTracesIdentifierForSession(projectId, sessionId);
+ } catch (error) {
+ logger.warn("Failed to validate web callout session via traces table", {
+ projectId,
+ sessionId,
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ return [];
+ }
+};
+
+const tryGetTracesIdentifierForSessionFromEvents = async ({
+ projectId,
+ sessionId,
+}: {
+ projectId: string;
+ sessionId: string;
+}) => {
+ try {
+ return await getTracesIdentifierForSessionFromEvents(projectId, sessionId);
+ } catch (error) {
+ logger.warn("Failed to validate web callout session via events table", {
+ projectId,
+ sessionId,
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+ return [];
+ }
+};
+
+const shouldTryEventsTableFallback = (useEventsTable: boolean) =>
+ !useEventsTable &&
+ (env.LANGFUSE_ENABLE_EVENTS_TABLE_FLAGS === "true" ||
+ env.LANGFUSE_ENABLE_EVENTS_TABLE_UI === "true");
diff --git a/web/src/features/web-callouts/server/urlValidation.ts b/web/src/features/web-callouts/server/urlValidation.ts
new file mode 100644
index 0000000000..ca5a9fd946
--- /dev/null
+++ b/web/src/features/web-callouts/server/urlValidation.ts
@@ -0,0 +1,56 @@
+import { TRPCError } from "@trpc/server";
+
+import { env } from "@/src/env.mjs";
+import {
+ type RedirectUrlValidator,
+ type WebhookValidationWhitelist,
+ validateWebhookURL,
+ whitelistFromEnv,
+} from "@langfuse/shared/src/server";
+
+const LOCAL_DEVELOPMENT_CALLOUT_WHITELIST: WebhookValidationWhitelist = {
+ hosts: ["localhost", "127.0.0.1", "[::1]"],
+ ips: ["127.0.0.1", "::1"],
+ ip_ranges: ["127.0.0.0/8", "::1/128"],
+};
+
+export const webCalloutWhitelist = (): WebhookValidationWhitelist => {
+ const whitelist = whitelistFromEnv();
+
+ if (env.NODE_ENV !== "development") {
+ return whitelist;
+ }
+
+ return {
+ hosts: unique([
+ ...whitelist.hosts,
+ ...LOCAL_DEVELOPMENT_CALLOUT_WHITELIST.hosts,
+ ]),
+ ips: unique([...whitelist.ips, ...LOCAL_DEVELOPMENT_CALLOUT_WHITELIST.ips]),
+ ip_ranges: unique([
+ ...whitelist.ip_ranges,
+ ...LOCAL_DEVELOPMENT_CALLOUT_WHITELIST.ip_ranges,
+ ]),
+ };
+};
+
+export const validateWebCalloutUrl: RedirectUrlValidator = (
+ url,
+ whitelist = webCalloutWhitelist(),
+) => validateWebhookURL(url, whitelist, { allowedPorts: "any" });
+
+export const assertValidCalloutUrl = async (url: string) => {
+ try {
+ await validateWebCalloutUrl(url);
+ } catch (error) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ error instanceof Error
+ ? `Invalid web callout URL: ${error.message}`
+ : "Invalid web callout URL",
+ });
+ }
+};
+
+const unique = <T>(items: T[]): T[] => Array.from(new Set(items));
diff --git a/web/src/features/web-callouts/types.ts b/web/src/features/web-callouts/types.ts
new file mode 100644
index 0000000000..862f5fd145
--- /dev/null
+++ b/web/src/features/web-callouts/types.ts
@@ -0,0 +1,42 @@
+import { z } from "zod";
+
+export const WebCalloutHeadersSchema = z.record(z.string(), z.string());
+
+export type WebCalloutHeaders = z.infer<typeof WebCalloutHeadersSchema>;
+
+export const WebCalloutEndpointInputSchema = z.object({
+ id: z.string().optional(),
+ name: z.string().trim().min(1).max(100).default("Default"),
+ url: z.url(),
+ enabled: z.boolean().default(true),
+ toastMessage: z.string().trim().min(1).max(200).default("Callout sent"),
+ requestHeaders: WebCalloutHeadersSchema.default({}),
+});
+
+export type WebCalloutEndpointInput = z.infer<
+ typeof WebCalloutEndpointInputSchema
+>;
+
+export const WebCalloutEndpointUpsertInputSchema =
+ WebCalloutEndpointInputSchema.extend({
+ projectId: z.string(),
+ });
+
+export type WebCalloutPayload = {
+ version: 1;
+ items: Array<{
+ projectId: string;
+ traceId: string | null;
+ observationId: string | null;
+ sessionId: string | null;
+ }>;
+};
+
+export const WebCalloutInvokeInputSchema = z.object({
+ projectId: z.string(),
+ traceId: z.string().nullable(),
+ observationId: z.string().nullable(),
+ sessionId: z.string().nullable(),
+});
+
+export type WebCalloutInvokeInput = z.infer<typeof WebCalloutInvokeInputSchema>;
diff --git a/web/src/pages/project/[projectId]/settings/index.tsx b/web/src/pages/project/[projectId]/settings/index.tsx
index 94c71de991..f8da832a88 100644
--- a/web/src/pages/project/[projectId]/settings/index.tsx
+++ b/web/src/pages/project/[projectId]/settings/index.tsx
@@ -31,6 +31,7 @@ import { SiSlack } from "react-icons/si";
import { ScoreConfigSettings } from "@/src/features/score-configs/components/ScoreConfigSettings";
import { env } from "@/src/env.mjs";
import { NotificationSettings } from "@/src/features/notifications/components/NotificationSettings";
+import { WebCalloutIntegrationCard } from "@/src/features/web-callouts/components/WebCalloutSettingsPage";
import { DeveloperToolsSettings } from "@/src/features/developer-tools/components/DeveloperToolsSettings";
type ProjectSettingsPage = {
@@ -216,7 +217,7 @@ export const getProjectSettingsPages = ({
{
title: "Integrations",
slug: "integrations",
- cmdKKeywords: ["posthog", "mixpanel", "analytics"],
+ cmdKKeywords: ["posthog", "mixpanel", "analytics", "callback", "webhook"],
content: <Integrations projectId={project.id} />,
},
{
@@ -388,6 +389,11 @@ const Integrations = (props: { projectId: string }) => {
</ActionButton>
</div>
</Card>
+
+ <WebCalloutIntegrationCard
+ projectId={props.projectId}
+ hasAccess={hasAccess}
+ />
</div>
</div>
);
diff --git a/web/src/pages/project/[projectId]/settings/integrations/web-callouts.tsx b/web/src/pages/project/[projectId]/settings/integrations/web-callouts.tsx
new file mode 100644
index 0000000000..01976dd12d
--- /dev/null
+++ b/web/src/pages/project/[projectId]/settings/integrations/web-callouts.tsx
@@ -0,0 +1,37 @@
+import { ErrorPage } from "@/src/components/error-page";
+import ContainerPage from "@/src/components/layouts/container-page";
+import { WebCalloutSettingsPage } from "@/src/features/web-callouts/components/WebCalloutSettingsPage";
+import { api } from "@/src/utils/api";
+import { useRouter } from "next/router";
+
+export default function WebCalloutsSettings() {
+ const router = useRouter();
+ const projectId = router.query.projectId as string | undefined;
+ const availability = api.webCallouts.availability.useQuery(
+ { projectId: projectId ?? "" },
+ { enabled: Boolean(projectId), staleTime: 60_000 },
+ );
+
+ if (!projectId || availability.isPending) {
+ return null;
+ }
+
+ if (availability.data?.enabled !== true) {
+ return (
+ <ErrorPage title="Page not found" message="This page does not exist." />
+ );
+ }
+
+ return (
+ <ContainerPage
+ headerProps={{
+ title: "Web Callouts",
+ breadcrumb: [
+ { name: "Settings", href: `/project/${projectId}/settings` },
+ ],
+ }}
+ >
+ <WebCalloutSettingsPage projectId={projectId} />
+ </ContainerPage>
+ );
+}
diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.ts
index 362c4be049..0433946501 100644
--- a/web/src/server/api/root.ts
+++ b/web/src/server/api/root.ts
@@ -56,6 +56,7 @@ import { queueAssignmentRouter } from "@/src/features/annotation-queues/server/a
import { surveysRouter } from "@/src/server/api/routers/surveys";
import { naturalLanguageFilterRouter } from "@/src/features/natural-language-filters/server/router";
import { notificationPreferencesRouter } from "@/src/server/api/routers/notificationPreferences";
+import { webCalloutsRouter } from "@/src/features/web-callouts/server/router";
import { inAppAgentRouter } from "@/src/ee/features/in-app-agent/server/router";
/**
@@ -121,6 +122,7 @@ export const appRouter = createTRPCRouter({
surveys: surveysRouter,
naturalLanguageFilters: naturalLanguageFilterRouter,
notificationPreferences: notificationPreferencesRouter,
+ webCallouts: webCalloutsRouter,
inAppAgent: inAppAgentRouter,
});