Skip to content

How to Configure JavaScript Challenges

This guide shows you how to set up and customize JavaScript challenges in Peakhour's firewall system to distinguish legitimate browsers from automated tools while maintaining a smooth user experience.

Before you begin: Ensure you have configured basic bot protection and understand firewall rule creation.

Understanding JavaScript Challenges

JavaScript challenges validate that visitors are using real browsers rather than automated scripts. The system injects lightweight JavaScript code that performs validation tests only real browsers can complete.

How Challenges Work

  1. Challenge Injection: JavaScript code is inserted into responses
  2. Browser Validation: Code performs tests that automation tools typically fail
  3. Token Generation: Successful validation creates authentication tokens
  4. Access Granted: Valid tokens allow continued site access
  5. Token Persistence: Challenges remain valid for configured duration

Challenge Types

Peakhour implements browser validation challenges that test:

  • JavaScript execution capability
  • DOM manipulation abilities
  • Browser-specific API availability
  • Timing-based validation
  • Cryptographic verification

Enable JavaScript Challenge System

Activate Challenge Infrastructure

  1. Navigate to Security > Bot Protection
  2. Enable "Inject lightweight JavaScript into the browser to assist with Bot detection"
  3. Verify the system shows "Challenge System: Active"

Select elements that form the challenge tracking key:

  1. Go to Firewall > Challenge Configuration
  2. Choose challenge key components:

Available Options:

  • ip: Track challenges per IP address
  • session_id: Per-session challenge tracking
  • fingerprint_tls: TLS fingerprint-based identification

Recommended Combinations:

Recommended for sensitive sites:

☑ ip
☑ fingerprint_tls
☐ session_id

Good for most sites:

☑ ip
☐ fingerprint_tls
☐ session_id

For applications requiring per-session validation:

☑ ip
☑ session_id
☐ fingerprint_tls

Test Challenge Activation

Verify challenges are working:

  1. Clear browser cache to remove any existing tokens
  2. Visit your site from an IP that triggers challenges
  3. Check developer tools for challenge JavaScript execution
  4. Verify access after successful challenge completion

Configure Challenge Triggers

Rate Limit Challenge Triggers

Set up rate limiting that escalates to challenges:

  1. Navigate to Rules > Rate Limiting
  2. Create rate limit with challenge action:
API Protection
Name: API Rate Limit Challenge
Pattern: http.request.uri.path starts_with "/api/"
Threshold: 100 requests per 10 minutes
Action: challenge
Duration: 3600 seconds (1 hour)
Login Protection
Name: Login Attempt Challenge  
Pattern: http.request.uri.path eq "/login" and http.request.method eq "POST"
Threshold: 5 requests per 5 minutes
Action: challenge
Duration: 1800 seconds (30 minutes)

Firewall Rule Challenge Triggers

Create firewall rules that trigger challenges for suspicious patterns:

  1. Navigate to Rules > Firewall
  2. Create rules with challenge action:
Suspicious User Agents
Name: Challenge Automation Tools
Expression: http.user_agent matches ".*(curl|wget|python|bot|crawler).*" and
           not http.user_agent contains "Googlebot"
Action: challenge
Priority: 10
Missing Browser Headers
Name: Challenge Headless Browsers
Expression: len(http.request.headers["accept"]) == 0 or
           any(http.request.headers["accept"][*] == "") or
           len(http.request.headers["accept-language"]) == 0
Action: challenge
Priority: 15
Geographic Challenge
Name: Challenge High-Risk Countries
Expression: ip.geoip.country in {"CN", "RU", "BR", "IN"} and
           not ip.src in $trusted_ips
Action: challenge
Priority: 20

Conditional Challenge Rules

Create sophisticated rules that challenge based on multiple factors:

Conditional API Access
Name: Challenge Suspicious API Usage
Expression: http.request.uri.path starts_with "/api/" and
           (http.user_agent not contains "MyApp" or
            ip.geoip.country not in {"US", "CA", "GB"})
Action: challenge
Priority: 5
Time-Based Challenges (using lists for maintenance windows)
Name: Challenge During Maintenance
Expression: http.host in $maintenance_domains and
           http.request.uri.path not starts_with "/status"
Action: challenge
Priority: 1

Customize Challenge Behavior

Configure Challenge Duration

Set how long successful challenges remain valid:

  1. Short Duration (15-60 minutes): High security, more user friction
  2. Medium Duration (4-12 hours): Balanced security and usability
  3. Long Duration (24-48 hours): Lower friction, reduced security

