=== TrustLens – Fraud Prevention & Chargeback Defense for WooCommerce ===
Contributors: webstepper, freemius
Tags: customer management, security, fraud prevention, chargeback, card testing
Requires at least: 6.4
Tested up to: 7.0
Requires PHP: 7.4
Stable tag: 1.2.8
License: GPLv3 or later
License URI: https://www.gnu.org/licenses/gpl-3.0.html

Prevent WooCommerce fraud with behavioral trust scoring. Catch chargebacks, return abuse, coupon fraud, and card-testing attacks.

== Description ==

**Stop losing money to WooCommerce fraud you can't see.** Serial returners, coupon abusers, fraud rings, and stolen-card bots quietly drain stores — often thousands per year. By the time the chargeback ratio climbs or your margin disappears, the damage is done.

TrustLens is a behavior-based **customer trust scoring and fraud detection plugin for WooCommerce**. It scores every shopper from **0 to 100** using real store behavior and sorts them into six risk segments — **VIP, Trusted, Normal, Caution, Risk, Critical**. Eight detection modules run in the background: returns, orders, coupons, categories, linked accounts, shipping anomalies, chargebacks, and card-testing attacks at checkout. You see exactly which signals moved each score, and **you decide what to do** about it.

**TrustLens never auto-blocks in Free.** You review the customer profile and choose: block at checkout, allowlist forever, or simply watch the trend. Nothing happens behind your back. All customer data stays inside your store — no third-party calls — and linked-account fingerprints are pseudonymized with keyed HMAC-SHA256 hashes.

= Video Tutorial =

https://youtu.be/Xxz8lcTnAlU

= Abuse patterns TrustLens catches =

TrustLens turns the WooCommerce data you already have into actionable customer intelligence. Instead of reading hundreds of orders and refunds line by line, you get one clear score per customer and a six-segment view of your entire customer base. The dashboard surfaces the patterns that move the needle:

* **Return abuse and wardrobing** — serial returners, high refund rates buried across hundreds of orders, customers with 90%+ full-refund ratios
* **Coupon and discount fraud** — repeat first-order coupon use, coupon-then-refund cycles, throwaway accounts created only to grab a discount
* **Multi-account fraud rings** — different emails sharing the same shipping address, IP, payment method, phone number, or device fingerprint
* **Chargeback exposure** — disputes per customer, blended store-wide chargeback ratio, brand-by-brand approach to Visa, Mastercard, Amex, and Discover monitoring thresholds
* **Card-testing attacks at checkout** — bots probing stolen cards through your payment gateway, racking up declines, fees, and downstream chargebacks
* **Shipping address fraud** — address hopping, billing/shipping country mismatches, rapid address-change velocity, reshipping patterns
* **Hidden VIPs** — long-tenured loyal customers you should protect from accidental friction or false positives

You see who's worth rewarding, who's silently costing you, and you take the call.

= What's included in the free version =

The WordPress.org download is the **complete plugin** — no trial limits, no disabled scoring, no locked modules. Everything below ships in Free.

**Detection — all 8 modules included**

* **Return Abuse Detection** — analyzes refund rate, refund frequency, refund value, and full-vs-partial refund ratio to spot serial returners and wardrobing
* **Order Pattern Analysis** — completion rates, cancellation patterns, unusual order velocity
* **Coupon Abuse Detection** — repeat first-order coupon use, coupon-then-refund pattern, excessive coupon stacking
* **Category-Aware Risk Scoring** — applies extra risk when customers show high return rates in specific product categories
* **Linked Accounts Detection** — identifies accounts sharing shipping addresses, billing addresses, phone numbers, IPs, payment methods, or device user-agent fingerprints
* **Shipping Address Anomalies** — address hopping, billing/shipping country mismatches, address-change velocity, configurable velocity window (7–90 days)
* **Chargeback Tracking** — per-customer dispute history with automatic ingestion from Stripe and WooPayments, manual entry form for other gateways, automatic card-brand capture for accurate ratio reporting
* **Card-Testing Defense** — real-time decline-velocity monitoring in 60-second and 10-minute rolling windows, attacker device fingerprints locked out for 90 seconds, VIP customer bypass on by default so repeat buyers are never disrupted, one-click Panic Freeze button that halts all checkouts for 15 minutes during an active attack

**Trust scoring engine**

* **0–100 trust score** for every customer, recalculated automatically when behavior changes
* **Six risk segments** — VIP, Trusted, Normal, Caution, Risk, Critical
* **Every signal visible on the customer profile** so you can see exactly how a score was calculated
* **Account-age loyalty bonus** up to +15 points for long-standing customers
* **Configurable scoring thresholds** — minimum orders required, return-risk levels, checkout-blocking settings

**Dashboard and monitoring**

* **Command Center dashboard** — trust score trends, segment distribution, refund activity, high-risk customer list, revenue-protection KPIs
* **Chargeback Ratio Speedometer** — blended calendar-month ratio with Healthy / Approaching threshold / Action-needed status against Visa, Mastercard, Amex, and Discover monitoring programs
* **Module status row** — quick on/off and one stat per detection module at a glance
* **Persistent plugin-wide admin header** with unified navigation, live status pill, notifications bell, and ⌘K command palette for fast access to any customer or setting

**Customer management**

* **Trust badges on the WooCommerce orders list** — sortable, filterable by segment, one click to the full customer profile
* **Detailed customer profile** with score history, event timeline, linked accounts, signal impact bars, and return-rate trend chart
* **Bulk actions** — block, unblock, allowlist, recalculate, delete in bulk
* **Allowlist protection** — locks a customer's score at 100 and prevents any negative signals from affecting them, protecting VIPs from false positives
* **Checkout enforcement** — blocked customers can't add items to cart or complete checkout (works on both Classic and WooCommerce Blocks / Store API checkout)
* **Customizable block message**

