📝

<secure-input>

A security-hardened text input component with built-in XSS prevention, type-specific validation, and comprehensive audit logging.

Overview

The <secure-input> component provides a security-first text input that wraps native HTML input elements with enhanced protection. It supports all standard input types while adding automatic sanitization, validation, and audit logging.

Progressive Enhancement
Works as a native <input> without JavaScript. When JS is enabled, additional security features like client-side validation and audit logging are activated.

Basic Usage

Simple Text Input HTML
<secure-input
	label="Full Name"
	name="fullname"
	type="text"
	placeholder="Enter your name"
	required>
</secure-input>
Live Demo

Input Types

All standard HTML5 input types are supported with type-specific validation and security measures.

TypeValidationSecurity Notes
textLength, patternHTML entities encoded, scripts stripped
emailEmail formatNormalized, validated using browser-native email format checking
passwordTier-based strengthStrength rules scale with tier, autocomplete disabled
telPatternValidated via pattern attribute, no auto-formatting
urlURL formatProtocol validation, javascript: blocked
numberMin/max, stepSafe integer range check, overflow protection
Different Input Types HTML
<!-- Email with validation -->
<secure-input
	type="email"
	label="Email Address"
	name="email"
	placeholder="user@example.com"
	security-tier="sensitive"
	required>
</secure-input>

<!-- Password with strength requirements -->
<secure-input
	type="password"
	label="Password"
	name="password"
	placeholder="Enter a strong password"
	security-tier="critical"
	required>
</secure-input>

<!-- Number with range -->
<secure-input
	type="number"
	label="Age"
	name="age"
	min="18"
	max="120"
	security-tier="public">
</secure-input>
Live Demo - Email Input

Security Tiers

Choose the appropriate security tier based on the sensitivity of the data being collected. Each tier adjusts validation strictness, visual indicators, and security features.

Public
Use for: Names, comments, general text
Features: Basic validation, autocomplete allowed
Authenticated
Use for: User preferences, settings
Features: Session validation, moderate logging
Sensitive
Use for: Email, phone, address (PII)
Features: No autocomplete, masking option, rate limited
Critical
Use for: Passwords, SSN, financial data
Features: Full masking, no storage, complete audit log
Security Tier Examples HTML
<!-- PUBLIC: General information -->
<secure-input
	security-tier="public"
	label="Website"
	name="website"
	type="url">
</secure-input>

<!-- SENSITIVE: Personal identifiable information -->
<secure-input
	security-tier="sensitive"
	label="Phone Number"
	name="phone"
	type="tel">
</secure-input>

<!-- CRITICAL: Highly sensitive data -->
<secure-input
	security-tier="critical"
	label="Social Security Number"
	name="ssn"
	type="text"
	pattern="[0-9]{3}-[0-9]{2}-[0-9]{4}">
</secure-input>
Live Demo - Security Tiers

Validation

Client-side validation provides immediate feedback while server-side validation is the authoritative source. Use HTML5 validation attributes alongside custom patterns.

Validation Attributes HTML
<!-- Required field -->
<secure-input
	label="Username"
	name="username"
	required>
</secure-input>

<!-- Length constraints -->
<secure-input
	label="Bio"
	name="bio"
	minlength="10"
	maxlength="500">
</secure-input>

<!-- Custom pattern -->
<secure-input
	label="Product Code"
	name="code"
	pattern="[A-Z]{3}-[0-9]{4}"
	placeholder="ABC-1234">
</secure-input>

<!-- Number range -->
<secure-input
	type="number"
	label="Quantity"
	name="quantity"
	min="1"
	max="100"
	step="1">
</secure-input>
Always Validate Server-Side
Client-side validation improves UX but can be bypassed. Always implement server-side validation as the authoritative check.

Threat Feedback

Add the threat-feedback boolean attribute to enable inline threat detection UI. When present, the component shows an amber warning message directly below the field whenever an injection pattern is detected — identifying the blocked pattern and the field's security tier. The message clears automatically when the input no longer matches any pattern.

This attribute is opt-in. Omit it on fields where injection patterns are legitimate input — such as a code editor or a support form that accepts HTML snippets. The underlying secure-threat-detected event fires regardless of whether threat-feedback is set, so server-side logging is unaffected.

Enabling Threat Feedback HTML
<!-- Threat feedback enabled: user sees inline warning on injection attempt -->
<secure-input
  type="text"
  label="Username"
  name="username"
  security-tier="authenticated"
  threat-feedback>
</secure-input>

<!-- Threat feedback disabled: silent detection only, event still fires -->
<secure-textarea
  label="Code Snippet"
  name="code"
  security-tier="public">
</secure-textarea>
What the user sees
When a threat is detected, the field border turns amber and a message appears below it: "Script injection blocked" with badges showing the pattern ID (e.g. script-tag) and the security tier. The message disappears as soon as the input no longer matches any injection pattern. The raw input value is never displayed.
Live Demo — type <script>alert(1)</script> to trigger

Server-Side Integration

The secure-threat-detected event fires in the browser as soon as an injection pattern is matched. This is a UX signal — it cannot be trusted as a security boundary. The authoritative check happens independently on the server, using the same detection logic applied to the submitted value before it touches your database.

End-to-End Injection Detection
Client and server detect injection independently using the same classification: ThreatHTMLInjection and ThreatScriptInjection. Neither relies on the other. An attacker who bypasses the client-side event still hits the server-side rejection.