Example Configurations:

Challenge Duration: 1 hour
Suitable for: Banking, admin panels, sensitive APIs
Challenge Duration: 12 hours  
Suitable for: Shopping sites, content platforms
Challenge Duration: 24 hours
Suitable for: Blogs, news sites, documentation

Configure Challenge Difficulty

Adjust challenge complexity based on threat level:

Standard Challenge (recommended for most sites):

  • Basic JavaScript execution tests
  • Simple DOM manipulation
  • Standard timing validation

Enhanced Challenge (high-security environments):

  • Multiple validation rounds
  • Advanced browser API tests
  • Extended timing requirements
  • Additional fingerprinting

Set Challenge Retry Logic

Configure what happens when challenges fail:

Retry Configuration
Failed Attempts: 3 maximum tries
Retry Delay: 30 seconds between attempts
Temporary Block: 15 minutes after 3 failures
Reset Period: 1 hour before retry counter resets

Handle Challenge Exceptions

Create Allow Lists

Bypass challenges for trusted sources:

Trusted IP Ranges
Name: Office Network Bypass
Expression: ip.src in {203.0.113.0/24, 198.51.100.0/24}
Action: allow
Priority: 1
Verified User Agents
Name: Legitimate Services
Expression: http.user_agent matches ".*(Googlebot|bingbot|facebookexternalhit).*"
Action: allow  
Priority: 2
API Keys or Tokens
Name: Authenticated API Access
Expression: len(http.request.headers["Authorization"]) > 0 and
           any(http.request.headers["Authorization"][*] matches "Bearer *")
Action: allow
Priority: 3

Handle Special Cases

Configure exceptions for specific scenarios:

Mobile App Access
Name: Mobile App Bypass
Expression: http.user_agent contains "MyMobileApp" and
           http.request.headers["X-App-Version"] exists
Action: allow
Priority: 4
Monitoring Services
Name: Uptime Monitoring  
Expression: http.user_agent matches ".*(pingdom|uptimerobot|statuscake).*" or
           http.request.uri.path eq "/health"
Action: allow
Priority: 5

Progressive Challenge Escalation

Implement graduated response based on risk level:

Low Risk - Log Only
Name: Log Suspicious Activity
Expression: http.user_agent contains "scanner" 
Action: log
Priority: 30
Medium Risk - Challenge
Name: Challenge Moderate Threats
Expression: ip.geoip.asn in $suspicious_asns
Action: challenge
Priority: 25
High Risk - Block
Name: Block Known Threats
Expression: ip.src in $malicious_ips
Action: deny
Priority: 20

Monitor Challenge Effectiveness

Review Challenge Analytics

Monitor key metrics to assess challenge performance:

  1. Navigate to Analytics > Security Events
  2. Review challenge-specific metrics:

  3. Challenge Success Rate: Percentage of challenges completed successfully

  4. Challenge Volume: Number of challenges triggered daily

  5. Failure Patterns: Common reasons for challenge failures

  6. Geographic Distribution: Challenge activity by location

Target Metrics:

  • Success Rate: 60-80% (indicates good balance)
  • False Positive Rate: < 5% (legitimate users affected)
  • Block Rate: Varies by threat level

Identify Challenge Issues

Look for patterns indicating problems:

High Failure Rate (> 80% failures):

  • Challenge difficulty too high
  • JavaScript compatibility issues
  • Legitimate users being affected

Low Challenge Volume (< expected):

  • Rules not triggering as intended
  • Allow lists too broad
  • Challenge thresholds too high

Geographic Anomalies:

  • Unexpected challenge patterns in certain regions
  • Legitimate traffic being challenged
  • Attack patterns from specific countries

Analyze Failed Challenges

Investigate challenge failures to improve accuracy:

Common Failure Patterns
Pattern: JavaScript disabled browsers
Solution: Provide alternative validation method

Pattern: Legitimate automation tools
Solution: Add user agent exceptions

Pattern: Slow network connections
Solution: Adjust challenge timeout values

Pattern: Browser compatibility issues  
Solution: Update challenge code for compatibility

Optimize Challenge Configuration

Fine-Tune Challenge Keys

Adjust challenge tracking based on observed patterns:

If seeing challenge bypasses:

  • Add fingerprint_tls to challenge keys
  • Consider adding session_id for session-specific tracking
  • Review IP-based challenges for distributed attacks

