<secure-telemetry-provider>

Replaces CAPTCHA with passive behavioral analysis. Collects environmental signals — webdriver and headless browser detection, DOM tampering, and user interaction patterns — and attaches a HMAC-SHA-256 signed envelope to every form submission. Real users see nothing; automated clients are identified before the request reaches your server.

<script type="module"
  src="/components/secure-telemetry-provider/secure-telemetry-provider.js">
</script>
View API Reference →
Live Demo

Why not CAPTCHA?

CAPTCHAsecure-telemetry-provider
User frictionHigh — puzzles, image grids, waitsNone — fully passive
AccessibilityFails WCAG for many usersTransparent to all users
AI bypass riskIncreasing — solvable by commodity modelsRaises attacker cost significantly
Data sharingSent to Google, Cloudflare, or third partyStays on your servers only
IntegrationSeparate SDK, extra script, API keyOne web component, no API key
CostPer-transaction fees at scaleZero — self-hosted
Sophisticated botsSolvable by commodity AI modelsHigher cost to bypass — use CAPTCHA as fallback only for flagged requests

For most applications, behavioral scoring eliminates CAPTCHA for the majority of traffic. Keep CAPTCHA as an optional fallback triggered only when risk score exceeds your threshold.

Configurations

Basic wrapper
Wrap any <secure-form> with <secure-telemetry-provider>. All form submissions automatically carry a HMAC-signed behavioral envelope — no changes required inside the form.
<secure-telemetry-provider
  signing-key="your-hmac-key">
  <secure-form action="/submit"
    method="POST">
    <!-- fields here -->
  </secure-form>
</secure-telemetry-provider>
JS: read signals manually
Access a point-in-time snapshot of environmental signals before submission, or build custom risk logic on top of the raw data without waiting for a form event.
const provider = document.querySelector(
  'secure-telemetry-provider'
);

// Point-in-time snapshot
const signals = provider.collectSignals();
console.log(signals.webdriverDetected);
console.log(signals.mouseMovementDetected);

// Signed envelope
// sign(signals, telemetry?, boundTo?) — pass the telemetry and the target
// path so the signature binds the envelope to this exact submission.
const envelope = await provider.sign(signals, telemetry, '/api/login');
console.log(envelope.signature);
With secure-card
Payment flows benefit most from behavioral telemetry. Wrapping <secure-card> applies bot detection to the highest-risk transaction in your application.
<secure-telemetry-provider
  signing-key="your-hmac-key">
  <secure-form action="/checkout"
    method="POST"
    security-tier="critical">
    <secure-card name="payment"
      required>
    </secure-card>
    <button type="submit">Pay</button>
  </secure-form>
</secure-telemetry-provider>

Signals Collected

All signals are heuristic. They raise the cost of automated attacks — not a guarantee of detection. Always validate server-side.

Automation DOM integrity Environment Behavioral Timing Threats
SignalMax weightHow detected
webdriverDetected+40navigator.webdriver present and truthy
headlessDetected+35User-agent contains HeadlessChrome or Headless
domMutationDetected+10MutationObserver on document.documentElement — detects dynamically injected elements
injectedScriptCount+10Count of <script> elements added after page load
suspiciousScreenSize+20Screen width or height is 0, or both dimensions under 100px
pointerType—First pointerdown event's pointerType: mouse / touch / pen / none. Suppresses the mouse-movement penalty for touch and pen devices
mouseMovementDetected+15At least one mousemove event received. Absence adds to score only for non-touch devices
keyboardActivityDetected+10At least one keydown event received
pageLoadToFirstKeystroke+20ms from component mount to first keydown event. Returns -1 if no keystroke before submit. Values below 200ms suggest programmatic input
loadToSubmit+30ms from component mount to form submission. Values below 500ms are consistent with automated submission
threatSignals—Array of ThreatDetectedDetail objects accumulated from all secure-threat-detected events during the session — injection patterns from child inputs and CSRF-absent signals from nested forms. Omitted from the envelope when no threats were detected

Signing key lifecycle

The signing key is a symmetric HMAC-SHA-256 secret stored in a private JS field — never in the DOM. It must also be known server-side to verify the signature. Use setSigningKey() to supply it; the key is never readable via getAttribute(), devtools, or XSS.

Cached CryptoKey Imported once per key value

The CryptoKey derived from the signing key is imported once and cached for the lifetime of the component. It is re-imported only when the key value changes via setSigningKey(), and cleared on disconnectedCallback. This avoids the cost of a SubtleCrypto.importKey() call on every form submission.

