Compare commits

...

8 Commits

Author SHA1 Message Date
Tiago Farto
0e0cb3946c chore: changed openapi 2026-03-17 14:43:57 +00:00
Tiago Farto
605d8f7f1d chore: change openapi 2026-03-17 13:56:06 +00:00
Tiago Farto
992a971026 chore: added v3 openapi specification 2026-03-17 13:15:15 +00:00
Tiago Farto
2ebc1b6b66 chore: removed unused parameter 2026-03-17 12:10:04 +00:00
Tiago Farto
075fd3f8dd chore: fixes 2026-03-17 11:59:11 +00:00
Tiago Farto
c0e3eed43b chore: removed /app part of the url 2026-03-17 11:34:13 +00:00
Tiago Farto
8789e9c6e7 chore: fix deprecated function 2026-03-17 10:08:48 +00:00
Tiago Farto
d96cc1d005 chore: API V3 Get Surveys 2026-03-16 17:48:58 +00:00
15 changed files with 1117 additions and 19 deletions

View File

@@ -0,0 +1,125 @@
import { describe, expect, test, vi } from "vitest";
import { AuthorizationError, ResourceNotFoundError } from "@formbricks/types/errors";
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
import { getOrganizationIdFromProjectId } from "@/lib/utils/helper";
import { getEnvironment } from "@/lib/utils/services";
import { requireSessionWorkspaceAccess } from "./auth";
vi.mock("@/lib/utils/helper", () => ({
getOrganizationIdFromProjectId: vi.fn(),
}));
vi.mock("@/lib/utils/services", () => ({
getEnvironment: vi.fn(),
}));
vi.mock("@/lib/utils/action-client/action-client-middleware", () => ({
checkAuthorizationUpdated: vi.fn(),
}));
const requestId = "req-123";
describe("requireSessionWorkspaceAccess", () => {
test("returns 401 when authentication is null", async () => {
const result = await requireSessionWorkspaceAccess(null, "proj_abc", "read", requestId);
expect(result).toBeInstanceOf(Response);
expect((result as Response).status).toBe(401);
expect((result as Response).headers.get("Content-Type")).toBe("application/problem+json");
const body = await (result as Response).json();
expect(body.requestId).toBe(requestId);
expect(body.status).toBe(401);
expect(body.code).toBe("not_authenticated");
expect(getEnvironment).not.toHaveBeenCalled();
expect(checkAuthorizationUpdated).not.toHaveBeenCalled();
});
test("returns 401 when authentication is API key (no user)", async () => {
const result = await requireSessionWorkspaceAccess(
{ apiKeyId: "key_1", organizationId: "org_1", environmentPermissions: [] } as any,
"proj_abc",
"read",
requestId
);
expect(result).toBeInstanceOf(Response);
expect((result as Response).status).toBe(401);
const body = await (result as Response).json();
expect(body.requestId).toBe(requestId);
expect(body.code).toBe("not_authenticated");
expect(getEnvironment).not.toHaveBeenCalled();
});
test("returns 403 when workspace (environment) is not found (avoid leaking existence)", async () => {
vi.mocked(getEnvironment).mockResolvedValueOnce(null);
const result = await requireSessionWorkspaceAccess(
{ user: { id: "user_1" }, expires: "" } as any,
"env_nonexistent",
"read",
requestId
);
expect(result).toBeInstanceOf(Response);
expect((result as Response).status).toBe(403);
expect((result as Response).headers.get("Content-Type")).toBe("application/problem+json");
const body = await (result as Response).json();
expect(body.requestId).toBe(requestId);
expect(body.code).toBe("forbidden");
expect(getEnvironment).toHaveBeenCalledWith("env_nonexistent");
expect(checkAuthorizationUpdated).not.toHaveBeenCalled();
});
test("returns 403 when user has no access to workspace", async () => {
vi.mocked(getEnvironment).mockResolvedValueOnce({
id: "env_abc",
projectId: "proj_abc",
} as any);
vi.mocked(getOrganizationIdFromProjectId).mockResolvedValueOnce("org_1");
vi.mocked(checkAuthorizationUpdated).mockRejectedValueOnce(new AuthorizationError("Not authorized"));
const result = await requireSessionWorkspaceAccess(
{ user: { id: "user_1" }, expires: "" } as any,
"env_abc",
"read",
requestId
);
expect(result).toBeInstanceOf(Response);
expect((result as Response).status).toBe(403);
const body = await (result as Response).json();
expect(body.requestId).toBe(requestId);
expect(body.code).toBe("forbidden");
expect(checkAuthorizationUpdated).toHaveBeenCalledWith({
userId: "user_1",
organizationId: "org_1",
access: [
{ type: "organization", roles: ["owner", "manager"] },
{ type: "projectTeam", projectId: "proj_abc", minPermission: "read" },
],
});
});
test("returns workspace context when session is valid and user has access", async () => {
vi.mocked(getEnvironment).mockResolvedValueOnce({
id: "env_abc",
projectId: "proj_abc",
} as any);
vi.mocked(getOrganizationIdFromProjectId).mockResolvedValueOnce("org_1");
vi.mocked(checkAuthorizationUpdated).mockResolvedValueOnce(undefined as any);
const result = await requireSessionWorkspaceAccess(
{ user: { id: "user_1" }, expires: "" } as any,
"env_abc",
"readWrite",
requestId
);
expect(result).not.toBeInstanceOf(Response);
expect(result).toEqual({
environmentId: "env_abc",
projectId: "proj_abc",
organizationId: "org_1",
});
expect(checkAuthorizationUpdated).toHaveBeenCalledWith({
userId: "user_1",
organizationId: "org_1",
access: [
{ type: "organization", roles: ["owner", "manager"] },
{ type: "projectTeam", projectId: "proj_abc", minPermission: "readWrite" },
],
});
});
});

