<secure-form>
A form wrapper with automatic CSRF protection, coordinated validation across all child components, and comprehensive submission handling.
Overview
The <secure-form> component wraps standard form elements and secure-ui components to provide coordinated security features. It automatically handles CSRF token injection, validates all child components before submission, and provides a unified event interface.
<secure-form> uses light DOM to ensure native form submission works correctly. All child elements participate in standard form submission.CSRF Protection
CSRF tokens are automatically injected into the form when the csrf-token attribute is set. The token is added as a hidden input field.
<!-- Server provides the CSRF token -->
<secure-form
action="/api/submit"
method="POST"
csrf-token="abc123..."
>
<secure-input name="email" type="email"></secure-input>
<button type="submit">Submit</button>
</secure-form>
<!-- Generates hidden field: -->
<!-- <input type="hidden" name="csrf_token" value="abc123..."> -->// Handler generates CSRF token
func (h *Handlers) ContactForm(w http.ResponseWriter, r *http.Request) {
csrfToken, _ := h.CSRFStore.GenerateToken()
pages.ContactForm(csrfToken).Render(r.Context(), w)
}
// Template uses the token
// <secure-form csrf-token={ csrfToken }>...</secure-form>Form Validation
The form validates all child secure-ui components before submission. If any component is invalid, submission is prevented and errors are displayed.
const form = document.querySelector('secure-form');
// Check form validity
if (form.valid) {
console.log('All fields are valid');
}
// Get form data
const data = form.getData();
// Returns: { email: 'user@example.com', name: 'John' }
// Listen for form events
form.addEventListener('secure-form-submit', (e) => {
console.log('Form submitting:', e.detail);
});
form.addEventListener('secure-form-success', (e) => {
console.log('Form succeeded:', e.detail);
});API Reference
Attributes
| Attribute | Type | Default | Description |
|---|---|---|---|
action | string | - | Form submission URL. Cross-origin URLs and non-http(s) schemes (e.g. javascript:) are rejected — the component only submits to the same origin. |
method | string | "POST" | HTTP method (GET, POST) |
csrf-token | string | - | CSRF token from server |
security-tier | string | "critical" | Default tier for child components |
novalidate | boolean | false | Disable client-side validation |
use-fetch | boolean | false | Enable JS fetch submission with JSON payload and telemetry. Without this attribute the form submits natively. |
csrf-header-name | string | "X-CSRF-Token" | HTTP header name used to send the CSRF token (use-fetch mode only) |
csrf-field-name | string | "csrf_token" | Hidden input field name for CSRF token in native submit fallback |
enctype | string | - | Form encoding type (native submit only) |
Properties
Methods
secure-audit event is also dispatched on every audit call.Events
| Event | Detail | Description |
|---|---|---|
secure-form-submit | cancelSubmission, telemetry | Fired before submission. Call e.detail.cancelSubmission() to abort the fetch and reset form state, or event.preventDefault() to cancel the event. |
secure-form-success | status, ok, telemetry | Fired after successful 2xx submission. formData and response are intentionally absent — field values must not propagate globally via a composed event. Read values from form.getData(); for full response control use cancelSubmission() in secure-form-submit. |
secure-threat-detected | fieldName, threatType: 'csrf-token-absent', patternId, tier, timestamp | Fired at submission on sensitive and critical tiers when a CSRF token is absent. A defence-in-depth signal — the request is also blocked server-side, but the event enables immediate client-side monitoring. |
Form State Feedback
<secure-form> sets a data-state attribute on itself that you can target with CSS:
| data-state | When set | Clears |
|---|---|---|
blocked | Injection threat detected in any child field | On reset() |
success | Server returns 2xx | Automatically after 3 s |
error | Server or network error | On next submission attempt |
Non-blocking telemetry signals (high velocity, paste-only entry, unfocused fill, etc.) surface as inline warning messages on the specific fields at submission — submission still proceeds. Override state styles by targeting secure-form[data-state="blocked"] .secure-form in CSS.
Risk Signals
At submission, <secure-form> computes a risk score (0–100) from behavioral signals. Blocking signals prevent submission; all others annotate fields with inline warnings and appear in telemetry.riskSignals.
| Signal | Condition | Score | Blocks |
|---|---|---|---|
injection_detected | Any field fired secure-threat-detected with threatType: 'injection' | +40 | Yes |
session_too_fast | Submitted in under 3 s | +30 | No |
all_fields_pasted | All fields filled by paste with no keystrokes | +25 | No |
csrf_token_absent | CSRF token absent on sensitive/critical tier | +20 | No |
field_filled_without_focus | Any field has focusCount = 0 | +15 | No |
high_velocity_typing | Any field velocity > 15 ks/s | +15 | No |
session_fast | Submitted in under 8 s | +10 | No |
form_probing | Field focused/blurred > 1× with no input | +10 | No |
high_correction_count | Any field with > 5 corrections | +5 | No |
autofill_detected | All fields autofilled (trust signal) | −10 | No |
SessionTelemetry shape on the telemetry object:
interface SessionTelemetry {
sessionDuration: number; // ms from form mount to submission
fieldCount: number;
fields: FieldTelemetrySnapshot[];
riskScore: number; // 0–100
riskSignals: string[];
submittedAt: string; // ISO 8601
detectedThreats?: ThreatDetectedDetail[]; // omitted when no threats
}Examples
Complete Contact Form
<secure-form
action="/api/contact"
method="POST"
csrf-token="server-generated-token"
security-tier="sensitive">
<secure-input
type="text"
label="Full Name"
name="name"
required>
</secure-input>
<secure-input
type="email"
label="Email"
name="email"
required>
</secure-input>
<secure-select
label="Subject"
name="subject"
required>
<option value="">Choose subject</option>
<option value="general">General Inquiry</option>
<option value="support">Technical Support</option>
<option value="sales">Sales</option>
</secure-select>
<secure-textarea
label="Message"
name="message"
rows="5"
required>
</secure-textarea>
<button type="submit" class="btn btn-primary">
Send Message
</button>
</secure-form>AJAX Form Submission
const form = document.querySelector('secure-form');
form.addEventListener('secure-form-submit', async (e) => {
// cancelSubmission() aborts the built-in fetch and re-enables the form.
// Use this when you want to handle the request yourself.
e.detail.cancelSubmission();
// Read field values from the element — formData is not in the event detail.
const data = form.getData();
const response = await fetch(form.getAttribute('action'), {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': form.getAttribute('csrf-token')
},
body: JSON.stringify(data)
});
if (response.ok) {
alert('Form submitted successfully!');
form.reset();
}
});