Rotate the key by fetching a fresh value from a per-session server endpoint and calling setSigningKey(newKey). The cached CryptoKey is invalidated before the next sign() call. The signing-key HTML attribute is supported for backward compatibility: if present, it is automatically migrated to the private field and removed from the DOM on connectedCallback.

Theming

<secure-telemetry-provider> renders no visible output and exposes no CSS custom properties. Apply all theming to the child <secure-form> and its field components directly.

Framework Examples

Client-side integration and server-side verification. The provider wraps any framework's form components without adapters.

Plain HTML html
<secure-telemetry-provider signing-key="SECRET">
  <secure-form action="/login" method="POST"
    security-tier="sensitive">
    <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>
</secure-telemetry-provider>
React (JSX) tsx
import { useEffect } from 'react';

export function ProtectedForm({
  signingKey,
}: { signingKey: string }) {
  useEffect(() => {
    import('/components/secure-telemetry-provider/secure-telemetry-provider.js');
    import('/components/secure-form/secure-form.js');
    import('/components/secure-input/secure-input.js');
  }, []);

  return (
    <secure-telemetry-provider signing-key={signingKey}>
      <secure-form action="/login" method="POST"
        security-tier="sensitive">
        <secure-input type="email" label="Email"
          name="email" security-tier="sensitive" required />
        <secure-input type="password" label="Password"
          name="password" security-tier="critical" required />
        <button type="submit">Sign In</button>
      </secure-form>
    </secure-telemetry-provider>
  );
}
Vue 3 vue
<template>
  <secure-telemetry-provider :signing-key="signingKey">
    <secure-form action="/login" method="POST"
      security-tier="sensitive">
      <secure-input type="email" label="Email" name="email"
        security-tier="sensitive" required />
      <secure-input type="password" label="Password"
        name="password" security-tier="critical" required />
      <button type="submit">Sign In</button>
    </secure-form>
  </secure-telemetry-provider>
</template>