**Operational**

* **Historical Sync** — build trust profiles from past WooCommerce orders in the background using small batches that don't slow the frontend
* **REST API** with 8 endpoints for integrations, customer lookups, score retrieval, segment filtering, and triggering recalculations
* **WooCommerce HPOS compatibility** — fully compatible with High-Performance Order Storage
* **GDPR privacy tools** — full WordPress privacy export and erasure integration, including signals, fingerprints, category stats, and automation logs
* **Order-screen integration** — trust score and segment displayed directly on every WooCommerce order edit page
* **Core email notifications** — blocked-checkout alerts, activation summary, weekly protection report

= What Pro adds =

Pro is for stores that want TrustLens to act on what it finds — automation, advanced alerts, deeper chargeback analytics, and payment-risk workflows.

**Advanced Chargeback Monitor**

A dedicated **TrustLens → Chargeback Monitor** page built to keep you clear of card-network monitoring programs:

* Per-brand ratio breakdown — **Visa VDMP/VFMP, Mastercard ECP, Amex, Discover** — with threshold progress bars
* **12-month trend chart** showing how each brand has moved over time
* **Trailing-30-day window** alongside the Free calendar-month view
* **Recent disputes activity feed** with case status
* **Top-disputed customers** with one-click access to a **Dispute Evidence Report** — print-ready professional behavioral risk report (trust score, signals, order history, return analysis vs store average, linked accounts, full event timeline) that you can submit alongside processor dispute responses
* **Customizable warn-threshold percent** (50–100%)
* **Auto-Block After N Lost Disputes** — configurable runtime enforcement

**Chargeback Ratio Email Alerts** — daily check that emails you before any brand crosses its network threshold, deduplicated per brand per calendar month so you're never spammed.

**Automation Rules**

Build trigger-based rules that fire when customer risk changes, orders are placed, refunds are processed, disputes are filed, linked accounts are detected, card-testing attacks happen, or shipping anomalies are spotted.

* **15+ triggers** including Chargeback Filed, Dispute Recorded, Linked Accounts Detected, Card Testing Attack, Shipping Anomaly
* **20+ condition fields** including trust score, segment, total order value, total disputes, customer age, country mismatch, coupon total, payment method, linked accounts count
* **Actions** — block customer, hold order, send email, fire webhook, allowlist customer, cancel order, tag customer
* **Async dispatch with automatic retry** (60s / 120s / 240s backoff)
* **HMAC-SHA256 signed webhooks** by default for security
* **Save-time validator** blocks rules that can never fire — unsatisfiable conditions, schema violations, contradictions — each with a specific inline reason
* **Inline rule inspector** shows SKIP status with the exact reason ("Cooldown active" / "Condition not met: trust_score > 50") so you can answer "why didn't my rule fire?" in one glance

**Card-Testing Defense Pro**

On top of free Card-Testing Defense, Pro adds attack-scale protection:

* **Auto-escalation** from targeted blocking to global Panic Freeze when an attack spreads across multiple device fingerprints (default: 3 distinct devices in 10 minutes)
* **Geographic-diversity safeguard** — before escalating, checks whether the decline burst is naturally distributed across ≥10 countries with no single country >50%, so legitimate flash-sale or viral traffic isn't mistaken for an attack
* **Fingerprint and IP CIDR allowlists** for QA, integration partners, and known-good traffic (IPv4 and IPv6 ranges supported)
* **Advanced fingerprint signal** — 12-font detection via baseline-width comparison, harder for botnets to spoof consistently across nodes
* **Per-fingerprint threshold overrides** for tighter or looser thresholds on specific known devices
* **Attack History tab** with 24-hour decline count, decline-code breakdown, top-10 attacking fingerprints, hourly timeline chart, CSV export of all velocity events
* **Slack and email alert dispatcher** for `attack_detected`, `auto_escalated`, and `panic_button_activated` events

**Payment Method Risk Controls** — hide specific payment gateways for high-risk customers, linked accounts, or velocity spikes. Fine-grained checkout protection without blocking the whole order.

**Scheduled Reports** — daily, weekly, or monthly email summaries of store risk activity, customer trends, and protection KPIs.

**10 advanced notification types** — High-Risk Order Alert, Segment Change Alert, Daily Digest, High-Value Order Alert, Repeat Refunder Alert, Velocity Alert, Score Recovery Alert, New Customer Risk Alert, Monthly Revenue Protection Report, Chargeback Filed Alert.

**Advanced Address Analysis** — diversity-trend detection and enhanced country-mismatch severity for deeper shipping-fraud insight.

**Bottom line:** Free surfaces the risk. Pro acts on it.

= How trust scoring works =

Every customer starts at a neutral **50**. TrustLens detection modules analyze behavior and apply positive or negative signals:

* **Completed orders** increase trust
* **Refunds** decrease trust based on frequency, value, and full-vs-partial ratio
* **Coupon abuse patterns** apply penalties (repeat first-order coupons, coupon-then-refund cycles)
* **High return rates in specific categories** add additional risk
* **Linked accounts** with already-risky customers reduce scores via fraud-ring detection
* **Disputes and chargebacks** apply significant penalties
* **Shipping anomalies** (address hopping, country mismatches, change velocity) reduce scores
* **Card-testing exposure** — customers tied to device fingerprints involved in past attacks lose trust
* **Account age** adds a loyalty bonus of up to **+15** for long-standing customers

Scores are always clamped to 0–100. Every signal is visible on the customer profile so you can see exactly how each score was calculated and trust the decision.

Customers below the configurable minimum order threshold (default: 3 orders) stay in the Normal segment until enough data exists for confident scoring — so new stores don't get noisy false positives in their first weeks.

= Who TrustLens is for =