View File

@@ -0,0 +1,65 @@
/**
* V3 app API session auth — require session + workspace access.
* workspaceId is resolved via workspace-context (today: workspaceId = environmentId).
* No environmentId in the API contract; callers only pass workspaceId.
*/
import { logger } from "@formbricks/logger";
import { AuthorizationError, ResourceNotFoundError } from "@formbricks/types/errors";
import type { TApiV1Authentication } from "@/app/lib/api/with-api-logging";
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
import type { TTeamPermission } from "@/modules/ee/teams/project-teams/types/team";
import { problem401, problem403 } from "./response";
import { type V3WorkspaceContext, resolveV3WorkspaceContext } from "./workspace-context";
/**
* Require session and workspace access. workspaceId is resolved via the V3 workspace-context layer.
* Returns a Response (401 or 403) on failure, or the resolved workspace context on success so callers
* use internal IDs (environmentId, projectId, organizationId) without resolving again.
* We use 403 (not 404) when the workspace is not found to avoid leaking resource existence.
*/
export async function requireSessionWorkspaceAccess(
authentication: TApiV1Authentication,
workspaceId: string,
minPermission: TTeamPermission,
requestId: string,
instance?: string
): Promise<Response | V3WorkspaceContext> {
// --- Session checks ---
if (!authentication) {
return problem401(requestId, "Not authenticated", instance);
}
if (!("user" in authentication) || !authentication.user?.id) {
return problem401(requestId, "Session required", instance);
}
const userId = authentication.user.id;
const log = logger.withContext({ requestId, workspaceId });
try {
// Resolve workspaceId → environmentId, projectId, organizationId (single place to change when Workspace exists).
const context = await resolveV3WorkspaceContext(workspaceId);
// Org + project-team access; we use internal IDs from context.
await checkAuthorizationUpdated({
userId,
organizationId: context.organizationId,
access: [
{ type: "organization", roles: ["owner", "manager"] },
{ type: "projectTeam", projectId: context.projectId, minPermission },
],
});
return context;
} catch (err) {
if (err instanceof ResourceNotFoundError) {
// Return 403 (not 404) so we don't leak whether the workspace exists to unauthenticated or unauthorized callers.
log.warn({ statusCode: 403, errorCode: err.name }, "Workspace not found");
return problem403(requestId, "You are not authorized to access this resource", instance);
}
if (err instanceof AuthorizationError) {
log.warn({ statusCode: 403, errorCode: err.name }, "Forbidden");
return problem403(requestId, "You are not authorized to access this resource", instance);
}
throw err;
}
}

View File

@@ -0,0 +1,153 @@
/**
* V3 API response helpers — RFC 9457 Problem Details (application/problem+json)
* and list envelope for success responses.
*/
const PROBLEM_JSON = "application/problem+json" as const;
const CACHE_NO_STORE = "private, no-store";
export type ProblemExtension = {
code?: string;
requestId: string;
details?: Record<string, unknown>;
invalid_params?: Array<{ name: string; reason: string }>;
};
export type ProblemBody = {
type?: string;
title: string;
status: number;
detail: string;
instance?: string;
} & ProblemExtension;
function problemResponse(
status: number,
title: string,
detail: string,
requestId: string,
options?: {
type?: string;
instance?: string;
code?: string;
details?: Record<string, unknown>;
invalid_params?: Array<{ name: string; reason: string }>;
headers?: Record<string, string>;
}
): Response {
const body: ProblemBody = {
title,
status,
detail,
requestId,
...(options?.type && { type: options.type }),
...(options?.instance && { instance: options.instance }),
...(options?.code && { code: options.code }),
...(options?.details && { details: options.details }),
...(options?.invalid_params && { invalid_params: options.invalid_params }),
};
const headers: Record<string, string> = {
"Content-Type": PROBLEM_JSON,
"Cache-Control": CACHE_NO_STORE,
...options?.headers,
};
return Response.json(body, { status, headers });
}
export function problem400(
requestId: string,
detail: string,
options?: { invalid_params?: Array<{ name: string; reason: string }>; instance?: string }
): Response {
return problemResponse(400, "Bad Request", detail, requestId, {
code: "bad_request",
instance: options?.instance,
invalid_params: options?.invalid_params,
});
}
export function problem401(
requestId: string,
detail: string = "Not authenticated",
instance?: string
): Response {
return problemResponse(401, "Unauthorized", detail, requestId, {
code: "not_authenticated",
instance,
});
}
export function problem403(
requestId: string,
detail: string = "You are not authorized to access this resource",
instance?: string
): Response {
return problemResponse(403, "Forbidden", detail, requestId, {
code: "forbidden",
instance,
});
}
/**
* 404 with resource details. Do not use for auth-sensitive or existence-sensitive resources:
* the body includes resource_type and resource_id, which can leak existence to unauthenticated or unauthorized callers.
* Prefer problem403 with a generic message for those cases.
*/
export function problem404(
requestId: string,
resourceType: string,
resourceId: string | null,
instance?: string
): Response {
return problemResponse(404, "Not Found", `${resourceType} not found`, requestId, {
code: "not_found",
details: { resource_type: resourceType, resource_id: resourceId },
instance,
});
}
export function problem500(
requestId: string,
detail: string = "An unexpected error occurred.",
instance?: string
): Response {
return problemResponse(500, "Internal Server Error", detail, requestId, {
code: "internal_server_error",
instance,
});
}
export function problem429(requestId: string, detail: string, retryAfter?: number): Response {
const headers: Record<string, string> = {};
if (retryAfter !== undefined) {
headers["Retry-After"] = String(retryAfter);
}
return problemResponse(429, "Too Many Requests", detail, requestId, {
code: "too_many_requests",
headers,
});
}
/** List envelope for GET list endpoints */
export type ListMeta = {
limit: number;
offset: number;
total?: number;
};
export function successListResponse<T>(
data: T[],
meta: ListMeta,
options?: { requestId?: string; cache?: string }
): Response {
const headers: Record<string, string> = {
"Content-Type": "application/json",
"Cache-Control": options?.cache ?? CACHE_NO_STORE,
};
if (options?.requestId) {
headers["X-Request-Id"] = options.requestId;
}
return Response.json({ data, meta }, { status: 200, headers });
}