The Go validation package exposes two functions for this. DetectThreat classifies the raw submitted value before any sanitization. NoHTML adds a validation error to reject the submission outright — the payload never reaches your service layer or database.

Server-Side Threat Detection — Go Go
// Capture raw values before any sanitization
rawFirstName := r.FormValue("first_name")
rawLastName  := r.FormValue("last_name")

// Log injection attempts — classified by severity
ip := r.RemoteAddr
for _, f := range []struct{ field, value string }{
    {"first_name", rawFirstName},
    {"last_name",  rawLastName},
} {
    if level := validation.DetectThreat(f.value); level != validation.ThreatNone {
        log.Printf("[SECURITY] injection attempt: field=%s threat=%d ip=%s payload=%.200q",
            f.field, level, ip, f.value)
    }
}

// Sanitize as defense-in-depth before storage
firstName := validation.SanitizeHTML(validation.Sanitize(rawFirstName))
lastName  := validation.SanitizeHTML(validation.Sanitize(rawLastName))

// Validate — NoHTML checks raw values and rejects the submission if HTML is present
v := validation.New()
v.Required("first_name", firstName, "First Name").
    MaxLength("first_name", firstName, 50, "First Name").
    NoHTML("first_name", rawFirstName, "First Name")
v.Required("last_name", lastName, "Last Name").
    MaxLength("last_name", lastName, 50, "Last Name").
    NoHTML("last_name", rawLastName, "Last Name")

if !v.Result().IsValid() {
    // Submission rejected — error message is generic ("contains invalid characters")
    // to avoid revealing detection logic to the attacker
    renderErrors(w, v.Result().Errors)
    return
}
Three independent layers
1. Client event — secure-threat-detected fires immediately as the user types, providing UX feedback and enabling client-side logging via <secure-telemetry-provider>.
2. Server rejection — NoHTML rejects the submission with a validation error. The payload never reaches the service layer.
3. Defense-in-depth sanitization — SanitizeHTML strips all HTML from values before any storage, regardless of validation outcome, using a strict bluemonday policy with no allowed tags.
Client-side detection does not replace server-side validation
The secure-threat-detected event can be suppressed by an attacker sending a crafted HTTP request directly, bypassing the browser entirely. Server-side DetectThreat and NoHTML are the authoritative enforcement layer. The client event is a UX and observability feature only.

API Reference

Attributes

AttributeTypeDefaultDescription
security-tierstring"critical"Security level: "public", "authenticated", "sensitive", "critical"
typestring"text"Input type: text, email, password, tel, url, number, etc.
namestring-Form field name for submission
labelstring-Accessible label text
placeholderstring-Placeholder text
requiredbooleanfalseField is required
disabledbooleanfalseDisable the input
readonlybooleanfalseMake input read-only
minlengthnumber-Minimum character length
maxlengthnumber-Maximum character length
minnumber-Minimum value (for number type)
maxnumber-Maximum value (for number type)
patternstring-Regex validation pattern. Patterns longer than 200 characters are not compiled client-side (ReDoS mitigation) — browser native validation applies instead.
threat-feedbackbooleanfalseShow inline amber warning when an injection pattern is detected. Opt-in — omit on fields where injection syntax is legitimate input (e.g. code editors).

Properties

value string Get or set the input value
valid boolean Whether the current value passes validation
securityTier string The current security tier (read-only after init)

Methods

focus(): void
Focus the input element
blur(): void
Remove focus from the input element
getAuditLog(): AuditLogEntry[]
Returns the component's audit log entries
getFieldTelemetry(): FieldTelemetry
Returns behavioral signals for this field: dwell time, typing velocity, correction count, paste/autofill detection, and focus metrics
reportError(message: string, variant?: 'error' | 'warning'): void
Display an external error or warning message on this field (e.g. from a server validation response). Default variant is 'error'.
clearExternalError(): void
Clear a message previously set by reportError()

Events

EventDetailDescription
secure-input-change{ name, masked, tier }Fired on every input change. value is intentionally absent — read (e.target as SecureInput).value directly.
secure-audit{ event, tier, timestamp, data? }Fired on every audit entry — validation, focus events, and submission signals
secure-threat-detected{ fieldName, threatType, patternId, tier, timestamp }Fired when an injection pattern matches. Raw value intentionally absent. Fires regardless of threat-feedback attribute.

Examples

Login Form

Complete Login Form HTML
<secure-form action="/login" method="POST">
	<secure-input
		type="email"
		label="Email"
		name="email"
		security-tier="sensitive"
		required>
	</secure-input>

	<secure-input
		type="password"
		label="Password"
		name="password"
		security-tier="critical"
		required>
	</secure-input>

	<button type="submit">Sign In</button>
</secure-form>

Accessing Component via JavaScript

JavaScript Integration JavaScript
// Get component reference
const emailInput = document.querySelector('secure-input[name="email"]');

// Read value
console.log(emailInput.value);

// Check validation
if (emailInput.valid) {
console.log('Email is valid');
}

// Listen for changes
emailInput.addEventListener('secure-input-change', (e) => {
// value is not in e.detail — read it from the element directly
console.log('New value:', e.target.value);
console.log('Security tier:', e.detail.tier);
});

// Get audit log
const auditLog = emailInput.getAuditLog();
console.log('Audit entries:', auditLog);