If seeing high false positives:

  • Remove session_id from challenge keys
  • Use IP-only challenges for broader compatibility
  • Implement more specific targeting rules

Adjust Challenge Sensitivity

Modify rules based on traffic analysis:

Reduce False Positives:

# Before: Too broad
http.user_agent not contains "Mozilla"

# After: More specific  
http.user_agent matches ".*(curl|wget).*" and 
not http.accept exists

Increase Bot Detection:

# Before: Basic detection
http.user_agent contains "bot"

# After: Comprehensive detection
(http.user_agent matches ".*(bot|crawler|spider).*" or
 not http.accept_language exists or
 http.user_agent matches ".*python.*") and
not http.user_agent matches ".*(googlebot|bingbot).*"

Implement Adaptive Thresholds

Adjust challenge triggers based on traffic patterns:

Low Traffic Periods
Rate Limit: 50 requests per 10 minutes
Challenge Trigger: More sensitive thresholds
High Traffic Periods
Rate Limit: 200 requests per 10 minutes  
Challenge Trigger: Less sensitive to avoid impacting legitimate users

Advanced Challenge Configurations

Multi-Stage Challenges

Implement progressive challenge difficulty:

Stage 1 - Basic Challenge
Name: Initial Bot Check
Expression: suspicious_pattern_basic
Action: challenge
Challenge Level: standard
Stage 2 - Enhanced Challenge (if Stage 1 failed)
Name: Advanced Bot Check  
Expression: failed_basic_challenge
Action: challenge
Challenge Level: enhanced

Context-Aware Challenges

Configure challenges based on request context:

API Endpoint Protection
Name: API Challenge
Expression: http.request.uri.path starts_with "/api/"
Action: challenge
Challenge Type: lightweight
Duration: 1 hour
Admin Area Protection
Name: Admin Challenge
Expression: http.request.uri.path starts_with "/admin"
Action: challenge  
Challenge Type: enhanced
Duration: 30 minutes

Integration with Rate Limiting

Coordinate challenges with rate limiting for comprehensive protection:

Cascading Protection:

  1. Rate Limit: Normal traffic allowed
  2. Challenge: Suspicious traffic challenged
  3. Block: Malicious traffic blocked
Cascading Protection
# Rule 1: Allow normal traffic
Expression: rate(1 minute) <= 60
Action: allow

# Rule 2: Challenge elevated traffic  
Expression: rate(1 minute) > 60 and rate(1 minute) <= 200
Action: challenge

# Rule 3: Block excessive traffic
Expression: rate(1 minute) > 200
Action: deny

Troubleshooting Common Issues

Challenge Loop Problems

Problem: Users stuck in repeated challenges Solution:

  • Check challenge cookie configuration for conflicts
  • Verify JavaScript compatibility with site frameworks
  • Review session management settings
  • Check for multiple overlapping challenge rules

Legitimate Users Challenged

Problem: Real users frequently receive challenges Solution:

  • Add user agent allow lists for legitimate tools
  • Review geographic rules for overly broad restrictions
  • Adjust rate limiting thresholds
  • Implement IP allow lists for trusted sources

Challenges Not Triggering

Problem: Expected challenges not appearing Solution:

  • Verify JavaScript injection is enabled
  • Check firewall rule priorities and ordering
  • Review rule expressions for syntax errors
  • Confirm rate limiting thresholds are appropriate

Performance Impact

Problem: Challenges affecting site performance Solution:

  • Optimize JavaScript challenge code
  • Review challenge frequency and duration
  • Implement more targeted rules to reduce challenge volume
  • Consider CDN optimization for challenge assets

Best Practices

Security

  • Use TLS fingerprinting for enhanced device identification
  • Implement progressive challenge escalation
  • Regular review and update of challenge rules
  • Monitor for challenge bypass attempts

User Experience

  • Keep challenge duration reasonable for your use case
  • Provide clear messaging during challenge process
  • Test challenge flow across different browsers and devices
  • Implement graceful fallbacks for JavaScript-disabled browsers

Performance

  • Minimize JavaScript challenge complexity
  • Cache challenge assets effectively
  • Monitor challenge success rates for optimization
  • Use targeted rules to reduce unnecessary challenges

Your JavaScript challenge system is now configured to provide robust protection against automated threats while maintaining accessibility for legitimate users and services.