View File

@@ -0,0 +1,38 @@
import { describe, expect, test, vi } from "vitest";
import { ResourceNotFoundError } from "@formbricks/types/errors";
import { getOrganizationIdFromProjectId } from "@/lib/utils/helper";
import { getEnvironment } from "@/lib/utils/services";
import { resolveV3WorkspaceContext } from "./workspace-context";
vi.mock("@/lib/utils/helper", () => ({
getOrganizationIdFromProjectId: vi.fn(),
}));
vi.mock("@/lib/utils/services", () => ({
getEnvironment: vi.fn(),
}));
describe("resolveV3WorkspaceContext", () => {
test("returns environmentId, projectId and organizationId when workspace exists (today: workspaceId === environmentId)", async () => {
vi.mocked(getEnvironment).mockResolvedValueOnce({
id: "env_abc",
projectId: "proj_xyz",
} as any);
vi.mocked(getOrganizationIdFromProjectId).mockResolvedValueOnce("org_123");
const result = await resolveV3WorkspaceContext("env_abc");
expect(result).toEqual({
environmentId: "env_abc",
projectId: "proj_xyz",
organizationId: "org_123",
});
expect(getEnvironment).toHaveBeenCalledWith("env_abc");
expect(getOrganizationIdFromProjectId).toHaveBeenCalledWith("proj_xyz");
});
test("throws when workspace (environment) does not exist", async () => {
vi.mocked(getEnvironment).mockResolvedValueOnce(null);
await expect(resolveV3WorkspaceContext("env_nonexistent")).rejects.toThrow(ResourceNotFoundError);
expect(getEnvironment).toHaveBeenCalledWith("env_nonexistent");
expect(getOrganizationIdFromProjectId).not.toHaveBeenCalled();
});
});

View File

@@ -0,0 +1,50 @@
/**
* V3 API workspace → internal IDs translation layer (retro-compatibility / future-proofing).
*
* Workspace is the default container for surveys. We are deprecating Environment and making
* Workspace that container. In the API, workspaceId refers to that container.
*
* Today: workspaceId is mapped to environmentId (Environment is the current container for surveys).
* When Environment is deprecated and Workspace exists: resolve workspaceId to the Workspace entity
* (and derive environmentId or equivalent from it). Change only this file.
*/
import { ResourceNotFoundError } from "@formbricks/types/errors";
import { getOrganizationIdFromProjectId } from "@/lib/utils/helper";
import { getEnvironment } from "@/lib/utils/services";
/**
* Internal IDs derived from a V3 workspace identifier.
* Today: environmentId is the workspace (Environment = container for surveys until Workspace exists).
*/
export type V3WorkspaceContext = {
/** Environment ID — the container for surveys today. Replaced by workspace when Environment is deprecated. */
environmentId: string;
/** Project ID used for projectTeam auth. */
projectId: string;
/** Organization ID used for org-level auth. */
organizationId: string;
};
/**
* Resolves a V3 API workspaceId to internal environmentId, projectId, and organizationId.
* Today: workspaceId is treated as environmentId (workspace = container for surveys = Environment).
*
* @throws ResourceNotFoundError if the workspace (environment) does not exist.
*/
export async function resolveV3WorkspaceContext(workspaceId: string): Promise<V3WorkspaceContext> {
// Today: workspaceId is the environment id (survey container). Look it up.
const environment = await getEnvironment(workspaceId);
if (!environment) {
throw new ResourceNotFoundError("environment", workspaceId);
}
// Derive org for auth; project comes from the environment.
const organizationId = await getOrganizationIdFromProjectId(environment.projectId);
// We looked up by workspaceId (as environment id), so the resolved environment id is workspaceId.
return {
environmentId: workspaceId,
projectId: environment.projectId,
organizationId,
};
}

View File

