<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.
<input> without JavaScript. When JS is enabled, additional security features like client-side validation and audit logging are activated.Basic Usage
<secure-input
label="Full Name"
name="fullname"
type="text"
placeholder="Enter your name"
required>
</secure-input>Input Types
All standard HTML5 input types are supported with type-specific validation and security measures.
| Type | Validation | Security Notes |
|---|---|---|
text | Length, pattern | HTML entities encoded, scripts stripped |
email | Email format | Normalized, validated using browser-native email format checking |
password | Tier-based strength | Strength rules scale with tier, autocomplete disabled |
tel | Pattern | Validated via pattern attribute, no auto-formatting |
url | URL format | Protocol validation, javascript: blocked |
number | Min/max, step | Safe integer range check, overflow protection |
<!-- 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>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.
Features: Basic validation, autocomplete allowed
Features: Session validation, moderate logging
Features: No autocomplete, masking option, rate limited
Features: Full masking, no storage, complete audit log
<!-- 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>Validation
Client-side validation provides immediate feedback while server-side validation is the authoritative source. Use HTML5 validation attributes alongside custom patterns.
<!-- 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>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.
<!-- 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>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.<script>alert(1)</script> to triggerServer-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.
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.
// 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
}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.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
| Attribute | Type | Default | Description |
|---|---|---|---|
security-tier | string | "critical" | Security level: "public", "authenticated", "sensitive", "critical" |
type | string | "text" | Input type: text, email, password, tel, url, number, etc. |
name | string | - | Form field name for submission |
label | string | - | Accessible label text |
placeholder | string | - | Placeholder text |
required | boolean | false | Field is required |
disabled | boolean | false | Disable the input |
readonly | boolean | false | Make input read-only |
minlength | number | - | Minimum character length |
maxlength | number | - | Maximum character length |
min | number | - | Minimum value (for number type) |
max | number | - | Maximum value (for number type) |
pattern | string | - | Regex validation pattern. Patterns longer than 200 characters are not compiled client-side (ReDoS mitigation) — browser native validation applies instead. |
threat-feedback | boolean | false | Show 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
Methods
'error'.reportError()Events
| Event | Detail | Description |
|---|---|---|
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
<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
// 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);