<script setup>
import { onMounted } from 'vue';
const props = defineProps({ signingKey: String });
onMounted(async () => {
  await import('/components/secure-telemetry-provider/secure-telemetry-provider.js');
  await import('/components/secure-form/secure-form.js');
  await import('/components/secure-input/secure-input.js');
});
</script>
Angular typescript
import { Component, CUSTOM_ELEMENTS_SCHEMA,
         OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-protected-form',
  template: `
    <secure-telemetry-provider [attr.signing-key]="signingKey">
      <secure-form action="/login" method="POST"
        security-tier="sensitive">
        <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>
    </secure-telemetry-provider>
  `,
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class ProtectedFormComponent implements OnInit {
  @Input() signingKey = '';
  ngOnInit() {
    import('/components/secure-telemetry-provider/secure-telemetry-provider.js');
    import('/components/secure-form/secure-form.js');
    import('/components/secure-input/secure-input.js');
  }
}
Svelte svelte
<script>
  import { onMount } from 'svelte';
  export let signingKey = '';
  onMount(async () => {
    await import('/components/secure-telemetry-provider/secure-telemetry-provider.js');
    await import('/components/secure-form/secure-form.js');
    await import('/components/secure-input/secure-input.js');
  });
</script>

<secure-telemetry-provider signing-key={signingKey}>
  <secure-form action="/login" method="POST"
    security-tier="sensitive">
    <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>
</secure-telemetry-provider>
Go / Templ templ
templ LoginForm(action string) {
  <secure-telemetry-provider signing-key="SECRET">
    <secure-form
      action={ action }
      method="POST"
      security-tier="sensitive">
      <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>
  </secure-telemetry-provider>
}
Server-side verification (Go) go
// The signed envelope arrives in the POST body as
// _telemetry._env. Verify it before trusting any risk score.
//
// v0.5.0 changed the signed payload. The signature now covers the WHOLE
// envelope (minus the signature itself) as canonical JSON, not just the
// environment block, and the envelope carries telemetryDigest and boundTo so
// it cannot be lifted onto a different submission.

type Envelope struct {
    V               int                  `json:"v"`
    Nonce           string               `json:"nonce"`
    IssuedAt        time.Time            `json:"issuedAt"`
    Environment     EnvironmentalSignals `json:"environment"`
    TelemetryDigest string               `json:"telemetryDigest"`
    BoundTo         *string              `json:"boundTo"`
    Signature       string               `json:"signature"`
}

// Verify recomputes the HMAC over the canonical form of the envelope.
//
// raw is the _env object exactly as received. Decode with UseNumber so numeric
// literals keep the text the browser sent — re-formatting a float is the usual
// reason an honest submission fails to verify.
func Verify(raw []byte, key []byte) (bool, error) {
    var claims map[string]any
    dec := json.NewDecoder(bytes.NewReader(raw))
    dec.UseNumber()
    if err := dec.Decode(&claims); err != nil {
        return false, err
    }

    sig, _ := claims["signature"].(string)
    if sig == "" {
        return false, nil // unsigned: lowest trust, never "valid"
    }
    delete(claims, "signature")

    var buf bytes.Buffer
    if err := canonical(&buf, claims); err != nil {
        return false, err
    }

    mac := hmac.New(sha256.New, key)
    mac.Write(buf.Bytes())
    want := hex.EncodeToString(mac.Sum(nil))

    // Constant-time compare.
    return hmac.Equal([]byte(want), []byte(sig)), nil
}

// canonical writes JSON with object keys sorted recursively and no HTML
// escaping — byte-for-byte what the component signed.
func canonical(w *bytes.Buffer, v any) error {
    switch t := v.(type) {
    case map[string]any:
        keys := make([]string, 0, len(t))
        for k := range t {
            keys = append(keys, k)
        }
        sort.Strings(keys)
        w.WriteByte('{')
        for i, k := range keys {
            if i > 0 {
                w.WriteByte(',')
            }
            if err := writeString(w, k); err != nil {
                return err
            }
            w.WriteByte(':')
            if err := canonical(w, t[k]); err != nil {
                return err
            }
        }
        w.WriteByte('}')
    case []any:
        w.WriteByte('[')
        for i, e := range t {
            if i > 0 {
                w.WriteByte(',')
            }
            if err := canonical(w, e); err != nil {
                return err
            }
        }
        w.WriteByte(']')
    case json.Number:
        w.WriteString(t.String()) // verbatim, never re-formatted
    case string:
        return writeString(w, t)
    case bool:
        if t {
            w.WriteString("true")
        } else {
            w.WriteString("false")
        }
    case nil:
        w.WriteString("null")
    default:
        return fmt.Errorf("canonical: unsupported type %T", v)
    }
    return nil
}

// writeString encodes a JSON string WITHOUT HTML escaping. json.Marshal turns
// < > & into \u003c \u003e \u0026; JSON.stringify does not, so using it here
// would make every value containing those characters fail to verify.
func writeString(w *bytes.Buffer, s string) error {
    var b bytes.Buffer
    enc := json.NewEncoder(&b)
    enc.SetEscapeHTML(false)
    if err := enc.Encode(s); err != nil {
        return err
    }
    w.Write(bytes.TrimRight(b.Bytes(), "\n")) // Encode appends a newline
    return nil
}

// After Verify returns true, still check:
//   - claims["v"] == 1                     (reject unknown envelope versions)
//   - issuedAt is within a few minutes     (replay window)
//   - nonce has not been seen before       (replay)
//   - boundTo matches the endpoint hit     (envelope lifted from another form)
//   - telemetryDigest matches sha256(canonical(_telemetry without _env))
Risk scoring (Go) go
// Score returns 0–100. Higher = more suspicious.
// Threshold guidance:
//   0–30  → allow
//   31–60 → log / challenge with CAPTCHA
//   61+   → reject or require step-up auth

func Score(env EnvironmentalSignals) int {
    score := 0

    // Hard bot signals
    if env.WebdriverDetected  { score += 40 }
    if env.HeadlessDetected   { score += 35 }

    // Suspicious environment
    if env.SuspiciousScreenSize { score += 20 }
    if env.DOMMutationDetected  { score += 10 }
    if env.InjectedScriptCount > 2 { score += 10 }

    // Timing signals — bots fill forms instantly or at fixed intervals
    if env.LoadToSubmit < 500 {
        score += 30 // submitted in under 500ms
    } else if env.LoadToSubmit < 2000 {
        score += 10
    }
    if env.PageLoadToFirstKeystroke >= 0 && env.PageLoadToFirstKeystroke < 200 {
        score += 20 // first keystroke in under 200ms
    }

    // Interaction signals — mobile-aware:
    // Touch devices never produce mouse events;
    // suppress the mouse-movement penalty for them.
    isTouchDevice := env.PointerType == "touch" ||
                     env.PointerType == "pen"

    if !isTouchDevice && !env.MouseMovementDetected {
        score += 15
    }
    if !env.KeyboardActivityDetected {
        score += 10
    }

    if score > 100 { score = 100 }
    return score
}