@@ -0,0 +1,224 @@
import { NextRequest } from "next/server";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { requireSessionWorkspaceAccess } from "@/app/api/v3/lib/auth";
import { getSurveyCount, getSurveys } from "@/modules/survey/list/lib/survey";
import { GET } from "./route";
vi.mock("next-auth", () => ({
getServerSession: vi.fn(),
}));
vi.mock("@/modules/core/rate-limit/helpers", () => ({
applyRateLimit: vi.fn().mockResolvedValue(undefined),
applyIPRateLimit: vi.fn().mockResolvedValue(undefined),
}));
vi.mock("@/lib/constants", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/lib/constants")>();
return { ...actual, AUDIT_LOG_ENABLED: false };
});
vi.mock("@/app/api/v3/lib/auth", () => ({
requireSessionWorkspaceAccess: vi.fn(),
}));
vi.mock("@/modules/survey/list/lib/survey", () => ({
getSurveys: vi.fn(),
getSurveyCount: vi.fn(),
}));
vi.mock("@formbricks/logger", () => ({
logger: {
withContext: vi.fn(() => ({
warn: vi.fn(),
error: vi.fn(),
})),
},
}));
const getServerSession = vi.mocked((await import("next-auth")).getServerSession);
/** Query param (workspace id in API); distinct from resolved DB environment id. */
const validWorkspaceId = "clxx1234567890123456789012";
const resolvedEnvironmentId = "clzz9876543210987654321098";
function createRequest(url: string, requestId?: string): NextRequest {
const headers: Record<string, string> = {};
if (requestId) headers["x-request-id"] = requestId;
return new NextRequest(url, { headers });
}
describe("GET /api/v3/surveys", () => {
beforeEach(() => {
vi.resetAllMocks();
getServerSession.mockResolvedValue({
user: { id: "user_1", name: "User", email: "u@example.com" },
expires: "2026-01-01",
} as any);
vi.mocked(requireSessionWorkspaceAccess).mockResolvedValue({
environmentId: resolvedEnvironmentId,
projectId: "proj_1",
organizationId: "org_1",
});
vi.mocked(getSurveys).mockResolvedValue([]);
vi.mocked(getSurveyCount).mockResolvedValue(0);
});
afterEach(() => {
vi.clearAllMocks();
});
test("returns 401 when no session (RFC 9457, handler not run)", async () => {
getServerSession.mockResolvedValue(null);
const req = createRequest(`http://localhost/api/v3/surveys?workspaceId=${validWorkspaceId}`);
const res = await GET(req, {} as any);
expect(res.status).toBe(401);
expect(res.headers.get("Content-Type")).toBe("application/problem+json");
expect(requireSessionWorkspaceAccess).not.toHaveBeenCalled();
});
test("returns 200 with list envelope when session and valid workspaceId", async () => {
const req = createRequest(`http://localhost/api/v3/surveys?workspaceId=${validWorkspaceId}`, "req-456");
const res = await GET(req, {} as any);
expect(res.status).toBe(200);
expect(res.headers.get("Content-Type")).toBe("application/json");
expect(res.headers.get("X-Request-Id")).toBe("req-456");
expect(res.headers.get("Cache-Control")).toContain("no-store");
const body = await res.json();
expect(body).toHaveProperty("data");
expect(body).toHaveProperty("meta");
expect(Array.isArray(body.data)).toBe(true);
expect(body.meta).toEqual({ limit: 20, offset: 0, total: 0 });
expect(requireSessionWorkspaceAccess).toHaveBeenCalledWith(
expect.any(Object),
validWorkspaceId,
"read",
"req-456",
"/api/v3/surveys"
);
expect(getSurveys).toHaveBeenCalledWith(resolvedEnvironmentId, 20, 0, undefined);
expect(getSurveyCount).toHaveBeenCalledWith(resolvedEnvironmentId, undefined);
});
test("returns 400 when workspaceId is missing", async () => {
const req = createRequest("http://localhost/api/v3/surveys");
const res = await GET(req, {} as any);
expect(res.status).toBe(400);
expect(res.headers.get("Content-Type")).toBe("application/problem+json");
const body = await res.json();
expect(body.requestId).toBeDefined();
expect(body.status).toBe(400);
expect(body.invalid_params).toBeDefined();
expect(requireSessionWorkspaceAccess).not.toHaveBeenCalled();
});
test("returns 400 when workspaceId is not cuid2", async () => {
const req = createRequest("http://localhost/api/v3/surveys?workspaceId=not-a-cuid");
const res = await GET(req, {} as any);
expect(res.status).toBe(400);
const body = await res.json();
expect(body.status).toBe(400);
expect(body.invalid_params).toBeDefined();
});
test("returns 400 when limit exceeds max", async () => {
const req = createRequest(`http://localhost/api/v3/surveys?workspaceId=${validWorkspaceId}&limit=101`);
const res = await GET(req, {} as any);
expect(res.status).toBe(400);
const body = await res.json();
expect(body.status).toBe(400);
});
test("reflects limit, offset and total in meta and passes to getSurveys", async () => {
vi.mocked(getSurveyCount).mockResolvedValue(42);
const req = createRequest(
`http://localhost/api/v3/surveys?workspaceId=${validWorkspaceId}&limit=10&offset=5`
);
const res = await GET(req, {} as any);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.meta).toEqual({ limit: 10, offset: 5, total: 42 });
expect(getSurveys).toHaveBeenCalledWith(resolvedEnvironmentId, 10, 5, undefined);
expect(getSurveyCount).toHaveBeenCalledWith(resolvedEnvironmentId, undefined);
});
test("passes filterCriteria to getSurveys and getSurveyCount so total matches filter", async () => {
const filterCriteria = { status: ["inProgress"], sortBy: "updatedAt" as const };
vi.mocked(getSurveys).mockResolvedValue([]);
vi.mocked(getSurveyCount).mockResolvedValue(7);
const req = createRequest(
`http://localhost/api/v3/surveys?workspaceId=${validWorkspaceId}&filterCriteria=${encodeURIComponent(JSON.stringify(filterCriteria))}`
);
const res = await GET(req, {} as any);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.meta.total).toBe(7);
expect(getSurveys).toHaveBeenCalledWith(resolvedEnvironmentId, 20, 0, filterCriteria);
expect(getSurveyCount).toHaveBeenCalledWith(resolvedEnvironmentId, filterCriteria);
});
test("overrides createdBy.userId with session user so clients cannot spoof creator filter", async () => {
const clientSent = {
createdBy: { userId: "attacker_id", value: ["you" as const] },
sortBy: "updatedAt" as const,
};
const expectedForDb = {
createdBy: { userId: "user_1", value: ["you" as const] },
sortBy: "updatedAt" as const,
};
vi.mocked(getSurveys).mockResolvedValue([]);
vi.mocked(getSurveyCount).mockResolvedValue(1);
const req = createRequest(
`http://localhost/api/v3/surveys?workspaceId=${validWorkspaceId}&filterCriteria=${encodeURIComponent(JSON.stringify(clientSent))}`
);
const res = await GET(req, {} as any);
expect(res.status).toBe(200);
expect(getSurveys).toHaveBeenCalledWith(resolvedEnvironmentId, 20, 0, expectedForDb);
expect(getSurveyCount).toHaveBeenCalledWith(resolvedEnvironmentId, expectedForDb);
});
test("returns 403 when auth helper returns 403", async () => {
const forbiddenResponse = new Response(
JSON.stringify({
title: "Forbidden",
status: 403,
detail: "You are not authorized to access this resource",
requestId: "req-789",
}),
{ status: 403, headers: { "Content-Type": "application/problem+json" } }
);
vi.mocked(requireSessionWorkspaceAccess).mockResolvedValueOnce(forbiddenResponse);
const req = createRequest(`http://localhost/api/v3/surveys?workspaceId=${validWorkspaceId}`);
const res = await GET(req, {} as any);
expect(res.status).toBe(403);
expect(res.headers.get("Content-Type")).toBe("application/problem+json");
const body = await res.json();
expect(body.requestId).toBeDefined();
expect(body.status).toBe(403);
});
test("success response does not include blocks/questions in list items", async () => {
const minimalSurvey = {
id: "s1",
name: "Survey 1",
environmentId: "env_1",
type: "link",
status: "draft",
createdAt: new Date(),
updatedAt: new Date(),
responseCount: 0,
creator: { name: "Test" },
singleUse: null,
};
vi.mocked(getSurveys).mockResolvedValue([minimalSurvey as any]);
const req = createRequest(`http://localhost/api/v3/surveys?workspaceId=${validWorkspaceId}`);
const res = await GET(req, {} as any);
expect(res.status).toBe(200);
const body = await res.json();
expect(body.data).toHaveLength(1);
expect(body.data[0]).not.toHaveProperty("blocks");
expect(body.data[0]).not.toHaveProperty("questions");
expect(body.data[0].id).toBe("s1");
expect(body.data[0].responseCount).toBe(0);
});
});