* **WooCommerce store owners** losing margin to serial returners, refund abuse, or coupon fraud
* **Operations and CX managers** who need data to back up customer policies with confidence
* **Fraud prevention teams** looking past payment-gateway signals into behavioral patterns
* **Merchants worried about Visa, Mastercard, Amex, or Discover** chargeback monitoring programs (VDMP / VFMP / ECP)
* **Stores with generous return policies** that attract both loyal customers and abuse
* **Stores using Stripe or WooPayments** — chargeback and card-brand data flow in automatically with no manual setup
* **Stores using other gateways** (PayPal, Square, offline, custom) — manual chargeback entry keeps your ratio accurate

= Privacy and data handling =

TrustLens works **entirely inside your WordPress and WooCommerce installation**. It does not send customer data to the plugin developer or to any default third-party service. External delivery only happens if you explicitly configure features like webhooks, Slack alerts, or email notifications.

* Customer identifiers are pseudonymized with **keyed HMAC-SHA256 hashes** so raw email and identifier values are never exposed or reused across sites
* Linked-account fingerprints (address, phone, IP, payment method, device) use the same keyed-hash approach
* **WordPress privacy tools** are fully integrated — customers can request data export or erasure through the standard WordPress workflow, and TrustLens responds with signals, fingerprints, category stats, and automation logs included
* **GDPR-compatible** by design
* All scoring signals are visible on the customer profile so customer-service teams can explain any score on request

= Built for production WooCommerce =

TrustLens is engineered for busy stores and growing order volume:

* **Asynchronous background scoring** via Action Scheduler — the same system WooCommerce uses for its own background jobs
* **WooCommerce HPOS compatibility** — fully compatible with High-Performance Order Storage and legacy stores alike
* **Transient-cached dashboard queries** (15-minute and 1-hour TTLs) with automatic invalidation on new events so the dashboard doesn't re-query order meta on every page load
* **Batch-based Historical Sync** that processes past orders in small chunks without blocking the frontend
* **Lightweight checkout enforcement** using a single email-hash lookup
* **Unified Request Gate** that intercepts both Classic and Blocks / Store API checkout through one rule-registration surface
* **PHP 7.4+ supported**, WordPress 6.4+ tested, WooCommerce-first throughout

If you need **chargeback prevention**, **return-abuse detection**, **fraud-ring detection**, or **stolen-card attack protection** for WooCommerce, TrustLens gives you the data and the tools to act — without taking control out of your hands.

== Installation ==

1. Install **TrustLens** directly from the WordPress plugin repository, or upload the `trustlens` folder to `/wp-content/plugins/`
2. Activate the plugin through the **Plugins** menu — TrustLens checks for WooCommerce automatically
3. Open **TrustLens → Dashboard** to see the Command Center
4. Click **Run Historical Sync** to build trust profiles from your existing WooCommerce orders — the sync runs in the background in small batches and does not affect site performance
5. Visit **TrustLens → Settings** to adjust scoring thresholds, checkout blocking, and notification preferences

**What works out of the box:**

* All 8 detection modules are enabled by default
* Card-Testing Defense ships **enabled** with sensible thresholds — no configuration required to start blocking stolen-card attacks
* VIP Customer Bypass is on, so repeat buyers are never disrupted by velocity rules
* Chargeback tracking is active for Stripe and WooPayments — disputes ingest automatically
* TrustLens **does not auto-block** any customer in Free until you explicitly choose to

If you use Stripe or WooPayments, no extra setup is required for chargeback and card-brand capture. Other gateways can be tracked through the manual chargeback entry form on the order edit page.

== Frequently Asked Questions ==

= Does TrustLens work with guest checkout? =

Yes. Customers are identified by a hash of their email address, so guest and registered customers are tracked equally. If a guest later registers, their history carries over.

= Will TrustLens automatically block customers? =

By default, no. The free version is manual: it surfaces customer risk data, and you decide when to block or allowlist someone. Pro can optionally automate specific actions, including alerts, order holds, verification requirements, and customer blocking if you configure automation rules or chargeback auto-blocking.

= How does linked accounts detection work? =

TrustLens creates fingerprints from shipping addresses, billing addresses, phone numbers, IP addresses, payment methods, and device user agents. When multiple customer accounts share fingerprints, they are flagged as linked. This helps detect multi-account abuse like repeated first-order discounts.

= Can TrustLens help reduce return abuse and refund abuse in WooCommerce? =

Yes. TrustLens tracks refund rate, refund value, refund frequency, category-specific return behavior, and related customer patterns over time. This helps you spot serial returners and high-risk refund behavior earlier instead of reviewing refunds one order at a time.

= Can TrustLens help with chargebacks and disputes? =

Yes — and the core chargeback tracking is in the **free** version. TrustLens automatically ingests disputes from Stripe and WooPayments, accepts manual entry for other gateways (PayPal, Square, offline), keeps per-customer dispute counters, and feeds dispute history into trust scores. The free dashboard also shows a **Chargeback Ratio Speedometer** with a Healthy / Approaching / Action-needed status against Visa, Mastercard, Amex, and Discover thresholds.

Pro adds a dedicated **Advanced Chargeback Monitor** with per-brand breakdown (Visa VDMP/VFMP, Mastercard ECP, Amex, Discover), 12-month trend, trailing-30-day window, daily ratio email alerts, a one-click Dispute Evidence Report for processor responses, and auto-block after N lost disputes.

= How does the Chargeback Ratio Monitor work? =

TrustLens captures the card brand on every Stripe and WooPayments paid order and tracks how many of those orders end up as disputes. Your blended monthly chargeback ratio is shown on the dashboard speedometer, with status colors keyed to **Visa VDMP/VFMP, Mastercard ECP, Amex, and Discover** monitoring thresholds — so you can see if you're approaching enrollment before it happens. Pro adds per-brand ratios, the 12-month trend chart, the trailing-30-day window, and daily email alerts.

