Compare commits

...

325 Commits

Author SHA1 Message Date
Tiago Farto afa4cee908 chore: v3 api post survey 2026-05-20 16:33:33 +00:00
Tiago Farto 19fb6126cc chore: update openapi example 2026-05-18 17:08:53 +00:00
Tiago Farto 49473f17e3 chore: always use language maps, allow filtering multiple languages 2026-05-18 17:05:44 +00:00
Tiago Farto 0df059adcd chore: remove version query param 2026-05-18 16:53:47 +00:00
Tiago Farto fb463f6fc4 chore: fix build; mcp related changes 2026-05-18 16:43:07 +00:00
Tiago Farto 311e49311b chore: assorted improvements 2026-05-18 15:31:51 +00:00
Tiago Farto ff7ac26ba5 Merge branch 'main' into chore/v3_get_survey 2026-05-18 15:09:18 +00:00
Matti Nannt bf4303cdb5 feat: make Cube a mandatory baseline dependency in v5 (#8042)
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
Co-authored-by: Dhruwang <dhruwangjariwala18@gmail.com>
2026-05-18 13:38:35 +00:00
Matti Nannt b3debbf0f6 fix: translate footer links based on survey language (ENG-673) (#8018)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 12:36:16 +00:00
Bhagya Amarasinghe e2bf79ce6c fix: harden storage presigned URL issuance (#8021)
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
2026-05-18 11:41:25 +00:00
Tiago 1032702b65 fix: fix sso redirect while deleting account (#8039) 2026-05-18 11:28:08 +00:00
Dhruwang Jariwala a9e6bd440d fix(a11y): add feedback source dialog cannot scroll on short screens (#8004) 2026-05-14 16:10:05 +05:30
Javi Aguilar 7c53e7deca fix: prevent duplicated charts in dashboards (#8002)
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
2026-05-14 14:37:49 +04:00
Dhruwang eaf6c889f8 fix(hub): replace missed FormbricksHub.APIError in deleteFeedbackRecord
PR #7992 converted four of the five `err instanceof FormbricksHub.APIError`
checks to `getErrorStatus(err)` and removed the `FormbricksHub` default
import, but left the inline check in `deleteFeedbackRecord`. Since the
import is gone, the orphan reference throws ReferenceError at runtime
(visible in SonarCloud's coverage run on `vitest run --coverage`).

Completes the conversion so all catch handlers use the duck-typed helper.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:45:06 +05:30
Dhruwang 365c8e88b7 Merge remote-tracking branch 'origin/epic/v5' into fix/eng-924-scrollable-dialog 2026-05-14 15:44:04 +05:30
Dhruwang 3486ab67d7 Removed unnecessary classes 2026-05-14 14:41:08 +05:30
Dhruwang Jariwala defd333d97 fix: refine saving icon and delete source dialog text (#8001) 2026-05-14 14:36:36 +05:30
Dhruwang Jariwala 0e7ea4637d feat(analytics): augment Cube measures with CSAT/CES + correctness fixes (ENG-804) (#7985) 2026-05-14 13:42:58 +05:30
Anshuman Pandey 0475232bad fix: fixes same survey responses from being reported as failures (#7992) 2026-05-14 10:55:51 +04:00
Javi Aguilar b656e94f07 fix(a11y): add feedback source dialog cannot scroll on short screens 2026-05-13 16:32:23 +02:00
Javi Aguilar d73e342028 fix missing dialog description 2026-05-13 15:37:03 +02:00
Javi Aguilar 0a09b68e08 fix: show only loading icon when in saving state 2026-05-13 15:33:49 +02:00
Dhruwang Jariwala 5f5860cb23 feat(unify): add delete option for feedback records (ENG-938) (#7991) 2026-05-13 15:56:55 +04:00
Anshuman Pandey b2a95d4cee fix: correct matrix/ranking feedback records (#7982) 2026-05-13 11:16:52 +04:00
Bhagya Amarasinghe 64b4e18c5a fix(helm): restore TEI float16 dtype (#7988) 2026-05-13 12:28:44 +05:30
Dhruwang Jariwala ae9c1e499a fix: add missing title in feedback directory (#7983) 2026-05-13 12:04:15 +05:30
Dhruwang 0a4e32b848 fix: test 2026-05-13 11:06:19 +05:30
Bhagya Amarasinghe daae319c7a fix(helm): restore TEI float16 dtype 2026-05-13 00:04:33 +05:30
Dhruwang 7d77ed04de refactor(analytics): drop unused dims, broaden CSAT and group-by surface
Remove sentiment, emotion, and the TopicsUnnested join from the Cube
schema, web registry, AI prompt, audit-allowlist, and i18n keys — these
required metadata enrichment that is no longer planned. Tests swap the
removed string dimensions for sourceType to keep coverage intact.

Add csatDissatisfiedCount and csatNeutralCount so dashboards can render
the standard satisfied/neutral/dissatisfied distribution alongside the
existing top-2-box metric.

Expose field_label, field_group_label, language, value_boolean,
value_date, created_at, and updated_at as Cube dimensions. fieldLabel
and fieldGroupLabel unlock "group by question" and the matrix/ranking
aggregations enabled by the recent composite-question PR; the others
round out coverage of the underlying feedback_records columns. Extend
FieldDefinition with a boolean type and matching filter operators.
2026-05-12 18:45:10 +05:30
Dhruwang Jariwala 5b70c99eb3 fix(dashboards): chart removal flow + add-charts dialog focus ring (ENG-901, ENG-903) (#7981) 2026-05-12 16:55:48 +05:30
Dhruwang 10c09f00a8 refactor(dashboards): address review on removeWidgetFromDashboard
- Drop the prisma.$transaction wrapper; find + delete is two sequential
  steps, doesn't need a transaction.
- Drop the redundant ResourceNotFoundError catch branch; the trailing
  `throw error` already lets it bubble.
- Let action-client infer ctx / parsedInput types.

Tests: cover the two catch branches (Prisma -> DatabaseError, unknown
rethrow) so the new function is fully line-covered.
2026-05-12 16:11:45 +05:30
Dhruwang 602ffd5bba feat(analytics): augment Cube measures with CSAT/CES + bug fixes (ENG-804)
Adds CSAT and CES measures, plus a couple of universal cross-type measures,
to the FeedbackRecords Cube. Also fixes correctness bugs in the existing NPS
measures and constrains the AI chart-query output to known measure / dimension
ids.

Measures added
- csatScore: % of answered CSAT responses rated 4 or 5 (top-2-box on 1-5).
- csatAverage: AVG of answered CSAT ratings.
- csatSatisfiedCount: count where field_type='csat' AND value_number >= 4.
- csatCount: count of answered CSAT responses.
- cesAverage: AVG of answered CES ratings (1-5 or 1-7 depending on the question).
- cesCount: count of answered CES responses.
- uniqueRespondents: countDistinct(user_id).
- uniqueResponses: countDistinct(submission_id).
- npsAverage: AVG of answered NPS ratings (replaces the old `averageScore`
  measure, which silently averaged every numeric value across all field types).

Bug fixes (existing NPS measures)
- promoterCount / passiveCount / detractorCount / npsScore now filter
  field_type = 'nps'. Before, any numeric value in the band was counted
  (so a CSAT 5/5 was lumped in as a detractor).
- npsScore now divides by *answered* NPS responses only (value_number IS NOT
  NULL); dismissed/abandoned NPS records no longer drag the score toward 0.
- npsScore returns NULL when no answered NPS responses exist instead of the
  literal 0, so empty-data days render as gaps rather than a misleading
  flat-zero line.
- Same NULL-safe denominator fix applied to csatScore.
- csatCount / cesCount now exclude dismissed (value_number IS NULL) responses
  so they match the score denominators.

Dimensions
- Renamed `npsValue` -> `valueNumber` (the underlying value_number column
  stores values for NPS, CSAT, CES, rating, and number field types).
- New `valueText` dimension for grouping by categorical / open-text answers.

AI chart generation
- ZGenerateAIQueryResponse now enum-constrains `measures`, `dimensions`,
  `timeDimensions.dimension`, and `filters.member` against the known ids
  derived from FEEDBACK_FIELDS. Vercel AI SDK + Gemini structured outputs
  enforce these at decoding time, so the model can no longer return invalid
  or hallucinated measure names.
- generateText now pins temperature: 0. Same prompt produces the same query.

Breaking changes
- Charts that referenced `FeedbackRecords.averageScore` need to switch to
  `FeedbackRecords.npsAverage`.
- Charts that referenced `FeedbackRecords.npsValue` need to switch to
  `FeedbackRecords.valueNumber`.

Pre-GA on epic/v5; no production charts are expected to be impacted yet.
2026-05-12 16:05:38 +05:30
Javi Aguilar 5f4f133dcb fix: add missing title in feedback directory 2026-05-12 11:07:02 +02:00
Dhruwang Jariwala 037b005d48 fix(charts): pie tooltip spacing + scroll to chart-name on empty save (ENG-914, ENG-916) (#7970) 2026-05-12 13:22:00 +05:30
Dhruwang ddd2d5e983 fix(dashboards): chart removal flow + add-charts dialog focus ring (ENG-901, ENG-903)
ENG-901: clicking Remove on a chart widget no longer enters dashboard edit mode
(which surfaced the rename input) and saving with the last widget removed no longer
surfaces a raw "widgets: Too small" zod error. Out of edit mode, Remove now goes
through a DeleteDialog -> dedicated removeWidgetFromDashboardAction. The batched
update path also allows an empty widgets array now that the lib already supports
deleting all widgets correctly.

ENG-903: add p-1 to AddExistingChartsDialog DialogBody so the focus ring on the
inner search input is no longer clipped by the body's overflow boundary.
2026-05-12 12:51:46 +05:30
Dhruwang Jariwala 6777b284b3 fix(a11y): large selects are not scrollable (#7963) 2026-05-12 12:08:38 +05:30
Anshuman Pandey c6282632e0 fix: fixes read only issues in feedback sources UI (#7974) 2026-05-12 10:20:30 +04:00
Dhruwang Jariwala f84c409bc4 feat: add beta badge to unify feedback navigation section (#7968) 2026-05-12 11:38:09 +05:30
Dhruwang Jariwala 98b475a2a4 fix(charts): time-range crash + sentiment/emotion/response-id cube column mismatches (ENG-907, ENG-906, ENG-915) (#7973) 2026-05-12 10:02:50 +04:00
Dhruwang c48474b943 chore(charts): drop sonar S6478 JSDoc on PieTooltipRow
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-12 11:31:38 +05:30
Anshuman Pandey 3c0d1e3fd7 fix: fixes connector modal UI errors (#7971) 2026-05-11 16:40:35 +04:00
Bhagya Amarasinghe 1f7a496967 fix(helm): stop forcing TEI float16 dtype (#7967) 2026-05-11 17:24:57 +05:30
Dhruwang 99e378ae2e chore: drop verbose doc comments on ChartDialogFooter props
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:44:15 +05:30
Dhruwang c6e39c3103 refactor(charts): hoist pie tooltip formatter to module scope (sonar S6478)
Same pattern as CartesianChart's ChartTooltipRow — a module-level
component that calls useTranslation internally, plus a thin formatter
function passed to ChartTooltipContent. Resolves the nested-component
warning.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:41:18 +05:30
Dhruwang 19472ca9d3 chore: inline form onSubmit to avoid deprecated FormEvent type alias
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:37:20 +05:30
Dhruwang 43feff0009 fix(charts): inline error styling for empty chart-name on submit
Switch from the native browser tooltip to the in-app inline error pattern:
red Label, isInvalid Input border, and helper text below the field. The
onInvalid handler suppresses the default tooltip and scrolls + focuses the
field via event.currentTarget — no ref needed. Typing clears the error.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:36:45 +05:30
Dhruwang 507cec6958 feat(charts): show translated message on empty chart-name validation
Browsers default to "Please fill in this field"; use the existing
workspace.analysis.charts.please_enter_chart_name key so the message
matches the toast we surface elsewhere. Clear custom validity on change
so the form unblocks once the user types.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:27:52 +05:30
Dhruwang d874b65be9 refactor(charts): use native form validation for chart-name field (ENG-916)
Replace the imperative scrollIntoView + focus on Save click with a tiny
<form> wrapping the required Input. The Save button becomes type=submit
with form="create-chart-form", so the browser handles scroll, focus, and
the "Please fill in this field" tooltip natively when the name is empty.

ChartDialogFooter now accepts either onSaveClick (button mode) or formId
(submit-button mode). All sibling buttons in the footer are explicitly
type="button" so they don't accidentally submit the form.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:25:17 +05:30
Dhruwang Jariwala c159af1a26 fix: format toast (ENG-893) (#7966) 2026-05-11 16:22:24 +05:30
Dhruwang 3ce2ef6cf4 fix(charts): scroll/focus chart-name input when save is blocked by empty name (ENG-916)
Clicking Save Chart with the name field empty fired a toast but left the
modal scrolled wherever the user was (e.g. on the chart preview at the
bottom), so they couldn't see what was wrong. Scroll the name field into
view and focus it before delegating to the existing save handler.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:20:57 +05:30
Dhruwang Jariwala baae6335c9 fix: validate workspace assignment on feedback directory create (ENG-900) (#7965)
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
2026-05-11 14:50:05 +04:00
Dhruwang 8e443db1f6 revert: drop YAxis integer-tick handling
The fractional-tick bar/line/area scenario isn't the bug we're shipping in
this PR. Keep only the pie tooltip spacing/formatting change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:13:40 +05:30
Dhruwang 18cd9afc2c fix(charts): space between value and name in pie tooltip
Returning [value, name] from the tooltip formatter rendered as two adjacent text nodes ("3Nps"). Return a fragment with an explicit space so it reads "3 Nps".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 16:08:22 +05:30
Dhruwang 680e1e1593 fix(charts): show integer y-axis ticks for COUNT measures and format pie tooltips
ENG-914

When a chart's measures are all whole numbers (e.g. COUNT grouped by a
dimension), Recharts was auto-generating fractional y-axis ticks like
0.5, 1.5, 2 — nonsensical for a discrete count. The pie tooltip also
rendered values via raw String() with no thousand separators.

- Add allValuesAreIntegers() + formatYAxisTick() to chart-utils.
- CartesianChart now passes allowDecimals={false} and a number-aware
  tickFormatter to YAxis when every measure value is an integer.
- ChartRenderer's pie tooltip routes the value through formatCellValue,
  matching the Cartesian tooltip behaviour.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 15:49:57 +05:30
Dhruwang 04bfdeef69 removed stale comment 2026-05-11 15:09:51 +05:30
Dhruwang 8a1db7b6aa reverted errorcode transform change 2026-05-11 15:08:58 +05:30
Dhruwang 1d22fe2da6 fix: surface translated inline form errors and prefer .at() over slice
- FormError ignored its children when an error was set, rendering the raw
  zod message instead of the translated text passed in. Prefer explicit
  children, fall back to the field error message.
- Use .at(-1) in getTranslatedFeedbackDirectoryError per SonarQube S7755.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 15:03:00 +05:30
Dhruwang d8a119712c revert: drop zero-workspace requirement on feedback directory create
Per Johannes on ENG-893: zero-workspace creation is acceptable — admins
move workspaces between directories and forcing at least one is an
arbitrary limitation. The unformatted-error fix
(getTranslatedFeedbackDirectoryError prefix stripping) is retained.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 14:54:54 +05:30
Cursor Agent 50089eeca4 feat: add beta badge to unify feedback section
Co-authored-by: Johannes <jobenjada@users.noreply.github.com>
2026-05-11 08:20:06 +00:00
Bhagya Amarasinghe d8fe832f5f fix(helm): stop forcing TEI float16 dtype 2026-05-11 13:24:49 +05:30
Dhruwang 1c904e2243 fix: require at least one workspace when creating a feedback directory
ENG-893

Why: A feedback directory with zero workspaces is useless — it groups
nothing. The create path allowed it, and any validation error that did
fire surfaced as a raw "field: CODE" string in the toast.

How:
- createFeedbackDirectory now rejects empty/missing workspaceIds with
  DIRECTORY_WORKSPACES_REQUIRED before touching the database.
- getTranslatedFeedbackDirectoryError strips the "<field>: " prefix that
  next-safe-action prepends to validation errors, so machine codes always
  map to a translated message.
- Add the new translation key across all 15 locales.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-11 13:04:47 +05:30
Javi Aguilar 4dbecc2d58 fix/a11y-select-scroll 2026-05-11 05:52:55 +02:00
Dhruwang Jariwala 72f4e93432 fix: support Redis Cluster for BullMQ jobs (#7960) 2026-05-08 15:28:10 +05:30
Dhruwang Jariwala 9007502804 feat(feedback-sources): add a Create Survey CTA if there are none (#7943) 2026-05-08 15:10:28 +05:30
Tiago Farto d84589452c Merge branch 'epic/v5' of https://github.com/formbricks/formbricks into fix/investigate-bullmq-issue
# Conflicts:
#	docs/development/technical-handbook/background-job-processing.mdx
2026-05-08 09:38:53 +00:00
Tiago Farto 43aaed3923 fix: support Redis Cluster for BullMQ jobs 2026-05-08 09:19:49 +00:00
Bhagya Amarasinghe 550bfc6a6c fix: update Hub runtime defaults for v5 staging (#7959) 2026-05-07 19:25:20 +02:00
Bhagya Amarasinghe 2c22b00ec6 fix: address Cube chart review feedback (#7956) 2026-05-07 17:27:55 +02:00
Bhagya Amarasinghe d64fb546d3 feat: add internal cube helm deployment (#7955) 2026-05-07 16:06:24 +02:00
Dhruwang Jariwala f4ca7c46ef fix: add Hub and Cube env vars to Docker build secrets (#7950) 2026-05-07 17:22:05 +05:30
Dhruwang c252d8c4c9 fix: update tests for required Cube and Hub env vars
Tests now expect validation failures when CUBEJS_API_URL, CUBEJS_API_SECRET,
or HUB_API_KEY are missing, and all test env helpers provide HUB_API_KEY.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 17:14:01 +05:30
Dhruwang 2bec3b040d fix: remove unused ZOptionalUrl variable
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 17:06:23 +05:30
Dhruwang 3c49b33dad feat: make HUB_API_KEY required and add to Docker build secrets
Hub is mandatory in v5, so HUB_API_KEY should fail fast at startup
if not configured.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 16:56:55 +05:30
Dhruwang 0f2f3d337e fix: restore CUBEJS_JWT_AUDIENCE and CUBEJS_JWT_ISSUER in env schema
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 16:48:57 +05:30
Dhruwang 4d1df795ad feat: make CUBEJS_API_SECRET and CUBEJS_API_URL required
Makes Cube env vars mandatory in env.ts (per PR #7913) and adds them
as Docker build secrets with fallback values, following the same pattern
as DATABASE_URL, REDIS_URL, and HUB_API_URL.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 16:45:46 +05:30
Bhagya Amarasinghe 3ce2998d0d feat(helm): add Hub worker and embeddings runtime (#7945) 2026-05-07 16:35:32 +05:30
Bhagya Amarasinghe b9a6520e10 fix(helm): address embeddings review feedback 2026-05-07 16:21:42 +05:30
Dhruwang 55bb9a525e fix: use secrets.DUMMY_HUB_API_URL instead of hardcoded value
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 16:20:48 +05:30
Dhruwang 11055f812e fix: add HUB_API_URL to Docker build secrets
HUB_API_URL is required by the Zod env validation at build time but was
not provided as a Docker secret, causing the release build to fail.

Adds HUB_API_URL with a dummy fallback (http://localhost:4000) to the
build pipeline, following the same pattern as DATABASE_URL/REDIS_URL.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 16:18:35 +05:30
Anshuman Pandey ecf3aacca3 fix: removes auto feedback directory linking with workspaces (#7947) 2026-05-07 13:46:25 +04:00
Dhruwang Jariwala a0f3d2a651 chore: upgrade Hub to 0.3.0 and SDK to 0.5.0 (#7948) 2026-05-07 14:59:11 +05:30
Dhruwang 16bbd7a447 chore: upgrade Hub to 0.3.0 and SDK to 0.5.0
Hub 0.3.0 renames the `user_identifier` API field to `user_id` (breaking
change). This commit bumps the Hub Docker image, upgrades the
@formbricks/hub TypeScript SDK from 0.4.3 to 0.5.0, and renames every
`user_identifier` reference in Zod schemas, server actions, transform
pipeline, form components, CubeJS schema, connector types, and seed data
to match the new API contract.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-07 14:31:09 +05:30
Bhagya Amarasinghe a276aa6d34 fix(helm): default embeddings model to gte multilingual 2026-05-07 13:46:29 +05:30
Javi Aguilar d192fbf839 add CR changes 2026-05-07 10:12:06 +02:00
Javi Aguilar c5d52df9b7 use i18n interpolation properly 2026-05-07 10:12:06 +02:00
Javi Aguilar 550e859a2d feat(unify): add CTA to create a survey before using it as feedback source if there are none 2026-05-07 10:12:06 +02:00
Dhruwang Jariwala 6fb9cf28b1 fix: add cursor-based pagination and fix refresh for feedback records (#7935)
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
2026-05-07 10:13:59 +04:00
Dhruwang Jariwala 8c47cdba73 chore: drop explicit feedback directory grants, use implicit auth (#7941) 2026-05-07 10:24:30 +05:30
Bhagya Amarasinghe e6b6f5e6d3 feat(helm): add Hub worker and embeddings runtime 2026-05-07 01:45:45 +05:30
pandeymangg 6218153351 fixes tests 2026-05-06 16:33:03 +05:30
pandeymangg 9ef4be270b fix: removes feedback directory auth from api keys 2026-05-06 16:29:06 +05:30
Dhruwang Jariwala ed42df34c4 feat(ai): support Vertex AI ADC credentials (#7938) 2026-05-06 12:37:24 +05:30
Dhruwang Jariwala 8c8ff8e396 feat: gate AI chart generation behind all AI checks (#7937) 2026-05-06 10:09:49 +05:30
Dhruwang 72cf2d6a50 test: add coverage for getAIDataAnalysisUnavailableReason 2026-05-05 18:06:02 +05:30
Bhagya Amarasinghe c5d629ef25 feat(ai): support Vertex AI ADC credentials 2026-05-05 18:04:30 +05:30
Dhruwang 71cb8bdff5 refactor: extract getAIDataAnalysisUnavailableReason to shared utility
Move duplicated function to @/lib/ai/service and export TAIUnavailableReason
type. Remove local copies from charts-list-page and dashboard-detail-page.
2026-05-05 17:40:42 +05:30
Dhruwang 850fb8acc3 feat: gate AI chart generation behind all 3 AI checks
- Server-side: Replace hardcoded OpenAI with provider-agnostic `getAiModel(env)` and enforce
  `assertOrganizationAIConfigured(organizationId, "dataAnalysis")` which validates license
  entitlement, org-level toggle, and instance configuration
- Client-side: Instead of hiding AI section when unavailable, show it disabled with a tooltip
  explaining the reason (not in plan / not enabled / instance not configured), following the
  same pattern as AI translate
- Thread `isAIAvailable` and `aiUnavailableReason` through the component chain from server
  pages down to `AIQuerySection`
- Update test mocks to match new provider-agnostic AI imports
2026-05-05 17:21:22 +05:30
Dhruwang Jariwala 94c9e8fcf1 feat: gate Unify Feedback, FRDs, Dashboards behind license (#7924) 2026-05-05 17:15:14 +05:30
pandeymangg 49a8c8c686 adds nav links 2026-05-05 16:33:35 +05:30
pandeymangg 2832831db1 chore: merge with epic/v5 2026-05-05 16:21:34 +05:30
pandeymangg b5e6567194 fixes 2026-05-05 16:13:12 +05:30
Dhruwang Jariwala 86d3f2fae1 chore: hardening cube tenant isolation (#7920) 2026-05-05 16:03:11 +05:30
pandeymangg 62d09f6a8f chore: merge with epic/v5 2026-05-05 15:14:53 +05:30
Johannes 74dd778630 feat: similar feedback preview (#7917)
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
2026-05-05 13:28:08 +04:00
Tiago Farto 7ac99c0840 chore: update 2026-05-05 08:50:03 +00:00
Tiago Farto dde0f8d32c Merge branch 'epic/v5' into chore/harden-cube-tenant-isolation 2026-05-05 08:49:36 +00:00
Tiago Farto bcd3c91075 chore: address PR concerns 2026-05-05 08:39:56 +00:00
Bhagya Amarasinghe f376c620ab docs: align self-hosting docs for Formbricks v5 (#7906) 2026-05-05 12:52:18 +05:30
Bhagya Amarasinghe 4865a78338 docs: align v5 cube deployment guidance 2026-05-05 12:50:41 +05:30
Bhagya Amarasinghe a7c8e1acf9 docs: add MinIO to RustFS migration pointer 2026-05-05 12:47:02 +05:30
Bhagya Amarasinghe e5a097e56e docs: address CodeRabbit review feedback 2026-05-05 12:47:02 +05:30
Bhagya Amarasinghe 1ddde9cac7 docs: align self-hosting docs for Formbricks v5 2026-05-05 12:47:02 +05:30
Anshuman Pandey 59f5cdfb4b fix: hub pinned at specific tag/digest (#7923) 2026-05-05 11:15:41 +04:00
pandeymangg 8431eaf9f6 chore: merge with epic/v5 2026-05-05 11:38:39 +05:30
Dhruwang Jariwala f228e8e06a chore: Rename FeedbackRecordDirectory to FeedbackDirectory (#7925) 2026-05-05 09:15:20 +04:00
Dhruwang Jariwala 5e6ab81cb1 fix: migrate feedback-sources page to unified settings navigation (#7928) 2026-05-05 10:09:30 +05:30
Tiago Farto 1417a5a654 chore: restore document 2026-05-04 13:05:53 +00:00
Tiago Farto f8ae92b3be chore: remove doc 2026-05-04 13:04:37 +00:00
Dhruwang 1bc3f79f30 fix: translations 2026-05-04 18:25:11 +05:30
Dhruwang 7151dd5234 fix: migrate feedback-sources page to unified settings navigation
The feedback-sources page was still using the old WorkspaceConfigNavigation
(secondary tabs) instead of the new unified settings sidebar introduced in
#7904. This caused an inconsistent navigation experience.

Changes:
- Create new route at /settings/workspace/feedback-sources
- Add feedback-sources entry to SettingsSidebarContent
- Remove old WorkspaceConfigNavigation from ConnectorsSection
- Redirect old /feedback-sources route to new settings path
- Update all stale /feedback-sources links across the codebase
2026-05-04 18:20:54 +05:30
Dhruwang Jariwala 086315ce33 feat: unify settings UI with shared sidebar navigation (#7904) 2026-05-04 17:37:53 +05:30
Tiago Farto e01b4311ca chore: cleaned documentation duplication 2026-05-04 11:52:41 +00:00
Tiago Farto dd757394af fix: make bundled cube optional 2026-05-04 11:03:37 +00:00
Dhruwang 507f80f9b0 fix: update stale settings routes to match new /settings/{organization,workspace}/ structure
All internal links (billing, enterprise, general, api-keys, feedback-record-directories,
integrations) now point to their correct nested paths under /settings/organization/ or
/settings/workspace/. Also adds feedback-record-directories to the new sidebar nav with
the member visibility rule.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-05-04 16:31:25 +05:30
pandeymangg 8562232280 adds tests 2026-05-04 13:27:22 +05:30
pandeymangg 1234e6685a fixes feedback 2026-05-04 13:15:37 +05:30
pandeymangg 40a5e8ea6a fixes tests and i18n validation 2026-05-04 13:12:38 +05:30
pandeymangg 319a76a70d moves connectors, dashboards and frd to ee 2026-05-04 12:55:34 +05:30
Tiago Farto 2abf8e1d8c fix: log rejected cube tenant queries 2026-04-30 16:52:41 +00:00
Tiago Farto a985dc698b refactor: simplify cube query filter traversal 2026-04-30 16:50:55 +00:00
Tiago Farto 7b59a6300e fix: address cube tenant isolation review 2026-04-30 16:34:09 +00:00
Tiago Farto bf8b4079fd test: isolate cube env config test 2026-04-30 16:20:29 +00:00
Tiago Farto 5704bfbc03 chore: hardening cube tenant isolation 2026-04-30 16:00:08 +00:00
Dhruwang 0920ccf2c3 fix: remove unused isBilling prop and stale translation keys
- Remove isBilling from WorkspaceBreadcrumb/WorkspaceAndOrgSwitch prop chain
- Remove unused common.organization_settings and common.unify translation keys

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-30 18:24:32 +05:30
Dhruwang db0c9e7c55 fix: update E2E action tests to wait for user-actions URL
The tests were waiting for a redirect to app-connection that no longer
exists — user-actions is now a standalone page.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-30 18:09:45 +05:30
Dhruwang ef87d899b9 fix: simplify dropdown menus and fix Connect Your App icon
- Replace individual settings items in workspace/org dropdowns with single Settings link
- Change Connect Your App icon from ListChecksIcon to UnplugIcon
- Remove unused code (isActiveOrganizationSetting, isActiveWorkspaceSetting, etc.)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-30 18:06:19 +05:30
Bhagya Amarasinghe ea92ef9fce feat: add FeedbackRecords Envoy gateway (#7818) 2026-04-30 17:17:05 +05:30
pandeymangg 778fc2acf1 fix 2026-04-30 16:36:09 +05:30
Dhruwang 2ffef36c89 fix: update E2E tests for user-actions route and Teams heading ambiguity
- action.spec.ts: navigate to user-actions page instead of app-connection
- organization.spec.ts: use level:1 to disambiguate "Teams" heading

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-30 16:30:22 +05:30
pandeymangg 1d6bda74df removes route test 2026-04-30 16:26:47 +05:30
pandeymangg 12ff0b7c0e sonar issue fix 2026-04-30 16:19:11 +05:30
Dhruwang fa1079bac1 fix: update E2E tests for renamed settings labels
- "Look & Feel" comments → "Appearance"
- "Members & Teams" heading assertion → "Teams"

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-30 16:07:18 +05:30
Dhruwang 1403f0bb01 fix: pass missing isBilling prop to WorkspaceBreadcrumb
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-30 16:06:34 +05:30
Dhruwang c79553633f fix: use export...from to re-export default in user-actions routes
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-30 16:04:04 +05:30
Bhagya Amarasinghe f16fb3b62f fix: restore required feedback record list params 2026-04-30 15:59:45 +05:30
Dhruwang 7dfc7f4825 docs: update references to renamed settings labels
- "Configuration" → "Settings"
- "Look & Feel" → "Appearance"
- "Website & App Connection" → "Connect Your App" / "User Actions"

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-30 15:46:47 +05:30
Dhruwang 1ecc9f1722 fix: restore settings sidebar, rename labels, fix SonarQube issues, and extract user-actions page
- Restore settings sidebar in MainNavigation (lost during epic/v5 merge)
- Rename "Configuration" to "Settings", "Look & Feel" to "Appearance", etc.
- Fix SonarQube issues: duplicate class, regex injection, nested ternary, inline arrow functions
- Extract User Actions from Connect Your App into its own settings page
- Update all i18n translation keys across locales

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-30 15:41:50 +05:30
Dhruwang 7d1c02b54b Merge remote-tracking branch 'origin/epic/v5' into feat/settings-cleanup-v5 2026-04-30 14:56:35 +05:30
Bhagya Amarasinghe f2c452d7f9 feat: make cubejs mandatory for xm suite v5 (#7913) 2026-04-30 14:34:50 +05:30
Bhagya Amarasinghe afcfbb7a3a fix: address cube review follow-ups 2026-04-30 14:17:54 +05:30
Bhagya Amarasinghe 7f8c9dcbb8 chore: merge epic/v5 into feedback records gateway 2026-04-30 01:22:24 +05:30
Bhagya Amarasinghe 3998e4da31 fix: resolve sonar quality gate warning 2026-04-30 00:59:25 +05:30
Bhagya Amarasinghe 48086faffc fix: address cube review feedback 2026-04-30 00:39:49 +05:30
Bhagya Amarasinghe 38a0d7c810 Merge remote-tracking branch 'origin/epic/v5' into bhagya/eng-765-make-cubejs-mandatory-for-xm-suite-v5 2026-04-30 00:32:05 +05:30
Bhagya Amarasinghe b17bb88daa fix: require cube env vars in app config 2026-04-30 00:30:11 +05:30
Anshuman Pandey f59e9f13ec feat: refresh analysis charts and dashboard feedback gating (#7915)
Co-authored-by: Johannes <johannes@formbricks.com>
Co-authored-by: Dhruwang <dhruwangjariwala18@gmail.com>
2026-04-29 16:29:14 +04:00
Anshuman Pandey 5169dec510 feat: wire workspace settings to feedback record directories (#7910)
Co-authored-by: Johannes <johannes@formbricks.com>
Co-authored-by: Dhruwang <dhruwangjariwala18@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-29 14:49:50 +04:00
Bhagya Amarasinghe 0df16f6f0c feat: make cubejs mandatory for xm suite v5 2026-04-29 16:08:24 +05:30
Anshuman Pandey 8442dedf9c fix: removes project references (#7907) 2026-04-29 14:17:42 +04:00
Dhruwang 22c27c5ebb fix: remove unused params prop from notifications page
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-29 15:27:50 +05:30
Dhruwang 6638dceb04 feat: disable settings for billing role, hide back button, add org switcher to landing sidebar
- Disable all workspace and select org settings items for billing-role users
- Hide the top bar (back button) for billing users in settings mode
- Add organization switcher with lazy-loaded org list to landing sidebar
- Pass isMultiOrgEnabled to landing sidebar for create-org option

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-29 15:24:42 +05:30
Dhruwang 8558121e46 feat: enhance SettingsSidebarContent with tooltip and popover for disabled items
- Added Tooltip and Popover components to provide user feedback for disabled navigation items.
- Implemented conditional rendering of tooltips and popovers based on item state.
- Introduced a disabledMessage prop to display appropriate messages for unauthorized actions.
2026-04-29 14:46:48 +05:30
Dhruwang f1279d51e5 fix: transaltions 2026-04-29 14:42:48 +05:30
Dhruwang 926706be9d fix: merge epic/v5, fix stale integration URLs and settings workspace switcher
- Resolve merge conflict in create-connector-modal (keep NoFeedbackRecordDirectoryAlert)
- Fix GoBackButton URLs in slack, google-sheets, airtable integration pages to use /settings/workspace/integrations path
- Fix connectHref values in integrations page (webhooks, google-sheets, airtable, slack, notion, JS SDK)
- Fix handleWorkspaceChange to stay in settings mode when switching workspace from settings sidebar

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-29 14:36:06 +05:30
Dhruwang 85b456e619 fix: navigate to surveys via URL in multi-language e2e test
The settings sidebar replaces the main nav, so the "Surveys" link is
not visible when on a settings page. Use direct URL navigation instead.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-29 13:46:34 +05:30
Bhagya Amarasinghe 3bac488a29 fix: address gateway review follow-ups 2026-04-29 12:27:41 +05:30
Johannes fbe2a31133 refactor: align connector enum with formbricks_survey (#7825)
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
2026-04-29 10:57:20 +04:00
Bhagya Amarasinghe 79d618f77c refactor: generalize gateway token minting 2026-04-29 12:16:08 +05:30
Anshuman Pandey 89eb04f813 fix: adds submission id to csv connector (#7898) 2026-04-29 10:36:16 +04:00
Dhruwang 8a2b349329 feat: unify settings under /workspaces/[id]/settings with shared sidebar navigation
Consolidate all settings (Account, Organization, Workspace) under a unified
URL structure with a shared sidebar that replaces the main navigation when
in settings mode. Remove horizontal nav bars, old dropdown-based navigation
patterns, and route group layouts in favor of real URL segments.

- Move workspace settings from /(workspace)/ to /settings/workspace/
- Move org settings from /settings/(organization)/ to /settings/organization/
- Move account settings from /settings/(account)/ to /settings/account/
- Add SettingsSidebarContent with inline workspace/org switchers
- Replace main sidebar with settings nav when pathname includes /settings
- Update all page headings to match sidebar nav labels
- Update e2e tests for new URL structure and navigation patterns
- Remove unused translation keys

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-28 18:26:58 +05:30
Dhruwang Jariwala a862b739f7 fix: consistent enabled/disabled wording for connector status (#7897) 2026-04-28 15:11:44 +05:30
Dhruwang 4e5df85538 fix: make pipeline dispatch fire-and-forget in management responses route
Pipeline errors (snapshot loading or dispatch) should not prevent the
201 response from being returned. Dispatch pipeline events without
awaiting so the response is returned immediately.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-28 14:31:24 +05:30
Dhruwang 727b349086 fix: resolve pre-existing build errors on epic/v5
- Add optional chaining for organization.billing in response pipeline
- Add missing feedbackRecordDirectoryId to Chart seed data

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-28 13:47:20 +05:30
Dhruwang f75db6b1d0 fix: translations 2026-04-28 12:39:12 +05:30
Dhruwang 7ffca53577 fix: use consistent enabled/disabled wording for connector status badges
The dropdown actions say "Enable"/"Disable" but the status badges showed
"In Progress"/"Paused". Now both use "Enabled"/"Disabled" for consistency.

Resolves ENG-769

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-28 12:24:49 +05:30
Dhruwang Jariwala 25614b23fc chore: remove legacy styling fields (questionColor, inputColor) (#7783) 2026-04-28 11:22:03 +05:30
Johannes 016e14d0f1 fix: (Depr Env QA) Surface legacy env var on Connection page (#7773) 2026-04-27 14:20:25 +00:00
Bhagya Amarasinghe be80db8418 fix: address envoy auth review findings 2026-04-27 19:31:43 +05:30
Bhagya Amarasinghe bcc3789ce8 refactor: generalize envoy auth dispatch 2026-04-27 18:31:58 +05:30
Dhruwang 5e76ebdfc1 fix: treat JSON null as absent in legacy styling migration
The `?` operator only checks key existence — if the form layer saved
`{"elementHeadlineColor": null}` (JSON null = "use default"), the
migration skipped the copy and then removed the legacy key, losing
the color value. Switch to COALESCE(styling->'field', 'null'::jsonb)
= 'null'::jsonb which catches both missing keys (SQL NULL) and JSON
null values.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-27 17:07:05 +05:30
Bhagya Amarasinghe 150f256721 fix: decouple pipeline from response ingestion (#7651) 2026-04-27 12:59:27 +05:30
pandeymangg da7971328c little cleanup 2026-04-27 12:58:42 +05:30
Bhagya Amarasinghe a6cd56b196 fix: migrate response pipeline to BullMQ (#7651) 2026-04-27 12:58:42 +05:30
pandeymangg 7c81cf119e adds test for schedulePipelineDrain when env vars are not set 2026-04-27 12:56:22 +05:30
Bhagya Amarasinghe 8d29b24352 fix: address latest pipeline review comments (#7651) 2026-04-27 12:56:22 +05:30
Bhagya Amarasinghe a1ae849496 fix: address CodeRabbit pipeline findings (#7651) 2026-04-27 12:56:22 +05:30
Bhagya Amarasinghe 4d0a686e89 fix: address pipeline PR checks (#7651) 2026-04-27 12:56:22 +05:30
Bhagya Amarasinghe 364915e4c8 fix: decouple pipeline from response ingestion (#1487) 2026-04-27 12:56:22 +05:30
Bhagya Amarasinghe ada2518d0c fix: address feedback records gateway build failures 2026-04-24 17:30:41 +05:30
Bhagya Amarasinghe 57d1c0ed99 fix: resolve feedback records PR check failures 2026-04-24 16:53:57 +05:30
Tiago 817b299436 chore: rename gcp ai provider to google (#7815) 2026-04-24 10:10:58 +00:00
Tiago Farto c140dae872 Merge branch 'epic/v5' into chore/rename_google 2026-04-24 09:51:39 +00:00
Bhagya Amarasinghe 6036a8c767 fix: harden FeedbackRecords Envoy auth routing 2026-04-24 13:51:54 +05:30
Dhruwang Jariwala bf592937f4 feat: AI-powered survey translation (#7793) 2026-04-24 12:55:36 +05:30
Bhagya Amarasinghe 1cfadd968a feat: add FeedbackRecords Envoy gateway 2026-04-24 02:17:54 +05:30
Tiago Farto 21ed383a46 chore: address PR concerns 2026-04-23 13:45:09 +00:00
Bhagya Amarasinghe 7ed7101ac1 feat: adds feedback record directory auth to api keys (#7804) 2026-04-23 18:04:17 +05:30
Tiago Farto 7aa12a4f0c chore: rename google ai things 2026-04-23 12:27:39 +00:00
pandeymangg 2e926936fb addressed feedback 2026-04-23 17:46:09 +05:30
Dhruwang 8edef8aede refactor: replace repeated union type with TDimension alias in TBaseStyling
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-23 16:22:13 +05:30
Dhruwang 54fb202285 fix: add jsonb_typeof guard to legacy styling migration
Ensures the UPDATE only processes JSONB objects, preventing errors
on unexpected scalar or array values in the styling column.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-23 16:16:50 +05:30
Dhruwang c720a462a7 fix: rename inputColor to inputTextColor in survey-ui storybook files
Aligns storybook story helpers and element stories with the legacy
field removal — inputColor → inputTextColor, mapping to
--fb-input-text-color CSS variable.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-23 16:12:53 +05:30
Dhruwang a386451e6e refactor: consolidate imports in actions.ts
Merged the import statements for ZAITranslationField and translateFields from the translate-fields module to streamline the code structure.
2026-04-23 15:17:31 +05:30
Dhruwang f0bf111e7b fix: test 2026-04-23 15:08:18 +05:30
Dhruwang 8a57a5b74b addressed feedback 2026-04-23 15:05:16 +05:30
Dhruwang 434cb1d0d0 refactor: remove BullMQ background jobs from AI translation
Replace the async job queue + Redis polling pattern with a direct
server action call. The translation now runs synchronously inside
translateSurveyFieldsAction, removing the need for BullMQ job
definitions, processors, cache keys, and client-side polling logic.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-23 14:11:28 +05:30
pandeymangg 8bde75a9ff chore: merge with epic/v5 2026-04-23 11:06:54 +05:30
pandeymangg 6b880f29cb chore: merge with epic/v5 2026-04-23 11:00:25 +05:30
Dhruwang Jariwala 969c9834e5 fix: (Depr Env QA) update lang keys (#7786) 2026-04-23 10:57:47 +05:30
pandeymangg 5e33b7c9a4 fixes and e2e fixes 2026-04-23 10:55:20 +05:30
Dhruwang 230ea744fa fix: simplify workspace permissions assignment in ViewPermissionModal 2026-04-23 10:38:18 +05:30
Anshuman Pandey fae1fb8f96 fix: cleans up environmentId references (#7792) 2026-04-23 09:05:00 +04:00
Dhruwang eac35daed9 fix: transllations 2026-04-23 10:34:29 +05:30
Johannes 45accc1edb fix: align workspace naming in setup and email preview
Replace remaining environment wording with workspace terminology across setup flows, API key permissions, and email preview text, and switch the email Tailwind config to ESM so formatting hooks run under the current Node runtime.

Made-with: Cursor
2026-04-23 10:30:30 +05:30
Dhruwang Jariwala 02ebe8e9f8 fix: (Depr Env QA) update docs (#7784) 2026-04-23 10:23:23 +05:30
pandeymangg cae859e326 sonarcloud fixes 2026-04-22 17:15:19 +05:30
pandeymangg 5352d563b6 fixes and consistency 2026-04-22 17:03:18 +05:30
Anshuman Pandey 711f2bfe67 chore: restores feedback record directory changes to epic/v5 (#7806) 2026-04-22 15:22:15 +04:00
Dhruwang 6fcb5d39a2 fix: address code review feedback for AI translation
- Reuse ZAITranslationField from @formbricks/jobs instead of duplicating
  the schema locally in actions.ts; tighten sourceLanguage/targetLanguage
  validators with .min(1) to match the downstream job schema

- Guard against undefined translations in getAITranslationResultAction
  instead of using the unsafe `translations!` assertion — return
  "pending" status for malformed cache entries

- Use createCacheKey.custom("ai-translation", jobId) instead of raw
  template strings to follow cache key conventions

- Improve JSON parsing robustness: strip markdown code fences before
  attempting JSON.parse, log raw response on parse failures

- Add stale-request guard and error handling to the AI availability
  useEffect in language-view.tsx

- Replace shared pollingCancelledRef boolean with per-invocation Symbol
  token to prevent stale polling loops from clobbering state when the
  modal is reopened

- Track timeout explicitly with a timedOut flag so the "timed out" toast
  doesn't fire when polling was actually cancelled

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 16:01:57 +05:30
pandeymangg 1ed9859ee7 fixes tests 2026-04-22 15:58:02 +05:30
pandeymangg cd72a0a78d adds translations 2026-04-22 15:44:45 +05:30
pandeymangg 2b09795787 feat: adds frd auth to api keys 2026-04-22 15:43:33 +05:30
Dhruwang 2451acb9bd fix: AI translation security, error handling, and test coverage
- Add userId verification in getAITranslationResultAction (security)
- Use OperationNotAllowedError for auth failures
- Store failure marker in cache on last BullMQ attempt
- Make JSON parsing more robust (extract first {...} block)
- Add "keep modal open" hint to translating toast
- Add test coverage for process-ai-translation-job

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 15:18:54 +05:30
Dhruwang 14dcded91b Merge branch 'epic/v5' of https://github.com/formbricks/formbricks into feat/ai-survey-translation 2026-04-22 15:01:12 +05:30
Dhruwang 46062f91cd refactors 2026-04-22 14:50:46 +05:30
Dhruwang Jariwala ffd4478184 chore: merge epic/dashboards into epic/v5 (#7798)
Signed-off-by: gulshank0 <gulshanbahadur002@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Theodór Tómas <theodortomas@gmail.com>
Co-authored-by: Anshuman Pandey <54475686+pandeymangg@users.noreply.github.com>
Co-authored-by: Bhagya Amarasinghe <b.sithumini@yahoo.com>
Co-authored-by: Chowdhury Tafsir Ahmed Siddiki <ctafsiras@gmail.com>
Co-authored-by: neila <40727091+neila@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Tiago <1585571+xernobyl@users.noreply.github.com>
Co-authored-by: Harsh Bhat <90265455+harshsbhat@users.noreply.github.com>
Co-authored-by: Harsh Bhat <harshbhat@Harshs-MacBook-Air.local>
Co-authored-by: Johannes <johannes@formbricks.com>
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
Co-authored-by: Balázs Úr <balazs@urbalazs.hu>
Co-authored-by: Johannes <72809645+jobenjada@users.noreply.github.com>
Co-authored-by: Gulshan <gulshanbahadur002@gmail.com>
Co-authored-by: Tiago Farto <tiago@formbricks.com>
Co-authored-by: Harsh Bhat <harsh121102@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 12:24:05 +04:00
Dhruwang 69da1862fa Merge latest epic/v5 (survey scheduling) into ai-translation branch
Resolve merge conflicts to combine AI translation and survey scheduling
features in jobs package, instrumentation, and tests.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-22 13:39:10 +05:30
Dhruwang c11d3241ab fix: test and translations 2026-04-22 12:59:27 +05:30
Tiago 3fb09a1a26 feat: survey scheduling (#7766) 2026-04-21 15:00:51 +00:00
Dhruwang 6efa449c10 feat: add AI-powered survey translation via BullMQ background jobs
Add a "Translate with AI" button to the Manage Translations modal that
auto-populates empty translation fields using the configured AI provider.
Translation runs as a BullMQ background job with results cached in Redis
and polled by the client.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-21 17:38:47 +05:30
Dhruwang 34b94689ca fix: address CodeRabbit review feedback on docs
- Fix broken API URLs in docs-feedback.mdx (remove /workspaces segment, fix https://, remove stray };)
- Add missing workspaceId path params to v2 spec (responses, displays, user)
- Remove environmentId from required arrays in v2 request schemas
- Fix stale terminology: environment→workspace in database-model, tenant-separation, tags, actions
- Fix broken link to removed test-environment page in webhooks.mdx
- Fix redundant "codebase" in naming-conventions description
- Use neutral hostname in audit-logging example
- Hyphenate "open-source" in license.mdx
- Consistent workspaceId formatting in wordpress.mdx
- Update link text to match anchor in actions.mdx
- Remove dual environmentId/workspaceId in headless-surveys example
- Fix stale <project_id> placeholder in headless-surveys
- Fix awkward Next.js card copy in framework-guides.mdx
- Clarify BC wording in v2 introduction.mdx

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-21 15:35:26 +05:30
Tiago Farto 901fac7e08 chore: fix env vars 2026-04-21 09:56:32 +00:00
Dhruwang 739c662863 chore: merge epic/v5 and resolve openapi.json conflicts
Accept epic/v5 removals (attribute-classes, people endpoints) and
re-apply workspaceId rename + deprecation notes + endpoint cleanup.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-21 15:22:17 +05:30
Dhruwang 535974ff8a fix: align API specs with actual routes and add environment deprecation notes
- Restore v1 openapi.json from main with environmentId→workspaceId rename
- Remove 5 non-existent v1 endpoints and their orphaned MDX pages
- Update v1 descriptions from "environment" to "workspace" terminology
- Add environment deprecation notes to all v1 client API endpoints
- Remove 2 non-existent v2 client endpoints (contacts attributes, identify)
- Rename v2 project-teams → workspace-teams (path, operationIds, schema)
- Preserve environment deprecation notes in v2 spec

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-21 15:15:52 +05:30
Tiago Farto a8b97abe9a Merge remote-tracking branch 'origin/epic/v5' into feat/survey-scheduling
# Conflicts:
#	pnpm-lock.yaml
2026-04-21 09:37:41 +00:00
Johannes 28103604b4 fix: (Depr Env QA) api v1/me regression (#7761)
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
2026-04-21 13:26:01 +04:00
Tiago Farto b5a7e15386 chore: fix build 2026-04-21 09:07:45 +00:00
Tiago Farto fec4746d5d chore: address PR comments 2026-04-21 08:51:32 +00:00
pandeymangg 175323e7d9 chore: merge with main 2026-04-21 14:07:14 +05:30
Tiago Farto 6130737d51 chore: fix DST bug 2026-04-20 16:57:48 +00:00
Tiago Farto bf10a8d0b2 Merge branch 'epic/v5' into feat/survey-scheduling 2026-04-20 16:09:16 +00:00
Tiago Farto 612f8dceb8 chore: fix test 2026-04-20 15:50:38 +00:00
Tiago 0303f16db4 feat: BullMQ background jobs + response pipeline (#7779) 2026-04-20 15:30:20 +00:00
Tiago Farto 07635b160e chore: fix test; migration 2026-04-20 15:13:27 +00:00
Tiago Farto 9cfcffdb5e chore: bug fix; tests 2026-04-20 14:22:06 +00:00
Tiago Farto 02264ffc5f chore: build fix 2026-04-20 13:25:01 +00:00
Tiago Farto 7dde3edd8d chore: fix tests 2026-04-20 12:30:03 +00:00
Dhruwang 730ab6a609 fix: use valid hex colors in styles unit tests
Replace invalid fake hex values (e.g. "#btn-bg", "#headline-color") with
valid hex colors so isLight() and mixColor() don't throw. Add missing
inputTextColor to the survey styling test so --fb-placeholder-color is set.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-20 17:41:19 +05:30
Johannes 4304a7efd6 Rename Projects to Workspaces in docs 2026-04-20 13:56:27 +02:00
Tiago Farto a89d598f8d Merge branch 'epic/bullmq' into feat/survey-scheduling 2026-04-20 11:46:13 +00:00
Tiago Farto 6ff5af712f chore: clean tests 2026-04-20 11:35:47 +00:00
Anshuman Pandey 398ba79e7e feat: ces and csat questions (#7688)
Co-authored-by: Johannes <johannes@formbricks.com>
2026-04-20 15:33:26 +04:00
Dhruwang 4e75a57692 chore: remove legacy styling fields (questionColor, inputColor) for v5
Add a SQL migration that copies legacy coarse-grained styling fields
to granular equivalents (e.g. questionColor → elementHeadlineColor,
inputColor → inputBgColor) and strips the legacy keys from the JSONB.

Remove the runtime deriveNewFieldsFromLegacy() shim, all fallback
chains in CSS variable generation, and update types, schemas, tests,
and OpenAPI spec to reflect the new canonical field names.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-04-20 17:00:20 +05:30
Tiago Farto 5127de9de0 chore: revert CI action 2026-04-20 11:11:09 +00:00
Tiago Farto 2bf7788a1b Merge branch 'epic/bullmq' into feat/survey-scheduling 2026-04-20 11:07:33 +00:00
Tiago Farto ee8122778b chore: address PR comments 2026-04-20 10:43:32 +00:00
Tiago Farto 8aaa7ed9c0 chore: build fix 2026-04-20 10:00:06 +00:00
Johannes bc7c8c5715 remove environment ID andenv references 2026-04-20 11:40:33 +02:00
Dhruwang Jariwala ab1ea7a5ce fix: remove legacy API rewrites from next.config.mjs (#7764)
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
2026-04-20 13:38:30 +04:00
Tiago Farto 4f749355e0 chore: fix coverage test 2026-04-20 09:14:06 +00:00
Tiago Farto 18b60ddd35 chore: fix build 2026-04-20 08:52:59 +00:00
Tiago Farto 87f1b01c7a chore: fix broken tests 2026-04-20 08:40:44 +00:00
Tiago Farto 851ea0deb2 chore: fix broken lock 2026-04-20 08:32:45 +00:00
pandeymangg 9abbbfdd35 chore: merge with main 2026-04-20 13:07:36 +05:30
Johannes 990c0eee31 refined UX 2026-04-19 16:05:29 +02:00
Tiago Farto 07f16b8a43 chore: fix build 2026-04-17 23:23:51 +00:00
Tiago Farto bf556b0608 chore: fix linting 2026-04-17 22:26:57 +00:00
Tiago Farto 8b0766a46e chore: bix fuild 2026-04-17 22:16:17 +00:00
Tiago Farto 1f995d6e25 chore: build fix 2026-04-17 20:05:11 +00:00
Tiago Farto 975a4d57f8 chore: fix build 2026-04-17 19:50:23 +00:00
Tiago Farto 69bd576fc5 chore: fix build 2026-04-17 16:37:22 +00:00
Tiago Farto a2e4a3bbd7 chore: fix build 2026-04-17 16:27:18 +00:00
Tiago Farto 281f854332 chore: address PR comments 2026-04-17 15:36:12 +00:00
Tiago Farto 24496774a5 chore: fix build 2026-04-17 14:57:55 +00:00
Tiago Farto aeaf3215b4 chore: fix 2026-04-17 14:51:51 +00:00
Tiago Farto f4c5162590 Merge epic/bullmq into feat/survey-scheduling 2026-04-17 14:47:05 +00:00
Tiago Farto dedb7389f0 Merge origin/epic/v5 into epic/bullmq 2026-04-17 14:33:21 +00:00
Tiago Farto 7aed1b84de chore: translations, fixes 2026-04-17 11:59:17 +00:00
Bhagya Amarasinghe 9d2e988c59 feat: remove app rate limits for Envoy-covered routes (#7714)
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
2026-04-17 12:43:22 +04:00
Tiago 31d2ea7444 chore: Move Response Pipeline to BullMQ (#7695) 2026-04-15 10:12:41 +03:00
pandeymangg 3da7129413 fixes tests 2026-04-14 17:09:13 +05:30
pandeymangg 75fbb23190 chore: merge with main 2026-04-14 17:01:17 +05:30
Tiago Farto d361c334d3 chore: fixed management snapshot gap 2026-04-13 14:28:31 +03:00
Tiago Farto a4d808b479 chore: build fix 2026-04-13 13:10:33 +03:00
Tiago Farto 18ae1748d3 chore: address PR comments 2026-04-13 12:50:21 +03:00
Dhruwang Jariwala 60f6ca9463 chore: deprecate environments (#7693)
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
Co-authored-by: pandeymangg <anshuman.pandey9999@gmail.com>
2026-04-10 09:13:47 +04:00
Tiago Farto 3404e0c494 chore: fix string date convertion error 2026-04-09 17:14:14 +03:00
Tiago Farto 83499ae552 chore: fix build 2026-04-09 15:14:44 +03:00
Tiago Farto 2ac0c1eb07 chore: refactor 2026-04-09 15:04:31 +03:00
Tiago Farto 54ede3015e chore: fix build 2026-04-09 14:09:46 +03:00
Tiago Farto 1b4f05a062 chore: fix linting issue 2026-04-09 13:59:34 +03:00
Tiago Farto 197dbf5aa6 chore: address pr comments 2026-04-09 13:45:32 +03:00
pandeymangg aa27d242bb chore: merge with main 2026-04-09 15:26:30 +05:30
Tiago 7ca52a7a93 feat: Introduce BullMQ setup to Formbricks (#7684) 2026-04-09 11:47:58 +03:00
Tiago Farto 4a48839d17 Merge branch 'feat/background_workers_v1' into chore/response-to-bullmq 2026-04-09 11:43:30 +03:00
Tiago Farto 92bd9bdac7 chore: address PR comments 2026-04-09 11:26:12 +03:00
Tiago Farto ad4b6f8b8c chore: addressing additional PR comments 2026-04-09 10:39:01 +03:00
Tiago Farto 8de5079db3 chore: lint fix 2026-04-09 10:07:29 +03:00
Tiago Farto a60206dd44 chore: fix sonarqube warnings 2026-04-09 09:59:09 +03:00
Tiago Farto d66abdcdaf chore: refactoring 2026-04-09 09:26:38 +03:00
Tiago Farto 03fa41a911 fix: tighten v2 response validation details typing 2026-04-08 23:23:37 +03:00
Tiago Farto cab438e474 chore: refactor 2026-04-08 21:47:15 +03:00
Tiago Farto a6dfe78c81 fix: restore response pipeline safety guards 2026-04-08 20:47:47 +03:00
Tiago Farto e4d96f4379 fix: resolve jobs runtime type import for web build 2026-04-08 17:16:17 +03:00
Tiago Farto 581a66b4a9 chore: fix problems 2026-04-08 17:00:36 +03:00
Tiago Farto 5cf0c15812 chore: response to bullmq 2026-04-08 14:43:50 +03:00
Tiago Farto ebaa2d363c chore: fix flaky test 2026-04-08 10:25:48 +03:00
Tiago Farto 597ea40b75 chore: fix linting issues 2026-04-08 10:16:24 +03:00
Tiago Farto 3c39dcc2de chore: increased test coverage 2026-04-08 09:51:58 +03:00
Tiago Farto e8df1dbb35 chore: fix sonarqube warning 2026-04-07 22:15:10 +03:00
Tiago Farto 84987ce557 chore: linter fixes 2026-04-07 21:42:23 +03:00
Tiago Farto 784ed855d7 chore: additional tests; address PR comments 2026-04-07 21:14:52 +03:00
Tiago Farto 5a17d4144d fix: normalize storage result typing for web build 2026-04-07 19:07:15 +03:00
Tiago Farto 65c9db86c6 fix: separate storage type exports and imports 2026-04-07 18:04:27 +03:00
Tiago Farto bc94d34d1e fix: narrow storage route results by property 2026-04-07 17:41:13 +03:00
Tiago Farto 22be60a0ba fix: align storage type exports for web build 2026-04-07 17:18:53 +03:00
Tiago Farto a384963863 fix: type storage delete wrappers 2026-04-07 16:34:51 +03:00
Tiago Farto c067ae73bb fix: narrow storage delete result in route 2026-04-07 16:25:36 +03:00
Tiago Farto dc78a30cbe fix: repair pnpm lockfile for BullMQ branch 2026-04-07 16:13:17 +03:00
Tiago Farto 9c9ae8a3a2 test: fix env test on v5 branch 2026-04-07 16:01:21 +03:00
Tiago Farto 29a08151aa chore: addressed PR concerns 2026-04-07 15:59:20 +03:00
Tiago Farto f42a8822a9 chore: background workers trough bullMQ 2026-04-07 15:56:12 +03:00
Dhruwang Jariwala a771ae189a refactor: rename Project to Workspace across entire codebase (#7620) 2026-03-31 17:01:17 +05:30
Anshuman Pandey 029e069af6 feat: feedback record directories (#7592) 2026-03-27 04:18:20 -07:00
Matti Nannt 81272b96e1 feat: port hub xm-suite config to epic/v5 (#7578) 2026-03-25 11:04:42 +00:00
59 changed files with 6430 additions and 800 deletions
+4 -6
View File
@@ -76,12 +76,10 @@ HUB_DATABASE_URL=postgresql://postgres:postgres@postgres:5432/hub?sslmode=disabl
# EMBEDDING_MODEL=gemini-embedding-001
# EMBEDDING_PROVIDER_API_KEY=
###########################
# CUBE ANALYTICS (XM V5) #
###########################
# XM Suite v5 analysis features require Cube.js. The optional xm dev profile exposes Cube on port 4000.
# Uncomment COMPOSE_PROFILES=xm to run the optional Cube analytics service.
# COMPOSE_PROFILES=xm
####################
# CUBE ANALYTICS #
####################
# Cube semantic-layer API. Required. The bundled Docker stack exposes Cube on port 4000.
CUBEJS_API_URL=http://localhost:4000
# Generate with: openssl rand -hex 32. `pnpm dev:setup` will create/preserve this automatically.
CUBEJS_API_SECRET=
@@ -1,10 +0,0 @@
import { redirect } from "next/navigation";
import { completeAccountDeletionSsoIdentityConfirmationAndGetRedirectPath } from "./lib/account-deletion-sso-complete";
export default async function AccountDeletionSsoConfirmationCompletePage({
searchParams,
}: {
searchParams: Promise<{ intent?: string | string[] }>;
}) {
redirect(await completeAccountDeletionSsoIdentityConfirmationAndGetRedirectPath(await searchParams));
}
@@ -0,0 +1,20 @@
import { type NextRequest, NextResponse } from "next/server";
import { completeAccountDeletionSsoIdentityConfirmationAndGetRedirectPath } from "./lib/account-deletion-sso-complete";
const getIntentSearchParam = (request: NextRequest): string | string[] | undefined => {
const intentValues = request.nextUrl.searchParams.getAll("intent");
if (intentValues.length === 0) {
return undefined;
}
return intentValues.length === 1 ? intentValues[0] : intentValues;
};
export const GET = async (request: NextRequest) => {
const redirectPath = await completeAccountDeletionSsoIdentityConfirmationAndGetRedirectPath({
intent: getIntentSearchParam(request),
});
return NextResponse.redirect(new URL(redirectPath, request.url));
};
@@ -12,7 +12,7 @@ import { applyRateLimit } from "@/modules/core/rate-limit/helpers";
import { rateLimitConfigs } from "@/modules/core/rate-limit/rate-limit-configs";
import { getBiggerUploadFileSizePermission } from "@/modules/ee/license-check/lib/utils";
import { getSignedUrlForUpload } from "@/modules/storage/service";
import { getErrorResponseFromStorageError } from "@/modules/storage/utils";
import { getErrorResponseFromStorageError, validateSurveyAllowsFileUpload } from "@/modules/storage/utils";
export const OPTIONS = async (): Promise<Response> => {
return responses.successResponse(
@@ -107,6 +107,23 @@ export const POST = withV1ApiWrapper({
};
}
const fileUploadPermission = validateSurveyAllowsFileUpload({
fileName,
blocks: survey.blocks,
questions: survey.questions,
});
if (!fileUploadPermission.ok) {
return {
response: responses.badRequestResponse(
fileUploadPermission.reason === "no_file_upload_question"
? "Survey does not allow file uploads"
: "File extension is not allowed for this survey",
undefined
),
};
}
const isBiggerFileUploadAllowed = await getBiggerUploadFileSizePermission(organization.id);
const maxFileUploadSize = isBiggerFileUploadAllowed
? MAX_FILE_UPLOAD_SIZES.big
+1 -1
View File
@@ -135,7 +135,7 @@ describe("withV3ApiWrapper", () => {
apiKeyId: "key_1",
organizationId: "org_1",
organizationAccess: { accessControl: { read: true, write: true } },
environmentPermissions: [],
workspacePermissions: [],
});
const wrapped = withV3ApiWrapper({
+13 -13
View File
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
import { AuthorizationError } from "@formbricks/types/errors";
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
import { getOrganizationIdFromWorkspaceId } from "@/lib/utils/helper";
import { findWorkspaceByIdOrLegacyEnvId } from "@/lib/utils/resolve-client-id";
import { getWorkspace } from "@/lib/workspace/service";
import { requireSessionWorkspaceAccess, requireV3WorkspaceAccess } from "./auth";
vi.mock("@formbricks/logger", () => ({
@@ -19,8 +19,8 @@ vi.mock("@/lib/utils/helper", () => ({
getOrganizationIdFromWorkspaceId: vi.fn(),
}));
vi.mock("@/lib/utils/resolve-client-id", () => ({
findWorkspaceByIdOrLegacyEnvId: vi.fn(),
vi.mock("@/lib/workspace/service", () => ({
getWorkspace: vi.fn(),
}));
vi.mock("@/lib/utils/action-client/action-client-middleware", () => ({
@@ -39,7 +39,7 @@ describe("requireSessionWorkspaceAccess", () => {
expect(body.requestId).toBe(requestId);
expect(body.status).toBe(401);
expect(body.code).toBe("not_authenticated");
expect(findWorkspaceByIdOrLegacyEnvId).not.toHaveBeenCalled();
expect(getWorkspace).not.toHaveBeenCalled();
expect(checkAuthorizationUpdated).not.toHaveBeenCalled();
});
@@ -55,11 +55,11 @@ describe("requireSessionWorkspaceAccess", () => {
const body = await (result as Response).json();
expect(body.requestId).toBe(requestId);
expect(body.code).toBe("not_authenticated");
expect(findWorkspaceByIdOrLegacyEnvId).not.toHaveBeenCalled();
expect(getWorkspace).not.toHaveBeenCalled();
});
test("returns 403 when workspace is not found (avoid leaking existence)", async () => {
vi.mocked(findWorkspaceByIdOrLegacyEnvId).mockResolvedValueOnce(null);
vi.mocked(getWorkspace).mockResolvedValueOnce(null);
const result = await requireSessionWorkspaceAccess(
{ user: { id: "user_1" }, expires: "" } as any,
"ws_nonexistent",
@@ -72,12 +72,12 @@ describe("requireSessionWorkspaceAccess", () => {
const body = await (result as Response).json();
expect(body.requestId).toBe(requestId);
expect(body.code).toBe("forbidden");
expect(findWorkspaceByIdOrLegacyEnvId).toHaveBeenCalledWith("ws_nonexistent");
expect(getWorkspace).toHaveBeenCalledWith("ws_nonexistent");
expect(checkAuthorizationUpdated).not.toHaveBeenCalled();
});
test("returns 403 when user has no access to workspace", async () => {
vi.mocked(findWorkspaceByIdOrLegacyEnvId).mockResolvedValueOnce({ id: "proj_abc" });
vi.mocked(getWorkspace).mockResolvedValueOnce({ id: "proj_abc" } as any);
vi.mocked(getOrganizationIdFromWorkspaceId).mockResolvedValueOnce("org_1");
vi.mocked(checkAuthorizationUpdated).mockRejectedValueOnce(new AuthorizationError("Not authorized"));
const result = await requireSessionWorkspaceAccess(
@@ -102,7 +102,7 @@ describe("requireSessionWorkspaceAccess", () => {
});
test("returns workspace context when session is valid and user has access", async () => {
vi.mocked(findWorkspaceByIdOrLegacyEnvId).mockResolvedValueOnce({ id: "proj_abc" });
vi.mocked(getWorkspace).mockResolvedValueOnce({ id: "proj_abc" } as any);
vi.mocked(getOrganizationIdFromWorkspaceId).mockResolvedValueOnce("org_1");
vi.mocked(checkAuthorizationUpdated).mockResolvedValueOnce(undefined as any);
const result = await requireSessionWorkspaceAccess(
@@ -144,7 +144,7 @@ function wsPerm(workspaceId: string, permission: ApiKeyPermission = ApiKeyPermis
describe("requireV3WorkspaceAccess", () => {
beforeEach(() => {
vi.mocked(findWorkspaceByIdOrLegacyEnvId).mockResolvedValue({ id: "proj_k" });
vi.mocked(getWorkspace).mockResolvedValue({ id: "proj_k" } as any);
vi.mocked(getOrganizationIdFromWorkspaceId).mockResolvedValue("org_k");
});
@@ -154,7 +154,7 @@ describe("requireV3WorkspaceAccess", () => {
});
test("delegates to session flow when user is present", async () => {
vi.mocked(findWorkspaceByIdOrLegacyEnvId).mockResolvedValueOnce({ id: "proj_s" });
vi.mocked(getWorkspace).mockResolvedValueOnce({ id: "proj_s" } as any);
vi.mocked(getOrganizationIdFromWorkspaceId).mockResolvedValueOnce("org_s");
vi.mocked(checkAuthorizationUpdated).mockResolvedValueOnce(undefined as any);
const r = await requireV3WorkspaceAccess(
@@ -179,7 +179,7 @@ describe("requireV3WorkspaceAccess", () => {
workspaceId: "proj_k",
organizationId: "org_k",
});
expect(findWorkspaceByIdOrLegacyEnvId).toHaveBeenCalledWith("proj_k");
expect(getWorkspace).toHaveBeenCalledWith("proj_k");
});
test("returns context for API key with write on workspace", async () => {
@@ -239,7 +239,7 @@ describe("requireV3WorkspaceAccess", () => {
});
test("returns 403 when the workspace cannot be resolved for an API key", async () => {
vi.mocked(findWorkspaceByIdOrLegacyEnvId).mockResolvedValueOnce(null);
vi.mocked(getWorkspace).mockResolvedValueOnce(null);
const auth = {
...keyBase,
workspacePermissions: [wsPerm("proj_k", ApiKeyPermission.manage)],
+33
View File
@@ -1,5 +1,7 @@
import { describe, expect, test } from "vitest";
import {
createdResponse,
noContentResponse,
problemBadRequest,
problemForbidden,
problemInternalError,
@@ -118,3 +120,34 @@ describe("successResponse", () => {
expect(res.headers.get("Cache-Control")).toBe("private, max-age=60");
});
});
describe("createdResponse", () => {
test("returns 201 with Location, request id, and data envelope", async () => {
const res = createdResponse(
{ id: "survey_1" },
{
location: "/api/v3/surveys/survey_1",
requestId: "req-created",
}
);
expect(res.status).toBe(201);
expect(res.headers.get("Location")).toBe("/api/v3/surveys/survey_1");
expect(res.headers.get("X-Request-Id")).toBe("req-created");
expect(res.headers.get("Content-Type")).toBe("application/json");
expect(res.headers.get("Cache-Control")).toContain("no-store");
expect(await res.json()).toEqual({
data: { id: "survey_1" },
});
});
});
describe("noContentResponse", () => {
test("returns 204 without a body", async () => {
const res = noContentResponse({ requestId: "req-empty" });
expect(res.status).toBe(204);
expect(res.headers.get("X-Request-Id")).toBe("req-empty");
expect(res.headers.get("Cache-Control")).toContain("no-store");
expect(await res.text()).toBe("");
});
});
+40
View File
@@ -171,3 +171,43 @@ export function successResponse<T>(
}
);
}
export function createdResponse<T>(
data: T,
options: { location: string; requestId?: string; cache?: string }
): Response {
const headers: Record<string, string> = {
"Content-Type": "application/json",
"Cache-Control": options.cache ?? CACHE_NO_STORE,
Location: options.location,
};
if (options.requestId) {
headers["X-Request-Id"] = options.requestId;
}
return Response.json(
{
data,
},
{
status: 201,
headers,
}
);
}
export function noContentResponse(options?: { requestId?: string; cache?: string }): Response {
const headers: Record<string, string> = {
"Cache-Control": options?.cache ?? CACHE_NO_STORE,
};
if (options?.requestId) {
headers["X-Request-Id"] = options.requestId;
}
return new Response(null, {
status: 204,
headers,
});
}
@@ -1,45 +1,34 @@
import { describe, expect, test, vi } from "vitest";
import { ResourceNotFoundError } from "@formbricks/types/errors";
import { getOrganizationIdFromWorkspaceId } from "@/lib/utils/helper";
import { findWorkspaceByIdOrLegacyEnvId } from "@/lib/utils/resolve-client-id";
import { getWorkspace } from "@/lib/workspace/service";
import { resolveV3WorkspaceContext } from "./workspace-context";
vi.mock("@/lib/workspace/service", () => ({
getWorkspace: vi.fn(),
}));
vi.mock("@/lib/utils/helper", () => ({
getOrganizationIdFromWorkspaceId: vi.fn(),
}));
vi.mock("@/lib/utils/resolve-client-id", () => ({
findWorkspaceByIdOrLegacyEnvId: vi.fn(),
}));
describe("resolveV3WorkspaceContext", () => {
test("returns workspaceId and organizationId when workspace exists", async () => {
vi.mocked(findWorkspaceByIdOrLegacyEnvId).mockResolvedValueOnce({ id: "ws_abc" });
vi.mocked(getWorkspace).mockResolvedValueOnce({ id: "ws_abc" });
vi.mocked(getOrganizationIdFromWorkspaceId).mockResolvedValueOnce("org_123");
const result = await resolveV3WorkspaceContext("ws_abc");
expect(result).toEqual({
workspaceId: "ws_abc",
organizationId: "org_123",
});
expect(findWorkspaceByIdOrLegacyEnvId).toHaveBeenCalledWith("ws_abc");
expect(getWorkspace).toHaveBeenCalledWith("ws_abc");
expect(getOrganizationIdFromWorkspaceId).toHaveBeenCalledWith("ws_abc");
});
test("resolves legacy environmentId to canonical workspaceId", async () => {
vi.mocked(findWorkspaceByIdOrLegacyEnvId).mockResolvedValueOnce({ id: "ws_canonical" });
vi.mocked(getOrganizationIdFromWorkspaceId).mockResolvedValueOnce("org_456");
const result = await resolveV3WorkspaceContext("env_legacy");
expect(result).toEqual({
workspaceId: "ws_canonical",
organizationId: "org_456",
});
expect(getOrganizationIdFromWorkspaceId).toHaveBeenCalledWith("ws_canonical");
});
test("throws when workspace does not exist", async () => {
vi.mocked(findWorkspaceByIdOrLegacyEnvId).mockResolvedValueOnce(null);
vi.mocked(getWorkspace).mockResolvedValueOnce(null);
await expect(resolveV3WorkspaceContext("ws_nonexistent")).rejects.toThrow(ResourceNotFoundError);
expect(findWorkspaceByIdOrLegacyEnvId).toHaveBeenCalledWith("ws_nonexistent");
expect(getWorkspace).toHaveBeenCalledWith("ws_nonexistent");
expect(getOrganizationIdFromWorkspaceId).not.toHaveBeenCalled();
});
});
+5 -6
View File
@@ -6,7 +6,7 @@
*/
import { ResourceNotFoundError } from "@formbricks/types/errors";
import { getOrganizationIdFromWorkspaceId } from "@/lib/utils/helper";
import { findWorkspaceByIdOrLegacyEnvId } from "@/lib/utils/resolve-client-id";
import { getWorkspace } from "@/lib/workspace/service";
/**
* Internal IDs derived from a V3 workspace identifier.
@@ -19,21 +19,20 @@ export type V3WorkspaceContext = {
};
/**
* Resolves a V3 API workspaceId (or legacy environmentId) to internal workspaceId and organizationId.
* Resolves a V3 API workspaceId to internal workspaceId and organizationId.
*
* @throws ResourceNotFoundError if the workspace does not exist.
*/
export async function resolveV3WorkspaceContext(workspaceId: string): Promise<V3WorkspaceContext> {
const workspace = await findWorkspaceByIdOrLegacyEnvId(workspaceId);
const workspace = await getWorkspace(workspaceId);
if (!workspace) {
throw new ResourceNotFoundError("workspace", workspaceId);
}
const canonicalId = workspace.id;
const organizationId = await getOrganizationIdFromWorkspaceId(canonicalId);
const organizationId = await getOrganizationIdFromWorkspaceId(workspace.id);
return {
workspaceId: canonicalId,
workspaceId: workspace.id,
organizationId,
};
}
@@ -1,318 +0,0 @@
import { ApiKeyPermission } from "@prisma/client";
import { NextRequest } from "next/server";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { DatabaseError, ResourceNotFoundError } from "@formbricks/types/errors";
import { requireV3WorkspaceAccess } from "@/app/api/v3/lib/auth";
import { getSurvey } from "@/lib/survey/service";
import { deleteSurvey } from "@/modules/survey/lib/surveys";
import { DELETE } from "./route";
const { mockAuthenticateRequest } = vi.hoisted(() => ({
mockAuthenticateRequest: vi.fn(),
}));
const { mockQueueAuditEvent, mockBuildAuditLogBaseObject } = vi.hoisted(() => ({
mockQueueAuditEvent: vi.fn().mockImplementation(async () => undefined),
mockBuildAuditLogBaseObject: vi.fn((action: string, targetType: string, apiUrl: string) => ({
action,
targetType,
userId: "unknown",
targetId: "unknown",
organizationId: "unknown",
status: "failure",
oldObject: undefined,
newObject: undefined,
userType: "api",
apiUrl,
})),
}));
vi.mock("next-auth", () => ({
getServerSession: vi.fn(),
}));
vi.mock("@/app/api/v1/auth", async (importOriginal) => {
const actual = await importOriginal<typeof import("@/app/api/v1/auth")>();
return { ...actual, authenticateRequest: mockAuthenticateRequest };
});
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", () => ({
requireV3WorkspaceAccess: vi.fn(),
}));
vi.mock("@/lib/survey/service", () => ({
getSurvey: vi.fn(),
}));
vi.mock("@/modules/survey/lib/surveys", () => ({
deleteSurvey: vi.fn(),
}));
vi.mock("@/modules/ee/audit-logs/lib/handler", () => ({
queueAuditEvent: mockQueueAuditEvent,
}));
vi.mock("@/app/lib/api/with-api-logging", () => ({
buildAuditLogBaseObject: mockBuildAuditLogBaseObject,
}));
vi.mock("@formbricks/logger", () => ({
logger: {
withContext: vi.fn(() => ({
warn: vi.fn(),
error: vi.fn(),
})),
},
}));
const getServerSession = vi.mocked((await import("next-auth")).getServerSession);
const queueAuditEvent = vi.mocked((await import("@/modules/ee/audit-logs/lib/handler")).queueAuditEvent);
const surveyId = "clxx1234567890123456789012";
const workspaceId = "clzz9876543210987654321098";
function createRequest(url: string, requestId?: string, extraHeaders?: Record<string, string>): NextRequest {
const headers: Record<string, string> = { ...extraHeaders };
if (requestId) {
headers["x-request-id"] = requestId;
}
return new NextRequest(url, {
method: "DELETE",
headers,
});
}
const apiKeyAuth = {
type: "apiKey" as const,
apiKeyId: "key_1",
organizationId: "org_1",
organizationAccess: {
accessControl: { read: true, write: true },
},
workspacePermissions: [
{
workspaceId,
workspaceName: "W",
permission: ApiKeyPermission.write,
},
],
};
describe("DELETE /api/v3/surveys/[surveyId]", () => {
beforeEach(() => {
vi.resetAllMocks();
getServerSession.mockResolvedValue({
user: { id: "user_1", name: "User", email: "u@example.com" },
expires: "2026-01-01",
} as any);
mockAuthenticateRequest.mockResolvedValue(null);
vi.mocked(getSurvey).mockResolvedValue({
id: surveyId,
name: "Delete me",
workspaceId: workspaceId,
type: "link",
status: "draft",
createdAt: new Date("2026-04-15T10:00:00.000Z"),
updatedAt: new Date("2026-04-15T10:00:00.000Z"),
responseCount: 0,
creator: { name: "User" },
singleUse: null,
} as any);
vi.mocked(deleteSurvey).mockResolvedValue({
id: surveyId,
workspaceId,
type: "link",
segment: null,
triggers: [],
} as any);
vi.mocked(requireV3WorkspaceAccess).mockResolvedValue({
workspaceId,
organizationId: "org_1",
});
});
afterEach(() => {
vi.clearAllMocks();
});
test("returns 401 when no session and no API key", async () => {
getServerSession.mockResolvedValue(null);
mockAuthenticateRequest.mockResolvedValue(null);
const res = await DELETE(createRequest(`http://localhost/api/v3/surveys/${surveyId}`), {
params: Promise.resolve({ surveyId }),
} as never);
expect(res.status).toBe(401);
expect(vi.mocked(getSurvey)).not.toHaveBeenCalled();
});
test("returns 200 with session auth and deletes the survey", async () => {
const res = await DELETE(createRequest(`http://localhost/api/v3/surveys/${surveyId}`, "req-delete"), {
params: Promise.resolve({ surveyId }),
} as never);
expect(res.status).toBe(200);
expect(requireV3WorkspaceAccess).toHaveBeenCalledWith(
expect.objectContaining({ user: expect.any(Object) }),
workspaceId,
"readWrite",
"req-delete",
`/api/v3/surveys/${surveyId}`
);
expect(deleteSurvey).toHaveBeenCalledWith(surveyId);
expect(await res.json()).toEqual({
data: {
id: surveyId,
},
});
});
test("returns 200 with x-api-key when the key can delete in the survey workspace", async () => {
getServerSession.mockResolvedValue(null);
mockAuthenticateRequest.mockResolvedValue(apiKeyAuth as any);
const res = await DELETE(
createRequest(`http://localhost/api/v3/surveys/${surveyId}`, "req-api-key", {
"x-api-key": "fbk_test",
}),
{
params: Promise.resolve({ surveyId }),
} as never
);
expect(res.status).toBe(200);
expect(requireV3WorkspaceAccess).toHaveBeenCalledWith(
expect.objectContaining({ apiKeyId: "key_1" }),
workspaceId,
"readWrite",
"req-api-key",
`/api/v3/surveys/${surveyId}`
);
});
test("returns 400 when surveyId is invalid", async () => {
const res = await DELETE(createRequest("http://localhost/api/v3/surveys/not-a-cuid"), {
params: Promise.resolve({ surveyId: "not-a-cuid" }),
} as never);
expect(res.status).toBe(400);
expect(vi.mocked(getSurvey)).not.toHaveBeenCalled();
});
test("returns 403 when the survey does not exist", async () => {
vi.mocked(getSurvey).mockResolvedValueOnce(null);
const res = await DELETE(createRequest(`http://localhost/api/v3/surveys/${surveyId}`), {
params: Promise.resolve({ surveyId }),
} as never);
expect(res.status).toBe(403);
expect(deleteSurvey).not.toHaveBeenCalled();
});
test("returns 403 when the user lacks readWrite workspace access", async () => {
vi.mocked(requireV3WorkspaceAccess).mockResolvedValueOnce(
new Response(
JSON.stringify({
title: "Forbidden",
status: 403,
detail: "You are not authorized to access this resource",
requestId: "req-forbidden",
}),
{ status: 403, headers: { "Content-Type": "application/problem+json" } }
)
);
const res = await DELETE(createRequest(`http://localhost/api/v3/surveys/${surveyId}`, "req-forbidden"), {
params: Promise.resolve({ surveyId }),
} as never);
expect(res.status).toBe(403);
expect(deleteSurvey).not.toHaveBeenCalled();
expect(queueAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
action: "deleted",
targetType: "survey",
targetId: "unknown",
organizationId: "unknown",
userId: "user_1",
userType: "user",
status: "failure",
oldObject: undefined,
})
);
});
test("returns 500 when survey deletion fails", async () => {
vi.mocked(deleteSurvey).mockRejectedValueOnce(new DatabaseError("db down"));
const res = await DELETE(createRequest(`http://localhost/api/v3/surveys/${surveyId}`, "req-db"), {
params: Promise.resolve({ surveyId }),
} as never);
expect(res.status).toBe(500);
const body = await res.json();
expect(body.code).toBe("internal_server_error");
});
test("returns 403 when the survey is deleted after authorization succeeds", async () => {
vi.mocked(deleteSurvey).mockRejectedValueOnce(new ResourceNotFoundError("Survey", surveyId));
const res = await DELETE(createRequest(`http://localhost/api/v3/surveys/${surveyId}`, "req-race"), {
params: Promise.resolve({ surveyId }),
} as never);
expect(res.status).toBe(403);
const body = await res.json();
expect(body.code).toBe("forbidden");
expect(queueAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
action: "deleted",
targetType: "survey",
targetId: surveyId,
organizationId: "org_1",
userId: "user_1",
userType: "user",
status: "failure",
oldObject: expect.objectContaining({
id: surveyId,
workspaceId: workspaceId,
}),
})
);
});
test("queues an audit log with target, actor, organization, and old object", async () => {
await DELETE(createRequest(`http://localhost/api/v3/surveys/${surveyId}`, "req-audit"), {
params: Promise.resolve({ surveyId }),
} as never);
expect(queueAuditEvent).toHaveBeenCalledWith(
expect.objectContaining({
action: "deleted",
targetType: "survey",
targetId: surveyId,
organizationId: "org_1",
userId: "user_1",
userType: "user",
status: "success",
oldObject: expect.objectContaining({
id: surveyId,
workspaceId: workspaceId,
}),
})
);
});
});
+120 -27
View File
@@ -2,42 +2,140 @@ import { z } from "zod";
import { logger } from "@formbricks/logger";
import { DatabaseError, ResourceNotFoundError } from "@formbricks/types/errors";
import { withV3ApiWrapper } from "@/app/api/v3/lib/api-wrapper";
import { requireV3WorkspaceAccess } from "@/app/api/v3/lib/auth";
import { problemForbidden, problemInternalError, successResponse } from "@/app/api/v3/lib/response";
import { getSurvey } from "@/lib/survey/service";
import {
noContentResponse,
problemBadRequest,
problemForbidden,
problemInternalError,
successResponse,
} from "@/app/api/v3/lib/response";
import {
V3SurveyLanguageError,
V3SurveyUnsupportedShapeError,
serializeV3SurveyResource,
} from "@/app/api/v3/surveys/serializers";
import { deleteSurvey } from "@/modules/survey/lib/surveys";
import { getAuthorizedV3Survey } from "../authorization";
import { parseV3SurveyLanguageQuery } from "../language";
const surveyParamsSchema = z.object({
surveyId: z.cuid2(),
});
const surveyQuerySchema = z
.object({
lang: z
.union([z.string(), z.array(z.string())])
.transform((value, ctx) => {
const parsedLanguageQuery = parseV3SurveyLanguageQuery(value);
if (!parsedLanguageQuery.ok) {
ctx.addIssue({
code: "custom",
message: parsedLanguageQuery.message,
});
return z.NEVER;
}
return parsedLanguageQuery.languages;
})
.optional(),
})
.strict();
export const GET = withV3ApiWrapper({
auth: "both",
schemas: {
params: surveyParamsSchema,
query: surveyQuerySchema,
},
handler: async ({ parsedInput, authentication, requestId, instance }) => {
const surveyId = parsedInput.params.surveyId;
const log = logger.withContext({ requestId, surveyId });
try {
const { survey, response } = await getAuthorizedV3Survey({
surveyId,
authentication,
access: "read",
requestId,
instance,
});
if (response) {
log.warn({ statusCode: response.status }, "Survey not found or not accessible");
return response;
}
try {
return successResponse(serializeV3SurveyResource(survey, { lang: parsedInput.query.lang }), {
requestId,
cache: "private, no-store",
});
} catch (error) {
if (error instanceof V3SurveyLanguageError) {
log.warn({ statusCode: 400, lang: parsedInput.query.lang }, "Invalid survey language selector");
return problemBadRequest(requestId, error.message, {
instance,
invalid_params: [
{
name: "lang",
reason: error.message,
},
],
});
}
if (error instanceof V3SurveyUnsupportedShapeError) {
log.warn({ statusCode: 400 }, "Unsupported v3 survey shape");
return problemBadRequest(requestId, error.message, {
instance,
invalid_params: [
{
name: "survey",
reason: error.message,
},
],
});
}
throw error;
}
} catch (error) {
if (error instanceof DatabaseError) {
log.error({ error, statusCode: 500 }, "Database error");
return problemInternalError(requestId, "An unexpected error occurred.", instance);
}
log.error({ error, statusCode: 500 }, "V3 survey get unexpected error");
return problemInternalError(requestId, "An unexpected error occurred.", instance);
}
},
});
export const DELETE = withV3ApiWrapper({
auth: "both",
action: "deleted",
targetType: "survey",
schemas: {
params: z.object({
surveyId: z.cuid2(),
}),
params: surveyParamsSchema,
},
handler: async ({ parsedInput, authentication, requestId, instance, auditLog }) => {
const surveyId = parsedInput.params.surveyId;
const log = logger.withContext({ requestId, surveyId });
try {
const survey = await getSurvey(surveyId);
if (!survey) {
log.warn({ statusCode: 403 }, "Survey not found or not accessible");
return problemForbidden(requestId, "You are not authorized to access this resource", instance);
}
const authResult = await requireV3WorkspaceAccess(
const { survey, authResult, response } = await getAuthorizedV3Survey({
surveyId,
authentication,
survey.workspaceId,
"readWrite",
access: "readWrite",
requestId,
instance
);
instance,
});
if (authResult instanceof Response) {
return authResult;
if (response) {
log.warn({ statusCode: 403 }, "Survey not found or not accessible");
return response;
}
if (auditLog) {
@@ -46,14 +144,9 @@ export const DELETE = withV3ApiWrapper({
auditLog.oldObject = survey;
}
const deletedSurvey = await deleteSurvey(surveyId);
await deleteSurvey(surveyId);
return successResponse(
{
id: deletedSurvey.id,
},
{ requestId }
);
return noContentResponse({ requestId });
} catch (error) {
if (error instanceof ResourceNotFoundError) {
log.warn({ errorCode: error.name, statusCode: 403 }, "Survey not found or not accessible");
@@ -0,0 +1,71 @@
import { describe, expect, test, vi } from "vitest";
import { requireV3WorkspaceAccess } from "@/app/api/v3/lib/auth";
import { getSurvey } from "@/lib/survey/service";
import { getAuthorizedV3Survey } from "./authorization";
vi.mock("@/app/api/v3/lib/auth", () => ({
requireV3WorkspaceAccess: vi.fn(),
}));
vi.mock("@/lib/survey/service", () => ({
getSurvey: vi.fn(),
}));
const survey = {
id: "clsv1234567890123456789012",
workspaceId: "clxx1234567890123456789012",
};
const surveyRecord = survey as unknown as NonNullable<Awaited<ReturnType<typeof getSurvey>>>;
describe("getAuthorizedV3Survey", () => {
test("returns a generic forbidden response when the survey does not exist", async () => {
vi.mocked(getSurvey).mockResolvedValue(null);
const result = await getAuthorizedV3Survey({
surveyId: survey.id,
authentication: null,
access: "read",
requestId: "req_1",
instance: "/api/v3/surveys/clsv1234567890123456789012",
});
expect(result.response?.status).toBe(403);
expect(requireV3WorkspaceAccess).not.toHaveBeenCalled();
});
test("returns the authorization response when workspace access is denied", async () => {
const forbiddenResponse = new Response(null, { status: 403 });
vi.mocked(getSurvey).mockResolvedValue(surveyRecord);
vi.mocked(requireV3WorkspaceAccess).mockResolvedValue(forbiddenResponse);
const result = await getAuthorizedV3Survey({
surveyId: survey.id,
authentication: null,
access: "readWrite",
requestId: "req_2",
instance: "/api/v3/surveys/clsv1234567890123456789012",
});
expect(result.response).toBe(forbiddenResponse);
});
test("returns the survey and authorization context when access is allowed", async () => {
const authResult = { workspaceId: survey.workspaceId, organizationId: "org_1" };
vi.mocked(getSurvey).mockResolvedValue(surveyRecord);
vi.mocked(requireV3WorkspaceAccess).mockResolvedValue(authResult);
const result = await getAuthorizedV3Survey({
surveyId: survey.id,
authentication: null,
access: "read",
requestId: "req_3",
instance: "/api/v3/surveys/clsv1234567890123456789012",
});
expect(result).toEqual({
survey,
authResult,
response: null,
});
});
});
@@ -0,0 +1,37 @@
import { requireV3WorkspaceAccess } from "@/app/api/v3/lib/auth";
import { problemForbidden } from "@/app/api/v3/lib/response";
import type { TV3Authentication } from "@/app/api/v3/lib/types";
import { getSurvey } from "@/lib/survey/service";
export async function getAuthorizedV3Survey(params: {
surveyId: string;
authentication: TV3Authentication;
access: "read" | "readWrite";
requestId: string;
instance: string;
}) {
const { surveyId, authentication, access, requestId, instance } = params;
const survey = await getSurvey(surveyId);
if (!survey) {
return {
survey: null,
authResult: null,
response: problemForbidden(requestId, "You are not authorized to access this resource", instance),
};
}
const authResult = await requireV3WorkspaceAccess(
authentication,
survey.workspaceId,
access,
requestId,
instance
);
if (authResult instanceof Response) {
return { survey: null, authResult: null, response: authResult };
}
return { survey, authResult, response: null };
}
+241
View File
@@ -0,0 +1,241 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { prisma } from "@formbricks/database";
import type { TSurvey } from "@formbricks/types/surveys/types";
import { getOrganizationByWorkspaceId } from "@/lib/organization/service";
import { createSurvey } from "@/lib/survey/service";
import { getExternalUrlsPermission } from "@/modules/survey/lib/permission";
import { V3SurveyCreatePermissionError, createV3Survey } from "./create";
import { ZV3CreateSurveyBody } from "./schemas";
vi.mock("server-only", () => ({}));
vi.mock("@formbricks/database", () => ({
prisma: {
language: {
upsert: vi.fn(),
},
},
}));
vi.mock("@/lib/survey/service", () => ({
createSurvey: vi.fn(),
}));
vi.mock("@/lib/organization/service", () => ({
getOrganizationByWorkspaceId: vi.fn(),
}));
vi.mock("@/modules/survey/lib/permission", () => ({
getExternalUrlsPermission: vi.fn(),
}));
vi.mock("@formbricks/logger", () => ({
logger: {
withContext: vi.fn(() => ({
error: vi.fn(),
warn: vi.fn(),
})),
},
}));
const workspaceId = "clxx1234567890123456789012";
const rawCreateBody = {
workspaceId,
name: "Product Feedback",
defaultLanguage: "en-US",
metadata: {
cx_operation: "enterprise_onboarding",
title: { "en-US": "Product Feedback", "de-DE": "Produktfeedback" },
},
blocks: [
{
id: "clbk1234567890123456789012",
name: "Main Block",
elements: [
{
id: "satisfaction",
type: "openText",
headline: {
"en-US": "What should we improve?",
"de-DE": "Was sollen wir verbessern?",
},
required: true,
},
],
},
],
};
const createBody = ZV3CreateSurveyBody.parse(rawCreateBody);
const createdSurvey = {
id: "clsv1234567890123456789012",
workspaceId,
createdAt: new Date("2026-04-21T10:00:00.000Z"),
updatedAt: new Date("2026-04-21T10:00:00.000Z"),
name: "Product Feedback",
type: "link",
status: "draft",
metadata: {},
languages: [],
questions: [],
welcomeCard: { enabled: false },
blocks: createBody.blocks,
endings: [],
hiddenFields: { enabled: false },
variables: [],
} as unknown as TSurvey;
type TLanguageUpsertArgs = Parameters<typeof prisma.language.upsert>[0];
type TLanguageUpsertReturn = ReturnType<typeof prisma.language.upsert>;
describe("createV3Survey", () => {
beforeEach(() => {
vi.resetAllMocks();
vi.mocked(prisma.language.upsert).mockImplementation(
(args: TLanguageUpsertArgs): TLanguageUpsertReturn => {
const workspaceIdCode = args.where.workspaceId_code;
if (!workspaceIdCode) {
throw new Error("Expected workspaceId_code upsert selector");
}
return Promise.resolve({
id: `cllang${workspaceIdCode.code.toLowerCase().replaceAll("-", "")}`,
code: workspaceIdCode.code,
alias: null,
workspaceId: workspaceIdCode.workspaceId,
createdAt: new Date("2026-04-21T10:00:00.000Z"),
updatedAt: new Date("2026-04-21T10:00:00.000Z"),
}) as TLanguageUpsertReturn;
}
);
vi.mocked(createSurvey).mockResolvedValue(createdSurvey);
vi.mocked(getOrganizationByWorkspaceId).mockResolvedValue({
id: "org_1",
name: "Organization",
createdAt: new Date(),
updatedAt: new Date(),
billing: {
limits: { monthly: { responses: 1000 }, workspaces: 1 },
stripeCustomerId: null,
usageCycleAnchor: null,
},
isAISmartToolsEnabled: false,
isAIDataAnalysisEnabled: false,
whitelabel: undefined,
});
vi.mocked(getExternalUrlsPermission).mockResolvedValue(true);
});
test("maps the public v3 body to the internal create payload", async () => {
await createV3Survey(
createBody,
{
user: { id: "user_1", email: "user@example.com", name: "User" },
expires: "2026-05-01",
},
"req_1"
);
expect(prisma.language.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { workspaceId_code: { workspaceId, code: "en-US" } },
create: { workspaceId, code: "en-US", alias: null },
})
);
expect(prisma.language.upsert).toHaveBeenCalledWith(
expect.objectContaining({
where: { workspaceId_code: { workspaceId, code: "de-DE" } },
create: { workspaceId, code: "de-DE", alias: null },
})
);
expect(createSurvey).toHaveBeenCalledWith(
workspaceId,
expect.objectContaining({
name: "Product Feedback",
type: "link",
status: "draft",
createdBy: "user_1",
questions: [],
metadata: expect.objectContaining({
cx_operation: "enterprise_onboarding",
title: { default: "Product Feedback", "de-DE": "Produktfeedback" },
}),
blocks: [
expect.objectContaining({
elements: [
expect.objectContaining({
headline: {
default: "What should we improve?",
"de-DE": "Was sollen wir verbessern?",
},
}),
],
}),
],
languages: [
expect.objectContaining({ default: true, enabled: true }),
expect.objectContaining({ default: false, enabled: true }),
],
})
);
expect(getOrganizationByWorkspaceId).not.toHaveBeenCalled();
expect(getExternalUrlsPermission).not.toHaveBeenCalled();
});
test("keeps createdBy null for API key calls and honors explicit disabled languages", async () => {
const body = ZV3CreateSurveyBody.parse({
...rawCreateBody,
languages: [{ code: "fr-FR", enabled: false }],
});
await createV3Survey(
body,
{
type: "apiKey",
apiKeyId: "key_1",
organizationId: "org_1",
organizationAccess: { accessControl: { read: true, write: true } },
workspacePermissions: [],
},
"req_2"
);
expect(createSurvey).toHaveBeenCalledWith(
workspaceId,
expect.objectContaining({
createdBy: null,
languages: expect.arrayContaining([
expect.objectContaining({ language: expect.objectContaining({ code: "fr-FR" }), enabled: false }),
]),
})
);
});
test("rejects external CTA buttons when the organization does not have external URL permission", async () => {
vi.mocked(getExternalUrlsPermission).mockResolvedValue(false);
const body = ZV3CreateSurveyBody.parse({
...rawCreateBody,
blocks: [
{
...rawCreateBody.blocks[0],
elements: [
{
id: "external_cta",
type: "cta",
headline: { "en-US": "Continue" },
required: false,
buttonExternal: true,
buttonUrl: "https://example.com",
ctaButtonLabel: { "en-US": "Open" },
},
],
},
],
});
await expect(createV3Survey(body, null, "req_3")).rejects.toThrow(V3SurveyCreatePermissionError);
expect(createSurvey).not.toHaveBeenCalled();
});
});
+106
View File
@@ -0,0 +1,106 @@
import "server-only";
import type { TSurveyCreateInput } from "@formbricks/types/surveys/types";
import type { TV3Authentication } from "@/app/api/v3/lib/types";
import { getOrganizationByWorkspaceId } from "@/lib/organization/service";
import { createSurvey } from "@/lib/survey/service";
import { getElementsFromBlocks } from "@/lib/survey/utils";
import { getExternalUrlsPermission } from "@/modules/survey/lib/permission";
import { type TV3SurveyLanguageRequest, ensureV3WorkspaceLanguages } from "./languages";
import { prepareV3SurveyCreate } from "./prepare";
import { V3SurveyReferenceValidationError } from "./reference-validation";
import type { TV3CreateSurveyBody } from "./schemas";
export class V3SurveyCreatePermissionError extends Error {
constructor(message: string) {
super(message);
this.name = "V3SurveyCreatePermissionError";
}
}
function getCreatedBy(authentication: TV3Authentication): string | null {
if (authentication && "user" in authentication && authentication.user?.id) {
return authentication.user.id;
}
return null;
}
function hasExternalUrlReferences(input: TV3CreateSurveyBody): boolean {
const hasExternalEndingLink = input.endings.some(
(ending) => ending.type === "endScreen" && Boolean(ending.buttonLink)
);
const hasExternalCtaButton = getElementsFromBlocks(input.blocks).some(
(element) => element.type === "cta" && element.buttonExternal
);
return hasExternalEndingLink || hasExternalCtaButton;
}
async function assertV3SurveyCreatePermissions(
input: TV3CreateSurveyBody,
organizationId?: string
): Promise<void> {
if (!hasExternalUrlReferences(input)) {
return;
}
const resolvedOrganizationId =
organizationId ?? (await getOrganizationByWorkspaceId(input.workspaceId))?.id ?? null;
if (!resolvedOrganizationId) {
return;
}
const isExternalUrlsAllowed = await getExternalUrlsPermission(resolvedOrganizationId);
if (!isExternalUrlsAllowed) {
throw new V3SurveyCreatePermissionError(
"External URLs are not enabled for this organization. Upgrade to use external survey links."
);
}
}
export async function executeV3SurveyCreate(params: {
input: TV3CreateSurveyBody;
authentication: TV3Authentication;
languageRequests: TV3SurveyLanguageRequest[];
requestId?: string;
}) {
const { input, authentication, languageRequests, requestId } = params;
const languages = await ensureV3WorkspaceLanguages(input.workspaceId, languageRequests, requestId);
const surveyCreateInput: TSurveyCreateInput = {
name: input.name,
type: "link",
status: input.status,
metadata: input.metadata,
welcomeCard: input.welcomeCard,
blocks: input.blocks,
endings: input.endings,
hiddenFields: input.hiddenFields,
variables: input.variables,
languages,
questions: [],
createdBy: getCreatedBy(authentication),
};
return await createSurvey(input.workspaceId, surveyCreateInput);
}
export async function createV3Survey(
input: TV3CreateSurveyBody,
authentication: TV3Authentication,
requestId?: string,
organizationId?: string
) {
const preparation = prepareV3SurveyCreate(input);
if (!preparation.ok) {
throw new V3SurveyReferenceValidationError(preparation.validation.invalidParams);
}
await assertV3SurveyCreatePermissions(input, organizationId);
return await executeV3SurveyCreate({
input: preparation.document,
authentication,
languageRequests: preparation.languageRequests,
requestId,
});
}
@@ -0,0 +1,106 @@
import { describe, expect, test } from "vitest";
import {
normalizeV3SurveyLanguageTag,
parseV3SurveyLanguageQuery,
resolveV3SurveyLanguageCode,
} from "./language";
const languages = [
{ code: "en-US", enabled: true },
{ code: "de-DE", enabled: true },
{ code: "fr-FR", enabled: false },
];
describe("normalizeV3SurveyLanguageTag", () => {
test.each([
["EN_us", "en-US"],
["en-us", "en-US"],
["de", "de"],
["zh_hans_cn", "zh-Hans-CN"],
])("normalizes %s to %s", (input, expected) => {
expect(normalizeV3SurveyLanguageTag(input)).toBe(expected);
});
test("returns null for invalid language tags", () => {
expect(normalizeV3SurveyLanguageTag("not a locale")).toBeNull();
});
});
describe("parseV3SurveyLanguageQuery", () => {
test("parses comma-separated language selectors", () => {
expect(parseV3SurveyLanguageQuery("de-DE, pt_PT, EN_us")).toEqual({
ok: true,
languages: ["de-DE", "pt-PT", "en-US"],
});
});
test("parses repeated language selectors", () => {
expect(parseV3SurveyLanguageQuery(["de-DE", "pt_PT,en_us"])).toEqual({
ok: true,
languages: ["de-DE", "pt-PT", "en-US"],
});
});
test("deduplicates language selectors case-insensitively", () => {
expect(parseV3SurveyLanguageQuery("de-DE,DE_de")).toEqual({
ok: true,
languages: ["de-DE"],
});
});
test("rejects empty language selectors", () => {
expect(parseV3SurveyLanguageQuery("de-DE,")).toEqual({
ok: false,
message: "Language selector must contain valid comma-separated locale codes",
});
});
test("rejects invalid language selectors", () => {
expect(parseV3SurveyLanguageQuery("not a locale")).toEqual({
ok: false,
message: "Language 'not a locale' is not a valid locale code",
});
});
});
describe("resolveV3SurveyLanguageCode", () => {
test("matches configured languages case-insensitively and normalizes underscores", () => {
expect(resolveV3SurveyLanguageCode("DE_de", languages)).toEqual({ ok: true, code: "de-DE" });
});
test("resolves language-only tags when exactly one configured language matches", () => {
expect(resolveV3SurveyLanguageCode("de", languages)).toEqual({ ok: true, code: "de-DE" });
});
test("resolves disabled configured languages for management reads", () => {
expect(resolveV3SurveyLanguageCode("fr", languages)).toEqual({ ok: true, code: "fr-FR" });
});
test("returns ambiguous when language-only tags match multiple configured languages", () => {
expect(
resolveV3SurveyLanguageCode("pt", [
{ code: "pt-BR", enabled: true },
{ code: "pt-PT", enabled: true },
])
).toEqual({
ok: false,
reason: "ambiguous",
message: "Language 'pt' is ambiguous for this survey; use one of pt-BR, pt-PT",
});
});
test("returns unknown for languages not configured on the survey", () => {
expect(resolveV3SurveyLanguageCode("es-ES", languages)).toEqual({
ok: false,
reason: "unknown",
message: "Language 'es-ES' is not configured for this survey",
});
});
test("resolves the implicit default language for surveys without configured languages", () => {
expect(resolveV3SurveyLanguageCode("en", [{ code: "en-US", enabled: true }])).toEqual({
ok: true,
code: "en-US",
});
});
});
+149
View File
@@ -0,0 +1,149 @@
import type { TSurvey as TInternalSurvey } from "@formbricks/types/surveys/types";
type TV3SurveyLanguageInput = {
code: string;
enabled: boolean;
};
export type TV3SurveyLanguage = {
code: string;
default: boolean;
enabled: boolean;
};
type TV3SurveyLanguageQueryInput = string | string[];
type TResolveV3SurveyLanguageCodeResult =
| { ok: true; code: string }
| { ok: false; reason: "invalid" | "unknown" | "ambiguous"; message: string };
type TParseV3SurveyLanguageQueryResult = { ok: true; languages: string[] } | { ok: false; message: string };
export function normalizeV3SurveyLanguageTag(value: string): string | null {
const normalizedSeparators = value.trim().replaceAll("_", "-");
try {
return Intl.getCanonicalLocales(normalizedSeparators)[0] ?? null;
} catch {
return null;
}
}
export function parseV3SurveyLanguageQuery(
value: TV3SurveyLanguageQueryInput
): TParseV3SurveyLanguageQueryResult {
const requestedLanguages = (Array.isArray(value) ? value : [value])
.flatMap((entry) => entry.split(","))
.map((entry) => entry.trim());
if (requestedLanguages.some((entry) => entry.length === 0)) {
return {
ok: false,
message: "Language selector must contain valid comma-separated locale codes",
};
}
const normalizedLanguages: string[] = [];
for (const language of requestedLanguages) {
const normalizedLanguage = normalizeV3SurveyLanguageTag(language);
if (!normalizedLanguage) {
return {
ok: false,
message: `Language '${language}' is not a valid locale code`,
};
}
if (!normalizedLanguages.some((entry) => entry.toLowerCase() === normalizedLanguage.toLowerCase())) {
normalizedLanguages.push(normalizedLanguage);
}
}
return { ok: true, languages: normalizedLanguages };
}
function getLanguageSubtag(languageTag: string): string {
return languageTag.split("-")[0]?.toLowerCase() ?? languageTag.toLowerCase();
}
export function resolveV3SurveyLanguageCode(
requestedLanguage: string,
languages: TV3SurveyLanguageInput[]
): TResolveV3SurveyLanguageCodeResult {
const normalizedRequestedLanguage = normalizeV3SurveyLanguageTag(requestedLanguage);
if (!normalizedRequestedLanguage) {
return {
ok: false,
reason: "invalid",
message: `Language '${requestedLanguage}' is not a valid locale code`,
};
}
const normalizedLanguages = languages.map((language) => ({
...language,
code: normalizeV3SurveyLanguageTag(language.code) ?? language.code,
}));
const exactMatch = normalizedLanguages.find(
(language) => language.code.toLowerCase() === normalizedRequestedLanguage.toLowerCase()
);
if (exactMatch) {
return { ok: true, code: exactMatch.code };
}
const requestedSubtag = getLanguageSubtag(normalizedRequestedLanguage);
const hasRegionOrScript = normalizedRequestedLanguage.includes("-");
const matchingLanguages = hasRegionOrScript
? []
: normalizedLanguages.filter((language) => getLanguageSubtag(language.code) === requestedSubtag);
if (matchingLanguages.length > 1) {
return {
ok: false,
reason: "ambiguous",
message: `Language '${normalizedRequestedLanguage}' is ambiguous for this survey; use one of ${matchingLanguages.map((language) => language.code).join(", ")}`,
};
}
const languageMatch = matchingLanguages[0];
if (languageMatch) {
return { ok: true, code: languageMatch.code };
}
return {
ok: false,
reason: "unknown",
message: `Language '${normalizedRequestedLanguage}' is not configured for this survey`,
};
}
export function getV3SurveyLanguages(
survey: Pick<TInternalSurvey, "languages">,
fallbackLanguage: string
): TV3SurveyLanguage[] {
const languages = (survey.languages ?? []).map((surveyLanguage) => ({
code: normalizeV3SurveyLanguageTag(surveyLanguage.language.code) ?? surveyLanguage.language.code,
default: surveyLanguage.default,
enabled: surveyLanguage.enabled,
}));
if (languages.length === 0) {
return [{ code: fallbackLanguage, default: true, enabled: true }];
}
return languages;
}
export function getV3SurveyDefaultLanguage(
survey: Pick<TInternalSurvey, "languages">,
fallbackLanguage: string
): string {
const defaultLanguageCode = survey.languages?.find((surveyLanguage) => surveyLanguage.default)?.language
.code;
return defaultLanguageCode
? (normalizeV3SurveyLanguageTag(defaultLanguageCode) ?? defaultLanguageCode)
: fallbackLanguage;
}
+150
View File
@@ -0,0 +1,150 @@
import "server-only";
import { Prisma } from "@prisma/client";
import { prisma } from "@formbricks/database";
import { logger } from "@formbricks/logger";
import { DatabaseError } from "@formbricks/types/errors";
import type { TI18nString } from "@formbricks/types/i18n";
import type { TSurveyLanguage } from "@formbricks/types/surveys/types";
import type { TLanguage } from "@formbricks/types/workspace";
import { normalizeV3SurveyLanguageTag } from "./language";
import type { TV3SurveyDocument } from "./schemas";
export type TV3SurveyLanguageRequest = {
code: string;
default: boolean;
enabled: boolean;
};
const languageSelect = {
id: true,
code: true,
alias: true,
workspaceId: true,
createdAt: true,
updatedAt: true,
} satisfies Prisma.LanguageSelect;
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isInternalI18nString(value: unknown): value is TI18nString {
return (
isPlainObject(value) &&
typeof value.default === "string" &&
Object.values(value).every((entry) => typeof entry === "string")
);
}
function collectI18nLanguageCodes(value: unknown, languageCodes: Set<string>): void {
if (Array.isArray(value)) {
value.forEach((entry) => collectI18nLanguageCodes(entry, languageCodes));
return;
}
if (!isPlainObject(value)) {
return;
}
if (isInternalI18nString(value)) {
Object.keys(value).forEach((languageCode) => {
if (languageCode !== "default") {
const normalizedLanguageCode = normalizeV3SurveyLanguageTag(languageCode);
if (normalizedLanguageCode) {
languageCodes.add(normalizedLanguageCode);
}
}
});
return;
}
Object.values(value).forEach((entry) => collectI18nLanguageCodes(entry, languageCodes));
}
export function deriveV3SurveyLanguageRequests(input: TV3SurveyDocument): TV3SurveyLanguageRequest[] {
const requestedLanguages = new Map<string, TV3SurveyLanguageRequest>();
const addLanguage = (code: string, enabled = true): void => {
requestedLanguages.set(code, {
code,
default: code.toLowerCase() === input.defaultLanguage.toLowerCase(),
enabled: code.toLowerCase() === input.defaultLanguage.toLowerCase() ? true : enabled,
});
};
addLanguage(input.defaultLanguage);
input.languages.forEach((language) => {
addLanguage(language.code, language.enabled);
});
const contentLanguageCodes = new Set<string>();
collectI18nLanguageCodes(input.welcomeCard, contentLanguageCodes);
collectI18nLanguageCodes(input.blocks, contentLanguageCodes);
collectI18nLanguageCodes(input.endings, contentLanguageCodes);
collectI18nLanguageCodes(input.metadata, contentLanguageCodes);
contentLanguageCodes.forEach((languageCode) => {
if (!requestedLanguages.has(languageCode)) {
addLanguage(languageCode);
}
});
return Array.from(requestedLanguages.values()).sort((left, right) => {
if (left.default) return -1;
if (right.default) return 1;
return left.code.localeCompare(right.code);
});
}
export async function ensureV3WorkspaceLanguages(
workspaceId: string,
languageRequests: TV3SurveyLanguageRequest[],
requestId?: string
): Promise<TSurveyLanguage[]> {
const log = logger.withContext({ requestId, workspaceId });
try {
const languages = await Promise.all(
languageRequests.map((languageRequest) =>
prisma.language.upsert({
where: {
workspaceId_code: {
workspaceId,
code: languageRequest.code,
},
},
update: {},
create: {
workspaceId,
code: languageRequest.code,
alias: null,
},
select: languageSelect,
})
)
);
const languageByCode = new Map(
languages.map((language) => [language.code.toLowerCase(), language as TLanguage])
);
return languageRequests.map((languageRequest) => {
const language = languageByCode.get(languageRequest.code.toLowerCase());
if (!language) {
throw new DatabaseError(`Failed to resolve language '${languageRequest.code}'`);
}
return {
language,
default: languageRequest.default,
enabled: languageRequest.enabled,
};
});
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError) {
log.error({ error }, "Error creating workspace languages for v3 survey write");
throw new DatabaseError(error.message);
}
throw error;
}
}
+165
View File
@@ -0,0 +1,165 @@
import { describe, expect, test, vi } from "vitest";
import type { TSurvey } from "@formbricks/types/surveys/types";
import { prepareV3SurveyCreate, prepareV3SurveyCreateInput, prepareV3SurveyPatchInput } from "./prepare";
import { ZV3CreateSurveyBody } from "./schemas";
vi.mock("server-only", () => ({}));
const workspaceId = "clxx1234567890123456789012";
const rawCreateBody = {
workspaceId,
name: "Product Feedback",
defaultLanguage: "en-US",
blocks: [
{
id: "clbk1234567890123456789012",
name: "Main Block",
elements: [
{
id: "satisfaction",
type: "openText",
headline: { "en-US": "What should we improve?", "de-DE": "Was sollen wir verbessern?" },
required: true,
},
],
},
],
};
const createBody = ZV3CreateSurveyBody.parse(rawCreateBody);
const survey = {
id: "clsv1234567890123456789012",
workspaceId,
createdAt: new Date("2026-04-21T10:00:00.000Z"),
updatedAt: new Date("2026-04-21T10:00:00.000Z"),
name: "Product Feedback",
type: "link",
status: "draft",
metadata: {},
languages: [
{
language: {
id: "cllangenus000000000000000",
code: "en-US",
alias: null,
workspaceId,
createdAt: new Date("2026-04-21T10:00:00.000Z"),
updatedAt: new Date("2026-04-21T10:00:00.000Z"),
},
default: true,
enabled: true,
},
],
questions: [],
welcomeCard: { enabled: false },
blocks: createBody.blocks,
endings: [],
hiddenFields: { enabled: false },
variables: [],
} as unknown as TSurvey;
describe("v3 survey preparation", () => {
test("prepares a valid create document and derives language side effects", () => {
const preparation = prepareV3SurveyCreate(createBody);
expect(preparation.ok).toBe(true);
if (!preparation.ok) {
throw new Error("Expected create preparation to succeed");
}
expect(preparation.languageRequests).toEqual([
{ code: "en-US", default: true, enabled: true },
{ code: "de-DE", default: false, enabled: true },
]);
});
test("returns validation results instead of throwing for invalid create input", () => {
const preparation = prepareV3SurveyCreateInput({
...rawCreateBody,
blocks: [
{
...rawCreateBody.blocks[0],
elements: [
{
...rawCreateBody.blocks[0].elements[0],
buttonUrl: "https://example.com",
},
],
},
],
});
expect(preparation.ok).toBe(false);
if (!preparation.ok) {
expect(preparation.validation.invalidParams).toEqual(
expect.arrayContaining([expect.objectContaining({ name: "blocks.0.elements.0.buttonUrl" })])
);
}
});
test("applies a patch over the current document before validating references", () => {
const preparation = prepareV3SurveyPatchInput(survey, {
blocks: [
{
...rawCreateBody.blocks[0],
logicFallback: "clmiss12345678901234567890",
},
],
});
expect(preparation.ok).toBe(false);
if (!preparation.ok) {
expect(preparation.validation.invalidParams).toEqual(
expect.arrayContaining([expect.objectContaining({ name: "blocks.0.logicFallback" })])
);
}
});
test("rejects patch input with immutable fields as validation results", () => {
const preparation = prepareV3SurveyPatchInput(survey, {
workspaceId,
});
expect(preparation.ok).toBe(false);
if (!preparation.ok) {
expect(preparation.validation.invalidParams).toEqual(
expect.arrayContaining([expect.objectContaining({ name: "workspaceId" })])
);
}
});
test("rejects non-draft element id changes on non-draft surveys", () => {
const preparation = prepareV3SurveyPatchInput(
{
...survey,
status: "inProgress",
} as TSurvey,
{
blocks: [
{
...rawCreateBody.blocks[0],
elements: [
{
...rawCreateBody.blocks[0].elements[0],
id: "renamed_satisfaction",
},
],
},
],
}
);
expect(preparation.ok).toBe(false);
if (!preparation.ok) {
expect(preparation.validation.invalidParams).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "blocks.0.elements.0.id",
reason: expect.stringContaining("cannot be changed"),
}),
])
);
}
});
});
+178
View File
@@ -0,0 +1,178 @@
import type { TSurvey as TInternalSurvey } from "@formbricks/types/surveys/types";
import type { InvalidParam } from "@/app/api/v3/lib/response";
import { getV3SurveyDefaultLanguage, getV3SurveyLanguages } from "./language";
import { type TV3SurveyLanguageRequest, deriveV3SurveyLanguageRequests } from "./languages";
import {
DEFAULT_V3_SURVEY_LANGUAGE,
type TV3CreateSurveyBody,
type TV3PatchSurveyBody,
type TV3SurveyDocument,
ZV3CreateSurveyBody,
ZV3SurveyDocumentBase,
createZV3PatchSurveyBodySchema,
formatV3ZodInvalidParams,
} from "./schemas";
import { type TV3SurveyDocumentValidationResult, validateV3SurveyDocument } from "./validation";
type TV3SurveyPrepareSuccess<TDocument> = {
ok: true;
document: TDocument;
validation: Extract<TV3SurveyDocumentValidationResult, { valid: true }>;
languageRequests: TV3SurveyLanguageRequest[];
};
type TV3SurveyPrepareFailure = {
ok: false;
validation: Extract<TV3SurveyDocumentValidationResult, { valid: false }>;
};
export type TV3SurveyPrepareResult<TDocument> = TV3SurveyPrepareSuccess<TDocument> | TV3SurveyPrepareFailure;
function invalidPreparation(invalidParams: InvalidParam[]): TV3SurveyPrepareFailure {
return {
ok: false,
validation: {
valid: false,
invalidParams,
},
};
}
function validPreparation<TDocument extends TV3SurveyDocument>(
document: TDocument
): TV3SurveyPrepareResult<TDocument> {
const validation = validateV3SurveyDocument(document);
if (!validation.valid) {
return invalidPreparation(validation.invalidParams);
}
return {
ok: true,
document,
validation,
languageRequests: deriveV3SurveyLanguageRequests(document),
};
}
function buildDocumentFromSurvey(survey: TInternalSurvey): TV3SurveyPrepareResult<TV3SurveyDocument> {
if (Array.isArray(survey.questions) && survey.questions.length > 0) {
return invalidPreparation([
{
name: "survey",
reason: "Legacy question-based surveys are not supported by the v3 survey management API",
},
]);
}
const documentResult = ZV3SurveyDocumentBase.safeParse({
name: survey.name,
status: survey.status,
metadata: survey.metadata ?? {},
defaultLanguage: getV3SurveyDefaultLanguage(survey, DEFAULT_V3_SURVEY_LANGUAGE),
languages: getV3SurveyLanguages(survey, DEFAULT_V3_SURVEY_LANGUAGE),
welcomeCard: survey.welcomeCard,
blocks: survey.blocks,
endings: survey.endings,
hiddenFields: survey.hiddenFields,
variables: survey.variables,
});
if (!documentResult.success) {
return invalidPreparation(formatV3ZodInvalidParams(documentResult.error, "survey"));
}
return validPreparation(documentResult.data);
}
function mergeV3SurveyPatch(document: TV3SurveyDocument, patch: TV3PatchSurveyBody): TV3SurveyDocument {
return {
...document,
...Object.fromEntries(Object.entries(patch).filter(([, value]) => value !== undefined)),
};
}
function getElementIds(document: TV3SurveyDocument): Set<string> {
return new Set(document.blocks.flatMap((block) => block.elements.map((element) => element.id)));
}
function getImmutableElementIdIssues(
currentDocument: TV3SurveyDocument,
patchedDocument: TV3SurveyDocument
): InvalidParam[] {
if (currentDocument.status === "draft") {
return [];
}
const patchedElementIds = getElementIds(patchedDocument);
const issues: InvalidParam[] = [];
currentDocument.blocks.forEach((currentBlock) => {
const patchedBlockIndex = patchedDocument.blocks.findIndex((block) => block.id === currentBlock.id);
if (patchedBlockIndex === -1) {
return;
}
const patchedBlock = patchedDocument.blocks[patchedBlockIndex];
currentBlock.elements.forEach((currentElement, elementIndex) => {
if (currentElement.isDraft || patchedElementIds.has(currentElement.id)) {
return;
}
const patchedElement = patchedBlock.elements[elementIndex];
if (!patchedElement || patchedElement.id === currentElement.id) {
return;
}
issues.push({
name: `blocks.${patchedBlockIndex}.elements.${elementIndex}.id`,
reason: `Element id '${currentElement.id}' cannot be changed because the survey and element are no longer drafts`,
});
});
});
return issues;
}
export function prepareV3SurveyCreate(
document: TV3CreateSurveyBody
): TV3SurveyPrepareResult<TV3CreateSurveyBody> {
return validPreparation(document);
}
export function prepareV3SurveyCreateInput(input: unknown): TV3SurveyPrepareResult<TV3CreateSurveyBody> {
const parsed = ZV3CreateSurveyBody.safeParse(input);
if (!parsed.success) {
return invalidPreparation(formatV3ZodInvalidParams(parsed.error, "data"));
}
return prepareV3SurveyCreate(parsed.data);
}
export function prepareV3SurveyPatchInput(
survey: TInternalSurvey,
input: unknown
): TV3SurveyPrepareResult<TV3SurveyDocument> {
const currentDocument = buildDocumentFromSurvey(survey);
if (!currentDocument.ok) {
return currentDocument;
}
const parsedPatch = createZV3PatchSurveyBodySchema(currentDocument.document.defaultLanguage).safeParse(
input
);
if (!parsedPatch.success) {
return invalidPreparation(formatV3ZodInvalidParams(parsedPatch.error, "data"));
}
const patchedDocument = mergeV3SurveyPatch(currentDocument.document, parsedPatch.data);
const immutableElementIdIssues = getImmutableElementIdIssues(currentDocument.document, patchedDocument);
if (immutableElementIdIssues.length > 0) {
return invalidPreparation(immutableElementIdIssues);
}
return validPreparation(patchedDocument);
}
@@ -0,0 +1,269 @@
import { describe, expect, test } from "vitest";
import { validateV3SurveyReferences } from "./reference-validation";
import { ZV3CreateSurveyBody } from "./schemas";
const validSurvey = ZV3CreateSurveyBody.parse({
workspaceId: "clxx1234567890123456789012",
name: "Product Feedback",
hiddenFields: {
enabled: true,
fieldIds: ["account_id"],
},
variables: [
{
id: "clvar123456789012345678901",
name: "score",
type: "number",
value: 0,
},
],
endings: [
{
id: "clend123456789012345678901",
type: "endScreen",
headline: { "en-US": "Thanks" },
},
],
blocks: [
{
id: "clbk1234567890123456789012",
name: "Main Block",
logicFallback: "clend123456789012345678901",
elements: [
{
id: "satisfaction",
type: "openText",
headline: { "en-US": "What should we improve?" },
required: true,
},
],
logic: [
{
id: "cllog123456789012345678901",
conditions: {
id: "clgrp123456789012345678901",
connector: "and",
conditions: [
{
id: "clcon123456789012345678901",
leftOperand: { type: "element", value: "satisfaction" },
operator: "isSubmitted",
},
],
},
actions: [
{
id: "clact123456789012345678901",
objective: "calculate",
variableId: "clvar123456789012345678901",
operator: "add",
value: { type: "static", value: 1 },
},
],
},
],
},
],
});
describe("validateV3SurveyReferences", () => {
test("accepts a survey with consistent stable identifiers", () => {
expect(
validateV3SurveyReferences({
blocks: validSurvey.blocks,
endings: validSurvey.endings,
hiddenFields: validSurvey.hiddenFields,
variables: validSurvey.variables,
})
).toEqual({ ok: true, invalidParams: [] });
});
test("rejects duplicate block, element, variable, and hidden field identifiers", () => {
const survey = {
...validSurvey,
hiddenFields: { enabled: true, fieldIds: ["account_id", "account_id"] },
variables: [
...validSurvey.variables,
{
id: "clvar123456789012345678901",
name: "score",
type: "number" as const,
value: 0,
},
],
blocks: [
...validSurvey.blocks,
{
...validSurvey.blocks[0],
elements: [{ ...validSurvey.blocks[0].elements[0] }],
},
],
};
const result = validateV3SurveyReferences({
blocks: survey.blocks,
endings: survey.endings,
hiddenFields: survey.hiddenFields,
variables: survey.variables,
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.invalidParams).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "blocks.1.id" }),
expect.objectContaining({ name: "blocks.1.elements.0.id" }),
expect.objectContaining({ name: "variables.1.id" }),
expect.objectContaining({ name: "hiddenFields.fieldIds.1" }),
])
);
}
});
test("rejects cross-namespace identifier collisions", () => {
const result = validateV3SurveyReferences({
blocks: validSurvey.blocks,
endings: validSurvey.endings,
hiddenFields: { enabled: true, fieldIds: ["account_id", "satisfaction"] },
variables: [
{
id: "satisfaction",
name: "account_id",
type: "number",
value: 0,
},
],
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.invalidParams).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "hiddenFields.fieldIds.1" }),
expect.objectContaining({ name: "variables.0.id" }),
expect.objectContaining({ name: "variables.0.name" }),
])
);
}
});
test("reports dangling logic references with actionable paths", () => {
const survey = {
...validSurvey,
blocks: [
{
...validSurvey.blocks[0],
logicFallback: "clmiss12345678901234567890",
logic: [
{
...validSurvey.blocks[0].logic![0],
actions: [
{
...validSurvey.blocks[0].logic![0].actions[0],
variableId: "clmiss12345678901234567890",
},
{
id: "cljmp123456789012345678901",
objective: "jumpToBlock" as const,
target: "clmiss12345678901234567890",
},
],
},
],
},
],
};
const result = validateV3SurveyReferences({
blocks: survey.blocks,
endings: survey.endings,
hiddenFields: survey.hiddenFields,
variables: survey.variables,
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.invalidParams).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "blocks.0.logicFallback" }),
expect.objectContaining({ name: "blocks.0.logic.0.actions.0.variableId" }),
expect.objectContaining({ name: "blocks.0.logic.0.actions.1.target" }),
])
);
}
});
test("reports dangling recall references with actionable paths", () => {
const survey = {
...validSurvey,
blocks: [
{
...validSurvey.blocks[0],
elements: [
{
...validSurvey.blocks[0].elements[0],
headline: {
default: "Please explain #recall:missing_id/fallback:your answer#",
},
},
],
},
],
};
const result = validateV3SurveyReferences({
blocks: survey.blocks,
endings: survey.endings,
hiddenFields: survey.hiddenFields,
variables: survey.variables,
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.invalidParams).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "blocks.0.elements.0.headline.default",
reason: expect.stringContaining("missing_id"),
}),
])
);
}
});
test("reports dangling recall references in survey-level translatable fields", () => {
const result = validateV3SurveyReferences({
blocks: validSurvey.blocks,
endings: validSurvey.endings,
hiddenFields: validSurvey.hiddenFields,
metadata: {
title: {
default: "Metadata #recall:missing_metadata_reference/fallback:value#",
},
},
variables: validSurvey.variables,
welcomeCard: {
enabled: true,
headline: {
default: "Welcome #recall:missing_welcome_reference/fallback:there#",
},
},
});
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.invalidParams).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "welcomeCard.headline.default",
reason: expect.stringContaining("missing_welcome_reference"),
}),
expect.objectContaining({
name: "metadata.title.default",
reason: expect.stringContaining("missing_metadata_reference"),
}),
])
);
}
});
});
@@ -0,0 +1,342 @@
import type { TSurveyBlocks } from "@formbricks/types/surveys/blocks";
import type { TConditionGroup, TDynamicLogicFieldValue } from "@formbricks/types/surveys/logic";
import type { TSurveyEndings, TSurveyHiddenFields, TSurveyVariables } from "@formbricks/types/surveys/types";
import type { InvalidParam } from "@/app/api/v3/lib/response";
type TReferenceValidationInput = {
blocks: TSurveyBlocks;
endings: TSurveyEndings;
hiddenFields: TSurveyHiddenFields;
metadata?: unknown;
variables: TSurveyVariables;
welcomeCard?: unknown;
};
type TNamedReference = {
id: string;
path: string;
namespace: "block" | "element" | "ending" | "hiddenField" | "variable" | "variableName";
};
export class V3SurveyReferenceValidationError extends Error {
invalidParams: InvalidParam[];
constructor(invalidParams: InvalidParam[]) {
super("Survey contains invalid references");
this.name = "V3SurveyReferenceValidationError";
this.invalidParams = invalidParams;
}
}
export type TV3SurveyReferenceValidationResult =
| { ok: true; invalidParams: [] }
| { ok: false; invalidParams: InvalidParam[] };
function addDuplicateIdIssues(
entries: { id: string; path: string }[],
label: string,
issues: InvalidParam[]
): void {
const firstPathById = new Map<string, string>();
entries.forEach(({ id, path }) => {
const firstPath = firstPathById.get(id);
if (firstPath !== undefined) {
issues.push({
name: path,
reason: `${label} id '${id}' is duplicated; first used at ${firstPath}`,
});
return;
}
firstPathById.set(id, path);
});
}
function addDuplicateValueIssues(
values: string[],
pathForIndex: (index: number) => string,
label: string,
issues: InvalidParam[]
): void {
const firstIndexByValue = new Map<string, number>();
values.forEach((value, index) => {
const firstIndex = firstIndexByValue.get(value);
if (firstIndex !== undefined) {
issues.push({
name: pathForIndex(index),
reason: `${label} '${value}' is duplicated; first used at ${pathForIndex(firstIndex)}`,
});
return;
}
firstIndexByValue.set(value, index);
});
}
function addCrossNamespaceCollisionIssues(entries: TNamedReference[], issues: InvalidParam[]): void {
const firstEntryById = new Map<string, TNamedReference>();
entries.forEach((entry) => {
const lookupId = entry.id.toLowerCase();
const firstEntry = firstEntryById.get(lookupId);
if (!firstEntry) {
firstEntryById.set(lookupId, entry);
return;
}
if (firstEntry.namespace === entry.namespace) {
return;
}
issues.push({
name: entry.path,
reason: `${entry.namespace} identifier '${entry.id}' conflicts with ${firstEntry.namespace} identifier at ${firstEntry.path}`,
});
});
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function addRecallReferenceIssues(
value: unknown,
path: string,
references: {
elementIds: Set<string>;
variableIds: Set<string>;
hiddenFieldIds: Set<string>;
},
issues: InvalidParam[]
): void {
if (typeof value === "string") {
const recallPattern = /#recall:([A-Za-z0-9_-]+)/g;
for (const match of value.matchAll(recallPattern)) {
const recallId = match[1];
const isKnownReference =
references.elementIds.has(recallId) ||
references.variableIds.has(recallId) ||
references.hiddenFieldIds.has(recallId);
if (!isKnownReference) {
issues.push({
name: path,
reason: `Recall reference '${recallId}' is not defined in blocks, variables, or hiddenFields.fieldIds`,
});
}
}
return;
}
if (Array.isArray(value)) {
value.forEach((entry, index) => addRecallReferenceIssues(entry, `${path}.${index}`, references, issues));
return;
}
if (!isPlainObject(value)) {
return;
}
Object.entries(value).forEach(([key, entry]) => {
addRecallReferenceIssues(entry, path ? `${path}.${key}` : key, references, issues);
});
}
function validateDynamicOperand(
operand: TDynamicLogicFieldValue,
path: string,
references: {
elementIds: Set<string>;
variableIds: Set<string>;
hiddenFieldIds: Set<string>;
},
issues: InvalidParam[]
): void {
if (operand.type === "element" && !references.elementIds.has(operand.value)) {
issues.push({
name: `${path}.value`,
reason: `Element id '${operand.value}' is not defined in blocks`,
});
}
if (operand.type === "variable" && !references.variableIds.has(operand.value)) {
issues.push({
name: `${path}.value`,
reason: `Variable id '${operand.value}' is not defined in variables`,
});
}
if (operand.type === "hiddenField" && !references.hiddenFieldIds.has(operand.value)) {
issues.push({
name: `${path}.value`,
reason: `Hidden field id '${operand.value}' is not defined in hiddenFields.fieldIds`,
});
}
}
function validateConditionGroup(
conditionGroup: TConditionGroup,
path: string,
references: {
elementIds: Set<string>;
variableIds: Set<string>;
hiddenFieldIds: Set<string>;
},
issues: InvalidParam[]
): void {
conditionGroup.conditions.forEach((condition, index) => {
const conditionPath = `${path}.conditions.${index}`;
if ("conditions" in condition) {
validateConditionGroup(condition, conditionPath, references, issues);
return;
}
validateDynamicOperand(condition.leftOperand, `${conditionPath}.leftOperand`, references, issues);
if (condition.rightOperand?.type && condition.rightOperand.type !== "static") {
validateDynamicOperand(condition.rightOperand, `${conditionPath}.rightOperand`, references, issues);
}
});
}
export function getV3SurveyReferenceInvalidParams(input: TReferenceValidationInput): InvalidParam[] {
const issues: InvalidParam[] = [];
const blockIds = input.blocks.map((block) => block.id);
const blockEntries = input.blocks.map((block, index) => ({
id: block.id,
path: `blocks.${index}.id`,
}));
const endingIds = input.endings.map((ending) => ending.id);
const endingEntries = input.endings.map((ending, index) => ({
id: ending.id,
path: `endings.${index}.id`,
}));
const elementEntries = input.blocks.flatMap((block, blockIndex) =>
block.elements.map((element, elementIndex) => ({
id: element.id,
path: `blocks.${blockIndex}.elements.${elementIndex}.id`,
}))
);
const elementIds = elementEntries.map((element) => element.id);
const hiddenFieldIds = input.hiddenFields.fieldIds ?? [];
const hiddenFieldEntries = hiddenFieldIds.map((id, index) => ({
id,
path: `hiddenFields.fieldIds.${index}`,
}));
const variableIds = input.variables.map((variable) => variable.id);
const variableIdEntries = variableIds.map((id, index) => ({
id,
path: `variables.${index}.id`,
}));
const variableNames = input.variables.map((variable) => variable.name);
const variableNameEntries = variableNames.map((id, index) => ({
id,
path: `variables.${index}.name`,
}));
const navigationTargetIds = new Set([...blockIds, ...endingIds]);
const references = {
elementIds: new Set(elementIds),
variableIds: new Set(variableIds),
hiddenFieldIds: new Set(hiddenFieldIds),
};
addDuplicateIdIssues(blockEntries, "Block", issues);
addDuplicateIdIssues(elementEntries, "Element", issues);
addDuplicateIdIssues(variableIdEntries, "Variable", issues);
addDuplicateValueIssues(
hiddenFieldIds,
(index) => `hiddenFields.fieldIds.${index}`,
"Hidden field id",
issues
);
addDuplicateValueIssues(variableNames, (index) => `variables.${index}.name`, "Variable name", issues);
addCrossNamespaceCollisionIssues(
[
...blockEntries.map((entry) => ({ ...entry, namespace: "block" as const })),
...elementEntries.map((entry) => ({ ...entry, namespace: "element" as const })),
...endingEntries.map((entry) => ({ ...entry, namespace: "ending" as const })),
...hiddenFieldEntries.map((entry) => ({ ...entry, namespace: "hiddenField" as const })),
...variableIdEntries.map((entry) => ({ ...entry, namespace: "variable" as const })),
...variableNameEntries.map((entry) => ({ ...entry, namespace: "variableName" as const })),
],
issues
);
input.blocks.forEach((block, blockIndex) => {
if (block.logicFallback && !navigationTargetIds.has(block.logicFallback)) {
issues.push({
name: `blocks.${blockIndex}.logicFallback`,
reason: `Logic fallback target '${block.logicFallback}' is not defined in blocks or endings`,
});
}
block.logic?.forEach((logic, logicIndex) => {
const logicPath = `blocks.${blockIndex}.logic.${logicIndex}`;
validateConditionGroup(logic.conditions, `${logicPath}.conditions`, references, issues);
logic.actions.forEach((action, actionIndex) => {
const actionPath = `${logicPath}.actions.${actionIndex}`;
if (action.objective === "calculate") {
if (!references.variableIds.has(action.variableId)) {
issues.push({
name: `${actionPath}.variableId`,
reason: `Variable id '${action.variableId}' is not defined in variables`,
});
}
if (action.value.type !== "static") {
validateDynamicOperand(action.value, `${actionPath}.value`, references, issues);
}
}
if (action.objective === "requireAnswer" && !references.elementIds.has(action.target)) {
issues.push({
name: `${actionPath}.target`,
reason: `Element id '${action.target}' is not defined in blocks`,
});
}
if (action.objective === "jumpToBlock" && !navigationTargetIds.has(action.target)) {
issues.push({
name: `${actionPath}.target`,
reason: `Jump target '${action.target}' is not defined in blocks or endings`,
});
}
});
});
});
addRecallReferenceIssues(input.blocks, "blocks", references, issues);
addRecallReferenceIssues(input.endings, "endings", references, issues);
addRecallReferenceIssues(input.welcomeCard, "welcomeCard", references, issues);
addRecallReferenceIssues(input.metadata, "metadata", references, issues);
return issues;
}
export function validateV3SurveyReferences(
input: TReferenceValidationInput
): TV3SurveyReferenceValidationResult {
const invalidParams = getV3SurveyReferenceInvalidParams(input);
if (invalidParams.length > 0) {
return { ok: false, invalidParams };
}
return { ok: true, invalidParams: [] };
}
export function assertValidV3SurveyReferences(input: TReferenceValidationInput): void {
const result = validateV3SurveyReferences(input);
if (!result.ok) {
throw new V3SurveyReferenceValidationError(result.invalidParams);
}
}
@@ -50,6 +50,10 @@ vi.mock("@/modules/survey/list/lib/survey", async (importOriginal) => {
};
});
vi.mock("./create", () => ({
createV3Survey: vi.fn(),
}));
vi.mock("@formbricks/logger", () => ({
logger: {
withContext: vi.fn(() => ({
+88 -2
View File
@@ -1,5 +1,5 @@
/**
* GET /api/v3/surveys — list surveys for a workspace.
* /api/v3/surveys — list and create block-based survey management resources.
* Session cookie or x-api-key; scope by workspaceId only.
*/
import { logger } from "@formbricks/logger";
@@ -7,6 +7,7 @@ import { DatabaseError, ResourceNotFoundError } from "@formbricks/types/errors";
import { withV3ApiWrapper } from "@/app/api/v3/lib/api-wrapper";
import { requireV3WorkspaceAccess } from "@/app/api/v3/lib/auth";
import {
createdResponse,
problemBadRequest,
problemForbidden,
problemInternalError,
@@ -14,8 +15,15 @@ import {
} from "@/app/api/v3/lib/response";
import { getSurveyCount } from "@/modules/survey/list/lib/survey";
import { getSurveyListPage } from "@/modules/survey/list/lib/survey-page";
import { V3SurveyCreatePermissionError, createV3Survey } from "./create";
import { parseV3SurveysListQuery } from "./parse-v3-surveys-list-query";
import { serializeV3SurveyListItem } from "./serializers";
import { V3SurveyReferenceValidationError } from "./reference-validation";
import { ZV3CreateSurveyBody } from "./schemas";
import {
V3SurveyUnsupportedShapeError,
serializeV3SurveyListItem,
serializeV3SurveyResource,
} from "./serializers";
export const GET = withV3ApiWrapper({
auth: "both",
@@ -80,3 +88,81 @@ export const GET = withV3ApiWrapper({
}
},
});
export const POST = withV3ApiWrapper({
auth: "both",
schemas: {
body: ZV3CreateSurveyBody,
},
action: "created",
targetType: "survey",
handler: async ({ authentication, auditLog, parsedInput, requestId, instance }) => {
const { body } = parsedInput;
const log = logger.withContext({ requestId, workspaceId: body.workspaceId });
try {
const authResult = await requireV3WorkspaceAccess(
authentication,
body.workspaceId,
"readWrite",
requestId,
instance
);
if (authResult instanceof Response) {
return authResult;
}
const survey = await createV3Survey(
{
...body,
workspaceId: authResult.workspaceId,
},
authentication,
requestId,
authResult.organizationId
);
const resource = serializeV3SurveyResource(survey);
if (auditLog) {
auditLog.organizationId = authResult.organizationId;
auditLog.targetId = survey.id;
auditLog.newObject = resource;
}
return createdResponse(resource, {
requestId,
location: `/api/v3/surveys/${survey.id}`,
});
} catch (err) {
if (err instanceof V3SurveyReferenceValidationError) {
log.warn({ statusCode: 400, invalidParams: err.invalidParams }, "Survey reference validation failed");
return problemBadRequest(requestId, "Invalid survey references", {
invalid_params: err.invalidParams,
instance,
});
}
if (err instanceof V3SurveyUnsupportedShapeError) {
log.warn({ statusCode: 400, errorCode: err.name }, "Unsupported survey shape");
return problemBadRequest(requestId, err.message, {
invalid_params: [{ name: "body", reason: err.message }],
instance,
});
}
if (err instanceof V3SurveyCreatePermissionError) {
log.warn({ statusCode: 403, errorCode: err.name }, "Survey create permission check failed");
return problemForbidden(requestId, err.message, instance);
}
if (err instanceof ResourceNotFoundError) {
log.warn({ statusCode: 403, errorCode: err.name }, "Resource not found");
return problemForbidden(requestId, "You are not authorized to access this resource", instance);
}
if (err instanceof DatabaseError) {
log.error({ error: err, statusCode: 500 }, "Database error");
return problemInternalError(requestId, "An unexpected error occurred.", instance);
}
log.error({ error: err, statusCode: 500 }, "V3 survey create unexpected error");
return problemInternalError(requestId, "An unexpected error occurred.", instance);
}
},
});
+403
View File
@@ -0,0 +1,403 @@
import { describe, expect, test } from "vitest";
import { ZV3CreateSurveyBody, ZV3PatchSurveyBody, createZV3PatchSurveyBodySchema } from "./schemas";
const validCreateBody = {
workspaceId: "clxx1234567890123456789012",
name: "Product Feedback",
blocks: [
{
id: "clbk1234567890123456789012",
name: "Main Block",
elements: [
{
id: "satisfaction",
type: "openText",
headline: { "en-US": "What should we improve?" },
required: true,
},
],
},
],
};
describe("ZV3CreateSurveyBody", () => {
test("accepts a valid block-based create body and applies public defaults", () => {
const parsed = ZV3CreateSurveyBody.parse(validCreateBody);
expect(parsed).toMatchObject({
workspaceId: validCreateBody.workspaceId,
name: "Product Feedback",
type: "link",
status: "draft",
metadata: {},
defaultLanguage: "en-US",
languages: [],
welcomeCard: { enabled: false },
endings: [],
hiddenFields: { enabled: false },
variables: [],
});
expect(parsed.blocks[0].elements[0]).toMatchObject({
headline: { default: "What should we improve?" },
});
});
test("normalizes locale maps and language codes before shared survey validation", () => {
const parsed = ZV3CreateSurveyBody.parse({
...validCreateBody,
defaultLanguage: "en_us",
languages: [{ code: "de_de" }],
welcomeCard: {
enabled: true,
headline: { en_us: "Welcome", de_de: "Willkommen" },
},
blocks: [
{
...validCreateBody.blocks[0],
elements: [
{
...validCreateBody.blocks[0].elements[0],
headline: { en_us: "Hello", de_de: "Hallo" },
},
],
},
],
});
expect(parsed.defaultLanguage).toBe("en-US");
expect(parsed.languages).toEqual([{ code: "de-DE", enabled: true }]);
expect(parsed.welcomeCard).toMatchObject({
headline: { default: "Welcome", "de-DE": "Willkommen" },
});
expect(parsed.blocks[0].elements[0]).toMatchObject({
headline: { default: "Hello", "de-DE": "Hallo" },
});
});
test("rejects an invalid defaultLanguage instead of silently defaulting", () => {
const result = ZV3CreateSurveyBody.safeParse({
...validCreateBody,
defaultLanguage: "not a locale",
});
expect(result.success).toBe(false);
expect(result.error?.issues.map((issue) => issue.path.join("."))).toContain("defaultLanguage");
});
test("rejects duplicate locale keys after normalization", () => {
const result = ZV3CreateSurveyBody.safeParse({
...validCreateBody,
blocks: [
{
...validCreateBody.blocks[0],
elements: [
{
...validCreateBody.blocks[0].elements[0],
headline: { "en-US": "Hello", en_us: "Duplicate" },
},
],
},
],
});
expect(result.success).toBe(false);
expect(result.error?.issues.map((issue) => issue.path.join("."))).toContain(
"blocks.0.elements.0.headline.en_us"
);
});
test("rejects unsupported top-level fields instead of silently ignoring them", () => {
const result = ZV3CreateSurveyBody.safeParse({
...validCreateBody,
questions: [],
styling: {},
createdBy: "user_1",
});
expect(result.success).toBe(false);
expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual(
expect.arrayContaining(["questions", "styling", "createdBy"])
);
});
test("rejects unsupported nested fields instead of stripping them", () => {
const result = ZV3CreateSurveyBody.safeParse({
...validCreateBody,
blocks: [
{
...validCreateBody.blocks[0],
targeting: {},
elements: [
{
...validCreateBody.blocks[0].elements[0],
analytics: {},
},
],
},
],
});
expect(result.success).toBe(false);
expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual(
expect.arrayContaining(["blocks.0.targeting", "blocks.0.elements.0.analytics"])
);
});
test("rejects element fields that do not belong to the selected element type", () => {
const result = ZV3CreateSurveyBody.safeParse({
...validCreateBody,
blocks: [
{
...validCreateBody.blocks[0],
elements: [
{
...validCreateBody.blocks[0].elements[0],
buttonUrl: "https://example.com",
scale: "star",
},
],
},
],
});
expect(result.success).toBe(false);
expect(result.error?.issues.map((issue) => issue.path.join("."))).toContain(
"blocks.0.elements.0.buttonUrl"
);
expect(result.error?.issues.map((issue) => issue.path.join("."))).toContain("blocks.0.elements.0.scale");
expect(
result.error?.issues.find((issue) => issue.path.join(".") === "blocks.0.elements.0.buttonUrl")
).toMatchObject({
message: expect.stringContaining("element type 'openText'"),
});
});
test("rejects choice fields that do not belong to the selected element type", () => {
const result = ZV3CreateSurveyBody.safeParse({
...validCreateBody,
blocks: [
{
...validCreateBody.blocks[0],
elements: [
{
id: "choices",
type: "multipleChoiceSingle",
headline: { "en-US": "Pick one" },
required: true,
choices: [
{ id: "choice_1", label: { "en-US": "A" }, imageUrl: "https://example.com/a.png" },
{ id: "choice_2", label: { "en-US": "B" } },
],
},
],
},
],
});
expect(result.success).toBe(false);
expect(result.error?.issues.map((issue) => issue.path.join("."))).toContain(
"blocks.0.elements.0.choices.0.imageUrl"
);
expect(
result.error?.issues.find((issue) => issue.path.join(".") === "blocks.0.elements.0.choices.0.imageUrl")
).toMatchObject({
message: expect.stringContaining("Allowed fields: id, label"),
});
});
test("does not rewrite locale-shaped objects in logic metadata", () => {
const result = ZV3CreateSurveyBody.safeParse({
...validCreateBody,
blocks: [
{
...validCreateBody.blocks[0],
elements: [
{
...validCreateBody.blocks[0].elements[0],
},
],
logic: [
{
id: "cllog123456789012345678901",
conditions: {
id: "clgrp123456789012345678901",
connector: "and",
conditions: [
{
id: "clcon123456789012345678901",
leftOperand: {
type: "element",
value: "satisfaction",
meta: { "en-US": "metadata" },
},
operator: "isSubmitted",
},
],
},
actions: [
{
id: "clact123456789012345678901",
objective: "requireAnswer",
target: "satisfaction",
},
],
},
],
},
],
});
expect(result.success).toBe(true);
if (!result.success) {
throw new Error("Expected schema validation to pass");
}
expect(result.data.blocks[0].logic?.[0].conditions.conditions[0]).toMatchObject({
leftOperand: {
meta: { "en-US": "metadata" },
},
});
});
test("rejects the internal default translation key in public v3 input", () => {
const result = ZV3CreateSurveyBody.safeParse({
...validCreateBody,
blocks: [
{
...validCreateBody.blocks[0],
elements: [
{
...validCreateBody.blocks[0].elements[0],
headline: { default: "Internal key should not be public" },
},
],
},
],
});
expect(result.success).toBe(false);
expect(result.error?.issues[0].path.join(".")).toBe("blocks.0.elements.0.headline.default");
});
test("preserves arbitrary metadata while normalizing known translatable metadata fields", () => {
const parsed = ZV3CreateSurveyBody.parse({
...validCreateBody,
metadata: {
cx_context: {
"de-DE": "This is arbitrary customer metadata, not translation content",
},
title: {
"en-US": "Feedback Survey",
"de-DE": "Feedback-Umfrage",
},
},
});
expect(parsed.metadata).toMatchObject({
cx_context: {
"de-DE": "This is arbitrary customer metadata, not translation content",
},
title: {
default: "Feedback Survey",
"de-DE": "Feedback-Umfrage",
},
});
});
test("rejects non-link survey types for this survey-template endpoint", () => {
const result = ZV3CreateSurveyBody.safeParse({
...validCreateBody,
type: "app",
});
expect(result.success).toBe(false);
expect(result.error?.issues[0].path).toEqual(["type"]);
});
test("rejects malformed locale maps that do not include the default language", () => {
const result = ZV3CreateSurveyBody.safeParse({
...validCreateBody,
blocks: [
{
...validCreateBody.blocks[0],
elements: [
{
...validCreateBody.blocks[0].elements[0],
headline: { "not a locale": "Hello" },
},
],
},
],
});
expect(result.success).toBe(false);
});
test("rejects duplicate language entries and disabled default language", () => {
const result = ZV3CreateSurveyBody.safeParse({
...validCreateBody,
languages: [{ code: "en-US", enabled: false }, { code: "en_us" }],
});
expect(result.success).toBe(false);
expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual(
expect.arrayContaining(["languages.0.enabled", "languages.1.code"])
);
});
});
describe("ZV3PatchSurveyBody", () => {
test("accepts a strict top-level partial and preserves omitted defaults", () => {
const parsed = ZV3PatchSurveyBody.parse({
name: "Updated survey",
});
expect(parsed).toEqual({ name: "Updated survey" });
});
test("rejects an empty patch body", () => {
const result = ZV3PatchSurveyBody.safeParse({});
expect(result.success).toBe(false);
expect(result.error?.issues[0]).toMatchObject({
message: "Request body must include at least one updatable field",
});
});
test("rejects immutable and out-of-scope fields", () => {
const result = ZV3PatchSurveyBody.safeParse({
id: "clsv1234567890123456789012",
workspaceId: "clxx1234567890123456789012",
type: "link",
questions: [],
});
expect(result.success).toBe(false);
expect(result.error?.issues.map((issue) => issue.path.join("."))).toEqual(
expect.arrayContaining(["id", "workspaceId", "type", "questions"])
);
});
test("normalizes patch translation maps using the current default language", () => {
const parsed = createZV3PatchSurveyBodySchema("de-DE").parse({
blocks: [
{
id: "clbk1234567890123456789012",
name: "Main Block",
elements: [
{
id: "satisfaction",
type: "openText",
headline: { de_de: "Hallo", en_us: "Hello" },
required: true,
},
],
},
],
});
expect(parsed.blocks?.[0].elements[0]).toMatchObject({
headline: { default: "Hallo", "en-US": "Hello" },
});
expect(parsed).not.toHaveProperty("defaultLanguage");
});
});
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,274 @@
import { describe, expect, test } from "vitest";
import type { TSurvey } from "@formbricks/types/surveys/types";
import { V3SurveyUnsupportedShapeError, serializeV3SurveyResource } from "./serializers";
const baseSurvey = {
id: "survey_1",
workspaceId: "workspace_1",
createdAt: new Date("2026-04-21T10:00:00.000Z"),
updatedAt: new Date("2026-04-21T11:00:00.000Z"),
name: "Product Feedback",
type: "link",
status: "draft",
metadata: { cx: "enterprise" },
languages: [
{
default: true,
enabled: true,
language: { id: "lang_1", code: "en-US", alias: "en", createdAt: new Date(), updatedAt: new Date() },
},
{
default: false,
enabled: true,
language: { id: "lang_2", code: "de-DE", alias: "de", createdAt: new Date(), updatedAt: new Date() },
},
{
default: false,
enabled: false,
language: { id: "lang_3", code: "fr-FR", alias: "fr", createdAt: new Date(), updatedAt: new Date() },
},
],
questions: [],
welcomeCard: {
enabled: true,
headline: { default: "Welcome", "de-DE": "Willkommen", "fr-FR": "Bienvenue" },
},
blocks: [
{
id: "block_1",
name: "Intro",
elements: [
{
id: "satisfaction",
type: "openText",
headline: { default: "What should we improve?", "de-DE": "Was sollen wir verbessern?" },
subheader: { default: "Tell us more" },
required: true,
},
],
},
],
endings: [],
hiddenFields: { enabled: false, fieldIds: [] },
variables: [],
} as unknown as TSurvey;
describe("serializeV3SurveyResource", () => {
test("returns canonical multilingual fields using real locale codes", () => {
const resource = serializeV3SurveyResource(baseSurvey);
expect(resource.defaultLanguage).toBe("en-US");
expect(resource).not.toHaveProperty("language");
expect(resource.languages).toEqual([
{ code: "en-US", default: true, enabled: true },
{ code: "de-DE", default: false, enabled: true },
{ code: "fr-FR", default: false, enabled: false },
]);
expect(resource).toMatchObject({
welcomeCard: {
headline: {
"en-US": "Welcome",
"de-DE": "Willkommen",
"fr-FR": "Bienvenue",
},
},
});
expect(resource).toMatchObject({
blocks: [
{
elements: [
{
headline: {
"en-US": "What should we improve?",
"de-DE": "Was sollen wir verbessern?",
},
},
],
},
],
});
});
test("does not expose the internal default pseudo-locale for surveys without configured languages", () => {
const survey = {
...baseSurvey,
languages: [],
welcomeCard: {
enabled: true,
headline: { default: "Welcome" },
},
blocks: [
{
id: "block_1",
name: "Intro",
elements: [
{
id: "satisfaction",
type: "openText",
headline: { default: "What should we improve?" },
required: true,
},
],
},
],
} as unknown as TSurvey;
const resource = serializeV3SurveyResource(survey);
expect(resource.defaultLanguage).toBe("en-US");
expect(resource.languages).toEqual([{ code: "en-US", default: true, enabled: true }]);
expect(resource).toMatchObject({
welcomeCard: { headline: { "en-US": "Welcome" } },
blocks: [
{
elements: [
{
headline: { "en-US": "What should we improve?" },
},
],
},
],
});
});
test("filters the implicit default language for surveys without configured languages", () => {
const survey = {
...baseSurvey,
languages: [],
welcomeCard: {
enabled: true,
headline: { default: "Welcome" },
},
} as unknown as TSurvey;
const resource = serializeV3SurveyResource(survey, { lang: ["en"] });
expect(resource).not.toHaveProperty("language");
expect(resource).toMatchObject({ welcomeCard: { headline: { "en-US": "Welcome" } } });
});
test("preserves stored locale variants when their keys use non-canonical casing or separators", () => {
const survey = {
...baseSurvey,
welcomeCard: {
enabled: true,
headline: { default: "Welcome", de_de: "Willkommen" },
},
} as unknown as TSurvey;
const resource = serializeV3SurveyResource(survey);
expect(resource).toMatchObject({
welcomeCard: {
headline: {
"en-US": "Welcome",
"de-DE": "Willkommen",
},
},
});
});
test("filters fields for case-insensitive underscore language selectors while preserving maps", () => {
const resource = serializeV3SurveyResource(baseSurvey, { lang: ["DE_de"] });
expect(resource).not.toHaveProperty("language");
expect(resource).toMatchObject({
welcomeCard: { headline: { "de-DE": "Willkommen" } },
blocks: [
{
elements: [
{
headline: { "de-DE": "Was sollen wir verbessern?" },
subheader: { "de-DE": "Tell us more" },
},
],
},
],
});
});
test("resolves language-only selectors against configured survey languages", () => {
const resource = serializeV3SurveyResource(baseSurvey, { lang: ["de"] });
expect(resource).toMatchObject({ welcomeCard: { headline: { "de-DE": "Willkommen" } } });
});
test("filters disabled configured languages for management reads", () => {
const resource = serializeV3SurveyResource(baseSurvey, { lang: ["fr"] });
expect(resource).toMatchObject({ welcomeCard: { headline: { "fr-FR": "Bienvenue" } } });
});
test("filters multiple requested languages while preserving maps", () => {
const resource = serializeV3SurveyResource(baseSurvey, { lang: ["en-US", "de"] });
expect(resource).not.toHaveProperty("language");
expect(resource).toMatchObject({
welcomeCard: {
headline: {
"en-US": "Welcome",
"de-DE": "Willkommen",
},
},
blocks: [
{
elements: [
{
headline: {
"en-US": "What should we improve?",
"de-DE": "Was sollen wir verbessern?",
},
},
],
},
],
});
});
test("rejects ambiguous language-only selectors", () => {
const survey = {
...baseSurvey,
languages: [
{
default: true,
enabled: true,
language: {
id: "lang_1",
code: "pt-BR",
alias: "br",
createdAt: new Date(),
updatedAt: new Date(),
},
},
{
default: false,
enabled: true,
language: {
id: "lang_2",
code: "pt-PT",
alias: "pt",
createdAt: new Date(),
updatedAt: new Date(),
},
},
],
} as unknown as TSurvey;
expect(() => serializeV3SurveyResource(survey, { lang: ["pt"] })).toThrow(
"Language 'pt' is ambiguous for this survey; use one of pt-BR, pt-PT"
);
});
test("rejects legacy question-based survey shapes instead of returning an incomplete block resource", () => {
const survey = {
...baseSurvey,
questions: [{ id: "legacy_question", type: "openText", headline: { default: "Legacy question" } }],
blocks: [],
} as unknown as TSurvey;
expect(() => serializeV3SurveyResource(survey)).toThrow(V3SurveyUnsupportedShapeError);
expect(() => serializeV3SurveyResource(survey)).toThrow(
"Legacy question-based surveys are not supported by the v3 survey management API"
);
});
});
+160 -3
View File
@@ -1,13 +1,170 @@
import type { TSurvey } from "@/modules/survey/list/types/surveys";
import type { TSurvey as TInternalSurvey } from "@formbricks/types/surveys/types";
import type { TSurvey as TSurveyListRecord } from "@/modules/survey/list/types/surveys";
import {
type TV3SurveyLanguage,
getV3SurveyDefaultLanguage,
getV3SurveyLanguages,
normalizeV3SurveyLanguageTag,
resolveV3SurveyLanguageCode,
} from "./language";
export type TV3SurveyListItem = Omit<TSurvey, "singleUse">;
export type TV3SurveyListItem = Omit<TSurveyListRecord, "singleUse">;
const DEFAULT_V3_SURVEY_LANGUAGE = "en-US";
type TSerializedValue =
| string
| number
| boolean
| null
| TSerializedValue[]
| { [key: string]: TSerializedValue };
export class V3SurveyLanguageError extends Error {
constructor(message: string) {
super(message);
this.name = "V3SurveyLanguageError";
}
}
export class V3SurveyUnsupportedShapeError extends Error {
constructor(message: string) {
super(message);
this.name = "V3SurveyUnsupportedShapeError";
}
}
/**
* Keep the v3 API contract isolated from internal persistence naming.
* Surveys are scoped by workspaceId.
*/
export function serializeV3SurveyListItem(survey: TSurvey): TV3SurveyListItem {
export function serializeV3SurveyListItem(survey: TSurveyListRecord): TV3SurveyListItem {
const { singleUse: _omitSingleUse, ...rest } = survey;
return rest;
}
function toIsoString(value: Date | string): string {
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isI18nString(value: unknown): value is Record<string, string> {
return (
isPlainObject(value) &&
typeof value.default === "string" &&
Object.values(value).every((entry) => typeof entry === "string")
);
}
function getI18nValueForLanguage(value: Record<string, string>, languageCode: string): string | undefined {
if (typeof value[languageCode] === "string") {
return value[languageCode];
}
const matchingKey = Object.keys(value).find(
(key) => normalizeV3SurveyLanguageTag(key)?.toLowerCase() === languageCode.toLowerCase()
);
return matchingKey ? value[matchingKey] : undefined;
}
function serializeCanonicalValue(
value: unknown,
defaultLanguage: string,
languageCodes: Set<string>,
options?: { fallbackMissingTranslations?: boolean }
): TSerializedValue {
if (isI18nString(value)) {
const result: Record<string, string> = {
[defaultLanguage]: value.default,
};
for (const languageCode of languageCodes) {
const translatedValue = getI18nValueForLanguage(value, languageCode);
if (languageCode !== defaultLanguage) {
if (translatedValue !== undefined) {
result[languageCode] = translatedValue;
} else if (options?.fallbackMissingTranslations) {
result[languageCode] = value.default;
}
}
}
if (!languageCodes.has(defaultLanguage)) {
delete result[defaultLanguage];
}
return result;
}
if (Array.isArray(value)) {
return value.map((entry) => serializeCanonicalValue(entry, defaultLanguage, languageCodes, options));
}
if (isPlainObject(value)) {
return Object.fromEntries(
Object.entries(value).map(([key, entry]) => [
key,
serializeCanonicalValue(entry, defaultLanguage, languageCodes, options),
])
);
}
return value as TSerializedValue;
}
function resolveRequestedLanguage(languages: TV3SurveyLanguage[], language: string): string {
const result = resolveV3SurveyLanguageCode(language, languages);
if (!result.ok) {
throw new V3SurveyLanguageError(result.message);
}
return result.code;
}
function resolveRequestedLanguages(languages: TV3SurveyLanguage[], requestedLanguages?: string[]): string[] {
if (!requestedLanguages) {
return [];
}
return requestedLanguages.map((language) => resolveRequestedLanguage(languages, language));
}
export function serializeV3SurveyResource(survey: TInternalSurvey, options?: { lang?: string[] }) {
if (Array.isArray(survey.questions) && survey.questions.length > 0) {
throw new V3SurveyUnsupportedShapeError(
"Legacy question-based surveys are not supported by the v3 survey management API"
);
}
const defaultLanguage = getV3SurveyDefaultLanguage(survey, DEFAULT_V3_SURVEY_LANGUAGE);
const languages = getV3SurveyLanguages(survey, DEFAULT_V3_SURVEY_LANGUAGE);
const configuredLanguageCodes = new Set(languages.map((language) => language.code));
const requestedLanguages = resolveRequestedLanguages(languages, options?.lang);
const languageCodes = requestedLanguages.length > 0 ? new Set(requestedLanguages) : configuredLanguageCodes;
const serializeValue = (value: unknown) =>
serializeCanonicalValue(value, defaultLanguage, languageCodes, {
fallbackMissingTranslations: requestedLanguages.length > 0,
});
return {
id: survey.id,
workspaceId: survey.workspaceId,
createdAt: toIsoString(survey.createdAt),
updatedAt: toIsoString(survey.updatedAt),
name: survey.name,
type: survey.type,
status: survey.status,
metadata: survey.metadata,
defaultLanguage,
languages,
welcomeCard: serializeValue(survey.welcomeCard),
blocks: serializeValue(survey.blocks),
endings: serializeValue(survey.endings),
hiddenFields: survey.hiddenFields,
variables: survey.variables,
};
}
@@ -0,0 +1,108 @@
import { z } from "zod";
import { logger } from "@formbricks/logger";
import { DatabaseError } from "@formbricks/types/errors";
import { withV3ApiWrapper } from "@/app/api/v3/lib/api-wrapper";
import { requireV3WorkspaceAccess } from "@/app/api/v3/lib/auth";
import { problemInternalError, successResponse } from "@/app/api/v3/lib/response";
import { getAuthorizedV3Survey } from "../authorization";
import {
type TV3SurveyPrepareResult,
prepareV3SurveyCreateInput,
prepareV3SurveyPatchInput,
} from "../prepare";
import { type TV3SurveyDocument, ZV3EmptyQuery, ZV3SurveyValidationRequestBody } from "../schemas";
const createWorkspaceSchema = z.object({
workspaceId: z.cuid2(),
});
function serializeValidationResult<TDocument extends TV3SurveyDocument>(
operation: "create" | "patch",
preparation: TV3SurveyPrepareResult<TDocument>
) {
if (!preparation.ok) {
return {
valid: false,
operation,
invalid_params: preparation.validation.invalidParams,
};
}
return {
valid: true,
operation,
invalid_params: [],
languages: preparation.languageRequests.map((languageRequest) => ({
...languageRequest,
writeBehavior: "connect_or_create" as const,
})),
};
}
export const POST = withV3ApiWrapper({
auth: "both",
schemas: {
body: ZV3SurveyValidationRequestBody,
query: ZV3EmptyQuery,
},
handler: async ({ parsedInput, authentication, requestId, instance }) => {
const { body } = parsedInput;
const log = logger.withContext({ requestId, operation: body.operation });
try {
if (body.operation === "create") {
const workspaceResult = createWorkspaceSchema.safeParse(body.data);
if (workspaceResult.success) {
const authResult = await requireV3WorkspaceAccess(
authentication,
workspaceResult.data.workspaceId,
"readWrite",
requestId,
instance
);
if (authResult instanceof Response) {
return authResult;
}
}
return successResponse(serializeValidationResult("create", prepareV3SurveyCreateInput(body.data)), {
requestId,
cache: "private, no-store",
});
}
const { survey, response } = await getAuthorizedV3Survey({
surveyId: body.surveyId,
authentication,
access: "readWrite",
requestId,
instance,
});
if (response) {
log.warn(
{ statusCode: response.status, surveyId: body.surveyId },
"Survey not found or not accessible"
);
return response;
}
return successResponse(
serializeValidationResult("patch", prepareV3SurveyPatchInput(survey, body.data)),
{
requestId,
cache: "private, no-store",
}
);
} catch (error) {
if (error instanceof DatabaseError) {
log.error({ error, statusCode: 500 }, "Database error");
return problemInternalError(requestId, "An unexpected error occurred.", instance);
}
log.error({ error, statusCode: 500 }, "V3 survey validation unexpected error");
return problemInternalError(requestId, "An unexpected error occurred.", instance);
}
},
});
+27
View File
@@ -0,0 +1,27 @@
import type { InvalidParam } from "@/app/api/v3/lib/response";
import { validateV3SurveyReferences } from "./reference-validation";
import type { TV3SurveyDocument } from "./schemas";
export type TV3SurveyDocumentValidationResult =
| { valid: true; invalidParams: [] }
| { valid: false; invalidParams: InvalidParam[] };
export function validateV3SurveyDocument(document: TV3SurveyDocument): TV3SurveyDocumentValidationResult {
const referenceValidation = validateV3SurveyReferences({
blocks: document.blocks,
endings: document.endings,
hiddenFields: document.hiddenFields,
metadata: document.metadata,
variables: document.variables,
welcomeCard: document.welcomeCard,
});
if (!referenceValidation.ok) {
return {
valid: false,
invalidParams: referenceValidation.invalidParams,
};
}
return { valid: true, invalidParams: [] };
}
+79
View File
@@ -733,6 +733,85 @@ describe("Tests for createSurvey", () => {
})
);
});
test("creates survey languages from validated language inputs", async () => {
vi.mocked(getOrganizationByWorkspaceId).mockResolvedValueOnce(mockOrganizationOutput);
prisma.survey.create.mockResolvedValueOnce({
...mockSurveyOutput,
});
await createSurvey(mockWorkspaceId, {
...mockCreateSurveyInput,
languages: [
{
default: true,
enabled: true,
language: {
id: "cllang12345678901234567890",
code: "en-US",
alias: null,
workspaceId: mockWorkspaceId,
createdAt: new Date(),
updatedAt: new Date(),
},
},
],
});
expect(prisma.survey.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
languages: {
create: [
{
language: {
connect: {
id: "cllang12345678901234567890",
},
},
default: true,
enabled: true,
},
],
},
}),
})
);
});
test("preserves an explicitly provided segment relation for existing callers", async () => {
vi.mocked(getOrganizationByWorkspaceId).mockResolvedValueOnce(mockOrganizationOutput);
prisma.survey.create.mockResolvedValueOnce({
...mockSurveyOutput,
});
await createSurvey(mockWorkspaceId, {
...mockCreateSurveyInput,
segment: {
id: "clseg123456789012345678901",
title: "Segment",
description: null,
isPrivate: false,
filters: [],
workspaceId: mockWorkspaceId,
surveys: [],
createdAt: new Date(),
updatedAt: new Date(),
},
});
expect(prisma.survey.create).toHaveBeenCalledWith(
expect.objectContaining({
data: expect.objectContaining({
segment: {
connect: {
id: "clseg123456789012345678901",
},
},
}),
})
);
});
});
describe("Sad Path", () => {
+18 -7
View File
@@ -628,9 +628,23 @@ export const createSurvey = async (workspaceId: string, surveyBody: TSurveyCreat
);
try {
const { createdBy, languages, ...restSurveyBody } = parsedSurveyBody;
const { createdBy, languages, segment, followUps, ...restSurveyBody } = parsedSurveyBody;
const normalizedCloseOn = restSurveyBody.closeOn instanceof Date ? restSurveyBody.closeOn : null;
const normalizedPublishOn = restSurveyBody.publishOn instanceof Date ? restSurveyBody.publishOn : null;
const surveyLanguagesCreateData: Prisma.SurveyLanguageCreateNestedManyWithoutSurveyInput | undefined =
languages?.length
? {
create: languages.map((surveyLanguage) => ({
language: {
connect: {
id: surveyLanguage.language.id,
},
},
default: surveyLanguage.default,
enabled: surveyLanguage.enabled,
})),
}
: undefined;
const actionClasses = await getActionClasses(parsedWorkspaceId);
@@ -641,18 +655,15 @@ export const createSurvey = async (workspaceId: string, surveyBody: TSurveyCreat
publishOn: normalizedPublishOn,
status: restSurveyBody.status ?? "draft",
}),
// @ts-expect-error - languages would be undefined in case of empty array
languages: languages?.length ? languages : undefined,
languages: surveyLanguagesCreateData,
segment: segment?.id ? { connect: { id: segment.id } } : undefined,
triggers: restSurveyBody.triggers
? handleTriggerUpdates(restSurveyBody.triggers, [], actionClasses)
: undefined,
attributeFilters: undefined,
};
const data = validateSurveyCreateDataMedia(
attachSurveyFollowUpsToCreateData(
attachSurveyCreatorToCreateData(baseData, createdBy),
restSurveyBody.followUps
)
attachSurveyFollowUpsToCreateData(attachSurveyCreatorToCreateData(baseData, createdBy), followUps)
);
const organization = await getOrganizationByWorkspaceId(parsedWorkspaceId);
@@ -5,7 +5,6 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import {
AuthenticationError,
AuthorizationError,
ConfigurationError,
EXPECTED_ERROR_NAMES,
INVALID_PASSWORD_RESET_TOKEN_ERROR_CODE,
InvalidInputError,
@@ -75,7 +74,6 @@ describe("isExpectedError (shared helper)", () => {
"ValidationError",
"AuthenticationError",
"OperationNotAllowedError",
"ConfigurationError",
"QueryExecutionError",
"TooManyRequestsError",
"InvalidPasswordResetTokenError",
@@ -96,7 +94,6 @@ describe("isExpectedError (shared helper)", () => {
{ ErrorClass: InvalidInputError, args: ["Invalid input"] },
{ ErrorClass: ValidationError, args: ["Invalid data"] },
{ ErrorClass: OperationNotAllowedError, args: ["Not allowed"] },
{ ErrorClass: ConfigurationError, args: ["Cube is not configured"] },
{ ErrorClass: QueryExecutionError, args: ["Cube query failed. Details: connect ECONNREFUSED"] },
{ ErrorClass: InvalidPasswordResetTokenError, args: [INVALID_PASSWORD_RESET_TOKEN_ERROR_CODE] },
{ ErrorClass: UniqueConstraintError, args: ["Already exists"] },
@@ -188,12 +185,6 @@ describe("actionClient handleServerError", () => {
expect(Sentry.captureException).not.toHaveBeenCalled();
});
test("ConfigurationError returns its message and is not sent to Sentry", async () => {
const result = await executeThrowingAction(new ConfigurationError("Cube is not configured"));
expect(result?.serverError).toBe("Cube is not configured");
expect(Sentry.captureException).not.toHaveBeenCalled();
});
test("QueryExecutionError returns its message and is not sent to Sentry", async () => {
const result = await executeThrowingAction(
new QueryExecutionError("Cube query failed. Details: connect ECONNREFUSED")
+3 -3
View File
@@ -2710,6 +2710,8 @@
"save_the_following_backup_codes_in_a_safe_place": "Speichere die folgenden Backup-Codes an einem sicheren Ort.",
"scan_the_qr_code_below_with_your_authenticator_app": "Scanne den QR-Code unten mit deiner Authenticator-App.",
"security_description": "Verwalte dein Passwort und andere Sicherheitseinstellungen wie die Zwei-Faktor-Authentifizierung (2FA).",
"sso_identity_confirmation_failed": "SSO-Identitätsbestätigung fehlgeschlagen. Bitte versuche erneut, dein Konto zu löschen.",
"sso_identity_confirmation_may_be_required_for_deletion": "Bei SSO-Konten kann dich die Auswahl von Löschen zu deinem Identitätsanbieter weiterleiten, um dieses Konto zu bestätigen. Wenn dasselbe Konto bestätigt wird, wird die Löschung automatisch fortgesetzt.",
"two_factor_authentication": "Zwei-Faktor-Authentifizierung",
"two_factor_authentication_description": "Füge deinem Konto eine zusätzliche Sicherheitsebene hinzu, falls dein Passwort gestohlen wird.",
"two_factor_authentication_enabled_please_enter_the_six_digit_code_from_your_authenticator_app": "Zwei-Faktor-Authentifizierung aktiviert. Bitte gib den sechsstelligen Code aus deiner Authenticator-App ein.",
@@ -2718,9 +2720,7 @@
"update_personal_info": "Aktualisiere deine persönlichen Informationen",
"warning_cannot_delete_account": "Du bist der einzige Inhaber dieser Organisation. Bitte übertrage zuerst die Inhaberschaft auf ein anderes Mitglied.",
"warning_cannot_undo": "Dies kann nicht rückgängig gemacht werden",
"wrong_password": "Falsches Passwort",
"sso_identity_confirmation_failed": "SSO-Identitätsbestätigung fehlgeschlagen. Bitte versuche erneut, dein Konto zu löschen.",
"sso_identity_confirmation_may_be_required_for_deletion": "Bei SSO-Konten kann dich die Auswahl von Löschen zu deinem Identitätsanbieter weiterleiten, um dieses Konto zu bestätigen. Wenn dasselbe Konto bestätigt wird, wird die Löschung automatisch fortgesetzt."
"wrong_password": "Falsches Passwort"
},
"teams": {
"add_members_description": "Füge Mitglieder zum Team hinzu und lege ihre Rolle fest.",
+3 -3
View File
@@ -2710,6 +2710,8 @@
"save_the_following_backup_codes_in_a_safe_place": "Aşağıdaki yedekleme kodlarını güvenli bir yerde sakla.",
"scan_the_qr_code_below_with_your_authenticator_app": "Aşağıdaki QR kodunu kimlik doğrulayıcı uygulamanla tara.",
"security_description": "Şifreni ve iki faktörlü kimlik doğrulama (2FA) gibi diğer güvenlik ayarlarını yönet.",
"sso_identity_confirmation_failed": "SSO kimlik doğrulaması başarısız oldu. Lütfen hesabınızı silmeyi tekrar deneyin.",
"sso_identity_confirmation_may_be_required_for_deletion": "SSO hesaplarında Sil'i seçmek, bu hesabı onaylamanız için sizi kimlik sağlayıcınıza yönlendirebilir. Aynı hesap onaylanırsa silme işlemi otomatik olarak devam eder.",
"two_factor_authentication": "İki faktörlü kimlik doğrulama",
"two_factor_authentication_description": "Şifren çalınması durumunda hesabına ekstra bir güvenlik katmanı ekle.",
"two_factor_authentication_enabled_please_enter_the_six_digit_code_from_your_authenticator_app": "İki faktörlü kimlik doğrulama etkinleştirildi. Lütfen kimlik doğrulayıcı uygulamandaki altı haneli kodu gir.",
@@ -2718,9 +2720,7 @@
"update_personal_info": "Kişisel bilgilerini güncelle",
"warning_cannot_delete_account": "Bu organizasyonun tek sahibi sensin. Lütfen önce sahipliği başka bir üyeye aktar.",
"warning_cannot_undo": "Bu geri alınamaz",
"wrong_password": "Yanlış şifre",
"sso_identity_confirmation_failed": "SSO kimlik doğrulaması başarısız oldu. Lütfen hesabınızı silmeyi tekrar deneyin.",
"sso_identity_confirmation_may_be_required_for_deletion": "SSO hesaplarında Sil'i seçmek, bu hesabı onaylamanız için sizi kimlik sağlayıcınıza yönlendirebilir. Aynı hesap onaylanırsa silme işlemi otomatik olarak devam eder."
"wrong_password": "Yanlış şifre"
},
"teams": {
"add_members_description": "Ekibe üye ekle ve rollerini belirle.",
@@ -112,4 +112,12 @@ describe("cube-config", () => {
await expect(import("./cube-config")).rejects.toThrow("Invalid environment variables");
});
test("fails at env validation when CUBEJS_API_SECRET is an empty string", async () => {
setTestEnv({
CUBEJS_API_SECRET: "",
});
await expect(import("./cube-config")).rejects.toThrow("Invalid environment variables");
});
});
@@ -1,11 +1,8 @@
import "server-only";
import jwt from "jsonwebtoken";
import { randomUUID } from "node:crypto";
import { ConfigurationError } from "@formbricks/types/errors";
import { env } from "@/lib/env";
export const CUBE_CONFIGURATION_ERROR_MESSAGE =
"Cube is not configured on this instance. Set CUBEJS_API_URL and CUBEJS_API_SECRET.";
export const CUBE_API_TOKEN_TTL_SECONDS = 5 * 60;
export const CUBE_QUERY_SCOPE = "xm:cube:query";
export const DEFAULT_CUBE_JWT_AUDIENCE = "formbricks-cube";
@@ -39,18 +36,12 @@ export const normalizeCubeApiUrl = (baseUrl: string): string => {
return `${normalizedBaseUrl}/cubejs-api/v1`;
};
export const getCubeApiCredentials = () => {
if (!env.CUBEJS_API_URL || !env.CUBEJS_API_SECRET) {
throw new ConfigurationError(CUBE_CONFIGURATION_ERROR_MESSAGE);
}
return {
apiUrl: normalizeCubeApiUrl(env.CUBEJS_API_URL),
apiSecret: env.CUBEJS_API_SECRET,
audience: env.CUBEJS_JWT_AUDIENCE ?? DEFAULT_CUBE_JWT_AUDIENCE,
issuer: env.CUBEJS_JWT_ISSUER ?? DEFAULT_CUBE_JWT_ISSUER,
};
};
export const getCubeApiCredentials = () => ({
apiUrl: normalizeCubeApiUrl(env.CUBEJS_API_URL),
apiSecret: env.CUBEJS_API_SECRET,
audience: env.CUBEJS_JWT_AUDIENCE ?? DEFAULT_CUBE_JWT_AUDIENCE,
issuer: env.CUBEJS_JWT_ISSUER ?? DEFAULT_CUBE_JWT_ISSUER,
});
export const createCubeApiToken = (
apiSecret: string,
+144
View File
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
import { StorageErrorCode } from "@formbricks/storage";
import { TResponseData } from "@formbricks/types/responses";
import { ZAllowedFileExtension } from "@formbricks/types/storage";
import { TSurveyBlock } from "@formbricks/types/surveys/blocks";
import { TSurveyQuestion } from "@formbricks/types/surveys/types";
import {
isAllowedFileExtension,
@@ -12,6 +13,7 @@ import {
sanitizeFileName,
validateFileUploads,
validateSingleFile,
validateSurveyAllowsFileUpload,
} from "@/modules/storage/utils";
// Mock the getOriginalFileNameFromUrl function
@@ -351,6 +353,148 @@ describe("storage utils", () => {
});
});
describe("validateSurveyAllowsFileUpload", () => {
test("should allow a matching extension from a modern file upload block element", () => {
const blocks = [
{
id: "block1",
name: "Block 1",
elements: [
{
id: "element1",
type: "fileUpload" as const,
allowedFileExtensions: ["pdf"],
},
],
},
] as unknown as TSurveyBlock[];
expect(validateSurveyAllowsFileUpload({ fileName: "report.pdf", blocks })).toEqual({ ok: true });
});
test("should allow a matching extension from a legacy file upload question", () => {
const questions = [
{
id: "question1",
type: "fileUpload" as const,
allowedFileExtensions: ["png"],
},
] as TSurveyQuestion[];
expect(validateSurveyAllowsFileUpload({ fileName: "image.png", questions })).toEqual({ ok: true });
});
test("should allow any globally safe extension when a file upload has no survey restriction", () => {
const blocks = [
{
id: "block1",
name: "Block 1",
elements: [
{
id: "element1",
type: "fileUpload" as const,
},
],
},
] as unknown as TSurveyBlock[];
expect(validateSurveyAllowsFileUpload({ fileName: "report.pdf", blocks })).toEqual({ ok: true });
});
test("should reject surveys without file upload blocks or questions", () => {
const blocks = [
{
id: "block1",
name: "Block 1",
elements: [
{
id: "element1",
type: "openText" as const,
},
],
},
] as unknown as TSurveyBlock[];
const questions = [
{
id: "question1",
type: "openText" as const,
},
] as TSurveyQuestion[];
expect(validateSurveyAllowsFileUpload({ fileName: "report.pdf", blocks, questions })).toEqual({
ok: false,
reason: "no_file_upload_question",
});
});
test("should reject when no file upload entry allows the requested extension", () => {
const blocks = [
{
id: "block1",
name: "Block 1",
elements: [
{
id: "element1",
type: "fileUpload" as const,
allowedFileExtensions: ["jpg"],
},
{
id: "element2",
type: "fileUpload" as const,
allowedFileExtensions: ["png"],
},
],
},
] as unknown as TSurveyBlock[];
expect(validateSurveyAllowsFileUpload({ fileName: "report.pdf", blocks })).toEqual({
ok: false,
reason: "file_extension_not_allowed",
});
});
test("should allow when any file upload entry permits the requested extension", () => {
const blocks = [
{
id: "block1",
name: "Block 1",
elements: [
{
id: "element1",
type: "fileUpload" as const,
allowedFileExtensions: ["jpg"],
},
{
id: "element2",
type: "fileUpload" as const,
allowedFileExtensions: ["pdf"],
},
],
},
] as unknown as TSurveyBlock[];
expect(validateSurveyAllowsFileUpload({ fileName: "report.pdf", blocks })).toEqual({ ok: true });
});
test("should reject files without a globally safe extension even when the survey has an unrestricted upload", () => {
const questions = [
{
id: "question1",
type: "fileUpload" as const,
},
] as TSurveyQuestion[];
expect(validateSurveyAllowsFileUpload({ fileName: "report", questions })).toEqual({
ok: false,
reason: "file_extension_not_allowed",
});
expect(validateSurveyAllowsFileUpload({ fileName: "malware.exe", questions })).toEqual({
ok: false,
reason: "file_extension_not_allowed",
});
});
});
describe("isValidImageFile", () => {
test("should return true for valid image file extensions", () => {
expect(isValidImageFile("https://example.com/image.jpg")).toBe(true);
+82 -4
View File
@@ -2,6 +2,8 @@ import "server-only";
import { type StorageError, StorageErrorCode } from "@formbricks/storage";
import { TResponseData } from "@formbricks/types/responses";
import { TAllowedFileExtension, ZAllowedFileExtension } from "@formbricks/types/storage";
import { TSurveyBlock } from "@formbricks/types/surveys/blocks";
import { TSurveyElementTypeEnum, TSurveyFileUploadElement } from "@formbricks/types/surveys/elements";
import { TSurveyQuestion, TSurveyQuestionTypeEnum } from "@formbricks/types/surveys/types";
import { responses } from "@/app/lib/api/response";
import { WEBAPP_URL } from "@/lib/constants";
@@ -57,15 +59,27 @@ export const sanitizeFileName = (rawFileName: string): string => {
return result;
};
/**
* Extracts the lowercase file extension from a file name
* @param fileName The name of the file
* @returns {string | null} The lowercase extension, or null when no extension exists
*/
const extractFileExtension = (fileName: string): string | null => {
const extension = fileName.split(".").pop()?.toLowerCase();
if (!extension || extension === fileName.toLowerCase()) return null;
return extension;
};
/**
* Validates if the file extension is allowed
* @param fileName The name of the file to validate
* @returns {boolean} True if the file extension is allowed, false otherwise
*/
export const isAllowedFileExtension = (fileName: string): boolean => {
// Extract the file extension
const extension = fileName.split(".").pop()?.toLowerCase();
if (!extension || extension === fileName.toLowerCase()) return false;
const extension = extractFileExtension(fileName);
if (!extension) return false;
// Check if the extension is in the allowed list
return Object.values(ZAllowedFileExtension.enum).includes(extension as TAllowedFileExtension);
@@ -77,7 +91,7 @@ export const validateSingleFile = (
): boolean => {
const fileName = getOriginalFileNameFromUrl(fileUrl);
if (!fileName) return false;
const extension = fileName.split(".").pop()?.toLowerCase();
const extension = extractFileExtension(fileName);
if (!extension) return false;
return !allowedFileExtensions || allowedFileExtensions.includes(extension as TAllowedFileExtension);
};
@@ -100,6 +114,70 @@ export const validateFileUploads = (data?: TResponseData, questions?: TSurveyQue
return true;
};
export type TSurveyFileUploadPermissionResult =
| {
ok: true;
}
| {
ok: false;
reason: "no_file_upload_question" | "file_extension_not_allowed";
};
const getAllowedFileExtensionFromFileName = (fileName: string): TAllowedFileExtension | null => {
const extension = extractFileExtension(fileName);
if (!extension) return null;
const extensionValidation = ZAllowedFileExtension.safeParse(extension);
return extensionValidation.success ? extensionValidation.data : null;
};
export const validateSurveyAllowsFileUpload = ({
fileName,
blocks,
questions,
}: {
fileName: string;
blocks?: TSurveyBlock[] | null;
questions?: TSurveyQuestion[] | null;
}): TSurveyFileUploadPermissionResult => {
const fileUploadConfigs = [
...(blocks ?? [])
.flatMap((block) => block.elements)
.filter((element) => element.type === TSurveyElementTypeEnum.FileUpload),
...(questions ?? []).filter((question) => question.type === TSurveyQuestionTypeEnum.FileUpload),
] as TSurveyFileUploadElement[];
if (fileUploadConfigs.length === 0) {
return {
ok: false,
reason: "no_file_upload_question",
};
}
const fileExtension = getAllowedFileExtensionFromFileName(fileName);
if (!fileExtension) {
return {
ok: false,
reason: "file_extension_not_allowed",
};
}
const isFileExtensionAllowed = fileUploadConfigs.some((fileUploadConfig) => {
const { allowedFileExtensions } = fileUploadConfig;
return allowedFileExtensions === undefined || allowedFileExtensions.includes(fileExtension);
});
return isFileExtensionAllowed
? { ok: true }
: {
ok: false,
reason: "file_extension_not_allowed",
};
};
export const isValidImageFile = (fileUrl: string): boolean => {
const fileName = getOriginalFileNameFromUrl(fileUrl);
if (!fileName || fileName.endsWith(".")) return false;
@@ -3,6 +3,7 @@
import { Workspace } from "@prisma/client";
import { useSearchParams } from "next/navigation";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { TResponseData } from "@formbricks/types/responses";
import { TSurvey, TSurveyStyling } from "@formbricks/types/surveys/types";
import { TWorkspaceStyling } from "@formbricks/types/workspace";
@@ -13,7 +14,7 @@ import { LinkSurveyWrapper } from "@/modules/survey/link/components/link-survey-
import { OfflineAlert } from "@/modules/survey/link/components/offline-alert";
import { getPrefillValue } from "@/modules/survey/link/lib/prefill";
import { getUserIdFromSearchParams } from "@/modules/survey/link/lib/user-id";
import { isRTLLanguage } from "@/modules/survey/link/lib/utils";
import { getWebAppLocale, isRTLLanguage } from "@/modules/survey/link/lib/utils";
import { SurveyInline } from "@/modules/ui/components/survey";
interface SurveyClientWrapperProps {
@@ -63,6 +64,17 @@ export const SurveyClientWrapper = ({
IS_FORMBRICKS_CLOUD,
}: SurveyClientWrapperProps) => {
const searchParams = useSearchParams();
const { i18n } = useTranslation();
useEffect(() => {
const webAppLocale = getWebAppLocale(languageCode, survey);
if (i18n.language !== webAppLocale) {
i18n.changeLanguage(webAppLocale).catch(() => {
i18n.changeLanguage("en-US");
});
}
}, [languageCode, survey, i18n]);
const skipPrefilled = searchParams.get("skipPrefilled") === "true";
const offlineSupport = searchParams.get("offlineSupport") === "true";
const userId = canReadUserIdFromUrl ? getUserIdFromSearchParams(searchParams) : undefined;
@@ -99,12 +99,7 @@ describe("useDeleteSurvey", () => {
0
);
resolveFetch?.(
new Response(JSON.stringify({ data: { id: "survey_1" } }), {
status: 200,
headers: { "Content-Type": "application/json" },
})
);
resolveFetch?.(new Response(null, { status: 204 }));
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(invalidateQueriesSpy).toHaveBeenCalledWith({ queryKey: surveyKeys.lists() });
@@ -1,5 +1,10 @@
import { describe, expect, test } from "vitest";
import { buildSurveyListSearchParams } from "./v3-surveys-client";
import { afterEach, describe, expect, test, vi } from "vitest";
import type { V3ApiError } from "@/modules/api/lib/v3-client";
import { buildSurveyListSearchParams, deleteSurvey } from "./v3-surveys-client";
afterEach(() => {
vi.unstubAllGlobals();
});
describe("buildSurveyListSearchParams", () => {
test("emits only supported v3 params using normalized filter values", () => {
@@ -39,3 +44,39 @@ describe("buildSurveyListSearchParams", () => {
);
});
});
describe("deleteSurvey", () => {
test("treats 204 No Content as a successful delete", async () => {
const fetchMock = vi.fn().mockResolvedValue(new Response(null, { status: 204 }));
vi.stubGlobal("fetch", fetchMock);
await expect(deleteSurvey("survey_1")).resolves.toBeUndefined();
expect(fetchMock).toHaveBeenCalledWith("/api/v3/surveys/survey_1", {
method: "DELETE",
cache: "no-store",
});
});
test("maps v3 problem responses to V3ApiError", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue(
Response.json(
{
status: 403,
detail: "You are not authorized to access this resource",
code: "forbidden",
},
{ status: 403 }
)
)
);
await expect(deleteSurvey("survey_1")).rejects.toMatchObject<V3ApiError>({
status: 403,
detail: "You are not authorized to access this resource",
code: "forbidden",
});
});
});
@@ -13,12 +13,6 @@ type TV3SurveyListResponse = {
meta: TSurveyListPage["meta"];
};
type TV3DeleteSurveyResponse = {
data: {
id: string;
};
};
export type TSurveyListPage = {
data: TSurveyListItem[];
meta: {
@@ -122,7 +116,7 @@ export async function listSurveys({
};
}
export async function deleteSurvey(surveyId: string): Promise<{ id: string }> {
export async function deleteSurvey(surveyId: string): Promise<void> {
const response = await fetch(`/api/v3/surveys/${surveyId}`, {
method: "DELETE",
cache: "no-store",
@@ -131,7 +125,4 @@ export async function deleteSurvey(surveyId: string): Promise<{ id: string }> {
if (!response.ok) {
throw await parseV3ApiError(response);
}
const body = (await response.json()) as TV3DeleteSurveyResponse;
return body.data;
}
+6 -5
View File
@@ -46,14 +46,15 @@ The intended defaults are:
- self-hosted / single-tenant clusters: bundled controller mode
- shared clusters with an existing platform controller: external-controller mode
## Cube.js for XM Suite v5
## Cube
XM Suite v5 dashboard and analysis features require Cube.js. Set `cube.enabled=true` to deploy an
internal Cube service from this chart, or provide an external Cube endpoint.
Cube is part of the baseline Formbricks v5 stack and is deployed by this chart by default
(`cube.enabled: true`).
- For chart-managed Cube, set `deployment.env.CUBEJS_API_URL` to `http://formbricks-cube:4000`
- For the chart-managed Cube, `deployment.env.CUBEJS_API_URL` should point at `http://formbricks-cube:4000`
when using the default release name.
- For external Cube, set `deployment.env.CUBEJS_API_URL` to your Cube endpoint.
- For an external Cube, set `cube.enabled: false` and point `deployment.env.CUBEJS_API_URL` at your
endpoint.
- Provide `CUBEJS_API_SECRET` through your existing secret management flow, such as the generated app secret override or `deployment.envFrom`.
- Provide `CUBEJS_DB_*` connection variables to the Cube deployment through `cube.envFrom` or `cube.env`.
- Keep `cube.replicas=1` while `cube.env.CUBEJS_CACHE_AND_QUEUE_DRIVER` is `memory`. Configure Cube Store before running multiple Cube replicas.
+6 -8
View File
@@ -96,8 +96,8 @@ deployment:
# nameSuffix: app-secrets
# Environment variables passed to the app container.
# XM Suite v5 analytics requires an external Cube endpoint when using Helm:
# set deployment.env.CUBEJS_API_URL and provide CUBEJS_API_SECRET through a Secret referenced by envFrom/existingSecret.
# Cube is bundled by default (see the `cube` section below). To use an external Cube cluster instead,
# set `cube.enabled: false` and provide CUBEJS_API_URL / CUBEJS_API_SECRET here via deployment.env or envFrom.
env: {}
# Tolerations for scheduling pods on tainted nodes
@@ -561,8 +561,10 @@ serviceMonitor:
# Cube.js Analytics Configuration
##########################################################
cube:
# Optional internal Cube.js service for XM Suite v5 analytics.
enabled: false
# Cube semantic-layer service used by Formbricks analytics. Bundled by default.
# Set to false only if you want to point the app at an external Cube cluster
# via deployment.env.CUBEJS_API_URL (CUBEJS_API_SECRET must still be provided).
enabled: true
replicas: 1
image:
@@ -900,10 +902,6 @@ hub:
affinity: {}
topologySpreadConstraints: []
# XM Suite v5 analytics also requires Cube. Use cube.enabled=true to deploy
# the internal chart-managed Cube service, or set deployment.env.CUBEJS_API_URL
# to an operator-managed Cube endpoint.
# Upgrade migration job runs goose + river before Helm upgrades Hub resources.
# Fresh installs run the same migrations through the Hub deployment init container.
migration:
-1
View File
@@ -155,7 +155,6 @@ services:
<<: *hub-runtime-environment
cube:
profiles: ["xm"]
image: cubejs/cube:v1.6.6
env_file:
- apps/web/.env
+4 -4
View File
@@ -30,13 +30,13 @@ That's it! After running the command and providing the required information, vis
## Formbricks Hub and Cube
The stack includes the [Formbricks Hub](https://github.com/formbricks/hub) API (`ghcr.io/formbricks/hub`) and can also run a bundled Cube.js service for XM Suite v5 analytics. Hub and Cube share the same database as Formbricks by default, and Cube is enabled through the optional Docker Compose `xm` profile.
The stack includes the [Formbricks Hub](https://github.com/formbricks/hub) API (`ghcr.io/formbricks/hub`) and the bundled Cube service. Hub and Cube share the same database as Formbricks by default and both start as part of the baseline `docker compose up`.
- **Migrations**: A `hub-migrate` service runs Hub's database migrations (goose + river) before the Hub API starts. It runs on every `docker compose up` and is idempotent.
- **Production** (`docker/docker-compose.yml`): Set `HUB_API_KEY` (required). `HUB_API_URL` defaults to `http://hub:8080` so the Formbricks app can reach Hub inside the compose network. To enable XM Suite v5 analytics, set `COMPOSE_PROFILES=xm` and `CUBEJS_API_SECRET`; `CUBEJS_API_URL` defaults to `http://cube:4000`. Cube JWT issuer/audience default to `formbricks-web` and `formbricks-cube`, and the bundled Cube service exposes only `meta,data` API scopes. Override `HUB_DATABASE_URL` and `CUBEJS_DB_*` only if Hub or Cube should use a separate database. The Hub image tracks `:latest` by default so `formbricks.sh update` advances Hub in lockstep with the app. `hub` and `hub-migrate` always resolve to the same image. To pin to an immutable reference, set `HUB_IMAGE_REF` in `docker/.env` to either a tag (e.g. `:0.3.0`) or a digest (e.g. `@sha256:14db7b3d...`).
- **Development** (`docker-compose.dev.yml`): Hub uses a dedicated local `hub` database and `HUB_API_KEY` defaults to `dev-api-key`. The dev stack starts `hub` plus `hub-worker`; set `EMBEDDING_PROVIDER`, `EMBEDDING_MODEL`, and any provider credentials in the repo root `.env` to enable Hub embeddings locally. See the [Hub embeddings environment reference](https://hub.formbricks.com/reference/environment-variables/#embeddings) for provider-specific values. Cube is behind the `xm` profile, `CUBEJS_API_URL` defaults to `http://localhost:4000`, and `pnpm dev:setup` generates `CUBEJS_API_SECRET` in the repo root `.env`. The Hub image is pinned to a semver tag (`hub`, `hub-worker`, and `hub-migrate` share the same value); override `HUB_IMAGE_TAG` in the repo root `.env` to test a specific Hub release.
- **Production** (`docker/docker-compose.yml`): Set `HUB_API_KEY` and `CUBEJS_API_SECRET` (both required). `HUB_API_URL` defaults to `http://hub:8080` and `CUBEJS_API_URL` defaults to `http://cube:4000` so the Formbricks app reaches Hub and Cube inside the compose network. Cube JWT issuer/audience default to `formbricks-web` and `formbricks-cube`, and the bundled Cube service exposes only `meta,data` API scopes. Override `HUB_DATABASE_URL` and `CUBEJS_DB_*` only if Hub or Cube should use a separate database. The Hub image tracks `:latest` by default so `formbricks.sh update` advances Hub in lockstep with the app. `hub` and `hub-migrate` always resolve to the same image. To pin to an immutable reference, set `HUB_IMAGE_REF` in `docker/.env` to either a tag (e.g. `:0.3.0`) or a digest (e.g. `@sha256:14db7b3d...`).
- **Development** (`docker-compose.dev.yml`): Hub uses a dedicated local `hub` database and `HUB_API_KEY` defaults to `dev-api-key`. The dev stack starts `hub` plus `hub-worker`; set `EMBEDDING_PROVIDER`, `EMBEDDING_MODEL`, and any provider credentials in the repo root `.env` to enable Hub embeddings locally. See the [Hub embeddings environment reference](https://hub.formbricks.com/reference/environment-variables/#embeddings) for provider-specific values. Cube starts with the dev stack, `CUBEJS_API_URL` defaults to `http://localhost:4000`, and `pnpm dev:setup` generates `CUBEJS_API_SECRET` in the repo root `.env`. The Hub image is pinned to a semver tag (`hub`, `hub-worker`, and `hub-migrate` share the same value); override `HUB_IMAGE_TAG` in the repo root `.env` to test a specific Hub release.
In development, Hub is exposed locally on port **8080**. When the `xm` profile is enabled, Cube is exposed on **4000** (with the Cube playground on **4001**). In production Docker Compose, Hub stays internal to the compose network at `http://hub:8080`; Cube also stays internal at `http://cube:4000` when enabled.
In development, Hub is exposed locally on port **8080** and Cube on **4000** (with the Cube playground on **4001**). In production Docker Compose, both stay internal to the compose network at `http://hub:8080` and `http://cube:4000`.
The one-click Traefik installer exposes Hub-backed FeedbackRecords on the Formbricks origin at
`/api/v3/feedbackRecords` and `/v1/feedback-records`. Traefik uses Formbricks gateway auth, rewrites the v3
+10 -3
View File
@@ -38,7 +38,7 @@ x-environment: &environment
# Hub database URL (optional). Default: same Postgres as Formbricks. Set only if Hub uses a separate DB.
# HUB_DATABASE_URL:
# Cube.js analytics for XM Suite v5. Enable the optional xm profile and set CUBEJS_API_SECRET to run Cube.
# Cube semantic-layer API used by Formbricks analytics. Required.
CUBEJS_API_URL: ${CUBEJS_API_URL:-http://cube:4000}
CUBEJS_API_SECRET: ${CUBEJS_API_SECRET:-}
CUBEJS_JWT_ISSUER: ${CUBEJS_JWT_ISSUER:-formbricks-web}
@@ -257,6 +257,8 @@ services:
condition: service_healthy
redis:
condition: service_healthy
cube:
condition: service_healthy
ports:
- 3000:3000
volumes:
@@ -294,9 +296,8 @@ services:
API_KEY: ${HUB_API_KEY:?HUB_API_KEY is required to run Hub}
DATABASE_URL: ${HUB_DATABASE_URL:-postgresql://postgres:postgres@postgres:5432/formbricks?sslmode=disable}
# Optional Cube.js analytics service for XM Suite v5. Enable with COMPOSE_PROFILES=xm and set CUBEJS_API_SECRET.
# Cube semantic-layer API used by Formbricks analytics dashboards.
cube:
profiles: ["xm"]
restart: always
image: cubejs/cube:v1.6.6
depends_on:
@@ -319,6 +320,12 @@ services:
volumes:
- ./cube/cube.js:/cube/conf/cube.js:ro
- ./cube/schema:/cube/conf/model:ro
healthcheck:
test: ["CMD", "wget", "-qO-", "http://localhost:4000/readyz"]
interval: 10s
timeout: 5s
retries: 12
start_period: 30s
volumes:
postgres:
-1
View File
@@ -527,7 +527,6 @@ EOT
hub_api_key=$(openssl rand -hex 32)
cubejs_api_secret=$(openssl rand -hex 32)
cat <<EOF > .env
COMPOSE_PROFILES=xm
HUB_API_KEY=$hub_api_key
CUBEJS_API_SECRET=$cubejs_api_secret
CUBEJS_JWT_ISSUER=formbricks-web
File diff suppressed because it is too large Load Diff
+29 -25
View File
@@ -12,11 +12,12 @@ deployment, review this section before starting the new version.
### What Changes In v5
- **Formbricks Hub is now mandatory** for self-hosted Formbricks v5 deployments.
- **Cube is now part of the baseline stack** alongside Hub. Docker, one-click, and Helm all bundle Cube by
default; `CUBEJS_API_SECRET` is required. Operators can disable the bundled Cube deployment in Helm to use
an external cluster instead.
- **Edge rate limiting is now required** for specific public and API-key routes. Those routes are no longer
throttled inside the application server.
- **AI features are configured at the instance level** via `AI_*` environment variables.
- **XM Suite v5 analytics depends on Cube.js**. The Docker and one-click stack bundle it, while Helm
deployments still need a separate reachable Cube.js instance and `CUBEJS_API_SECRET`.
<Warning>
Formbricks v5 removes application-level rate limiting for several routes that are now expected to be
@@ -32,7 +33,8 @@ Before you restart your instance on Formbricks v5:
- identify your current deployment type: one-click, manual Docker Compose, or Kubernetes/Helm
- confirm Redis/Valkey and your file storage setup are already healthy from your v4 baseline
- identify whether file uploads use external S3-compatible storage or a legacy bundled MinIO service
- decide whether this instance needs AI features, dashboards/analysis, or only core survey flows
- budget approximately ~500 MB additional RAM headroom for the bundled Cube container (dashboards and analysis are part of the baseline now)
- decide whether this instance needs optional AI features
- verify whether you already run Envoy Gateway or another equivalent edge rate limiter for the covered routes
### Required Config And Infrastructure Changes
@@ -75,13 +77,15 @@ enterprise functionality.
- `AI_PROVIDER=azure` requires `AI_AZURE_API_KEY` and either `AI_AZURE_BASE_URL` or
`AI_AZURE_RESOURCE_NAME`
#### Cube.js Analytics
#### Cube
XM Suite v5 dashboard and analysis features require Cube.js.
Cube is part of the baseline Formbricks v5 stack.
- the Docker and one-click stack bundle the `cube` service and expect `CUBEJS_API_SECRET`
- Helm deployments still need a separate reachable Cube.js instance
- the Formbricks app expects `CUBEJS_API_URL` and `CUBEJS_API_SECRET`
- the Docker, one-click, and Helm deployments all bundle the `cube` service by default
- the Formbricks app requires `CUBEJS_API_URL` and `CUBEJS_API_SECRET`; the install/dev-setup scripts
generate the secret automatically for new installs
- Helm operators who want to run an external Cube cluster can set `cube.enabled: false` and provide their
own endpoint via `deployment.env.CUBEJS_API_URL`
- if you run Cube yourself, you may also need to override `CUBEJS_DB_*` values for the Cube service
### Upgrade Steps By Deployment Type
@@ -142,15 +146,15 @@ XM Suite v5 dashboard and analysis features require Cube.js.
- add a non-empty `HUB_API_KEY` and reuse the same value wherever your deployment resolves Hub auth
- keep `HUB_API_URL` at `http://hub:8080` unless Hub runs elsewhere
- include the bundled `hub-migrate` and `hub` services
- if you use the bundled XM Suite v5 analytics stack, sync `formbricks/cube/cube.js` and
`formbricks/cube/schema/FeedbackRecords.js` from the current release and ensure
`formbricks/.env` contains `CUBEJS_API_SECRET`
- sync `formbricks/cube/cube.js` and `formbricks/cube/schema/FeedbackRecords.js` from the current
release and ensure `formbricks/.env` contains `CUBEJS_API_SECRET` (Cube is part of the baseline stack
in v5)
- if your older setup still uses bundled MinIO for uploads, review that storage path separately before the
first v5 restart; newer self-hosting updates move the bundled object-storage path to RustFS, while
external S3-compatible storage keeps the same `S3_*` app contract
- add any `AI_*` variables you need
- if you do not run the bundled Docker analytics path, point `CUBEJS_API_URL` at your external Cube.js
instance and provide the matching `CUBEJS_API_SECRET`
- if you prefer to run an external Cube instance, point `CUBEJS_API_URL` at it and provide the matching
`CUBEJS_API_SECRET`; otherwise the bundled `cube` service runs against the local Postgres
After the compose file is updated and your edge rate limiter is in place:
@@ -171,15 +175,14 @@ XM Suite v5 dashboard and analysis features require Cube.js.
- `HUB_API_KEY` is configured and the same value is available wherever your deployment resolves Hub auth
- `HUB_API_URL` points to the Hub service the app can reach
- the compose stack includes `hub-migrate` and `hub`
- the XM Suite v5 Docker stack also includes `cube`, `cube/cube.js`, and
`cube/schema/FeedbackRecords.js`, with `CUBEJS_API_SECRET` available through your `.env` or shell
environment
- the v5 stack also includes `cube`, `cube/cube.js`, and `cube/schema/FeedbackRecords.js`, with
`CUBEJS_API_SECRET` available through your `.env` or shell environment
- if your legacy Compose file still includes bundled MinIO for uploads, treat that as a separate storage
review when comparing files; newer bundled storage guidance uses RustFS, while external S3-compatible
storage keeps the same `S3_*` app contract
- any `AI_*` variables you need are set
- if you override the bundled analytics path, point `CUBEJS_API_URL` at your external Cube.js instance and
supply the matching `CUBEJS_API_SECRET`
- if you prefer to run an external Cube instance, point `CUBEJS_API_URL` at it and supply the matching
`CUBEJS_API_SECRET`; otherwise the bundled `cube` service runs against the local Postgres
Then restart the stack:
@@ -190,8 +193,8 @@ XM Suite v5 dashboard and analysis features require Cube.js.
```
<Info>
The XM Suite v5 Docker Compose stack bundles Hub and Cube.js. Keep the bundled `cube/` config files in
sync with `docker-compose.yml` when you update this path.
The v5 Docker Compose stack bundles Hub and Cube. Keep the bundled `cube/` config files in sync with
`docker-compose.yml` when you update this path.
</Info>
</Tab>
<Tab title="Kubernetes">
@@ -211,8 +214,8 @@ XM Suite v5 dashboard and analysis features require Cube.js.
- `envoy.controller.enabled=false` when the cluster already has a compatible Envoy Gateway controller
- if you use bundled Envoy rate limiting, enable a dedicated backend with `envoyRedis.enabled=true`
- if you already have an equivalent edge rate limiter outside the chart, keep that protection in place
- if the instance needs XM Suite v5 analytics or dashboards, provide `CUBEJS_API_URL` and
`CUBEJS_API_SECRET` for the external Cube.js deployment
- `CUBEJS_API_SECRET` is provided (Cube is bundled by default at `cube.enabled: true`; set to `false`
and point `CUBEJS_API_URL` at your own endpoint if you prefer an external Cube cluster)
</Tab>
</Tabs>
@@ -225,8 +228,7 @@ After the upgrade:
- verify any Hub-backed connector or feedback flows you use
- verify covered routes are rate-limited at the edge layer
- verify AI features only if you configured the required `AI_*` variables
- verify dashboards and analysis flows only if your deployment path includes Cube.js or points to an external
Cube.js instance
- verify dashboards and analysis flows against the bundled (or external) Cube endpoint
### Troubleshooting And Rollback
@@ -238,7 +240,9 @@ Common upgrade issues:
protected by the legacy in-app limiter
- **Missing AI credentials**: AI features remain unavailable until `AI_PROVIDER`, `AI_MODEL`, and the matching
provider credentials are set correctly
- **Cube not configured**: dashboards or analysis queries fail even though the core Formbricks app is healthy
- **Missing `CUBEJS_API_SECRET`** (or unreachable Cube endpoint): the Formbricks app fails env validation
at boot, or — if env vars are present but Cube is unreachable — dashboards and analysis queries fail
while the rest of the app stays healthy
If you need to roll back:
@@ -119,30 +119,30 @@ bundled Docker Compose or Helm assets, the following variables apply:
| HUB_API_URL | Base URL the Formbricks app uses to call Hub. With the bundled Docker stack, keep this at `http://hub:8080` unless Hub runs elsewhere. | required | `http://hub:8080` (bundled Docker), `http://localhost:8080` (local dev) |
| HUB_DATABASE_URL | PostgreSQL connection URL for Hub. Omit to use the same database as Formbricks. | optional | Same as Formbricks `DATABASE_URL` (shared database) |
#### Cube.js Analytics for XM Suite v5
#### Cube Analytics
XM Suite v5 dashboard and analysis features require a reachable Cube.js instance. Formbricks generates the backend
Cube is part of the baseline Formbricks v5 stack and is required. Formbricks generates the backend
Cube JWT from `CUBEJS_API_SECRET`, so `CUBEJS_API_TOKEN` is not part of the supported setup contract.
If you do not use XM Suite v5 analytics, omit the Cube variables and leave the bundled Docker `xm` profile disabled.
| Variable | Description | Required | Default |
| ------------------------- | ------------------------------------------------------------------------------------------------------ | ---------------------------------- | ------------------------------------ |
| CUBEJS_API_URL | Base URL the Formbricks app uses to call Cube. Use `http://localhost:4000` locally. | required for XM Suite v5 analytics | `http://localhost:4000` in local dev |
| CUBEJS_API_SECRET | Shared secret Formbricks uses to sign Cube API JWTs. Generate with `openssl rand -hex 32`. | required for XM Suite v5 analytics | |
| CUBEJS_JWT_ISSUER | JWT issuer expected by Cube and used by Formbricks when signing per-request Cube tokens. | optional | `formbricks-web` |
| CUBEJS_JWT_AUDIENCE | JWT audience expected by Cube and used by Formbricks when signing per-request Cube tokens. | optional | `formbricks-cube` |
| CUBEJS_DB_HOST | Database host for the Cube service. Only needed when you run Cube yourself and override defaults. | optional | Depends on your Cube deployment |
| CUBEJS_DB_PORT | Database port for the Cube service. Only needed when you run Cube yourself and override defaults. | optional | Depends on your Cube deployment |
| CUBEJS_DB_NAME | Database name for the Cube service. Only needed when you run Cube yourself and override defaults. | optional | Depends on your Cube deployment |
| CUBEJS_DB_USER | Database user for the Cube service. Only needed when you run Cube yourself and override defaults. | optional | Depends on your Cube deployment |
| CUBEJS_DB_PASS | Database password for the Cube service. Only needed when you run Cube yourself and override defaults. | optional | Depends on your Cube deployment |
| Variable | Description | Required | Default |
| ------------------------- | ------------------------------------------------------------------------------------------------------ | -------- | ------------------------------------ |
| CUBEJS_API_URL | Base URL the Formbricks app uses to call Cube. Local dev (app on host): `http://localhost:4000`. Docker/container: `http://cube:4000` (service name). | required | |
| CUBEJS_API_SECRET | Shared secret Formbricks uses to sign Cube API JWTs. Generate with `openssl rand -hex 32`. | required | |
| CUBEJS_JWT_ISSUER | JWT issuer expected by Cube and used by Formbricks when signing per-request Cube tokens. | optional | `formbricks-web` |
| CUBEJS_JWT_AUDIENCE | JWT audience expected by Cube and used by Formbricks when signing per-request Cube tokens. | optional | `formbricks-cube` |
| CUBEJS_DB_HOST | Database host for the Cube service. Only needed when you run Cube yourself and override defaults. | optional | Depends on your Cube deployment |
| CUBEJS_DB_PORT | Database port for the Cube service. Only needed when you run Cube yourself and override defaults. | optional | Depends on your Cube deployment |
| CUBEJS_DB_NAME | Database name for the Cube service. Only needed when you run Cube yourself and override defaults. | optional | Depends on your Cube deployment |
| CUBEJS_DB_USER | Database user for the Cube service. Only needed when you run Cube yourself and override defaults. | optional | Depends on your Cube deployment |
| CUBEJS_DB_PASS | Database password for the Cube service. Only needed when you run Cube yourself and override defaults. | optional | Depends on your Cube deployment |
The bundled Docker Compose Cube service sets `CUBEJS_DEFAULT_API_SCOPES=meta,data` directly on the Cube
container. If you run Cube outside the bundled Compose stack, configure the equivalent Cube service environment
there rather than adding it to the Formbricks app environment.
For Helm deployments, Formbricks does not deploy Cube for you in this chart. Provide an external Cube endpoint with
`CUBEJS_API_URL` and supply `CUBEJS_API_SECRET` through your existing secret management setup.
For Helm deployments, the chart deploys Cube by default (`cube.enabled: true`). To use an external Cube
cluster instead, set `cube.enabled: false`, point `CUBEJS_API_URL` at your endpoint, and supply
`CUBEJS_API_SECRET` through your existing secret management setup.
<!-- prettier-ignore-end -->
+10 -14
View File
@@ -16,8 +16,8 @@ Make sure Docker and Docker Compose are installed on your system. These are usua
</Note>
<Info>
Starting with Formbricks v5, the production Docker Compose stack includes Formbricks Hub and the XM Suite v5
Cube.js services. Generate `HUB_API_KEY` and `CUBEJS_API_SECRET` during setup, keep `HUB_API_URL` at its
Starting with Formbricks v5, the production Docker Compose stack includes Formbricks Hub and Cube as part of
the baseline. Generate `HUB_API_KEY` and `CUBEJS_API_SECRET` during setup, keep `HUB_API_URL` at its
internal default unless Hub runs elsewhere, and use the [migration guide](/self-hosting/advanced/migration#v5)
when upgrading an existing 4.x instance.
</Info>
@@ -34,7 +34,7 @@ Make sure Docker and Docker Compose are installed on your system. These are usua
1. **Download the Docker Files**
Get the Docker Compose file plus the Cube.js configuration shipped with the XM Suite v5 stack:
Get the Docker Compose file plus the Cube configuration shipped with the baseline stack:
```bash
mkdir -p cube/schema
@@ -43,15 +43,12 @@ Make sure Docker and Docker Compose are installed on your system. These are usua
curl -o cube/schema/FeedbackRecords.js https://raw.githubusercontent.com/formbricks/formbricks/stable/docker/cube/schema/FeedbackRecords.js
```
1. **Generate Hub Secret and Optional Cube Secret**
1. **Generate Hub and Cube Secrets**
Formbricks Hub requires an API key. XM Suite v5 analytics also requires Cube.js; set the optional `xm`
Compose profile and Cube secret when you want to run the bundled Cube service. For a Hub-only stack, create
`.env` with just `HUB_API_KEY` and omit `COMPOSE_PROFILES` and `CUBEJS_API_SECRET`.
Formbricks Hub and Cube each require a shared secret. Create `.env` with both:
```bash
cat <<EOF > .env
COMPOSE_PROFILES=xm
HUB_API_KEY=$(openssl rand -hex 32)
CUBEJS_API_SECRET=$(openssl rand -hex 32)
CUBEJS_JWT_ISSUER=formbricks-web
@@ -133,8 +130,7 @@ Make sure Docker and Docker Compose are installed on your system. These are usua
1. **Start the Docker Setup**
Now, you're ready to run Formbricks with Docker. Use the command below to start Formbricks together with
PostgreSQL, Redis, and Formbricks Hub. If the `xm` profile is set in `.env`, Docker Compose also starts Cube.js
for XM Suite v5 analytics.
PostgreSQL, Redis, Formbricks Hub, and Cube.
```bash
docker compose up -d
@@ -147,8 +143,8 @@ Make sure Docker and Docker Compose are installed on your system. These are usua
Once the setup is running, open [**http://localhost:3000**](http://localhost:3000) in your browser to access Formbricks. The first time you visit, you'll see a setup wizard. Follow the steps to create your first user and start using Formbricks.
<Note>
The bundled Docker stack keeps Formbricks Hub internal to the compose network. When the `xm` profile is
enabled, Cube.js is internal too. The app reaches them through `http://hub:8080` and `http://cube:4000`.
The bundled Docker stack keeps Formbricks Hub and Cube internal to the compose network. The app reaches
them through `http://hub:8080` and `http://cube:4000`.
</Note>
<Info>
@@ -164,8 +160,8 @@ Please take a look at our [migration guide](/self-hosting/advanced/migration) fo
<Info>
For a major migration such as Formbricks 4.x to 5.0, update your compose structure and configuration first.
Pulling images alone is not enough if your stack does not yet include Hub, `HUB_API_KEY`, the bundled
`cube/` config files plus `CUBEJS_API_SECRET`, or the new edge rate-limiting setup.
Pulling images alone is not enough if your stack does not yet include Hub (`HUB_API_KEY`), Cube (`cube/`
config files plus `CUBEJS_API_SECRET`), or the new edge rate-limiting setup.
</Info>
1. Pull the latest Formbricks image
+8 -6
View File
@@ -109,13 +109,14 @@ envoyRedis:
This keeps Envoy rate-limiting state separate from the application's own Redis traffic.
### Cube Is Optional
### Cube
Cube is only needed for analytics dashboards or other analysis flows that depend on Cube queries.
Cube is part of the baseline Formbricks v5 stack and is bundled with the chart by default
(`cube.enabled: true`). To run an external Cube cluster instead:
- deploy Cube separately when you need it
- configure `CUBEJS_API_URL` and `CUBEJS_API_SECRET` for the Formbricks app
- do not expect the main Formbricks chart to provision Cube automatically
- set `cube.enabled: false` to skip the bundled Cube deployment
- point the app at your external endpoint via `deployment.env.CUBEJS_API_URL`
- supply `CUBEJS_API_SECRET` via `deployment.env` or `deployment.envFrom`
## 4. Upgrade The Deployment
@@ -133,7 +134,8 @@ For a Formbricks 4.x to 5.0 migration, confirm the following before running the
- `HUB_API_KEY` is present
- your edge rate-limiting plan is in place
- any required `AI_*` variables are added
- Cube is configured only if this instance needs analytics dashboards or analysis queries
- `CUBEJS_API_SECRET` is configured (Cube is bundled by default; provide an external endpoint if you set
`cube.enabled: false`)
## 5. Key Values
+2 -2
View File
@@ -53,8 +53,8 @@ curl -fsSL https://raw.githubusercontent.com/formbricks/formbricks/stable/docker
```
<Info>
The current v5 one-click stack is based on the production Docker Compose file and includes Formbricks Hub plus
the bundled XM Suite v5 Cube.js files under `formbricks/cube/`. Ensure your generated
The current v5 one-click stack is based on the production Docker Compose file and includes Formbricks Hub
and Cube as part of the baseline (Cube configuration lives under `formbricks/cube/`). Ensure your generated
`formbricks/docker-compose.yml` contains a non-empty `HUB_API_KEY` and that `formbricks/.env` contains
`CUBEJS_API_SECRET` before treating the v5 stack as ready. If either value is missing after the script
finishes, add it manually. `HUB_API_URL` should normally stay at `http://hub:8080`.
-10
View File
@@ -31,14 +31,6 @@ class ValidationError extends Error {
}
}
class ConfigurationError extends Error {
statusCode = 503;
constructor(message: string) {
super(message);
this.name = "ConfigurationError";
}
}
class QueryExecutionError extends Error {
statusCode = 500;
constructor(message: string) {
@@ -151,7 +143,6 @@ export {
ResourceNotFoundError,
InvalidInputError,
ValidationError,
ConfigurationError,
QueryExecutionError,
DatabaseError,
UniqueConstraintError,
@@ -181,7 +172,6 @@ export const EXPECTED_ERROR_NAMES = new Set([
"AuthorizationError",
"InvalidInputError",
"ValidationError",
"ConfigurationError",
"QueryExecutionError",
"AuthenticationError",
"OperationNotAllowedError",
+7 -5
View File
@@ -278,11 +278,13 @@ export const ZSurveyRecaptcha = z
export type TSurveyRecaptcha = z.infer<typeof ZSurveyRecaptcha>;
export const ZSurveyMetadata = z.object({
title: ZI18nString.optional(),
description: ZI18nString.optional(),
ogImage: ZStorageUrl.optional(),
});
export const ZSurveyMetadata = z
.object({
title: ZI18nString.optional(),
description: ZI18nString.optional(),
ogImage: ZStorageUrl.optional(),
})
.catchall(z.unknown());
export type TSurveyMetadata = z.infer<typeof ZSurveyMetadata>;
+58 -180
View File
@@ -1,237 +1,135 @@
{
"$schema": "https://turborepo.org/schema.json",
"globalEnv": [],
"tasks": {
"@formbricks/ai#build": {
"dependsOn": [
"@formbricks/logger#build"
],
"outputs": [
"dist/**"
]
"dependsOn": ["@formbricks/logger#build"],
"outputs": ["dist/**"]
},
"@formbricks/ai#lint": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/ai#test": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/ai#test:coverage": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/cache#build": {
"dependsOn": [
"@formbricks/logger#build"
],
"outputs": [
"dist/**"
]
"dependsOn": ["@formbricks/logger#build"],
"outputs": ["dist/**"]
},
"@formbricks/cache#go": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/cache#lint": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/cache#test": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/cache#test:coverage": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/database#build": {
"dependsOn": [
"^build"
],
"outputs": [
"dist/**",
"../../node_modules/.prisma/client/**"
]
"dependsOn": ["^build"],
"outputs": ["dist/**", "../../node_modules/.prisma/client/**"]
},
"@formbricks/database#lint": {
"dependsOn": [
"@formbricks/logger#build",
"@formbricks/database#build"
]
"dependsOn": ["@formbricks/logger#build", "@formbricks/database#build"]
},
"@formbricks/email#build": {
"dependsOn": [
"^build"
],
"dependsOn": ["^build"],
"outputs": []
},
"@formbricks/i18n-utils#build": {
"dependsOn": [
"^build"
],
"outputs": [
"dist/**"
]
"dependsOn": ["^build"],
"outputs": ["dist/**"]
},
"@formbricks/i18n-utils#lint": {
"dependsOn": [
"^lint"
]
"dependsOn": ["^lint"]
},
"@formbricks/i18n-utils#test": {
"dependsOn": [
"@formbricks/i18n-utils#build"
]
"dependsOn": ["@formbricks/i18n-utils#build"]
},
"@formbricks/jobs#build": {
"dependsOn": [
"@formbricks/logger#build"
],
"outputs": [
"dist/**"
]
"dependsOn": ["@formbricks/logger#build"],
"outputs": ["dist/**"]
},
"@formbricks/jobs#lint": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/jobs#test": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/jobs#test:coverage": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/js-core#build": {
"dependsOn": [
"^build",
"@formbricks/database#build"
],
"outputs": [
"dist/**"
]
"dependsOn": ["^build", "@formbricks/database#build"],
"outputs": ["dist/**"]
},
"@formbricks/js-core#go": {
"cache": false,
"dependsOn": [
"@formbricks/database#db:setup"
],
"dependsOn": ["@formbricks/database#db:setup"],
"persistent": true
},
"@formbricks/js-core#lint": {
"dependsOn": [
"@formbricks/database#build"
]
"dependsOn": ["@formbricks/database#build"]
},
"@formbricks/logger#build": {
"dependsOn": [
"^build"
],
"outputs": [
"dist/**"
]
"dependsOn": ["^build"],
"outputs": ["dist/**"]
},
"@formbricks/storage#build": {
"dependsOn": [
"@formbricks/logger#build"
],
"outputs": [
"dist/**"
]
"dependsOn": ["@formbricks/logger#build"],
"outputs": ["dist/**"]
},
"@formbricks/storage#go": {
"cache": false,
"dependsOn": [
"@formbricks/storage#build"
],
"dependsOn": ["@formbricks/storage#build"],
"persistent": true
},
"@formbricks/storage#lint": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/storage#test": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/storage#test:coverage": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"@formbricks/survey-ui#build": {
"dependsOn": [
"^build"
],
"outputs": [
"dist/**"
]
"dependsOn": ["^build"],
"outputs": ["dist/**"]
},
"@formbricks/survey-ui#build:dev": {
"dependsOn": [
"^build:dev"
],
"outputs": [
"dist/**"
]
"dependsOn": ["^build:dev"],
"outputs": ["dist/**"]
},
"@formbricks/survey-ui#go": {
"cache": false,
"dependsOn": [
"@formbricks/survey-ui#build"
],
"dependsOn": ["@formbricks/survey-ui#build"],
"persistent": true
},
"@formbricks/surveys#build": {
"dependsOn": [
"^build",
"@formbricks/survey-ui#build"
],
"outputs": [
"dist/**"
]
"dependsOn": ["^build", "@formbricks/survey-ui#build"],
"outputs": ["dist/**"]
},
"@formbricks/surveys#build:dev": {
"dependsOn": [
"^build:dev",
"@formbricks/i18n-utils#build",
"@formbricks/survey-ui#build:dev"
],
"outputs": [
"dist/**"
]
"dependsOn": ["^build:dev", "@formbricks/i18n-utils#build", "@formbricks/survey-ui#build:dev"],
"outputs": ["dist/**"]
},
"@formbricks/surveys#go": {
"cache": false,
"dependsOn": [
"@formbricks/survey-ui#build",
"@formbricks/surveys#build"
],
"dependsOn": ["@formbricks/survey-ui#build", "@formbricks/surveys#build"],
"persistent": true
},
"@formbricks/surveys#test": {
"dependsOn": [
"@formbricks/survey-ui#build"
]
"dependsOn": ["@formbricks/survey-ui#build"]
},
"@formbricks/surveys#test:coverage": {
"dependsOn": [
"@formbricks/survey-ui#build"
]
"dependsOn": ["@formbricks/survey-ui#build"]
},
"@formbricks/web#dev": {
"cache": false,
@@ -281,9 +179,7 @@
]
},
"build": {
"dependsOn": [
"^build"
],
"dependsOn": ["^build"],
"env": [
"AUDIT_LOG_ENABLED",
"AUDIT_LOG_GET_USER_IP",
@@ -428,19 +324,11 @@
"PROMETHEUS_EXPORTER_PORT",
"USER_MANAGEMENT_MINIMUM_ROLE"
],
"outputs": [
"dist/**",
".next/**"
]
"outputs": ["dist/**", ".next/**"]
},
"build:dev": {
"dependsOn": [
"^build:dev"
],
"outputs": [
"dist/**",
".next/**"
]
"dependsOn": ["^build:dev"],
"outputs": ["dist/**", ".next/**"]
},
"clean": {
"cache": false,
@@ -462,17 +350,12 @@
"outputs": []
},
"db:seed": {
"env": [
"ALLOW_SEED"
],
"env": ["ALLOW_SEED"],
"outputs": []
},
"db:setup": {
"cache": false,
"dependsOn": [
"@formbricks/logger#build",
"@formbricks/database#build"
],
"dependsOn": ["@formbricks/logger#build", "@formbricks/database#build"],
"outputs": []
},
"db:start": {
@@ -487,9 +370,7 @@
"persistent": true
},
"generate": {
"dependsOn": [
"^generate"
]
"dependsOn": ["^generate"]
},
"go": {
"cache": false,
@@ -506,9 +387,7 @@
"persistent": true
},
"storybook#storybook": {
"dependsOn": [
"@formbricks/logger#build"
]
"dependsOn": ["@formbricks/logger#build"]
},
"test": {
"outputs": []
@@ -517,6 +396,5 @@
"outputs": []
}
},
"ui": "stream",
"globalEnv": []
"ui": "stream"
}