📜

<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.

Light DOM for Form Submission
Unlike other secure-ui components, <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.

CSRF Token Usage HTML
<!-- 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..."> -->
Go/Templ Server Integration Go
// 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.

Validation Flow JavaScript
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);
});
Server-Side Validation Required
Client-side validation is for UX only. Always validate and sanitize all data on the server.

API Reference

Attributes

AttributeTypeDefaultDescription
actionstring-Form submission URL. Cross-origin URLs and non-http(s) schemes (e.g. javascript:) are rejected — the component only submits to the same origin.
methodstring"POST"HTTP method (GET, POST)
csrf-tokenstring-CSRF token from server
security-tierstring"critical"Default tier for child components
novalidatebooleanfalseDisable client-side validation
use-fetchbooleanfalseEnable JS fetch submission with JSON payload and telemetry. Without this attribute the form submits natively.
csrf-header-namestring"X-CSRF-Token"HTTP header name used to send the CSRF token (use-fetch mode only)
csrf-field-namestring"csrf_token"Hidden input field name for CSRF token in native submit fallback
enctypestring-Form encoding type (native submit only)

Properties

valid boolean Whether all child components pass validation (read-only)
securityTier string Active security tier (read-only after connection)

Methods

getData(): Record<string, string>
Get all form field values as an object
reset(): void
Reset all form fields to initial values
submit(): void
Programmatically submit the form
getAuditLog(): AuditLogEntry[]
Returns a copy of the form's internal audit log (capped at 1000 entries). Each entry includes event name, tier, ISO timestamp, and optional metadata. A secure-audit event is also dispatched on every audit call.

Events

EventDetailDescription
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-stateWhen setClears
blockedInjection threat detected in any child fieldOn reset()
successServer returns 2xxAutomatically after 3 s
errorServer or network errorOn 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.

SignalConditionScoreBlocks
injection_detectedAny field fired secure-threat-detected with threatType: 'injection'+40Yes
session_too_fastSubmitted in under 3 s+30No
all_fields_pastedAll fields filled by paste with no keystrokes+25No
csrf_token_absentCSRF token absent on sensitive/critical tier+20No
field_filled_without_focusAny field has focusCount = 0+15No
high_velocity_typingAny field velocity > 15 ks/s+15No
session_fastSubmitted in under 8 s+10No
form_probingField focused/blurred > 1× with no input+10No
high_correction_countAny field with > 5 corrections+5No
autofill_detectedAll fields autofilled (trust signal)−10No

SessionTelemetry shape on the telemetry object:

SessionTelemetry TypeScript
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

Contact Form with All Features HTML
<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

JavaScript Submission JavaScript
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();
  }
});