= What is Card-Testing Defense? =

Card-Testing Defense (free) is real-time protection against stolen-card attack bots that probe your checkout with thousands of declined payment attempts. TrustLens watches per-device decline rates in 60-second and 10-minute rolling windows. When a device crosses the threshold it's locked out of checkout for 90 seconds, blocking the attack before it reaches your payment gateway and runs up gateway fees, fraud fees, and downstream chargebacks.

**VIP Customer Bypass** is enabled by default, so customers with at least one successful past order are never blocked by velocity. A one-click **Panic Freeze** button halts all checkouts for 15 minutes during an active attack your thresholds haven't caught.

Pro adds auto-escalation, a geographic-diversity safeguard so flash-sale traffic isn't mistaken for an attack, fingerprint and IP CIDR allowlists, attack analytics with CSV export, and Slack alerts.

= Can I automate actions based on customer risk? =

Yes, with Pro. Automation Rules let you build trigger-based rules that fire when customer risk changes, orders are placed, refunds are processed, disputes are filed, linked accounts are detected, card-testing attacks happen, or shipping anomalies are spotted. Each rule supports 20+ condition fields and actions like block customer, hold order, send email, fire webhook, allowlist customer, cancel order, or tag customer.

Pro automation also includes a save-time validator that blocks rules that can never fire, an inline inspector that shows exactly why each rule fired or didn't, and async HMAC-SHA256-signed webhooks with automatic retry.

= What happens when I block a customer? =

Blocked customers see a customizable message when they try to add items to their cart or proceed to checkout. The block applies to both logged-in users and guest checkouts matching the blocked email. All blocked checkout attempts are logged.

= Can I undo a block? =

Yes. You can unblock a customer at any time from their profile page or the customer list. You can also add customers to the allowlist, which locks their score at 100 and prevents any negative signals from affecting them.

= What happens right after I install TrustLens? =

New WooCommerce orders are analyzed automatically after activation. If you already have historical orders, you can run Historical Sync from the dashboard to build trust profiles from your existing store data without slowing down the frontend.

= Does this slow down my store? =

No. Score calculations run asynchronously via Action Scheduler (the same system WooCommerce uses). Checkout blocking uses a lightweight email-hash lookup. The historical sync processes orders in small batches in the background.

= Does TrustLens send customer data to an external service? =

No. TrustLens works inside your WordPress and WooCommerce installation. It does not send customer data to the plugin developer or to any default third-party service. External delivery only happens if you explicitly configure features like webhooks or email notifications.

= Is TrustLens compatible with WooCommerce HPOS? =

Yes. TrustLens declares full compatibility with High-Performance Order Storage and works with both legacy and HPOS-enabled stores.

= Does TrustLens store personal data? =

TrustLens stores customer email addresses and behavioral data (order counts, refund counts, trust scores) in custom database tables. Matching identifiers used for linked-account detection are pseudonymized using keyed HMAC-SHA256 hashes, preventing the raw values from being exposed or reused across sites. The plugin integrates with WordPress privacy tools — customers can request data export or erasure through the standard WordPress privacy workflow.

= Can I access TrustLens data from external systems? =

Yes. TrustLens includes a REST API with 8 endpoints for looking up customers, retrieving scores, filtering by segment, and triggering recalculations. API access requires either the `manage_woocommerce` capability or a valid API key configured in settings.

= Can I get alerts and reports by email? =

Yes. The free version includes core email notifications such as blocked checkout alerts, a welcome summary, and a weekly summary. Pro adds advanced alerts, daily digests, monthly revenue protection reports, and scheduled email reports.

= What is the minimum data needed for accurate scoring? =

By default, customers need at least 3 orders before they move out of the Normal segment. You can adjust this threshold in Settings > General. Customers below the threshold still accumulate signals — they just aren't classified until enough data exists.

= Does the free version include all detection modules? =

Yes. All **8 detection modules** ship in the free version — returns, orders, coupons, categories, linked accounts, shipping address anomalies, chargebacks, and card-testing defense. There are no trial limits, no disabled scoring, and no locked modules.

Pro adds automation rules, webhooks, scheduled reports, payment-method risk controls, the advanced per-brand Chargeback Monitor with daily alerts, Card-Testing Defense Pro (auto-escalation + analytics + Slack alerts), and 10 advanced notification types.

= What happens if I rotate my WordPress secret keys? =

**Important:** TrustLens uses your WordPress `auth` secret key (via `wp_salt('auth')`) as the HMAC keying material for hashing customer emails and linked-account fingerprints. This is a deliberate security choice — it makes stored hashes non-reversible and non-portable across sites.

