Skip to content

Beautiful Open-Source Form Builder

Harden sanitization in form/template pipelines and admin alerts

Julien Nahum73f7bfde64db
diff --git a/.cursor/commands/commit.md b/.cursor/commands/commit.md
new file mode 100644
index 000000000..76222ad51
--- /dev/null
+++ b/.cursor/commands/commit.md
@@ -0,0 +1,58 @@
+# Commit Quality Gate
+
+## Goal
+
+Run all required quality checks before creating a commit:
+
+- back-end tests
+- front-end tests
+- back-end linters
+- front-end linters
+- fix issues found during those checks
+- generate a commit message proposal based on the git diff
+
+## Steps
+
+1. Run checks in this order:
+ - `cd api && ./vendor/bin/pest -p`
+ - `cd client && npm run test --if-present`
+ - `cd api && ./vendor/bin/pint --test`
+ - `cd client && npm run lint`
+
+2. If a command fails:
+ - Identify the root cause from the error output.
+ - Apply a focused code fix.
+ - Re-run only the failing command until it passes.
+ - After each fix, re-run all previous checks in the sequence to ensure no regressions.
+ - Continue until all checks pass, or clearly report any blocker that cannot be fixed safely.
+
+3. After all checks pass, prepare commit context:
+ - `git status`
+ - `git diff --stat`
+ - `git diff`
+ - `git diff --cached`
+ - `git log -5 --oneline`
+
+4. Generate a commit message proposal from the diff:
+ - 1 short subject line.
+ - 1 concise body paragraph focused on why.
+ - A compact bullet list of key changed areas/files.
+ - Include a short diff summary (main additions/removals and notable files touched).
+
+## Output Format
+
+- Check results in order (pass/fail per command).
+- For each failure:
+ - failing command
+ - root cause
+ - fix applied
+ - re-check result
+- Final section:
+ - "Ready to commit" status
+ - proposed commit message (subject + body)
+ - short diff summary
+
+## Constraints
+
+- Do not commit automatically.
+- Make only minimal, relevant fixes required to pass checks.
diff --git a/api/app/Http/Requests/UserFormRequest.php b/api/app/Http/Requests/UserFormRequest.php
index 3e6e18d6f..da2526f15 100644
--- a/api/app/Http/Requests/UserFormRequest.php
+++ b/api/app/Http/Requests/UserFormRequest.php
@@ -12,6 +12,7 @@ use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Http\Request;
use App\Rules\CssOnlyRule;
+use Stevebauman\Purify\Facades\Purify;
/**
* Abstract class to validate create/update forms
@@ -34,8 +35,15 @@ abstract class UserFormRequest extends \Illuminate\Foundation\Http\FormRequest
if (isset($data['properties']) && is_array($data['properties'])) {
$data['properties'] = array_map(function ($property) {
- if (isset($property['help']) && is_string($property['help']) && strip_tags($property['help']) === '') {
- $property['help'] = null;
+ if (isset($property['name']) && is_string($property['name'])) {
+ $property['name'] = trim(strip_tags($property['name']));
+ }
+
+ if (isset($property['help']) && is_string($property['help'])) {
+ $property['help'] = Purify::clean($property['help']);
+ if (strip_tags($property['help']) === '') {
+ $property['help'] = null;
+ }
}
return $property;
}, $data['properties']);
diff --git a/api/app/Models/Template.php b/api/app/Models/Template.php
index 63963c188..6ad1c568e 100644
--- a/api/app/Models/Template.php
+++ b/api/app/Models/Template.php
@@ -61,6 +61,35 @@ class Template extends Model
$this->attributes['description'] = Purify::clean($value);
}
+ public function setQuestionsAttribute($value)
+ {
+ if (!is_array($value)) {
+ $this->attributes['questions'] = json_encode([]);
+ return;
+ }
+
+ $sanitizedQuestions = array_map(function ($item) {
+ $question = is_array($item) ? $item : [];
+
+ $questionText = '';
+ if (isset($question['question']) && is_string($question['question'])) {
+ $questionText = trim(strip_tags($question['question']));
+ }
+
+ $answerHtml = '';
+ if (isset($question['answer']) && is_string($question['answer'])) {
+ $answerHtml = Purify::clean($question['answer']);
+ }
+
+ return [
+ 'question' => $questionText,
+ 'answer' => $answerHtml,
+ ];
+ }, $value);
+
+ $this->attributes['questions'] = json_encode($sanitizedQuestions);
+ }
+
public function scopePubliclyListed($query)
{
return $this->where('publicly_listed', true);
diff --git a/api/app/Service/Forms/FormCleaner.php b/api/app/Service/Forms/FormCleaner.php
index e4103b072..379dfe3d7 100644
--- a/api/app/Service/Forms/FormCleaner.php
+++ b/api/app/Service/Forms/FormCleaner.php
@@ -108,6 +108,9 @@ class FormCleaner
public function processRequest(UserFormRequest $request): FormCleaner
{
$data = $request->validated();
+ $customDomain = $data['custom_domain'] ?? $request->form?->custom_domain ?? null;
+ $allowOnSelfHosted = config('app.self_hosted', true) && (bool) config('opnform.custom_code.enable_self_hosted', false);
+ $this->allowCustomCode = !empty($customDomain) || $allowOnSelfHosted;
$this->data = $this->commonCleaning($data);
return $this;
diff --git a/api/tests/Feature/TemplateTest.php b/api/tests/Feature/TemplateTest.php
index 7211ca7cb..7f0bc4e2b 100644
--- a/api/tests/Feature/TemplateTest.php
+++ b/api/tests/Feature/TemplateTest.php
@@ -92,3 +92,39 @@ it('returns empty response when template slug does not exist', function () {
// Laravel returns empty string for null responses
expect($response->getContent())->toBeEmpty();
});
+
+it('sanitizes FAQ answers and strips tags from FAQ questions', function () {
+ $user = $this->createUser([
+ 'email' => '[email protected]',
+ ]);
+ $this->actingAsUser($user);
+
+ $workspace = $this->createUserWorkspace($user);
+ $form = $this->makeForm($user, $workspace);
+
+ $templateData = [
+ 'name' => 'Sanitized FAQ Template',
+ 'slug' => 'sanitized-faq-template',
+ 'short_description' => 'Template with sanitized FAQ data',
+ 'description' => '<p>Safe description</p>',
+ 'image_url' => 'https://example.com/image.jpg',
+ 'publicly_listed' => true,
+ 'form' => $form->getAttributes(),
+ 'questions' => [[
+ 'question' => '<img src=x onerror=alert(1)>What is this?',
+ 'answer' => '<p onclick=alert(1)><script>alert(1)</script><strong>Safe</strong></p>',
+ ]],
+ ];
+
+ $response = $this->postJson(route('templates.create'), $templateData)
+ ->assertSuccessful();
+
+ $templateId = $response->json('template_id');
+ $template = Template::findOrFail($templateId);
+ $faq = $template->questions[0] ?? [];
+
+ expect($faq['question'] ?? '')->toBe('What is this?')
+ ->and($faq['answer'] ?? '')->toContain('<strong>Safe</strong>')
+ ->and($faq['answer'] ?? '')->not->toContain('<script')
+ ->and($faq['answer'] ?? '')->not->toContain('onclick=');
+});
diff --git a/client/components/forms/core/validation/HasError.vue b/client/components/forms/core/validation/HasError.vue
index 7e1a92557..c6a41dc1c 100644
--- a/client/components/forms/core/validation/HasError.vue
+++ b/client/components/forms/core/validation/HasError.vue
@@ -9,6 +9,8 @@
</template>
<script>
+import { escapeHtml } from '~/lib/utils'
+
export default {
name: 'HasError',
props: {
@@ -51,7 +53,8 @@ export default {
baseError = baseError.replace(`The ${this.fieldName} field`, 'This field')
}
- const coreError = `<p class='text-red-500'>${baseError}</p>`
+ const escapedBaseError = escapeHtml(baseError)
+ const coreError = `<p class='text-red-500'>${escapedBaseError}</p>`
if (subErrorsKeys.length) {
return coreError + `<ul class='list-disc list-inside'>${subErrorsKeys.map(
(key) => {
@@ -65,7 +68,7 @@ export default {
},
methods: {
getSubError(subErrorKey) {
- return this.form.errors.get(subErrorKey).replace(subErrorKey, 'item')
+ return escapeHtml(this.form.errors.get(subErrorKey).replace(subErrorKey, 'item'))
},
},
}
diff --git a/client/components/pages/admin/BlockUser.vue b/client/components/pages/admin/BlockUser.vue
index c6d3a2cb6..3e9a63a99 100644
--- a/client/components/pages/admin/BlockUser.vue
+++ b/client/components/pages/admin/BlockUser.vue
@@ -58,6 +58,8 @@
<script setup>
+import { escapeHtml } from '~/lib/utils'
+
const props = defineProps({
user: { type: Object, required: true }
})
@@ -118,7 +120,9 @@ const lastBlock = computed(() => {
const alertContent = computed(() => {
if (isBlocked.value) {
- const blockedBy = lastBlock.value?.blocked_by || 'Automatically blocked by our AI'
+ const blockedBy = escapeHtml(lastBlock.value?.blocked_by || 'Automatically blocked by our AI')
+ const blockedOn = escapeHtml(new Date(props.user.blocked_at).toLocaleString())
+ const reason = escapeHtml(lastBlock.value?.reason || '')
return {
icon: 'i-heroicons-exclamation-triangle',
color: 'error',
@@ -126,11 +130,11 @@ const alertContent = computed(() => {
content: `
This will unblock the user and allow them to log in again. Their forms will remain in draft status.
<div class="mt-2">
- <b>Blocked on:</b> ${new Date(props.user.blocked_at).toLocaleString()}
+ <b>Blocked on:</b> ${blockedOn}
<br>
<b>Blocked by:</b> ${blockedBy}
<br>
- <b>Reason:</b> ${lastBlock.value?.reason || ''}
+ <b>Reason:</b> ${reason}
</div>
`
}
diff --git a/client/components/pages/forms/show/FormCleanings.vue b/client/components/pages/forms/show/FormCleanings.vue
index c88534be7..056ba95af 100644
--- a/client/components/pages/forms/show/FormCleanings.vue
+++ b/client/components/pages/forms/show/FormCleanings.vue
@@ -61,6 +61,7 @@
<script setup>
import VTransition from '~/components/global/transitions/VTransition.vue'
import TrackClick from '~/components/global/TrackClick.vue'
+import { escapeHtml } from '~/lib/utils'
const props = defineProps({
form: { type: Object, required: true },
@@ -112,10 +113,11 @@ const cleaningContent = computed(() => {
if (fieldName !== 'Form') {
fieldName = '"' + fieldName + '" field'
}
- let fieldInfo = '<br><span class="font-semibold">' + fieldName + '</span><br/><ul class=\'list-disc list-inside\'>'
+ const safeFieldName = escapeHtml(fieldName)
+ let fieldInfo = '<br><span class="font-semibold">' + safeFieldName + '</span><br/><ul class=\'list-disc list-inside\'>'
cleanings.value[key].forEach((msg) => {
if (!msg) return
- fieldInfo = fieldInfo + '<li>' + msg + '</li>'
+ fieldInfo = fieldInfo + '<li>' + escapeHtml(msg) + '</li>'
})
if (fieldInfo) {
message = message + fieldInfo + '</ul>'
diff --git a/client/lib/utils.js b/client/lib/utils.js
index 7a699dd7c..5d7ce53c0 100644
--- a/client/lib/utils.js
+++ b/client/lib/utils.js
@@ -150,6 +150,19 @@ export function cleanQuotes(str) {
return str.replace(/^"|"$/g, '')
}
+/**
+ * Escape user-provided text before string interpolation into HTML.
+ */
+export function escapeHtml(value) {
+ if (value === null || value === undefined) return ''
+ return String(value)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;')
+}
+
/**
* Shuffles an array
* @param {Array} array - The array to shuffle