Beautiful Open-Source Form Builder
Custom css (#901)
Julien Nahuma18d5dc76a13
diff --git a/api/app/Http/Requests/UserFormRequest.php b/api/app/Http/Requests/UserFormRequest.phpindex 4bc9b7c65..72c21fffe 100644--- a/api/app/Http/Requests/UserFormRequest.php+++ b/api/app/Http/Requests/UserFormRequest.php@@ -12,6 +12,7 @@ use Illuminate\Validation\ValidationException;use Illuminate\Contracts\Validation\Validator;use Illuminate\Validation\Rule;use Illuminate\Http\Request;+use App\Rules\CssOnlyRule;/*** Abstract class to validate create/update forms@@ -67,7 +68,7 @@ abstract class UserFormRequest extends \Illuminate\Foundation\Http\FormRequest];// Log to both default channel and Slack- if (!in_array(\App::environment(), ['testing'])) {+ if (!app()->environment('testing')) {Log::channel('slack_errors')->warning('Frontend validation bypass detected in form submission',$logData@@ -127,6 +128,7 @@ abstract class UserFormRequest extends \Illuminate\Foundation\Http\FormRequest// Custom Code'custom_code' => 'string|nullable',+ 'custom_css' => ['string', 'nullable', new CssOnlyRule()],// Submission'submit_button_text' => 'nullable|string|max:50',diff --git a/api/app/Http/Resources/FormResource.php b/api/app/Http/Resources/FormResource.phpindex 552c199e7..d8b25f4d4 100644--- a/api/app/Http/Resources/FormResource.php+++ b/api/app/Http/Resources/FormResource.php@@ -77,6 +77,7 @@ class FormResource extends JsonResource'description' => $this->description,'slug' => $this->slug,'custom_code' => $this->custom_code,+ 'custom_css' => $this->custom_css,'dark_mode' => $this->dark_mode,'transparent_background' => $this->transparent_background,'color' => $this->color,diff --git a/api/app/Models/Forms/Form.php b/api/app/Models/Forms/Form.phpindex 5805ac86a..5bcad7126 100644--- a/api/app/Models/Forms/Form.php+++ b/api/app/Models/Forms/Form.php@@ -73,6 +73,7 @@ class Form extends Model implements CachableAttributes// Custom Code'custom_code',+ 'custom_css',// Submission'submit_button_text',diff --git a/api/app/Rules/CssOnlyRule.php b/api/app/Rules/CssOnlyRule.phpnew file mode 100644index 000000000..56cdd2490--- /dev/null+++ b/api/app/Rules/CssOnlyRule.php@@ -0,0 +1,182 @@+<?php++namespace App\Rules;++use Closure;+use Illuminate\Contracts\Validation\ValidationRule;+use Sabberworm\CSS\Parser as CssParser;+use Sabberworm\CSS\Settings;+use Sabberworm\CSS\CSSList\CSSList;+use Sabberworm\CSS\CSSList\AtRuleBlockList;+use Sabberworm\CSS\CSSList\Document;+use Sabberworm\CSS\RuleSet\AtRuleSet;+use Sabberworm\CSS\RuleSet\DeclarationBlock;+use Sabberworm\CSS\Value\URL;+use Sabberworm\CSS\Value\CSSFunction;+use Throwable;++class CssOnlyRule implements ValidationRule+{+ /**+ * Validate the attribute is CSS-only (no HTML or scripts) with simple checks.+ */+ public function validate(string $attribute, mixed $value, Closure $fail): void+ {+ if ($value === null || $value === '') {+ return;+ }++ $css = (string) $value;++ // Parse CSS to ensure it is syntactically valid and free of HTML+ try {+ $settings = Settings::create()->beStrict();+ $document = (new CssParser($css, $settings))->parse();+ } catch (Throwable) {+ $fail('The :attribute must be valid CSS.');+ return;+ }++ // Validate allowed at-rules and URLs+ if (!$this->validateCssDocument($document, $css)) {+ $fail('The :attribute contains disallowed CSS constructs.');+ }+ }++ private function validateCssDocument(Document $document, string $rawCss): bool+ {+ if (!$this->validateCssList($document)) {+ return false;+ }++ // Fallback: explicitly validate @import urls in raw CSS (robust against parser representations)+ if (preg_match_all('/@import\b[^;]*url\s*\(\s*([\"\']?)([^\)\s]+)\1\s*\)/i', $rawCss, $matches)) {+ foreach ($matches[2] as $importUrl) {+ if (!$this->isAllowedUrl($importUrl)) {+ return false;+ }+ }+ }++ return true;+ }++ private function validateCssList(CSSList $list): bool+ {+ // Allowed at-rules list (case-insensitive)+ $allowedAtRules = [+ '@media',+ '@supports',+ '@font-face',+ '@keyframes',+ '@-webkit-keyframes',+ '@import',+ '@page'+ ];++ foreach ($list->getContents() as $content) {+ if ($content instanceof AtRuleBlockList) {+ $atRule = '@' . strtolower($content->atRuleName());+ if (!in_array($atRule, array_map('strtolower', $allowedAtRules), true)) {+ return false;+ }+ if (!$this->validateCssList($content)) {+ return false;+ }+ }++ if ($content instanceof AtRuleSet) {+ $atRule = '@' . strtolower($content->atRuleName());+ if (!in_array($atRule, array_map('strtolower', $allowedAtRules), true)) {+ return false;+ }+ if ($atRule === '@import') {+ $params = strtolower(trim((string) $content->atRuleArgs()));+ if (!$this->isAllowedUrlInParams($params)) {+ return false;+ }+ }+ }++ if ($content instanceof DeclarationBlock) {+ foreach ($content->getRules() as $rule) {+ $value = $rule->getValue();+ if (method_exists($rule, 'getRule')) {+ $propName = strtolower((string) $rule->getRule());+ if ($propName === 'behavior') {+ return false;+ }+ }+ foreach ($this->flattenValues($value) as $v) {+ if ($v instanceof CSSFunction) {+ if (strtolower($v->getName()) === 'expression') {+ return false;+ }+ }+ if ($v instanceof URL) {+ $urlVal = $v->getURL();+ $url = is_object($urlVal) && method_exists($urlVal, 'getString')+ ? $urlVal->getString()+ : (string) $urlVal;+ if (!$this->isAllowedUrl($url)) {+ return false;+ }+ }+ }+ }+ }++ // Generic recursion for any content that is a CSSList+ if (is_object($content) && $content instanceof CSSList) {+ if (!$this->validateCssList($content)) {+ return false;+ }+ }+ }++ return true;+ }++ private function flattenValues($value): array+ {+ $values = [];+ // Always include the node itself first so we don't lose function wrappers like expression()+ $values[] = $value;+ if (is_object($value) && method_exists($value, 'getListComponents')) {+ foreach ($value->getListComponents() as $component) {+ $values = array_merge($values, $this->flattenValues($component));+ }+ }+ return $values;+ }++ private function isAllowedUrlInParams(string $params): bool+ {+ // Extract url(...) or quoted URLs in @import parameters+ if (preg_match('/url\s*\(\s*([\"\"]?)(.*?)\1\s*\)/i', $params, $m)) {+ return $this->isAllowedUrl($m[2] ?? '');+ }+ if (preg_match('/^[\"\"](.*?)[\"\"]/', $params, $m)) {+ return $this->isAllowedUrl($m[1] ?? '');+ }+ // If no URL found, consider safe+ return true;+ }++ private function isAllowedUrl(string $url): bool+ {+ $url = trim($url);+ if ($url === '') {+ return true;+ }+ // Allow only http(s) and data:image/* URLs+ if (preg_match('/^https?:\/\//i', $url)) {+ return true;+ }+ // Allow only safe image data URLs (exclude SVG)+ if (preg_match('/^data:\s*image\/(png|gif|jpe?g|webp|avif|bmp)/i', $url)) {+ return true;+ }+ return false;+ }+}diff --git a/api/app/Service/Forms/FormCleaner.php b/api/app/Service/Forms/FormCleaner.phpindex 8cf49118f..01ec17f58 100644--- a/api/app/Service/Forms/FormCleaner.php+++ b/api/app/Service/Forms/FormCleaner.php@@ -18,7 +18,7 @@ class FormCleaner/*** All the performed cleanings*- * @var bool+ * @var array*/private array $cleanings = [];@@ -32,6 +32,7 @@ class FormCleaner'database_fields_update' => null,'editable_submissions' => false,'custom_code' => null,+ 'custom_css' => null,'seo_meta' => [],'redirect_url' => null,'enable_partial_submissions' => false,@@ -54,6 +55,7 @@ class FormCleaner'database_fields_update' => 'Form submission will only create new records (no updates).','editable_submissions' => 'Users will not be able to edit their submissions.','custom_code' => 'Custom code was disabled',+ 'custom_css' => 'Custom CSS was disabled','seo_meta' => 'Custom SEO was disabled','redirect_url' => 'Redirect Url was disabled','enable_partial_submissions' => 'Partial submissions were disabled',diff --git a/api/composer.json b/api/composer.jsonindex 42e85610b..a00870a76 100644--- a/api/composer.json+++ b/api/composer.json@@ -34,6 +34,7 @@"maatwebsite/excel": "^3.1","openai-php/client": "*","propaganistas/laravel-disposable-email": "*",+ "sabberworm/php-css-parser": "^9.1","sentry/sentry-laravel": "*","socialiteproviders/stripe": "^4.1","spatie/laravel-data": "^4.6",diff --git a/api/composer.lock b/api/composer.lockindex 53e5f5fe9..41f77ab7d 100644--- a/api/composer.lock+++ b/api/composer.lock@@ -4,7 +4,7 @@"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies","This file is @generated automatically"],- "content-hash": "1e57949df945ab435ed83204d339661a",+ "content-hash": "ed236be3f0416774f8bb9d2cba8899e6","packages": [{"name": "amphp/amp",@@ -8614,6 +8614,80 @@},"time": "2024-03-12T16:46:05+00:00"},+ {+ "name": "sabberworm/php-css-parser",+ "version": "v9.1.0",+ "source": {+ "type": "git",+ "url": "https://github.com/MyIntervals/PHP-CSS-Parser.git",+ "reference": "1b363fdbdc6dd0ca0f4bf98d3a4d7f388133f1fb"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/MyIntervals/PHP-CSS-Parser/zipball/1b363fdbdc6dd0ca0f4bf98d3a4d7f388133f1fb",+ "reference": "1b363fdbdc6dd0ca0f4bf98d3a4d7f388133f1fb",+ "shasum": ""+ },+ "require": {+ "ext-iconv": "*",+ "php": "^7.2.0 || ~8.0.0 || ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0",+ "thecodingmachine/safe": "^1.3 || ^2.5 || ^3.3"+ },+ "require-dev": {+ "php-parallel-lint/php-parallel-lint": "1.4.0",+ "phpstan/extension-installer": "1.4.3",+ "phpstan/phpstan": "1.12.28 || 2.1.25",+ "phpstan/phpstan-phpunit": "1.4.2 || 2.0.7",+ "phpstan/phpstan-strict-rules": "1.6.2 || 2.0.6",+ "phpunit/phpunit": "8.5.46",+ "rawr/phpunit-data-provider": "3.3.1",+ "rector/rector": "1.2.10 || 2.1.7",+ "rector/type-perfect": "1.0.0 || 2.1.0"+ },+ "suggest": {+ "ext-mbstring": "for parsing UTF-8 CSS"+ },+ "type": "library",+ "extra": {+ "branch-alias": {+ "dev-main": "9.2.x-dev"+ }+ },+ "autoload": {+ "psr-4": {+ "Sabberworm\\CSS\\": "src/"+ }+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "authors": [+ {+ "name": "Raphael Schweikert"+ },+ {+ "name": "Oliver Klee",+ "email": "[email protected]"+ },+ {+ "name": "Jake Hotson",+ "email": "[email protected]"+ }+ ],+ "description": "Parser for CSS Files written in PHP",+ "homepage": "https://www.sabberworm.com/blog/2010/6/10/php-css-parser",+ "keywords": [+ "css",+ "parser",+ "stylesheet"+ ],+ "support": {+ "issues": "https://github.com/MyIntervals/PHP-CSS-Parser/issues",+ "source": "https://github.com/MyIntervals/PHP-CSS-Parser/tree/v9.1.0"+ },+ "time": "2025-09-14T07:37:21+00:00"+ },{"name": "sentry/sentry","version": "4.10.0",@@ -12776,6 +12850,145 @@],"time": "2025-01-07T12:55:42+00:00"},+ {+ "name": "thecodingmachine/safe",+ "version": "v3.3.0",+ "source": {+ "type": "git",+ "url": "https://github.com/thecodingmachine/safe.git",+ "reference": "2cdd579eeaa2e78e51c7509b50cc9fb89a956236"+ },+ "dist": {+ "type": "zip",+ "url": "https://api.github.com/repos/thecodingmachine/safe/zipball/2cdd579eeaa2e78e51c7509b50cc9fb89a956236",+ "reference": "2cdd579eeaa2e78e51c7509b50cc9fb89a956236",+ "shasum": ""+ },+ "require": {+ "php": "^8.1"+ },+ "require-dev": {+ "php-parallel-lint/php-parallel-lint": "^1.4",+ "phpstan/phpstan": "^2",+ "phpunit/phpunit": "^10",+ "squizlabs/php_codesniffer": "^3.2"+ },+ "type": "library",+ "autoload": {+ "files": [+ "lib/special_cases.php",+ "generated/apache.php",+ "generated/apcu.php",+ "generated/array.php",+ "generated/bzip2.php",+ "generated/calendar.php",+ "generated/classobj.php",+ "generated/com.php",+ "generated/cubrid.php",+ "generated/curl.php",+ "generated/datetime.php",+ "generated/dir.php",+ "generated/eio.php",+ "generated/errorfunc.php",+ "generated/exec.php",+ "generated/fileinfo.php",+ "generated/filesystem.php",+ "generated/filter.php",+ "generated/fpm.php",+ "generated/ftp.php",+ "generated/funchand.php",+ "generated/gettext.php",+ "generated/gmp.php",+ "generated/gnupg.php",+ "generated/hash.php",+ "generated/ibase.php",+ "generated/ibmDb2.php",+ "generated/iconv.php",+ "generated/image.php",+ "generated/imap.php",+ "generated/info.php",+ "generated/inotify.php",+ "generated/json.php",+ "generated/ldap.php",+ "generated/libxml.php",+ "generated/lzf.php",+ "generated/mailparse.php",+ "generated/mbstring.php",+ "generated/misc.php",+ "generated/mysql.php",+ "generated/mysqli.php",+ "generated/network.php",+ "generated/oci8.php",+ "generated/opcache.php",+ "generated/openssl.php",+ "generated/outcontrol.php",+ "generated/pcntl.php",+ "generated/pcre.php",+ "generated/pgsql.php",+ "generated/posix.php",+ "generated/ps.php",+ "generated/pspell.php",+ "generated/readline.php",+ "generated/rnp.php",+ "generated/rpminfo.php",+ "generated/rrd.php",+ "generated/sem.php",+ "generated/session.php",+ "generated/shmop.php",+ "generated/sockets.php",+ "generated/sodium.php",+ "generated/solr.php",+ "generated/spl.php",+ "generated/sqlsrv.php",+ "generated/ssdeep.php",+ "generated/ssh2.php",+ "generated/stream.php",+ "generated/strings.php",+ "generated/swoole.php",+ "generated/uodbc.php",+ "generated/uopz.php",+ "generated/url.php",+ "generated/var.php",+ "generated/xdiff.php",+ "generated/xml.php",+ "generated/xmlrpc.php",+ "generated/yaml.php",+ "generated/yaz.php",+ "generated/zip.php",+ "generated/zlib.php"+ ],+ "classmap": [+ "lib/DateTime.php",+ "lib/DateTimeImmutable.php",+ "lib/Exceptions/",+ "generated/Exceptions/"+ ]+ },+ "notification-url": "https://packagist.org/downloads/",+ "license": [+ "MIT"+ ],+ "description": "PHP core functions that throw exceptions instead of returning FALSE on error",+ "support": {+ "issues": "https://github.com/thecodingmachine/safe/issues",+ "source": "https://github.com/thecodingmachine/safe/tree/v3.3.0"+ },+ "funding": [+ {+ "url": "https://github.com/OskarStark",+ "type": "github"+ },+ {+ "url": "https://github.com/shish",+ "type": "github"+ },+ {+ "url": "https://github.com/staabm",+ "type": "github"+ }+ ],+ "time": "2025-05-14T06:15:44+00:00"+ },{"name": "tijsverkoyen/css-to-inline-styles","version": "v2.3.0",@@ -16619,14 +16832,14 @@],"aliases": [],"minimum-stability": "dev",- "stability-flags": [],+ "stability-flags": {},"prefer-stable": true,"prefer-lowest": false,"platform": {"php": "^8.2","ext-json": "*"},- "platform-dev": [],+ "platform-dev": {},"platform-overrides": {"ext-pcntl": "8.0","ext-posix": "8.0"diff --git a/api/database/migrations/2025_09_28_000001_add_custom_css_to_forms_table.php b/api/database/migrations/2025_09_28_000001_add_custom_css_to_forms_table.phpnew file mode 100644index 000000000..68edbb91e--- /dev/null+++ b/api/database/migrations/2025_09_28_000001_add_custom_css_to_forms_table.php@@ -0,0 +1,27 @@+<?php++use Illuminate\Database\Migrations\Migration;+use Illuminate\Database\Schema\Blueprint;+use Illuminate\Support\Facades\Schema;++return new class () extends Migration {+ /**+ * Run the migrations.+ */+ public function up(): void+ {+ Schema::table('forms', function (Blueprint $table) {+ $table->text('custom_css')->nullable()->after('custom_code');+ });+ }++ /**+ * Reverse the migrations.+ */+ public function down(): void+ {+ Schema::table('forms', function (Blueprint $table) {+ $table->dropColumn('custom_css');+ });+ }+};diff --git a/api/tests/Unit/Rules/CssOnlyRuleTest.php b/api/tests/Unit/Rules/CssOnlyRuleTest.phpnew file mode 100644index 000000000..3f761ee04--- /dev/null+++ b/api/tests/Unit/Rules/CssOnlyRuleTest.php@@ -0,0 +1,93 @@+<?php++namespace Tests\Unit\Rules;++use App\Rules\CssOnlyRule;+use Illuminate\Support\Facades\Validator;+use Tests\TestCase;++class CssOnlyRuleTest extends TestCase+{+ /** @test */+ public function it_accepts_valid_css(): void+ {+ $data = ['css' => 'body { color: red; } .card > .title { font-weight: 700; }'];+ $v = Validator::make($data, ['css' => [new CssOnlyRule()]]);+ $this->assertTrue($v->passes());+ }++ /** @test */+ public function it_rejects_html_like_content(): void+ {+ $data = ['css' => '<div>bad</div>'];+ $v = Validator::make($data, ['css' => [new CssOnlyRule()]]);+ $this->assertFalse($v->passes());+ }++ /** @test */+ public function it_rejects_expression_function(): void+ {+ $data = ['css' => 'div { width: expression(alert(1)); }'];+ $v = Validator::make($data, ['css' => [new CssOnlyRule()]]);+ $this->assertFalse($v->passes());+ }++ /** @test */+ public function it_rejects_ie_behavior_property(): void+ {+ $data = ['css' => 'div { behavior: url(#default#VML); }'];+ $v = Validator::make($data, ['css' => [new CssOnlyRule()]]);+ $this->assertFalse($v->passes());+ }++ /** @test */+ public function it_accepts_http_https_urls_and_safe_data_images(): void+ {+ $ok = [+ 'div { background-image: url(https://example.com/a.png); }',+ 'div { background-image: url(data:image/png;base64,iVBORw0KGgo=); }',+ ];+ foreach ($ok as $css) {+ $v = Validator::make(['css' => $css], ['css' => [new CssOnlyRule()]]);+ $this->assertTrue($v->passes());+ }+ }++ /** @test */+ public function it_rejects_dangerous_urls(): void+ {+ $bad = [+ 'div { background: url(javascript:alert(1)); }',+ 'div { background: url(vbscript:alert(1)); }',+ 'div { background: url(data:text/html;base64,PHNjcmlwdD5hbGVydCgxKTwvc2NyaXB0Pg==); }',+ 'div { background: url(data:image/svg+xml;base64,PHN2ZyBvbmxvYWQ9YWxlcnQoMSk+); }',+ ];+ foreach ($bad as $css) {+ $v = Validator::make(['css' => $css], ['css' => [new CssOnlyRule()]]);+ $this->assertFalse($v->passes());+ }+ }++ /** @test */+ public function it_validates_import_urls(): void+ {+ $ok = ['@import url("https://example.com/styles.css"); body{color:#000}'];+ foreach ($ok as $css) {+ $v = Validator::make(['css' => $css], ['css' => [new CssOnlyRule()]]);+ $this->assertTrue($v->passes());+ }++ $bad = ['@import url("javascript:alert(1)");'];+ foreach ($bad as $css) {+ $v = Validator::make(['css' => $css], ['css' => [new CssOnlyRule()]]);+ $this->assertFalse($v->passes());+ }+ }++ /** @test */+ public function it_allows_empty_string(): void+ {+ $v = Validator::make(['css' => ''], ['css' => [new CssOnlyRule()]]);+ $this->assertTrue($v->passes());+ }+}diff --git a/client/components/forms/heavy/CodeInput.client.vue b/client/components/forms/heavy/CodeInput.client.vueindex ae26a0b08..6fc540911 100644--- a/client/components/forms/heavy/CodeInput.client.vue+++ b/client/components/forms/heavy/CodeInput.client.vue@@ -91,11 +91,16 @@<script setup>import { Codemirror } from "vue-codemirror"import { html } from "@codemirror/lang-html"+import { css as cssLang } from "@codemirror/lang-css"import { inputProps, useFormInput } from "../useFormInput.js"import { codeInputTheme } from '~/lib/forms/themes/code-input.theme.js'const props = defineProps({...inputProps,+ languageMode: {+ type: String,+ default: 'html', // 'html' | 'css'+ },allowFullscreen: {type: Boolean,default: false,@@ -104,7 +109,9 @@ const props = defineProps({const emit = defineEmits(['update:modelValue', 'focus', 'blur'])-const extensions = [html()]+const extensions = computed(() => {+ return props.languageMode === 'css' ? [cssLang()] : [html()]+})const isFullscreen = ref(false)const openFullscreen = () => {diff --git a/client/components/open/forms/components/form-components/FormCustomCode.vue b/client/components/open/forms/components/form-components/FormCustomCode.vueindex 655e569f7..a2d06a5ed 100644--- a/client/components/open/forms/components/form-components/FormCustomCode.vue+++ b/client/components/open/forms/components/form-components/FormCustomCode.vue@@ -32,6 +32,29 @@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."+ />+ </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>+ <CodeInput+ :allow-fullscreen="true"+ language-mode="css"+ name="custom_css"+ class="mt-4"+ :form="form"+ help="CSS only. Example: body { background: #f8fafc }"+ label="Custom CSS"+ placeholder="body { background: #f8fafc }"+ />+ </div></div></VForm></template>diff --git a/client/pages/forms/[slug]/index.vue b/client/pages/forms/[slug]/index.vueindex a8a0d9dc1..ea10586fd 100644--- a/client/pages/forms/[slug]/index.vue+++ b/client/pages/forms/[slug]/index.vue@@ -283,7 +283,10 @@ useHead({content: 'black-translucent'},] : {},- script: [{ src: '/widgets/iframeResizer.contentWindow.min.js' }]+ script: [{ src: '/widgets/iframeResizer.contentWindow.min.js' }],+ style: computed(() => form.value?.custom_css ? [+ { key: 'custom-css', textContent: form.value.custom_css }+ ] : [])})definePageMeta({