The trade-off is that **regenerating your WordPress secret keys** (whether through a security plugin's "regenerate keys" tool or by editing `wp-config.php` directly) will permanently invalidate every customer hash and fingerprint already stored in your TrustLens tables. After rotation, the plugin won't be able to match a returning customer to their existing trust profile, and linked-account detection will reset.

If you ever need to rotate WordPress secret keys, plan to **run Historical Sync afterward** so TrustLens rebuilds the customer table from your existing WooCommerce order data using the new keying material. Allowlisted/blocked status set manually on individual customer rows is the exception that won't auto-recover — re-apply those after the sync.

== Screenshots ==

1. **Command Center Dashboard** — Full analytics overview with health score, KPI cards, trust score trends, and segment distribution
2. **Customer List** — Searchable, sortable list with segment badges, trust scores, return rates, and quick actions
3. **Customer Detail Page** — Complete customer profile with score history, event timeline, linked accounts, and all behavioral signals
4. **Trust Score Trends Chart** — 30-day trend line showing average trust score movement across your customer base
5. **Revenue Protection Overview** — ROI scorecard showing money protected, money at risk, protection rate, and actions taken
6. **Detection Overview** — Coupon abuse stats and chargeback tracking at a glance
7. **Settings Page** — Configure scoring thresholds, checkout blocking message, and notification preferences
8. **Order Integration** — Customer trust score and segment displayed on the WooCommerce order edit screen
9. **Linked Accounts View** — Multi-account detection showing matched fingerprints and risk indicators

== Changelog ==

= 1.2.8 =
* New: Video walkthrough — a short explainer showing how TrustLens turns real shopping behavior into a 0–100 trust score and surfaces returns, coupon, linked-account and card-testing abuse, now on the plugin page.
* Update: Refreshed the plugin banner artwork.

= 1.2.7 =
* New: Dispute deadline worklist on Chargeback Monitor — every open dispute with its response deadline and a live countdown, plus a due-soon count on the dashboard, so a chargeback response window never slips past you.
* New: Ten new automation conditions — write rules on full and partial refunds, coupons used, first-order coupons, disputes won and lost, order edits, reviews-before-refund, and whether a customer is allowlisted or flagged.
* New: Skip trusted customers — rules can now exclude allowlisted buyers with an is_allowlisted condition, so blanket rules don't catch the people you've already vouched for.
* New: Flagged for review is now a real customer status — the Flag action shows a badge, adds a filter on the Customers screen, and clears in one click, instead of leaving a note nobody could find.
* Improvement: Automation Add Tag now writes a real customer tag — visible on the customer page and removable in bulk — instead of a hidden note.
* Fix: Rules that quietly never fired now fire — first-order rules at checkout, and card-testing blocks against brand-new attacker emails, now work as configured.
* Fix: Require Verification now actually holds the order for review (and flags it) instead of doing nothing.
* Fix: Webhook activity is counted honestly — each delivery counts once (queued, then delivered or failed) instead of logging both a success and a failure for the same call, and queued deliveries are properly cancelled when the plugin is deactivated.
* Fix: Allowlisting a customer now clears any review flag, so a trusted customer can't stay flagged.
* Fix: The rule builder no longer rejects valid rules — mixing 1 and true on a yes/no condition, or upper- and lower-case country codes, is understood correctly.
* Fix: Choosing to remove all data on uninstall now also drops the disputes table, and automation log cleanup keeps running even after a Pro license lapses.

= 1.2.6 =
* New: Quick Start setup card on the dashboard — three guided choices (block risky customers, email alerts, import past orders) get a new store protected without hunting through settings.
* New: Block reason picker — when you block a customer you can record why, from a preset or your own note; it's saved to the customer's notes and history so you keep an audit trail.
* New: Plain-language score summary on each customer — see at a glance what's weighing a score down and what's in their favour, instead of decoding raw signal bars.
* New: Segment glossary and inline help — a built-in legend for VIP through Critical with their score bands, plus ? tips that explain terms like “fingerprint” right where you need them.
* New: Recommended next actions on the dashboard and Card-Testing Defense — each screen now tells you what to do, not just what's happening.
* Improvement: Customer actions no longer reload the whole page — block and unblock update in place with a confirmation toast, and allowlist or recalculate keep your scroll position so you never lose your place.
* Improvement: Panic Freeze remembers your chosen duration instead of resetting to 15 minutes each time, and the misleading “1 hour” option (which the server capped at 30) has been removed.
* Improvement: Card-Testing Defense is now discoverable as the 8th detection module from the Modules tab in Settings.
* Improvement: Signal explanations on the customer page are now keyboard-accessible, not hover-only.
* Fix: The Automation tab now shows consistently in the in-app header, matching the WordPress admin menu.

= 1.2.5 =

**Dashboard visual refresh — every chart now reads as one product.**

**Changed**

* All dashboard charts repainted in the TrustLens emerald palette to match the website and the rest of the admin — Trust Score Trends, Segment Distribution, Refund Activity, Hourly Activity, Category Returns, Monthly Protection, the Chargeback Monitor 12-month trend, and the Card-Testing Defense Attack History timeline. Replaces the previous mix of Bootstrap red/orange/green and a stray purple that had drifted in over earlier releases.
* Chart tooltips switched from black bubbles to light cards with subtle slate borders and softer typography so they no longer overpower the data.
* Line charts now use thinner 2px strokes with smoother curves and gradient fills that fade fully to transparent; bar charts have rounded 6px caps.
* Snappier 600ms entry animation (was the Chart.js 1s default).
* Hourly Activity chart now uses an emerald intensity gradient (low → slate, high → emerald) instead of a purple-to-violet ramp, so quiet hours read as quiet and busy hours pop.
* New shared `chart-theme.js` module — every chart in the plugin pulls from one palette, so future charts pick up the same identity automatically.

**Fixed**

* Segment doughnut's "X customers" total now sits on the actual ring center. Previously, the bottom-positioned legend pushed the doughnut up but the label kept dividing the full canvas height in half, landing the text below the ring.
* Segment-doughnut legend markers (VIP / Trusted / Normal / Caution / Risk / Critical) now render as perfect circles instead of slightly-oval boxes.
* Empty charts now show a quiet "No data yet" message instead of a blank canvas, so a fresh install doesn't look broken before any orders have been scored.

= 1.2.4 =

**Card-Testing Defense — false-positive fix + WordPress 7.0 compatibility.**

**Fixed**

* **Card-Testing Defense self-blocking legitimate shoppers on Blocks checkout.** The velocity counter was incrementing on every Store API cart write — `add-item`, `update-item`, `apply-coupon`, `select-shipping-rate`, `update-customer` — not only on actual payment submissions. A normal shopper rapidly adjusting quantities or applying a coupon in a Blocks cart could cross the 10-submissions-per-60s threshold and target their own fingerprint for a 90-second lockdown, locking themselves out of checkout. Root cause: the gate context had no way to distinguish cart-write intent from checkout-submit intent, so the velocity recorder treated everything as a payment attempt. The gate now carries an explicit `intent` field populated from the route; the velocity recorder only counts true checkout submissions, and the card-testing module short-circuits on cart writes (which also removes 2 unnecessary `COUNT(*)` queries from every cart click). The email blocklist continues to fire on cart writes per the 1.3.0 design — known-bad customers still cannot add items to cart. No configuration change required; existing thresholds keep working but are now fed only real payment attempts.

**Compatibility**

* **Tested up to WordPress 7.0 ("Armstrong").** Full audit completed: PHPMailer 7.0.2 update, Backbone 1.6.1, CodeMirror v5 / Espree, Interactivity API `state.navigation` deprecation, Block API version, Block Hooks REST move, REST `permission_callback` coverage, early-init translation, and PHP-8 deprecation surfaces. No plugin changes were needed for 7.0.

= 1.2.3 =

**Security and reliability hardening.** Closes several issues surfaced during a pre-release audit.

**Fixed**

* **Card-Testing Defense — VIP bypass too permissive.** Previously, any customer with at least one completed order was permanently exempt from card-testing velocity blocks — meaning a fraud actor who completed a single order gained immunity from then on. The threshold now matches the plugin-wide `trustlens_min_orders` setting (default 3 orders) AND customers in `risk` or `critical` segments no longer bypass card-testing defense regardless of order count.
* **Chargeback meta not HPOS-compatible.** Manual chargeback writes used `update_post_meta()` / `get_post_meta()` directly, which silently target the wrong table on stores with WooCommerce High-Performance Order Storage enabled. Switched to `WC_Order::update_meta_data()` / `WC_Order::get_meta()` so the chargeback indicator and Record Manual Chargeback form work correctly on HPOS stores.
* **IP spoofing via forwarding headers.** `HTTP_X_FORWARDED_FOR` (request gate) and `HTTP_CLIENT_IP` + `HTTP_X_FORWARDED_FOR` (payment-method controls) were trusted unconditionally, letting an attacker send `X-Forwarded-For: 1.2.3.4` to rotate their apparent IP and defeat per-IP velocity rules. Both code paths now default to `REMOTE_ADDR`. Sites legitimately behind a trusted reverse proxy (Cloudflare, load balancer, Sucuri) can opt in to X-Forwarded-For via the new `trustlens/trust_proxy_headers` filter — the last entry in the header is used (the IP the closest trusted hop observed).
* **Webhook signing secret exposed in DOM.** The "Test" button on the Pro Webhooks settings page rendered the signing secret as a `data-secret` HTML attribute, making it readable by any browser extension or XSS payload running in the admin panel. The secret is no longer rendered to the page; the AJAX handler now looks up the endpoint server-side from the stored config.
* **Webhook async dispatch could pile up duplicates.** Automation rule webhooks used `as_enqueue_async_action()` without dedup, so a rapid burst of identical triggers (e.g. `score_updated` firing several times during a batch refund) queued multiple deliveries for the same rule+customer. Now dedup'd via `wstl_ensure_single_action`; retries from inside the dispatch handler still carry a distinct retry counter and bypass dedup so failed deliveries still get their 60s / 120s / 240s attempts.
* **Score-update queue race.** `wstl_queue_score_update()` used a read-then-write pattern that could double-schedule the score recalculation under concurrent events for the same customer. Replaced with `wstl_ensure_single_action`, which uses unschedule-then-schedule semantics and is race-free.
* **Chargeback record double-increment under concurrency.** The manual chargeback AJAX path ran two separate UPDATE statements (one for `total_disputes`, one for the outcome counter). Two concurrent calls for the same customer could leave `disputes_lost` exceeding `total_disputes`. Now done as a single atomic UPDATE when the outcome is known at record time.
* **Shipping anomaly re-entrancy.** The `trustlens/shipping_anomaly` action fired (and `address_anomaly_detected` was logged) from inside `get_signal()`, which runs on every score recalculation. That could spawn re-entrant Action Scheduler jobs through automation rules. Both events now fire once from `handle_order_completed`, so each detection produces exactly one event per order completion.
* **Guest-order automation actions silently dropped.** Customer-level actions (send email, block customer, tag, etc.) on order-bound rules silently returned when the order was a guest checkout. Now a `'skipped'` row is written to the rule log with the reason "Guest order: no customer email hash" — the inspector can finally answer "why didn't my rule fire?".
* **Lockdown targets transient race.** Card-Testing Defense stored every targeted device fingerprint in one shared transient map; concurrent attacks from different devices could clobber each other on write. Switched to one transient per fingerprint so concurrent target writes never conflict. Admin listing and "any-target-active" check use indexed `wp_options LIKE` queries.
* **Automation `is_first_order` matched 0-order customers.** Condition now requires `total_orders === 1` (exact), so rules don't fire against brand-new customer records that exist before any order has been counted.
* **Chargeback signal ignored min-orders threshold.** A one-time buyer who filed a legitimate dispute could trigger the -30 chargeback penalty before any other signals existed. The chargeback module now honors `trustlens_min_orders` like the returns, coupons, and shipping modules.
* **Dispute Report didn't validate the hash format.** `$_GET['hash']` is now checked against `wstl_is_email_hash()` before being passed to the lookup, matching the rest of the codebase.
* **Webhook log table escaping.** Endpoint URL inside `<code>` was escaped with `esc_url()` (an attribute-context function) instead of `esc_html()`. Switched to the correct function for text content.
* **Automation retention cron not cleared on deactivation.** The `trustlens/automation/retention_cleanup` event survived `Deactivate`, leaving an orphan WP-Cron entry. Now cleared alongside the other scheduled events.
* **Duplicate score-save logic.** `process_score_calculation()` and `TrustLens_Score_Calculator::recalculate_score()` each contained their own copy of the save-and-fire(`score_updated` / `segment_changed`) flow. The Action Scheduler callback now delegates to the calculator method so the two paths can't drift.
* **Redundant order re-fetches.** `class-module-orders` and `class-module-shipping-anomalies` registered `woocommerce_order_status_completed` with 1 arg and immediately called `wc_get_order()` on the order ID. Hooks now register with 2 args and use the `WC_Order` instance WooCommerce passes — with a defensive fallback for third-party callers firing the hook with one argument.
* **Card-testing defense bypass via client fingerprint rotation.** Bots that rotated their JavaScript-side fingerprint per request avoided the per-fingerprint velocity threshold (each rotated hash had count 1, never tripping the limit). Declines are now also recorded under the server-fallback fingerprint (IP + User-Agent + Accept-Language) — which stays stable across client-hash rotation — so the velocity detector accumulates and targets even rotating attackers. Lockdown checks test both hashes on every request, so an attacker who got the server hash targeted on attempt 3 stays blocked even if they rotate the client hash on attempt 4.
* **Panic Freeze duration ceiling.** The duration the panic-freeze AJAX accepted from the admin form was clamped to 3600s (1 hour). An admin mis-entering the value could accidentally block checkout for an hour. The server-side ceiling is now 30 minutes by default, filterable via `trustlens/card_testing/panic_max_duration` for sites that genuinely need longer.
* **Cron reconciliation on every page load.** `ensure_notification_schedules()` was hooked to `init` and ran on every frontend request, writing to `wp_options` on stores with notifications disabled. The reconciliation now self-throttles to once per hour, with explicit invalidation on notification-setting changes so toggles still take effect immediately.
* **Automation `customer_age_days` / `days_since_last_order` timezone drift.** Conditions mixed local-time (`current_time('timestamp')`) with UTC-stored MySQL timestamps, producing up to ±14 hours of drift on non-UTC sites — enough to push a daily-granularity condition off by a full day. Both sides now anchor to UTC.
* **Webhook endpoints option marked `autoload=no`.** The endpoint config (which contains plaintext HMAC signing secrets) was autoloaded on every request. It's now loaded only when a webhook actually needs to fire.
* **Card-Testing Defense not actually enabled by default.** The readme advertised "ships enabled with sensible thresholds" but the activation flow never set the `trustlens_module_card_testing_enabled` option, so the module sat dormant until merchants found the toggle in Settings. New installs now enable card-testing defense and the VIP customer bypass automatically, matching the documented promise. Existing sites keep whatever value they already have — no surprise behavior changes.
* **Welcome email never sent on default-off installs.** The 24-hour-post-activation welcome summary was gated behind the master `trustlens_enable_notifications` switch, which ships disabled. The handler silently returned and the carefully-built welcome email was dropped on every fresh install. The welcome email is now gated only by its own `trustlens_notify_welcome_summary` opt-out (which already defaults to on), so the onboarding email actually fires.
* **Plugin row "Dashboard" / "Settings" shortcuts.** The Plugins screen now surfaces direct links to the TrustLens dashboard and Settings page in the plugin row, matching standard WordPress plugin UX.
* **Dashboard onboarding card now signals active protection.** When a fresh install lands on the empty dashboard, a small pill next to the onboarding steps confirms that the detection modules are already scoring incoming orders, so merchants know protection is live and not deferred until they finish setup.

**Changed (potentially breaking for existing webhook receivers)**

* **Webhook signature scheme v2.** Outgoing webhook signatures now cover `timestamp + '.' + body` instead of `body` alone, and a new `X-TrustLens-Timestamp` header carries the Unix epoch. This lets receivers reject replayed deliveries by checking the timestamp falls within a short window (recommended: ±5 minutes). Verification on the receiver side: compute `'sha256=' + hmac_sha256(timestamp + '.' + body, secret)` and constant-time-compare against `X-TrustLens-Signature`. If you have an existing webhook receiver, update its verification code before upgrading.

**Internal**

* Centralized client-IP retrieval in `wstl_get_client_ip()` so future fraud modules don't have to re-solve the spoofable-header problem.
* Centralized webhook signature computation in `TrustLens_Webhooks::compute_signature()` so the three send sites (settings test, classic webhooks, automation webhooks) can't drift apart.
* Defensive: replaced `ActionScheduler_Store::STATUS_PENDING` constant reference with the literal `'pending'` in `wstl_queue_score_update()` so the function survives unusual AS bootstrap orderings.

= 1.2.2 =

**Automation Rules — reliability rewrite + major capability expansion.** Plus Card-Testing Defense admin UX consolidation.

**Automation**

* **Added triggers:** Chargeback Filed · Dispute Recorded · Linked Accounts Detected · Card Testing Attack · Shipping Anomaly.
* **Added condition fields:** Total Order Value · Total Disputes · Linked Accounts · Coupon Then Refund · Cancelled Orders · Customer Type · Is Blocked · Customer Age · Days Since Last Order · Payment Method · Shipping Country · Billing Country · Country Mismatch · Coupon Total.
* **Added actions:** Allowlist Customer · Cancel Order.
* **Added:** Save-time validator blocks rules that can never fire — unsatisfiable conditions, schema-bound violations, trigger-state contradictions, invalid operators for the field type, incomplete actions — each with a specific inline reason.
* **Added:** Inspector shows `SKIP` status on evaluations that didn't execute, with the reason ("Cooldown active" / "Condition not met: trust_score > 50"). Directly answers "why didn't my rule fire?".
* **Changed:** Webhooks now dispatch async with automatic retry (60s/120s/240s backoff) and are HMAC-SHA256 signed by default.
* **Changed:** Rule editor no longer full-page-reloads on save or delete; errors appear inline inside the modal.
* **Fixed:** Concurrent rule saves were last-write-wins — now serialized via advisory lock.
* **Fixed:** A failed action locked the rule out for an hour via cooldown — now clears on error so the next event retries.
* **Fixed:** Rules with an unknown condition field silently matched everything (catastrophic for `block_customer` rules). Now rejected.
* **Fixed:** Timezone drift between log timestamps and inspector counters when MySQL server TZ ≠ site TZ.
* **Fixed:** Operators `<`, `<=`, `<>` couldn't save at all.
* **Fixed:** "Send Email" action ignored the recipient field; now honors it as a per-rule override (falls back to site notification email when blank).
* **Fixed:** "Refund Processed" trigger silently dropped order context — order-only actions/conditions never fired on refunds.

**Admin UX — Card-Testing Defense + Dashboard**

* **Changed:** Card-Testing Defense page consolidated from four tabs into a single live view — panic controls, live state, and targeted fingerprints visible without clicking.
* **Added:** Dashboard alert band for active Panic Freeze, targeted lockdowns, and card-network programs over chargeback threshold.
* **Added:** Module-status pill row on the dashboard (on/off + one stat for each subsystem).
* **Added:** Persistent plugin-wide admin header with unified nav, live status pill, notifications bell, and ⌘K command palette.
* **Fixed:** Unchecking "Enable Card-Testing Defense" or "VIP bypass" didn't save (Settings API checkbox quirk).
* **Fixed:** Slack webhook delivery failures are now logged instead of swallowed.
* **Fixed:** Uninstall clears card-testing options and cron hooks; deactivation unschedules card-testing crons.
* **Fixed:** Card-testing attacks with an identifiable customer email now fire `trustlens/checkout_blocked` (once per newly-targeted fingerprint) so Notifications / Automation / Webhooks can react.

Safe additive upgrade — new composite index added idempotently, no data migration.

For the complete changelog of earlier versions, visit [the full changelog](https://webstepper.io/wordpress/plugins/trustlens/changelog/).

== External Services ==

This plugin may connect to external services as described below.

= Freemius SDK =

This plugin uses the [Freemius](https://freemius.com) SDK for optional usage tracking, license management, and plugin updates.

**When data is sent:**

* During plugin activation, only if the user explicitly opts in
* When checking for plugin updates
* When activating or deactivating a Pro license

**What data is sent:**

* Site URL, WordPress version, and PHP version
* Plugin version and activation status
* Admin email (only if opted in)
* License key (Pro version only)

**Important:** No data is sent unless you explicitly opt in during plugin activation. You can skip the opt-in entirely and use the free version without sharing any data.

* Service: [Freemius](https://freemius.com)
* Terms of Service: [https://freemius.com/terms/](https://freemius.com/terms/)
* Privacy Policy: [https://freemius.com/privacy/](https://freemius.com/privacy/)

= Webhooks (Pro, Optional) =

When webhooks are enabled in TrustLens settings (Pro feature), the plugin sends HTTP POST requests to URLs configured by the administrator.

**When data is sent:**

* When a customer's trust score is updated (if enabled)
* When a customer is blocked (if enabled)
* When a checkout is blocked (if enabled)
* When a high-risk order is placed (if enabled)
* When testing webhook connectivity

**What data is sent:**

* Customer email hash and, when available, the customer email stored in TrustLens
* Trust score and customer segment
* Event type and timestamp
* Order details for high-risk order events (order ID, total, status)
* Site URL and site name

**Important:** Webhook endpoints are entirely configured by you. No data is sent to any third-party service unless you explicitly add webhook URLs. The plugin does not send data to the plugin developer or any default external service.

== Upgrade Notice ==

= 1.2.8 =
Adds a video walkthrough to the plugin page and refreshes the banner artwork. No functional changes — safe to skip if you're current.

= 1.2.7 =
A major automation reliability pass, 10 new rule conditions, a first-class Flagged customer status, and a chargeback dispute-deadline worklist.

= 1.2.6 =
Smoother day-to-day controls: in-place customer actions, a guided setup card, plain-language score explanations, and clearer Card-Testing Defense.

= 1.2.5 =
Dashboard visual refresh — every chart repainted in the TrustLens emerald palette so the dashboard, Chargeback Monitor, and Card-Testing Attack History timeline read as one product. Tooltips switched from black bubbles to light cards; line charts use thinner strokes with smoother gradient fills; bar charts get rounded caps. Fixes the doughnut center label that was sitting below the ring and renders the VIP/Trusted/Normal/Caution/Risk/Critical legend markers as proper circles. Empty charts now show "No data yet" instead of a blank canvas. Pure visual change — no settings or data changes required.

= 1.2.4 =
Card-Testing Defense self-block fix — fixes a false-positive that could lock legitimate shoppers out of Blocks checkout after rapid cart interactions (quantity edits, coupon applies). Recommended for any store using the WooCommerce Blocks cart/checkout. WordPress 7.0 compatibility verified.

= 1.2.3 =
Security and reliability hardening — closes a card-testing defense bypass via fingerprint rotation, an IP-spoofing path through `X-Forwarded-For`, a webhook secret exposed in the DOM, and several race conditions in the score-update and chargeback paths. Also enables Card-Testing Defense by default on fresh installs (matching the documented promise) and fixes the welcome email so it actually fires after activation. **Breaking change for any existing webhook receiver**: outgoing signatures now sign `timestamp + '.' + body` with a new `X-TrustLens-Timestamp` header — update receiver verification before upgrading.

= 1.2.2 =
Automation Rules reliability rewrite and capability expansion — 5 new fraud-signal triggers, 14 new condition fields, 2 new actions, save-time validation that blocks rules which can never fire, async HMAC-signed webhooks with auto-retry, and inline skip logging that answers "why didn't my rule fire?". Plus Card-Testing Defense consolidated to a single live view and a persistent plugin-wide admin header with ⌘K palette. Safe additive upgrade.
