Beautiful Open-Source Form Builder
Code on custom domain (#908)
Julien Nahumaea3328ae0bb
diff --git a/api/app/Http/Controllers/Content/FeatureFlagsController.php b/api/app/Http/Controllers/Content/FeatureFlagsController.phpindex d032b311b..86772efa2 100644--- a/api/app/Http/Controllers/Content/FeatureFlagsController.php+++ b/api/app/Http/Controllers/Content/FeatureFlagsController.php@@ -42,6 +42,9 @@ class FeatureFlagsController extends Controller'google_sheets' => !empty(config('services.google.client_id')) && !empty(config('services.google.client_secret')),'telegram' => !empty(config('services.telegram.bot_token')),],+ 'custom_code' => [+ 'enable_self_hosted' => (bool) config('opnform.custom_code.enable_self_hosted', false),+ ],];});diff --git a/api/app/Service/Forms/FormCleaner.php b/api/app/Service/Forms/FormCleaner.phpindex 01ec17f58..dd28ad83c 100644--- a/api/app/Service/Forms/FormCleaner.php+++ b/api/app/Service/Forms/FormCleaner.php@@ -49,6 +49,9 @@ class FormCleaner'secret_input' => false,];+ // Policy toggles for current cleaning run+ private bool $allowCustomCode = true;+private array $cleaningMessages = [// For form'no_branding' => 'OpenForm branding is not hidden.',@@ -114,6 +117,18 @@ class FormCleanerpublic function processForm(Request $request, Form $form): FormCleaner{$data = (new FormResource($form))->toArray($request);++ // Determine if custom code is allowed in this response context+ $allowOnSelfHosted = config('app.self_hosted', true) && (bool) config('opnform.custom_code.enable_self_hosted', false);+ $hasCustomDomain = !empty($data['custom_domain'] ?? null);+ $this->allowCustomCode = $hasCustomDomain || $allowOnSelfHosted;++ // Suppress top-level custom_code if not allowed (silent, not recorded as cleaning)+ if (!$this->allowCustomCode) {+ $data['custom_code'] = null;+ }++ // Single pass over properties: sanitize text blocks and optionally remove nf-code blocks$this->data = $this->commonCleaning($data);return $this;@@ -171,10 +186,20 @@ class FormCleaner*/private function commonCleaning(array $data){- foreach ($data['properties'] as &$property) {- if ($property['type'] == 'nf-text' && isset($property['content'])) {- $property['content'] = Purify::clean($property['content']);+ if (!empty($data['properties']) && is_array($data['properties'])) {+ foreach ($data['properties'] as $index => &$property) {+ if (($property['type'] ?? null) === 'nf-text' && isset($property['content'])) {+ $property['content'] = Purify::clean($property['content']);+ }++ if (!$this->allowCustomCode && ($property['type'] ?? null) === 'nf-code') {+ // Remove the block entirely (silent, not recorded as cleaning)+ unset($data['properties'][$index]);+ }}+ unset($property);+ // Reindex properties array if any removals occurred+ $data['properties'] = array_values($data['properties']);}return $data;@@ -224,6 +249,7 @@ class FormCleaner// Clean pro field options$this->cleanField($property, $this->fieldDefaults, $simulation);}+ unset($property);}private function clean(array &$data, array $defaults, $simulation = false): voiddiff --git a/api/config/opnform.php b/api/config/opnform.phpindex cf01e3f9a..1a4ef1ba2 100644--- a/api/config/opnform.php+++ b/api/config/opnform.php@@ -7,4 +7,7 @@ return ['extra_pro_users_emails' => explode(',', env('EXTRA_PRO_USERS_EMAILS') ?? ''),'show_official_templates' => env('SHOW_OFFICIAL_TEMPLATES', true),'condition_mapping' => json_decode(file_get_contents(resource_path('data/open_filters.json')), true),+ 'custom_code' => [+ 'enable_self_hosted' => env('CUSTOM_CODE_ENABLE_SELF_HOSTED', false),+ ],];diff --git a/api/tests/Unit/Service/FormCleanerTest.php b/api/tests/Unit/Service/FormCleanerTest.phpnew file mode 100644index 000000000..eae7af798--- /dev/null+++ b/api/tests/Unit/Service/FormCleanerTest.php@@ -0,0 +1,110 @@+<?php++use App\Service\Forms\FormCleaner;+use Illuminate\Http\Request;++uses(\Tests\TestCase::class);++describe('FormCleaner custom code policy', function () {+ beforeEach(function () {+ // Sensible defaults for tests+ config()->set('app.self_hosted', false);+ config()->set('opnform.custom_code.enable_self_hosted', false);+ });++ it('suppresses custom_code and removes nf-code on SaaS without custom domain', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);++ $form = $this->createForm($user, $workspace, [+ 'custom_domain' => null,+ 'custom_code' => '<script>steal()</script>',+ 'custom_css' => 'body{color:red}',+ 'properties' => [+ [+ 'id' => 't1',+ 'name' => 'Text',+ 'type' => 'nf-text',+ 'content' => '<script>x</script><p>safe</p>'+ ],+ [+ 'id' => 'c1',+ 'name' => 'Code',+ 'type' => 'nf-code',+ 'content' => '<script>bad()</script>'+ ],+ [+ 'id' => 'email1',+ 'name' => 'Email',+ 'type' => 'email',+ ],+ ],+ ]);++ $request = Request::create('/', 'GET');+ $cleaner = (new FormCleaner())->processForm($request, $form);+ $data = $cleaner->getData();++ // custom_code suppressed+ expect($data['custom_code'])->toBeNull();+ // custom_css preserved+ expect($data['custom_css'])->toBe('body{color:red}');++ // nf-code removed entirely, nf-text sanitized, email remains+ $types = array_map(fn ($p) => $p['type'], $data['properties']);+ expect($types)->not->toContain('nf-code');++ $textBlock = collect($data['properties'])->firstWhere('id', 't1');+ expect($textBlock['content'])->not->toContain('<script>')+ ->and($textBlock['content'])->toContain('safe');++ // Policy-based removals are silent (no cleanings recorded)+ $messages = $cleaner->getPerformedCleanings();+ expect($messages)->toBeArray()->and($messages)->toBeEmpty();+ });++ it('keeps custom_code and nf-code when form has a custom domain', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);++ $form = $this->createForm($user, $workspace, [+ 'custom_domain' => 'example.com',+ 'custom_code' => '<script>ok()</script>',+ 'properties' => [+ [ 'id' => 'c1', 'name' => 'Code', 'type' => 'nf-code', 'content' => '<script>a()</script>' ],+ ],+ ]);++ $request = Request::create('/', 'GET');+ $cleaner = (new FormCleaner())->processForm($request, $form);+ $data = $cleaner->getData();++ expect($data['custom_code'])->not->toBeNull();+ $types = array_map(fn ($p) => $p['type'], $data['properties']);+ expect($types)->toContain('nf-code');+ });++ it('keeps custom_code and nf-code when self-hosted flag enabled', function () {+ config()->set('app.self_hosted', true);+ config()->set('opnform.custom_code.enable_self_hosted', true);++ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);++ $form = $this->createForm($user, $workspace, [+ 'custom_domain' => null,+ 'custom_code' => '<script>ok()</script>',+ 'properties' => [+ [ 'id' => 'c1', 'name' => 'Code', 'type' => 'nf-code', 'content' => '<script>a()</script>' ],+ ],+ ]);++ $request = Request::create('/', 'GET');+ $cleaner = (new FormCleaner())->processForm($request, $form);+ $data = $cleaner->getData();++ expect($data['custom_code'])->not->toBeNull();+ $types = array_map(fn ($p) => $p['type'], $data['properties']);+ expect($types)->toContain('nf-code');+ });+});diff --git a/client/components/open/forms/components/form-components/FormCustomCode.vue b/client/components/open/forms/components/form-components/FormCustomCode.vueindex a2d06a5ed..2c2dbc28e 100644--- a/client/components/open/forms/components/form-components/FormCustomCode.vue+++ b/client/components/open/forms/components/form-components/FormCustomCode.vue@@ -28,22 +28,34 @@name="custom_code"class="mt-4":form="form"- help="Saves changes and visit the actual form page to test."+ :disabled="!canUseCustomCode"+ :help="customCodeHelp"label="Custom Code"placeholder="<script>console.log('Hello World!')</script>"/><div class="pt-6">- <h3 class="text-lg font-medium text-neutral-900">- Custom CSS <ProTag- class="mb-2 block"- upgrade-modal-title="Upgrade to Unlock Custom CSS"- upgrade-modal-description="On the Free plan, you can explore custom CSS within the editor. Upgrade to apply custom styles to your live forms."+ <div class="flex flex-col flex-wrap items-start justify-between gap-4 sm:flex-row sm:items-center">+ <div>+ <h3 class="text-lg font-medium text-neutral-900">+ Custom CSS <ProTag+ class="mb-2 block"+ upgrade-modal-title="Upgrade to Unlock Custom CSS"+ upgrade-modal-description="On the Free plan, you can explore custom CSS within the editor. Upgrade to apply custom styles to your live forms."+ />+ </h3>+ <p class="mt-1 text-sm text-neutral-500">+ The CSS will be injected in the <b>head</b> of your form page.+ </p>+ </div>+ <UButton+ label="Help"+ icon="i-heroicons-question-mark-circle"+ variant="outline"+ color="neutral"+ @click="crisp.openHelpdeskArticle('can-i-style-my-form-with-some-custom-css-code-1v3dlr9')"/>- </h3>- <p class="mt-1 text-sm text-neutral-500">- The CSS will be injected in the <b>head</b> of your form page.- </p>+ </div><CodeInput:allow-fullscreen="true"language-mode="css"@@ -66,4 +78,20 @@ const workingFormStore = useWorkingFormStore()const { content: form } = storeToRefs(workingFormStore)const crisp = useCrisp()+const canUseCustomCode = computed(() => workingFormStore.isCustomCodeAllowed)++const customCodeHelp = computed(() => {+ const hasCustomDomain = !!form.value?.custom_domain+ const selfHosted = !!useFeatureFlag('self_hosted', false)+ const allowSelfHosted = !!useFeatureFlag('custom_code.enable_self_hosted', false)+ if (canUseCustomCode.value) {+ return 'Saves changes and visit the actual form page to test.'+ }+ // In self-hosted mode with flag disabled (and no custom domain), show safety notice with docs link+ if (selfHosted && !allowSelfHosted && !hasCustomDomain) {+ return 'Custom code is disabled for safety on self-hosted. Enable via CUSTOM_CODE_ENABLE_SELF_HOSTED=true. See technical docs: https://docs.opnform.com/introduction'+ }+ return 'Custom code requires to be using a custom domain.'+})+</script>diff --git a/client/pages/forms/[slug]/index.vue b/client/pages/forms/[slug]/index.vueindex ec122fc32..c7d12d9bf 100644--- a/client/pages/forms/[slug]/index.vue+++ b/client/pages/forms/[slug]/index.vue@@ -69,6 +69,7 @@ import {} from '~/lib/forms/public-page'import { FormMode } from "~/lib/forms/FormModeStrategy.js"import { formsApi } from '~/api'+import { customDomainUsed } from '~/lib/utils.js'const crisp = useCrisp()const appStore = useAppStore()@@ -156,7 +157,13 @@ onMounted(() => {})if (import.meta.client) {- if (form.value.custom_code) {+ const allowSelfHosted = !!useFeatureFlag('custom_code.enable_self_hosted', false)+ const isSelfHosted = !!useFeatureFlag('self_hosted', false)+ const isCustomDomain = customDomainUsed()++ const canExecuteCustomCode = isCustomDomain || (isSelfHosted && allowSelfHosted)++ if (form.value.custom_code && canExecuteCustomCode) {const scriptEl = document.createRange().createContextualFragment(form.value.custom_code)try {document.head.append(scriptEl)diff --git a/client/pages/forms/[slug]/show.vue b/client/pages/forms/[slug]/show.vueindex d3e9c5b1d..eea7f9acb 100644--- a/client/pages/forms/[slug]/show.vue+++ b/client/pages/forms/[slug]/show.vue@@ -134,9 +134,9 @@</div><!-- Status Badges and Form Cleanings -->- <div class="flex flex-wrap gap-2">- <FormStatusBadges class="mt-2" size="sm" :form="form" />- <FormCleanings class="mt-2" :form="form" />+ <div class="flex flex-wrap gap-2 flex-col mt-2">+ <FormStatusBadges size="sm" :form="form" />+ <FormCleanings :form="form" /></div></div></div>diff --git a/client/server/plugins/embeddable.js b/client/server/plugins/embeddable.jsindex cf2ec68aa..43162ba3c 100644--- a/client/server/plugins/embeddable.js+++ b/client/server/plugins/embeddable.js@@ -19,12 +19,16 @@ export default defineNitroPlugin((nitroApp) => {if (routePath && !routePath.startsWith("/forms/")) {// Build frame-ancestors for non-form routes: localhost variants + matching allowlisted domain (if Referer present)- const ancestors = ["'self'",- 'http://localhost:*', 'https://localhost:*',- 'http://127.0.0.1:*', 'https://127.0.0.1:*',- 'http://0.0.0.0:*', 'https://0.0.0.0:*',- 'http://[::1]:*', 'https://[::1]:*'- ]+ // Note: CSP frame-ancestors doesn't support port wildcards, so we list common dev ports+ const commonPorts = ['', ':3000', ':3001', ':4200', ':5000', ':5173', ':8000', ':8080', ':8081', ':9000']+ const ancestors = ["'self'"]++ commonPorts.forEach(port => {+ ancestors.push(`http://localhost${port}`)+ ancestors.push(`https://localhost${port}`)+ ancestors.push(`http://127.0.0.1${port}`)+ ancestors.push(`https://127.0.0.1${port}`)+ })const referer = event.node?.req?.headers?.referer || ''const refererHost = referer ? (getDomain(referer) || '').toLowerCase() : ''diff --git a/client/stores/auth.js b/client/stores/auth.jsindex ecff73d23..41156f57a 100644--- a/client/stores/auth.js+++ b/client/stores/auth.js@@ -49,7 +49,13 @@ export const useAuthStore = defineStore("auth", {setCookie(name, value, options = {}) {if (import.meta.client) {- useCookie(name, options).value = value+ const secureDefault = (typeof window !== 'undefined') ? window.location.protocol === 'https:' : true+ const safeOptions = {+ sameSite: options.sameSite ?? 'lax',+ secure: options.secure ?? secureDefault,+ ...options,+ }+ useCookie(name, safeOptions).value = value}},diff --git a/client/stores/working_form.js b/client/stores/working_form.jsindex 34abe0aa1..f52376c43 100644--- a/client/stores/working_form.js+++ b/client/stores/working_form.js@@ -27,6 +27,13 @@ export const useWorkingFormStore = defineStore("working_form", {formBlocks() {return this.content?.properties || []},+ // Whether custom code is allowed for the current form/context+ isCustomCodeAllowed() {+ const hasCustomDomain = !!this.content?.custom_domain+ const selfHosted = !!useFeatureFlag('self_hosted')+ const allowSelfHosted = !!useFeatureFlag('custom_code.enable_self_hosted')+ return hasCustomDomain || (selfHosted && allowSelfHosted)+ },// Get page count using structure servicesimplePageCount() {@@ -41,6 +48,30 @@ export const useWorkingFormStore = defineStore("working_form", {}},actions: {+ // Unified alert for disallowed custom code+ showCustomCodeDisabledAlert() {+ const selfHosted = !!useFeatureFlag('self_hosted')+ const actions = []+ let message = ''+ if (selfHosted) {+ // Self-hosted: safety notice + docs+ message = 'Custom code is disabled for safety on self-hosted. See technical docs to learn more.'+ actions.push({+ label: 'View docs',+ icon: 'i-heroicons-book-open',+ onclick: () => { if (import.meta.client) window.open('https://docs.opnform.com/introduction', '_blank') }+ })+ } else {+ // Cloud: require custom domain + Crisp help+ message = 'Your form needs to be using a custom domain to add a code block.'+ actions.push({+ label: 'Help',+ icon: 'i-heroicons-question-mark-circle',+ onclick: () => { try { useCrisp().openHelpdeskArticle('how-do-i-add-custom-code-to-my-form-1amadj3') } catch { /* noop */ } }+ })+ }+ useAlert().error(message, 10000, { title: 'Custom code disabled', actions })+ },set(form) {this.content = form// Don't reset structure service here - it's externally managed now@@ -181,6 +212,12 @@ export const useWorkingFormStore = defineStore("working_form", {const effectiveType = originalBlockDefinition?.actual_input || typeconst effectiveBlockDefinition = blocksTypes[effectiveType]+ // Block adding custom code blocks unless allowed (custom domain or self-hosted with explicit enable)+ if (effectiveType === 'nf-code' && !this.isCustomCodeAllowed) {+ this.showCustomCodeDisabledAlert()+ return+ }+if (originalBlockDefinition?.self_hosted !== undefined && !originalBlockDefinition.self_hosted && useFeatureFlag('self_hosted')) {useAlert().error(block?.title + ' is not allowed on self hosted. Please use our hosted version.')returndiff --git a/docs/configuration/environment-variables.mdx b/docs/configuration/environment-variables.mdxindex 0db549c7f..1aacc7e91 100644--- a/docs/configuration/environment-variables.mdx+++ b/docs/configuration/environment-variables.mdx@@ -21,37 +21,39 @@ There are dedicated configuration pages available for more detailed setup instru### Configuration Environment Variables-| Variable Name | Description |-| --------------------------- | -------------------------------------------------------------------------------------------------------- |-| `H_CAPTCHA_SITE_KEY` | Site key for hCaptcha integration. |-| `H_CAPTCHA_SECRET_KEY` | Secret key for hCaptcha integration. |-| `RE_CAPTCHA_SITE_KEY` | Site key for reCAPTCHA integration. |-| `RE_CAPTCHA_SECRET_KEY` | Secret key for reCAPTCHA integration. |-| `OPEN_AI_API_KEY` | API key for accessing OpenAI services. |-| `UNSPLASH_ACCESS_KEY` | Access key for Unsplash API. |-| `UNSPLASH_SECRET_KEY` | Secret key for Unsplash API. |-| `FRONT_URL` | Public facing URL of the front-end. |-| `FRONT_API_SECRET` | Shared secret with the front-end. |-| `JWT_TTL` | Time to live for JSON Web Tokens (JWT). |-| `JWT_SECRET` | Secret key used to sign JWTs. |-| `JWT_SKIP_IP_UA_VALIDATION` | Set to `true` to disable JWT IP and User Agent validation (defaults to `false`). Useful for dynamic IPs. |+| Variable Name | Description |+| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |+| `H_CAPTCHA_SITE_KEY` | Site key for hCaptcha integration. |+| `H_CAPTCHA_SECRET_KEY` | Secret key for hCaptcha integration. |+| `RE_CAPTCHA_SITE_KEY` | Site key for reCAPTCHA integration. |+| `RE_CAPTCHA_SECRET_KEY` | Secret key for reCAPTCHA integration. |+| `OPEN_AI_API_KEY` | API key for accessing OpenAI services. |+| `UNSPLASH_ACCESS_KEY` | Access key for Unsplash API. |+| `UNSPLASH_SECRET_KEY` | Secret key for Unsplash API. |+| `FRONT_URL` | Public facing URL of the front-end. |+| `FRONT_API_SECRET` | Shared secret with the front-end. |+| `JWT_TTL` | Time to live for JSON Web Tokens (JWT). |+| `JWT_SECRET` | Secret key used to sign JWTs. |+| `JWT_SKIP_IP_UA_VALIDATION` | Set to `true` to disable JWT IP and User Agent validation (defaults to `false`). Useful for dynamic IPs. |+| `CUSTOM_CODE_ENABLE_SELF_HOSTED` | Enables execution of user-provided custom code on self-hosted deployments. Defaults to `false` for safety reasons (XSS etc.). |### OAuth Integration Environment VariablesOAuth integrations enable user authentication and third-party service connections. OpnForm automatically handles OAuth redirect URLs - you don't need to manually configure redirect URIs in your OAuth applications.<Info>-For detailed setup instructions for each OAuth provider, see the [OAuth Integration Setup](../configuration/oauth-setup) guide.+ For detailed setup instructions for each OAuth provider, see the [OAuth+ Integration Setup](../configuration/oauth-setup) guide.</Info>-| Variable Name | Description |-| ----------------------- | --------------------------------------------------------------------------------------------------------- |-| `GOOGLE_CLIENT_ID` | Client ID for Google OAuth authentication and Google Sheets integration. |-| `GOOGLE_CLIENT_SECRET` | Client secret for Google OAuth authentication and Google Sheets integration. |-| `GOOGLE_FONTS_API_KEY` | API key for accessing Google Fonts (optional). |-| `STRIPE_CLIENT_ID` | Client ID for Stripe Connect OAuth integration for payment processing. |-| `STRIPE_CLIENT_SECRET` | Client secret for Stripe Connect OAuth integration. |-| `TELEGRAM_BOT_TOKEN` | Authentication token for your Telegram bot notifications (bot ID is extracted automatically). |+| Variable Name | Description |+| ---------------------- | --------------------------------------------------------------------------------------------- |+| `GOOGLE_CLIENT_ID` | Client ID for Google OAuth authentication and Google Sheets integration. |+| `GOOGLE_CLIENT_SECRET` | Client secret for Google OAuth authentication and Google Sheets integration. |+| `GOOGLE_FONTS_API_KEY` | API key for accessing Google Fonts (optional). |+| `STRIPE_CLIENT_ID` | Client ID for Stripe Connect OAuth integration for payment processing. |+| `STRIPE_CLIENT_SECRET` | Client secret for Stripe Connect OAuth integration. |+| `TELEGRAM_BOT_TOKEN` | Authentication token for your Telegram bot notifications (bot ID is extracted automatically). |### User Options Environment Variables