View File

@@ -0,0 +1,165 @@
/**
* GET /api/v3/surveys — list surveys for a workspace.
* Session auth; scope by workspaceId only (no environmentId in the API).
*/
import { z } from "zod";
import { logger } from "@formbricks/logger";
import { ZId } from "@formbricks/types/common";
import { DatabaseError, ResourceNotFoundError } from "@formbricks/types/errors";
import { type TSurveyFilterCriteria, ZSurveyFilterCriteria } from "@formbricks/types/surveys/types";
import { requireSessionWorkspaceAccess } from "@/app/api/v3/lib/auth";
import {
problem400,
problem401,
problem403,
problem500,
successListResponse,
} from "@/app/api/v3/lib/response";
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
import { getSurveyCount, getSurveys } from "@/modules/survey/list/lib/survey";
const DEFAULT_LIMIT = 20;
const MAX_LIMIT = 100;
/** Query schema: workspaceId required; limit/offset/filterCriteria optional. */
const ZQuery = z.object({
workspaceId: ZId,
limit: z.coerce.number().int().min(1).max(MAX_LIMIT).default(DEFAULT_LIMIT),
offset: z.coerce.number().int().min(0).default(0),
filterCriteria: z.string().optional(),
});
/** Parse optional JSON filterCriteria from query; invalid JSON is treated as missing. */
function parseFilterCriteria(value: string | undefined): TSurveyFilterCriteria | undefined {
if (!value) return undefined;
try {
const parsed = JSON.parse(value) as unknown;
const result = ZSurveyFilterCriteria.safeParse(parsed);
return result.success ? result.data : undefined;
} catch {
return undefined;
}
}
function applySessionToCreatedByFilter(
criteria: TSurveyFilterCriteria | undefined,
sessionUserId: string
): TSurveyFilterCriteria | undefined {
if (!criteria?.createdBy) return criteria;
return {
...criteria,
createdBy: {
...criteria.createdBy,
userId: sessionUserId,
},
};
}
export const GET = withV1ApiWrapper({
unauthenticatedResponse: (req) => {
const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
return problem401(requestId, "Not authenticated", req.nextUrl.pathname);
},
handler: async ({ req, authentication }) => {
const requestId = req.headers.get("x-request-id") ?? crypto.randomUUID();
const log = logger.withContext({ requestId });
const instance = new URL(req.url).pathname;
try {
if (!authentication || !("user" in authentication) || !authentication.user?.id) {
return { response: problem401(requestId, "Not authenticated", instance) };
}
const sessionUserId = authentication.user.id;
const searchParams = new URL(req.url).searchParams;
const workspaceId = searchParams.get("workspaceId");
const limitParam = searchParams.get("limit");
const offsetParam = searchParams.get("offset");
const filterCriteriaParam = searchParams.get("filterCriteria");
const queryResult = ZQuery.safeParse({
workspaceId,
limit: limitParam ?? undefined,
offset: offsetParam ?? undefined,
filterCriteria: filterCriteriaParam ?? undefined,
});
if (!queryResult.success) {
const invalidParams = queryResult.error.issues.map((issue) => ({
name: issue.path.join(".") || "query",
reason: issue.message,
}));
log.warn({ statusCode: 400, invalidParams }, "Validation failed");
return {
response: problem400(requestId, "Invalid query parameters", {
invalid_params: invalidParams,
instance,
}),
};
}
const parsedFilterCriteria = parseFilterCriteria(queryResult.data.filterCriteria);
if (
filterCriteriaParam !== null &&
filterCriteriaParam !== undefined &&
filterCriteriaParam !== "" &&
parsedFilterCriteria === undefined
) {
log.warn({ statusCode: 400 }, "Invalid filterCriteria JSON");
return {
response: problem400(requestId, "Invalid filterCriteria", {
invalid_params: [
{ name: "filterCriteria", reason: "Must be valid JSON matching filter criteria schema" },
],
instance,
}),
};
}
const filterCriteria = applySessionToCreatedByFilter(parsedFilterCriteria, sessionUserId);
const authResult = await requireSessionWorkspaceAccess(
authentication,
queryResult.data.workspaceId,
"read",
requestId,
instance
);
if (authResult instanceof Response) {
return { response: authResult };
}
const { environmentId } = authResult;
const [surveys, total] = await Promise.all([
getSurveys(environmentId, queryResult.data.limit, queryResult.data.offset, filterCriteria),
getSurveyCount(environmentId, filterCriteria),
]);
return {
response: successListResponse(
surveys,
{
limit: queryResult.data.limit,
offset: queryResult.data.offset,
total,
},
{ requestId, cache: "private, no-store" }
),
};
} catch (err) {
if (err instanceof ResourceNotFoundError) {
log.warn({ statusCode: 403, errorCode: err.name }, "Resource not found");
return {
response: problem403(requestId, "You are not authorized to access this resource", instance),
};
}
if (err instanceof DatabaseError) {
log.error({ error: err, statusCode: 500 }, "Database error");
return { response: problem500(requestId, "An unexpected error occurred.", instance) };
}
log.error({ error: err, statusCode: 500 }, "V3 surveys list unexpected error");
return { response: problem500(requestId, "An unexpected error occurred.", instance) };
}
},
});

