=== Vidal Security AI ===
Contributors: jmvidal2013
Tags: security, hardening, security scanner, login security, firewall
Requires at least: 6.0
Tested up to: 7.1
Requires PHP: 7.4
Stable tag: 1.25.4
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Security for WordPress and WooCommerce: plain-language scan, one-click hardening, order anti-fraud, checkout guard and payment monitoring.

== Description ==

Most security plugins speak in logs and codes. **Vidal Security AI** speaks like a person: it scans your site, gives you a clear 0–100 score, explains every problem in one plain sentence, and fixes the safe things with a single click. And if you sell online, it protects your store too: orders, checkout and payments.

**Free features:**

* **Security scan with a 0–100 score** — 13 real checks (outdated WordPress, users exposed through the REST API, XML-RPC left on, author enumeration, public readme.html, missing security headers, debug mode, default database prefix, SSL, PHP version, an account named "admin", automatic updates) each with a plain-language explanation.
* **Deep file scan** — every file examined one by one, on demand and weekly: core files against a baseline photo (or against the official WordPress checksums, if you turn that option on), plugins and themes file-by-file against a baseline photo, executable files hiding in uploads, and high-risk code patterns reported as suspicions, never verdicts. It runs in chunks for shared hosting, and it deletes nothing — it only reports, down to the exact file.
* **Mini firewall in observation mode** — every request is quietly checked against generic attack patterns (SQL injection, cross-site scripting, file-inclusion and traversal tricks, remote-file parameters, and probes of sensitive files like wp-config, .env or backup archives). In this version it ONLY observes: it writes down what it sees in its own log — and, with the AI Guardian on, reports it — but never blocks, redirects or changes a single request, so it cannot break your site.
* **Sensor Network (optional, off until you say yes)** — if you opt in, your site becomes a sensor of the Vidal Security network: it shares ATTACK data only (the attacker's IP, what was tried, the pattern family matched, the path without parameters, and a SHA-256 fingerprint of the sample) so an IP that attacks one site gets flagged for all. It NEVER shares your content, your users, your customers or request bodies — and nothing is sent until an administrator accepts the notice shown in wp-admin. The switch lives in the plugin panel and can be turned off anytime.
* **One-click hardening, fully reversible** — hide the user list from the REST API for visitors, disable XML-RPC, block author enumeration, hide the WordPress version, add security headers (X-Frame-Options, X-Content-Type-Options, Referrer-Policy, HSTS on HTTPS), and block readme.html / license.txt.
* **A dashboard with its own identity** — your score front and center, color-coded status cards, and clear next steps. No cryptic logs.

**🛒 WooCommerce protection (free, included):**

Running a store? Then the money side matters as much as the site itself. These guards switch on automatically when WooCommerce is active — and only then:

* **Order anti-fraud** — every order receives a local risk score (IP velocity, disposable email addresses, billing/shipping country mismatch, high-value first orders, failed-payment bursts), a traffic-light badge in the orders list, a downloadable evidence file for chargeback disputes, and an email alert when the risk is high.
* **Checkout guard** — an invisible anti-bot honeypot plus a minimum fill time on the classic checkout form, and a payment-attempt limiter that stops card testing (3 failed payments in 1 hour = a 30-minute checkout block). The limiter and the IP blocks cover both the classic checkout and the block checkout (Store API); the honeypot and the minimum fill time apply to the classic form, because the block checkout does not send those form fields.
* **Payments & webhook monitor** — an hourly watch for WooCommerce webhooks silently disabled, paid orders stuck without moving, and waves of failed payments, with clear email alerts that distinguish an attack from a gateway failure.

**Optional AI Guardian (premium service):**

With a site key, the plugin can connect to the Vidal Security AI cloud service (operated by Vidal Digital Miami on n8n) to classify attacks with AI and show a daily "guard's report" in plain language. In this WordPress.org edition the Guardian is advisory only: it never applies IP blocks or any other change ordered by the service — every block this edition enforces is decided locally by the plugin itself, on this site. This connection is **optional and off by default**. Your dashboard shows the agent as **the Sentinel**: a live card with your agent on watch — events watched, IPs blocked, last and next round — and the daily **watch rounds** log, written in plain language every morning. On the free version, the same card shows the agent asleep, and exactly what you are missing while it sleeps.

**Get the AI Guardian for your site:** https://vidaldigitalmiami.com/vidal-security-ai.html

**Privacy:** All external services are optional. The AI Guardian, Sensor Network, official core checksum lookup and search-engine bot DNS verification are off by default and have separate controls. Local security features work without enabling them. Loopback checks contact this site's own URLs and do not follow redirects. WordPress itself, the mail transport and other plugins may have their own network activity. See "External services" for the destinations, data and purpose of each optional connection.

== Installation ==

1. Upload the `vidal-security-ai` folder to `/wp-content/plugins/` or install it from the WordPress plugins screen.
2. Activate the plugin.
3. Go to **Vidal Security** in the admin menu and press **Scan now**.
4. Turn on the hardening switches you want and press **Save**. Everything is reversible.

== Frequently Asked Questions ==

= Does the free version phone home? =
Not by default. The basic scan makes loopback requests to your own site. Official core checksums and bot DNS verification require separate administrator permission. Sensor Network and AI Guardian sharing also require their own opt-in. Disabling an option prevents subsequent requests for that feature; an already dispatched request cannot be recalled.

= Will the hardening break my site? =
Each switch is conservative and reversible. The only file ever touched is `.htaccess`, only for the readme/license block, only on Apache/LiteSpeed servers where the file is writable, and the rules are written between clearly marked `# BEGIN Vidal Security AI` / `# END Vidal Security AI` markers. Turning the switch off (or deactivating the plugin) removes them.

= What does the AI Guardian add? =
AI classification of attacks (noise vs. real threat) and a daily plain-language report. In this edition the Guardian never orders or applies IP blocks: every blocking decision stays local to your site. It requires a site key and is a paid subscription service; the free plugin remains fully functional without it.

= Does it work on multisite? =
It is designed and tested for single-site installs in this version.

== Screenshots ==

1. The dashboard: hero with your 0-100 security score and color-coded check cards.
2. Watched IPs, the allowlist, two-factor authentication, the payments monitor and change watch.
3. The AI Guardian (premium) settings: site key, connection test and live counters.

== External services ==

This plugin can optionally connect to the **Vidal Security AI cloud service**, operated by Vidal Digital Miami, to power the premium AI Guardian. The connection is **off by default** and only happens when the site owner explicitly enables the AI Guardian and enters a site key in the plugin's settings.

* **What is sent, and when:** when the AI Guardian is enabled, the plugin sends technical security events in batches (about once an hour) to the service - `https://v8.vidalbooking.com/webhook/sec-ingest` with the standard brain, or `https://v8.vidalbooking.com/flow/sec-ingest` with the Vidal Flow brain, whichever the site owner selects in the settings. The payload includes this site host and site key, timestamps, event type, IP address, user agent, the requested path without query parameters, login usernames (including successful logins), and a short incident detail. Urgent alerts send their title and detail immediately; those details can include administrator identity or email, payment-failure context or changed file paths. The recipient also sees the server IP and HTTP user agent. With the Guardian active, the sends also carry a version inventory (PHP, WordPress, this plugin and every installed plugin version) so the service can check them against known, published vulnerabilities. The plugin also reads this site's own report from the matching `sec-report` endpoint. No file contents, passwords or complete order records are sent; security details may contain the account or transaction context described above.
* **Why:** the service classifies the events with AI (noise vs. real threat) and produces the daily plain-language guard's report. The Guardian only advises this edition: the service never sends IP blocks or any other order to the plugin, and this edition never receives or applies changes ordered by the service — every blocking decision is made locally by the plugin itself, on this site. Urgent alerts by WhatsApp, when enabled for the site, are sent by the service.

The plugin can also optionally connect to the same service as a **Sensor Network** node. This connection is **off by default** and only happens when an administrator explicitly opts in (an admin notice asks for the decision; nothing is sent before it).

* **What is sent, and when:** with the Sensor Network on, the plugin sends attack reports about once an hour to `https://v8.vidalbooking.com/flow/red-sensores`. Each report contains only: a random sensor identifier, this site's host, WordPress/plugin/PHP versions, and per attack event: source IP (which may belong to a legitimate visitor), event type (WAF hit, login burst, new administrator account, critical option change), the path tried (without query parameters) and a SHA-256 fingerprint of the sample. Usernames, email addresses, content, customer data and request bodies are NEVER sent.
* **Why:** so that an IP attacking several sites can be flagged for the whole network. Reports are kept for 90 days.

**WordPress.org checksum API (Deep file scan — opt-in, off by default):** the plugin contacts this service ONLY if an administrator turns on the official core checksums option in the Deep scan card. With the option on, when the Deep file scan runs (manually from the panel, or weekly on its own), the plugin requests the official checksums for your WordPress version from `https://api.wordpress.org/core/checksums/1.0/`, sending the version number and locale. The service also receives the server IP and the plugin user agent. Valid checksums are cached locally for 24 hours. It receives the published MD5 checksums of the core files and compares your files against them locally; no file content ever leaves your site. With the option off — the default — the scan always compares the core against its local baseline and no request is made; the same local-baseline fallback applies if the service is unreachable, and the panel says so.

**DNS bot verification (opt-in, off by default):** when a visitor claims to be a supported search-engine bot, the server can send that visitor IP for a reverse DNS lookup and the resulting hostname for a forward lookup through the server-configured DNS resolver. This verifies the claimed bot identity; no fixed third-party HTTP endpoint is used. Positive results are cached for seven days, negative results for one day. The resolver is controlled by the hosting provider, and its terms and privacy policy apply. With this setting off, no bot DNS lookup occurs; ordinary local rules and the administrator IP allowlist remain available.

* **WordPress.org checksum service terms:** https://wordpress.org/about/tos/
* **WordPress.org privacy policy:** https://wordpress.org/about/privacy/
* **Vidal service terms:** https://vidaldigitalmiami.com/vidal-security-ai-terms.html
* **Privacy policy:** https://vidaldigitalmiami.com/vidal-security-ai-privacy.html

== Changelog ==

= 1.25.4 =
* Enforce checksum consent inside the HTTP helper; validate paths and MD5 values, use the installed locale, cache responses and refuse redirects. Add explicit opt-in for forward/reverse bot DNS verification.
* Retain plugin identity and all modules. Move browser styles to enqueued assets; retain inline email styling for email clients. Escape panel and SVG output and preserve form controls.
* Resolve core paths from ABSPATH and support custom content, plugin, theme and upload directories with unique file identities. Reject traversal and escaping symlinks.
* Discover and scan files in bounded batches, with persistent cursors, a scan lock and an independent continuation job. Partial results retain the previous baseline. Daily snapshots prune skipped directories, stop at limits and reuse directory hashes.
* Clear every plugin cron hook on deactivation and uninstall. Load the required Core file/misc helpers when editing .htaccess. Preserve settings on deactivation, remove owned options and database transients on uninstall.
* Harden evidence-download headers and filenames, retain new queue entries arriving during a successful send, retain report timing on mail failure, preserve unrelated settings and keep the selected dashboard view.

= 1.25.3 =
* Deep file scan — the official WordPress core checksum check is now opt-in and off by default: the weekly and on-demand scans verify core files against a local baseline, and the plugin contacts api.wordpress.org (sending only your WordPress version number) only after an administrator enables the option in the Deep scan card.
* Plugin review fixes: the panel's view navigation moved to a properly enqueued script file, file paths are resolved through WordPress functions (wp_upload_dir(), get_theme_root(), get_home_path()), and panel output is escaped through a strict HTML allow-list.

= 1.25.2 =
* WordPress.org edition: the wording of the readme and the panel now states plainly what has been true of this edition since 1.25.0 — the AI Guardian is advisory only: it classifies events and writes its daily report, but it never receives or applies IP blocks or any other change ordered by the service, and every block this edition enforces is decided locally by the plugin itself.
* WordPress.org edition: the Guardian server address is no longer configurable — there is no server URL field, and the plugin only ever talks to Vidal's official endpoints, so a site key cannot be sent anywhere else.
* WordPress.org edition: the data disclosure is now exact (the username involved in login events, including successful logins, is declared), and event paths are recorded without query parameters. Turning the Guardian off now also clears the queued-events buffer, and uninstall cleanup covers every option this edition creates.

= 1.25.1 =
* WordPress.org edition: fixes for the directory's automated checks — the "Tested up to" version now uses the major.minor format, every translatable string with placeholders gained its translator comment, the mini firewall uses wp_strip_all_tags(), and the plugin header no longer points to a translations folder that is not shipped.
* WordPress.org edition: the checkout guard in this edition no longer includes the optional external CAPTCHA option — it protects the form with its local checks only (invisible trap, minimum fill time, payment-attempt limiter and IP blocks), so nothing is loaded from third-party servers at checkout.
* ES: Edición de WordPress.org: correcciones para las comprobaciones automáticas del directorio — la versión «Tested up to» usa el formato mayor.menor, cada texto traducible con marcadores lleva su comentario de traductor, el mini-firewall usa wp_strip_all_tags() y la cabecera ya no apunta a una carpeta de traducciones que no se incluye.
* ES: Edición de WordPress.org: la guardia de checkout de esta edición ya no incluye la opción de CAPTCHA externo opcional — protege el formulario solo con sus comprobaciones locales (trampa invisible, tiempo mínimo de relleno, limitador de intentos de pago y bloqueos de IP), así que en el checkout no se carga nada desde servidores de terceros.

= 1.25.0 =
* WordPress.org edition: the AI Guardian is advisory only in this edition — it classifies attacks and writes its report, but it never applies IP blocks or any other change ordered by the remote service, and no network reputation feed is downloaded or applied. Every block this edition enforces is decided locally by the plugin itself.
* NEW — Deep file scan: every file, one by one, on demand and weekly. Core files (wp-admin, wp-includes) are compared against the OFFICIAL WordPress checksums for your version — modified is critical, unknown or missing is flagged; if the checksum service is unreachable, the core falls back to the local baseline and the panel says so. Plugins, themes, mu-plugins and loose PHP are compared file-by-file against a baseline photo (the exact file that changed, appeared or vanished — the daily change watch only knew the folder). Executable files found inside uploads are critical. PHP code in wp-content is also checked for high-risk patterns (eval, gzinflate, commands fed from visitor input, very long base64, remote includes, known shell markers) — reported as a SUSPICION, never as confirmed malware. The scan runs in chunks so it survives shared-hosting time limits, deletes and changes NOTHING, emails the admin when it finds critical items, and any exact file can be marked "known" so it is not flagged again unless it changes. Pattern checks skip vendor folders.
* ES: NUEVO — Escaneo profundo de archivos: cada archivo, uno por uno, a petición y cada semana. Los archivos del núcleo (wp-admin, wp-includes) se comparan con las sumas OFICIALES de WordPress para tu versión — modificado es crítico; desconocido o ausente queda señalado; si el servicio de sumas no responde, el núcleo cae a la línea base local y el panel lo dice. Plugins, temas, mu-plugins y PHP suelto se comparan archivo a archivo contra una foto base (el archivo exacto que cambió, apareció o desapareció — la vigilancia diaria solo conocía la carpeta). Un ejecutable dentro de uploads es crítico. El código PHP de wp-content pasa además por patrones de alto riesgo (eval, gzinflate, comandos alimentados desde la entrada del visitante, base64 muy largo, includes remotos, marcadores de shells conocidas) — reportado como SOSPECHA, jamás como malware confirmado. El escaneo corre por trozos para sobrevivir a los límites de tiempo del hosting compartido, no borra ni cambia NADA, avisa por correo si encuentra críticos, y cualquier archivo exacto puede marcarse «conocido» para no volver a señalarlo salvo que cambie. Los patrones saltan las carpetas vendor.

= 1.24.0 =
* NEW — Country Guard: block visits from the countries you choose, right at the door. The country comes only from Cloudflare's CF-IPCountry header — a site that is not behind Cloudflare sees no country and the module stays inert instead of guessing. Off by default and switched on per site in its own panel card, with the country list validated against ISO codes. Logged-in administrators, allowlisted IPs and verified good bots are never blocked, and blocks are counted per country and day without storing visitor IPs. Nothing about these blocks is reported to the network.
* ES: NUEVO — Bloqueo por país: cierra la puerta a las visitas de los países que elijas. El país se lee solo de la cabecera CF-IPCountry de Cloudflare — un sitio que no esté detrás de Cloudflare no ve país y el módulo queda inerte en vez de adivinar. Apagado por defecto y encendido por sitio en su propia tarjeta del panel, con la lista validada contra los códigos ISO. Nunca se bloquea a administradores conectados, IPs de la lista blanca ni bots buenos verificados, y los bloqueos se cuentan por país y día sin guardar las IPs de los visitantes. Nada de estos bloqueos se reporta a la red.

= Earlier versions =
* 1.23.0 – 0.1.0: progressive rollout of the deep file scan, order anti-fraud, checkout guard, payment monitoring, hardening toolkit and the plain-language dashboard. Full history is kept in the changelog inside the plugin package.

== Upgrade Notice ==

= 1.25.4 =
Security and reliability fixes. Settings, consent, scan history and recognized files are retained. DNS bot verification now requires explicit permission. An unfinished 1.25.3 scan queue is discarded; start a new scan after upgrading.

= 1.25.3 =
The Deep file scan's official WordPress checksum check is now opt-in (off by default): core files are verified against the local baseline unless you enable the option in the Deep scan card. Includes the plugin review fixes for script enqueueing, file paths and output escaping.

= 1.25.2 =
Documentation and panel wording corrected: in this WordPress.org edition the AI Guardian is advisory only, the Guardian server address is no longer configurable, and the external-services data disclosure is exact. No security logic changed.

= 0.1.0 =
Initial release.

== Scan limits and verification ==

Deep scans process directory discovery and file checks together, normally at most 600 entries or 8 seconds per step, with a total cap of 50,000 directory entries per scan. Files over 10 MiB are not content-hashed; pattern inspection is limited to 2 MiB. Symlinks below configured roots are not followed. Cache, upgrade, .git and node_modules directories are excluded. If a file cannot be read, a symlink is encountered, or a size/entry limit is reached, the result is marked partial and the previous baseline is retained. Findings are capped at 500 and the panel shows the first 30. A clean or partial report is not a guarantee that the site is uncompromised.

Daily directory snapshots stop after 4,000 files per directory, a two-second traversal budget or a twelve-second overall processing budget. Incomplete snapshots do not overwrite their baseline; use the deep scan for a detailed review. Network requests have their own timeouts, so request duration is not a strict wall-clock guarantee.

Version 1.25.4 is validated with automated PHP and isolated WordPress Playground tests as described in its accompanying validation report. Playground uses PHP WebAssembly and SQLite and does not reproduce a production Apache/Nginx, MySQL, mail, payment or external Guardian environment.