View File

@@ -421,6 +421,38 @@ describe("withV1ApiWrapper", () => {
expect(handler).not.toHaveBeenCalled();
});
test("uses unauthenticatedResponse when provided instead of default 401", async () => {
const { isClientSideApiRoute, isManagementApiRoute, isIntegrationRoute } =
await import("@/app/middleware/endpoint-validator");
const { getServerSession } = await import("next-auth");
vi.mocked(isClientSideApiRoute).mockReturnValue({ isClientSideApi: false, isRateLimited: true });
vi.mocked(isManagementApiRoute).mockReturnValue({
isManagementApi: true,
authenticationMethod: AuthenticationMethod.Session,
});
vi.mocked(isIntegrationRoute).mockReturnValue(false);
vi.mocked(getServerSession).mockResolvedValue(null);
const custom401 = new Response(JSON.stringify({ title: "Custom", status: 401 }), {
status: 401,
headers: { "Content-Type": "application/problem+json" },
});
const handler = vi.fn();
const req = createMockRequest({ url: "https://api.test/api/v3/surveys" });
const { withV1ApiWrapper } = await import("./with-api-logging");
const wrapped = withV1ApiWrapper({
handler,
unauthenticatedResponse: () => custom401,
});
const res = await wrapped(req, undefined);
expect(res).toBe(custom401);
expect(handler).not.toHaveBeenCalled();
expect(mockContextualLoggerError).toHaveBeenCalled();
});
test("handles rate limiting errors", async () => {
const { applyRateLimit } = await import("@/modules/core/rate-limit/helpers");
const { isClientSideApiRoute, isManagementApiRoute, isIntegrationRoute } =

View File

@@ -38,6 +38,11 @@ export interface TWithV1ApiWrapperParams<TResult extends { response: Response },
action?: TAuditAction;
targetType?: TAuditTarget;
customRateLimitConfig?: TRateLimitConfig;
/**
* When the route requires auth but the client is unauthenticated, the wrapper normally returns
* the legacy JSON 401. Use this to return a custom response (e.g. RFC 9457 problem+json for V3).
*/
unauthenticatedResponse?: (req: NextRequest) => Response;
}
enum ApiV1RouteTypeEnum {
@@ -265,7 +270,7 @@ const getRouteType = (
export const withV1ApiWrapper = <TResult extends { response: Response }, TProps = unknown>(
params: TWithV1ApiWrapperParams<TResult, TProps>
): ((req: NextRequest, props: TProps) => Promise<Response>) => {
const { handler, action, targetType, customRateLimitConfig } = params;
const { handler, action, targetType, customRateLimitConfig, unauthenticatedResponse } = params;
return async (req: NextRequest, props: TProps): Promise<Response> => {
// === Audit Log Setup ===
const saveAuditLog = action && targetType;
@@ -287,6 +292,11 @@ export const withV1ApiWrapper = <TResult extends { response: Response }, TProps
const authentication = await handleAuthentication(authenticationMethod, req);
if (!authentication && routeType !== ApiV1RouteTypeEnum.Client) {
if (unauthenticatedResponse) {
const res = unauthenticatedResponse(req);
await processResponse(res, req, auditLog);
return res;
}
return responses.notAuthenticatedResponse();
}

View File

@@ -90,6 +90,17 @@ describe("endpoint-validator", () => {
});
describe("isManagementApiRoute", () => {
test("should return Session for v3 surveys routes", () => {
expect(isManagementApiRoute("/api/v3/surveys")).toEqual({
isManagementApi: true,
authenticationMethod: AuthenticationMethod.Session,
});
expect(isManagementApiRoute("/api/v3/surveys/clxxxxxxxxxxxxxxxxxxxxxxxx")).toEqual({
isManagementApi: true,
authenticationMethod: AuthenticationMethod.Session,
});
});
test("should return correct object for management API routes with API key authentication", () => {
expect(isManagementApiRoute("/api/v1/management/something")).toEqual({
isManagementApi: true,

View File

@@ -22,6 +22,9 @@ export const isClientSideApiRoute = (url: string): { isClientSideApi: boolean; i
export const isManagementApiRoute = (
url: string
): { isManagementApi: boolean; authenticationMethod: AuthenticationMethod } => {
// V3 session API (browser app): surveys and future routes under /api/v3/surveys/...
if (/^\/api\/v3\/surveys(?:\/|$)/.test(url))
return { isManagementApi: true, authenticationMethod: AuthenticationMethod.Session };
if (url.includes("/api/v1/management/storage"))
return { isManagementApi: true, authenticationMethod: AuthenticationMethod.Both };
if (url.includes("/api/v1/webhooks"))

View File

@@ -605,22 +605,26 @@ export const copySurveyToOtherEnvironment = async (
}
};
export const getSurveyCount = reactCache(async (environmentId: string): Promise<number> => {
validateInputs([environmentId, z.cuid2()]);
try {
const surveyCount = await prisma.survey.count({
where: {
environmentId: environmentId,
},
});
/** Count surveys in an environment, optionally with the same filter as getSurveys (so total matches list). */
export const getSurveyCount = reactCache(
async (environmentId: string, filterCriteria?: TSurveyFilterCriteria): Promise<number> => {
validateInputs([environmentId, z.cuid2()]);
try {
const surveyCount = await prisma.survey.count({
where: {
environmentId,
...buildWhereClause(filterCriteria),
},
});
return surveyCount;
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
logger.error(error, "Error getting survey count");
throw new DatabaseError(error.message);
return surveyCount;
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
logger.error(error, "Error getting survey count");
throw new DatabaseError(error.message);
}
throw error;
}
throw error;
}
});
);

View File

@@ -0,0 +1,218 @@
# V3 API — GET Surveys (hand-maintained; not generated by generate-api-specs).
# Implementation: apps/web/app/api/v3/surveys/route.ts
# See apps/web/app/api/v3/README.md and docs/Survey-Server-Actions.md (Part III) for full context.
openapi: 3.1.0
info:
title: Formbricks API v3 (Surveys)
description: |
Session-authenticated V3 slice. This file documents **GET /api/v3/surveys** only.
**Spec location:** `docs/api-v3-reference/openapi-surveys.yml` (alongside v2 at `docs/api-v2-reference/openapi.yml`).
**workspaceId (today)**
Query param `workspaceId` is the **environment id** (survey container in the DB). The API uses the name *workspace* because the product is moving toward **Workspace** as the default container; until that exists, resolution is implemented in `workspace-context.ts` (single place to change when Environment is deprecated).
**Auth order**
Session is verified **before** query validation. Unauthenticated callers get **401** without `invalid_params` for missing `workspaceId` (no query-shape leakage). With a session, missing/invalid query returns **400**.
**Pagination**
**limit** + **offset** (not cursor). Suited to page-based UIs (page 1/2/3, previous/next). Cursor-based pagination is intentionally **not** offered here (one-directional “next” only); revisit only for a high-volume feed-style endpoint.
**Security**
Missing/forbidden workspace returns **403** with a generic message (not **404**) so resource existence is not leaked. List responses use `private, no-store`.
**OpenAPI**
This YAML is **not** produced by `pnpm generate-api-specs` (that script only builds v2 → `docs/api-v2-reference/openapi.yml`). Update this file when the route contract changes.
**Next steps (out of scope for this spec)**
Additional v3 survey endpoints (single survey, CRUD), frontend cutover from `getSurveysAction`, optional ETag/304, field selection — see Survey-Server-Actions.md Part III.
version: 0.1.0
x-implementation-notes:
route: apps/web/app/api/v3/surveys/route.ts
auth: apps/web/app/api/v3/lib/auth.ts
workspace-resolution: apps/web/app/api/v3/lib/workspace-context.ts
openapi-generated: false
pagination-model: offset
cursor-pagination: not-supported
paths:
/api/v3/surveys:
get:
operationId: getSurveysV3
summary: List surveys
description: Returns surveys for the workspace. Requires session cookie.
tags:
- V3 Surveys
parameters:
- in: query
name: workspaceId
required: true
schema:
type: string
format: cuid2
description: |
Workspace identifier. **Today:** pass the **environment id** (the environment that contains the surveys). When Workspace replaces Environment in the data model, clients may pass workspace ids instead; resolution is centralized in workspace-context.
- in: query
name: limit
schema:
type: integer
minimum: 1
maximum: 100
default: 20
description: Page size (max 100)
- in: query
name: offset
schema:
type: integer
minimum: 0
default: 0
description: Pagination offset (0-based). No cursor/`after` token — see API info for rationale.
- in: query
name: filterCriteria
schema:
type: string
description: |
URL-encoded JSON object (optional). Parsed with `ZSurveyFilterCriteria` after auth:
- **name** (string, optional)
- **status** (array of `draft` | `inProgress` | `paused` | `completed`, optional)
- **type** (array of `link` | `app`, optional)
- **createdBy** (optional): `{ "userId": string, "value": ["you"] | ["others"] | ["you","others"] }` — **`userId` is ignored; server overwrites with the session user id**
- **sortBy** (optional): `createdAt` | `updatedAt` | `name` | `relevance`
Omitted or empty → no filter. Non-empty param that is invalid JSON or fails schema → **400** with `invalid_params` on `filterCriteria`.
responses:
"200":
description: Surveys retrieved successfully
headers:
X-Request-Id:
schema: { type: string }
description: Request correlation ID
Cache-Control:
schema: { type: string }
example: "private, no-store"
content:
application/json:
schema:
type: object
required: [data, meta]
properties:
data:
type: array
items:
$ref: "#/components/schemas/SurveyListItem"
meta:
type: object
required: [limit, offset, total]
properties:
limit: { type: integer }
offset: { type: integer }
total:
type: integer
description: Count of surveys matching filterCriteria (same as list filter)
"400":
description: Bad Request
content:
application/problem+json:
schema:
$ref: "#/components/schemas/Problem"
"401":
description: Not authenticated (no valid session)
content:
application/problem+json:
schema:
$ref: "#/components/schemas/Problem"
"403":
description: Forbidden — no access, or workspace/environment does not exist (404 not used; avoids existence leak)
content:
application/problem+json:
schema:
$ref: "#/components/schemas/Problem"
"429":
description: |
Rate limit exceeded (wrapper). Uses the **legacy v1 JSON** shape from `responses.tooManyRequestsResponse`.
content:
application/json:
schema:
$ref: "#/components/schemas/LegacyTooManyRequests"
"500":
description: |
Handler errors return RFC 9457 Problem Details. Uncaught errors from the API wrapper may return legacy v1 JSON (`code` / `message` / `details`).
content:
application/problem+json:
schema:
$ref: "#/components/schemas/Problem"
application/json:
schema:
$ref: "#/components/schemas/LegacyInternalError"
security:
- sessionAuth: []
components:
securitySchemes:
sessionAuth:
type: apiKey
in: cookie
name: next-auth.session-token
description: |
NextAuth session JWT cookie. **Development:** often `next-auth.session-token`.
**Production (HTTPS):** often `__Secure-next-auth.session-token`. Send the cookie your browser receives after sign-in.
schemas:
SurveyListItem:
type: object
description: |
Shape from `getSurveys` (`surveySelect` + `responseCount`). Serialized dates are ISO 8601 strings.
Legacy DB rows may include survey **type** values `website` or `web` (see Prisma); filter **type** only accepts `link` | `app`.
properties:
id: { type: string }
name: { type: string }
environmentId: { type: string }
type: { type: string, enum: [link, app, website, web] }
status:
type: string
enum: [draft, inProgress, paused, completed]
createdAt: { type: string, format: date-time }
updatedAt: { type: string, format: date-time }
responseCount: { type: integer }
creator: { type: object, nullable: true, properties: { name: { type: string } } }
singleUse:
type: object
nullable: true
properties:
enabled: { type: boolean }
isEncrypted: { type: boolean }
Problem:
type: object
description: RFC 9457-style body from `problem400` / `problem401` / `problem403` / `problem500` (always includes `code` in practice)
required: [title, status, detail, requestId]
properties:
type: { type: string, format: uri }
title: { type: string }
status: { type: integer }
detail: { type: string }
instance: { type: string }
code:
type: string
enum: [bad_request, not_authenticated, forbidden, internal_server_error]
requestId: { type: string }
details: { type: object }
invalid_params:
type: array
items:
type: object
properties:
name: { type: string }
reason: { type: string }
LegacyTooManyRequests:
type: object
required: [code, message, details]
properties:
code: { type: string, enum: [too_many_requests] }
message: { type: string }
details: { type: object }
LegacyInternalError:
type: object
required: [code, message, details]
properties:
code: { type: string, enum: [internal_server_error] }
message: { type: string }
details: { type: object }

View File

@@ -1,4 +1,4 @@
import { z } from "zod";
import { type z } from "zod";
import type { TI18nString } from "../i18n";
import type { TSurveyLanguage } from "./types";
import { getTextContent } from "./validation";

View File

@@ -1,5 +1,5 @@
import { parse } from "node-html-parser";
import { z } from "zod";
import { type z } from "zod";
import type { TI18nString } from "../i18n";
import type { TConditionGroup, TSingleCondition } from "./logic";
import type {