=== ATV Web Security ===
Contributors: atvsoftwarelabs
Tags: security, protection, malware, two-factor, ai
Requires at least: 6.0
Tested up to: 7.1.3
Requires PHP: 8.0
Stable tag: 1.0.53
License: GPL-2.0-or-later
License URI: https://www.gnu.org/licenses/gpl-2.0.html
Donate link: https://shop.atvsoftwarelabs.com/product/support-us/

Block persistent changes on a compromised WordPress site — with optional AI-assisted false-positive filtering.

== Description ==

ATV Web Security puts your WordPress website into a "protected" state where visitors can still read and use the site, but nothing can persist changes to it — not plugins, not compromised administrators, not direct database access, and not a PHP shell.

**AI-assisted false-positive filtering (new in 1.0.51).** Detection is only useful if you can tell an attack from WordPress doing its job. ATV Web Security can send metadata about a finding to Groq, using your own free API key, and show a plain-language verdict beside it: benign, suspicious or unknown, with a confidence, a risk level and a one-sentence reason. New files are reviewed as they are found; intrusion events can be reviewed with one click or automatically every five minutes. The verdict appears in the Integrity tab, the intrusion log and the dashboard widgets, so the answer sits next to the finding. The feature is optional, off by default, metadata-only, advisory and fail-open — see "AI false-positive filtering (Groq)" below for setup, payload and limits.

How it works — multiple independent layers:

* WordPress protection — plugin/theme/core operations, file editors, user creation, option writes and administrator actions are intercepted and denied.
* Database protection (manual) — revokes the database account's write privileges at the MySQL/MariaDB server level through a separate privileged account, keeping row-level INSERT/UPDATE/DELETE for allowed flows. The site account's own GRANT authority is never consumed, and an SQL firewall blocks writes when privileges cannot be changed. No tier turns this on.
* Filesystem protection (manual) — makes wp-config.php and .htaccess read-only and marks them plus the signing key immutable with chattr where supported, restoring the original permissions when switched off. wp-admin, wp-includes, plugins and themes stay writable so WordPress can update, with changes caught by integrity monitoring and the new-file watch. No tier turns this on.
* Upload protection — executable uploads are blocked by extension, MIME and content, and the uploads directory is hardened so scripts cannot execute there.
* API protection — REST, AJAX, XML-RPC, WP-CLI and cron-based mutation is blocked; reads remain available.
* PHP firewall integration — a small mu-plugin rejects traffic under wp-includes, blocks links to private files and neutralises low-level PHP tricks.
* Integrity monitoring — baseline hashes of core, configuration and plugin files are verified periodically and on demand.
* New-file and new-table watch — a scheduled scan reports files and database tables that were not there before. Each finding shows the path, detection time and size, with Dismiss and Delete after review; anything a WordPress core, plugin, theme or translation update explains is listed with its cause instead of being announced. Installs and updates performed outside WordPress are recognised too. Scan interval, email delivery and recipients are set on the Integrity tab.
* AI false-positive filtering (optional) — sends file-change and intrusion-event metadata to Groq with your own API key and labels each finding benign, suspicious or unknown with a confidence, risk level and one-sentence reason. Reviews are advisory: nothing is deleted, quarantined, blocked or dismissed automatically, every request fails open, and the feature stays off until you add a key.
* Access rules (optional) — AbuseIPDB-powered IP reputation blocking and a login-country rule, both off by default, with an IP/CIDR allowlist, fail-open lookups and caching.
* Backend lock — the plugin has its own top-level menu; once protection is ON and a master password is set, the settings stay behind a lock screen until that password is entered (12-hour unlock, forged-cookie safe, brute-force rate limited). The master password accepts 8-64 letters, digits and symbols and is the single password accepted to turn protection OFF.
* Email verification code (Two-Factor, optional) — a six-digit code emailed to administrators in addition to the WordPress password, entered on the login form itself. Codes last 10 minutes, can be resent once a minute (five per quarter hour), and the account locks for 15 minutes after five wrong entries. If the mailer cannot deliver, login stays blocked on purpose; recover with wp atvws otp disable.
* Passkeys / WebAuthn (optional) — registers a hardware-backed credential with Windows Hello / TPM, Touch ID, a phone or a security key. The private key never reaches the site, a cookie, JavaScript or a backup. With enforcement on, protected administrator logins are accepted only from a device whose passkey verifies; an account with no passkey is never blocked, and recovery stays available. A passkey also satisfies the device lock and replaces the emailed code.
* Trusted device lock (optional) — binds protected actions to one computer with a one-time token in a secure HttpOnly, SameSite cookie. Other computers get a "link your device" screen that requires the master password, and linking/unlinking always requires it. The Recovery tab stays reachable, so a lost device cannot lock the owner out permanently.
* Behavior policy (optional) — scores privileged activity per source IP over 24 hours and locks the session when the risk crosses a threshold: failed unlock (15), failed disable attempt (25), failed restore attempt (20), failed login (20), refused passkey login (10). The owner is never scored and can clear a lock with the master password.
* Cryptomining defence — strips miner script tags from rendered pages, refuses WordPress HTTP requests to pool domains, scans wp-content for native executables and miner markers, and searches posts and options for injected script blocks. The scans are report-only; nothing is quarantined by a heuristic match.
* Detection & monitoring — a signed login-page script/stylesheet baseline, a self-probe for exposed backups, dumps, dotfiles and debug logs, honeypot decoys with escalating temporary bans, and a local inventory of outdated, abandoned or delisted plugins and themes.
* Snapshot backup and restore — a signed copy of every file WordPress can change plus a full database dump with real CREATE TABLE schema. A snapshot is only saved after it validates row dumps, row counts and a working siteurl. Keep unlimited named snapshots plus automatic ones — daily, weekly, monthly, chosen weekdays or off — and delete the automatic copies in one click without touching the current or named snapshots. Nothing is deleted automatically. Restore requires protection and both manual write locks to be off, refuses a damaged or incomplete snapshot, quarantines extra files, drops extra tables, replays every row in a transaction and rolls back with the exact MySQL error on failure.
* Live progress — snapshot create, snapshot restore and integrity scans show a stage, item count and percentage while the operation runs.
* Total protection score — one number out of 100 on the Dashboard and on every screen. Points are earned only for verified active settings, so the score drops when a layer stops working, and the Dashboard lists what is still pending, what it is worth and which tab fixes it.
* Setup tour — a guided walkthrough through Diagnostics, Set protection level, Snapshot and the remaining configuration screens.
* Clear layout — screens are grouped into Everyday, Configure, Check and Incident, with a live protection badge, plain-language button descriptions and destructive actions separated from safe ones.
* Recoverable — reset a forgotten master password from the plugin's runtime directory (emergency-reset.key + emergency-reset.php) or with wp atvws password reset. Both sign out every session and are logged. WordPress account passwords can only be reset from WP-CLI, and email-code settings can be switched off with wp atvws otp disable.

Protection tiers:

* MEDIUM and STRONG apply the same WordPress-level layers: WordPress, REST, AJAX, XML-RPC, upload, PHP shielding, integrity, CLI and cryptomining defence. Neither touches database grants or file permissions.
* LIMITED means protection is on but a core layer is switched off or failed to verify; the dashboard shows which one.

Database and filesystem write protection are separate manual switches on the Dashboard. No tier turns them on, and changing tiers leaves them as they were; both require protection to be on. The database lock revokes write grants where a privileged MySQL account is configured (the wizard or ATVWS_DB_ADMIN_* constants) and reports partial when only the SQL firewall applies; the site account's GRANT authority is never consumed. The filesystem lock makes wp-config.php and .htaccess read-only and marks them plus the signing key immutable via chattr where available, restoring the original modes when switched off. wp-admin, wp-includes, plugins and themes stay writable so WordPress can update, with changes reported by integrity monitoring and the new-file watch.

Choosing or changing a tier requires the master password, so a hijacked admin session cannot quietly weaken the site. Every layer also has its own switch for fine-tuning, and picking a new tier resets those switches. The old names STANDARD, AUTO and HARDENED still work and map to Medium and Strong.

Allowed writes:

Persistent visitor flows (comments, contact forms, WooCommerce, user registration) are BLOCKED by default. Re-enable only what the site needs from the "Allowed Writes" page; everything else stays blocked.

Turning protection OFF is deliberately difficult: submit a form, confirm a checkbox, type the exact phrase and re-enter your account password (plus an optional passphrase). Emergency recovery paths (WP-CLI, a wp-config constant, a recovery file or manual panel instructions) are documented in docs/RECOVERY.md.

== AI false-positive filtering (Groq) ==

ATV Web Security can ask an AI model to review a finding and suggest whether it looks like ordinary activity or deserves a closer look. The feature is optional, off by default, and uses **your own Groq account**: there is no shared key and no request is paid for or proxied by the plugin author.

It reviews new files that no WordPress, plugin, theme or translation update explains, and intrusion events (BLOCKED, DETECTED or BYPASSED) that the plugin cannot judge with a deterministic rule. Every review returns benign, suspicious or unknown, a confidence percentage, a risk level and a one-sentence reason, shown beside the file on the Integrity tab and beside the event in the intrusion log.

**Reviews are advice, not action.** Nothing is deleted, quarantined, blocked, dismissed or emailed differently because of a review. The optional "Auto-explain high-confidence benign files" switch only changes how an alert is presented after its confidence threshold is met, and Dismiss and Delete remain manual.

How to configure it:

1. Create a free API key at https://console.groq.com/keys.
2. Open **ATV Web Security → Integrity** and find the **AI false-positive filtering (Groq)** card.
3. Paste the key into **Groq API key**, tick **Enable AI triage**, leave **Model** on *Automatic — best free model* (or choose any model your key can access), then click **Save AI settings**.
4. Click **Test connection**. The plugin validates the key against Groq's model list and tests a model the account can actually use, so a retired model id does not fail silently.
5. Choose **Review new files** and **Review intrusion events**. Intrusion review mode is **On demand** by default, which adds a *Show AI review* button to each unreviewed event; **Automatic** runs a background review every five minutes.
6. Click **Triage pending now** to label findings already waiting.

What is sent — metadata only:

* New file: path relative to the installation, extension, directory, size, modification time, and whether it is in uploads, a known cache directory, plugins or themes.
* Intrusion event: outcome, layer, action, target (150 characters, with query values named token, key, nonce, password, pass or auth replaced by `[REDACTED]`), target kind, static-asset and plugin/theme/uploads flags, whether a user was attached, role, hour of day, and an HMAC-SHA256 hash of the IP address.

Never sent: file contents, POST bodies, database rows, usernames or passwords, raw IP addresses, or any other site content.

Reliability and limits:

* Every request fails open. If Groq is unreachable, the key is rejected or the daily quota (100 requests by default) is reached, alerts stay exactly as they were and the card shows the last error.
* After an HTTP 429 the plugin pauses requests for 90 seconds and writes one warning per distinct failure per 30 minutes instead of flooding the Security Log.
* Reviews are cached per finding, so nothing is re-sent on every run; labels from older prompts are refreshed automatically. Clearing **Enable AI triage** stops all requests.

See **External services** below for the data-processing details and Groq's terms and privacy policy.

== Installation ==

1. Upload the `atv-web-security` folder to `/wp-content/plugins/`.
2. Activate the plugin through the Plugins screen.
3. Under the new top-level "ATV Web Security" admin menu, follow the setup tour: review the Diagnostics tab, then click "Turn ON Protection".
4. Store the recovery token that is displayed once.
5. Configure "Allowed Writes", "Protected Admins" and "Two-Factor" to match your site.
6. Optional: connect AI triage from the Integrity tab — paste a Groq API key, choose what to review, save, then click "Test connection". Leave it unconfigured to keep AI triage off. Details in the "AI false-positive filtering (Groq)" section above.

More detail: docs/INSTALL.md and docs/CONFIGURATION.md.

== Frequently Asked Questions ==

= Can visitors still read the site? =
Yes. The site remains fully readable and functional for browsing. Only persistent changes are blocked.

= What happens while protection is ON? =
Users (including administrators) can browse, read and perform allowed writes. Plugin, theme, core updates, file and database changes that are not explicitly allowlisted are blocked. Turn protection OFF to build, update or modify anything.

= How do I turn protection OFF? =
Use the Dashboard tab and follow the strong-disable form, or use one of the emergency recovery methods described in docs/RECOVERY.md.

= Which password is accepted to turn protection OFF? =
The master password (8-64 letters, digits and symbols) is accepted, and so is your WordPress account password as a fallback — so a site that never configured a master password is never locked out.

= How does the emailed verification code work? =
When enabled, administrators are asked for a six-digit code sent to their email address after their password is accepted. The code field appears on the login form itself, so no page refresh is needed and every step stays on one screen. A code is valid for 10 minutes, can be resent once a minute (five codes per quarter hour), and the account locks for 15 minutes after five wrong entries.

= What if I cannot receive the emailed code? =
The login stays blocked on purpose rather than silently downgrading to password-only. Recover from the shell with wp atvws otp disable (or re-enter the master password on an already-unlocked session).

= Passkey or email code — which do I need? =
Either factor alone satisfies the check. An account covered by a registered passkey skips the emailed code, and the passkey is hardware-bound so it survives cookie clearing and cannot be copied. Use the two-factor email code when a browser cannot do WebAuthn.

= Do I need a passkey, or is the device token enough? =
The device token is bound to the browser profile: clearing cookies or switching browsers unlinks it, and a copied cookie could be replayed. A passkey is bound to the device's secure hardware, so it survives cookie clearing and cannot be copied. If you can only pick one, pick the passkey; keep the token as the fallback for browsers that cannot do WebAuthn. Enforcement is off until you turn it on, and no account is ever blocked without a registered passkey.

= What does the Miners tab do? =
It reports cryptomining findings without touching anything: script tags naming mining services or pools are removed from rendered pages, WordPress's HTTP API is refused for pool domains, a filesystem scan flags native executables and miner configuration markers, and a database scan looks for injected script blocks. Every result is surfaced on the Miners tab for you to review and act on.

= How does the vulnerability checker decide what is abandoned? =
It measures locally, with no third-party call: a release older than two years is flagged as unmaintained, a plugin or theme still on disk but no longer listed in the wordpress.org API is flagged as closed, and the local modification time of the plugin directory cross-checks both. An online feed lookup exists but is opt-in and requires your own API key — nothing phones home about the site by default.

= Is my database really read-only? =
Only when you switch the manual database write lock on. With a privileged MySQL account configured it revokes the database account's write privileges and verifies the result; without one it still blocks write queries from PHP through the SQL firewall and reports the lock as partial. No tier turns this lock on. Details in docs/INSTALL.md and docs/SECURITY_LIMITATIONS.md.

= What about caching plugins? =
Cache plugins are confined to an explicit allowlist of cache directories; other paths stay read-only. See diagnostics for the ongoing compatibility status.

= What does a restore need before it will run? =
Protection OFF, and both manual write locks (Database and Filesystem) OFF. The Database lock's SQL firewall refuses the DROP and CREATE statements a restore needs, and the Filesystem lock makes wp-config.php and .htaccess read-only, so a restore under either lock would silently do half its job — the Snapshot tab tells you which switch is still on. The snapshot is also verified first: a damaged one, one missing a dump of any live WordPress core table, or one without the schema needed to recreate a missing table is refused before anything changes.

= Can a restore break my site? =
Every database write is checked and the whole row replay runs inside a transaction (InnoDB), so a failed restore rolls back to the previous state and shows the exact MySQL error instead of leaving half-restored tables. Files that are not in the snapshot are moved to the plugin's quarantine folder, never destroyed immediately. The restore runs while the site is live, so a visitor can write a row mid-restore; the snapshot's copy wins that collision, and restoring during a quiet period gives the cleanest result. Snapshots made before version 1.0.48 lack the real schema files — restore only from snapshots taken with 1.0.48 or later.

= Why does WordPress say "One or more database tables are unavailable"? =
That message appears when core tables exist but the options table cannot supply a non-empty siteurl, and the built-in repair page cannot fix it because it never inserts missing rows. With 1.0.48+ a restore verifies siteurl before committing, so it cannot cause this state anymore. If you see it anyway, docs/RECOVERY.md has the exact SQL to restore siteurl and home through phpMyAdmin.

= Is the AI feature required? =
No. AI triage is off until you add your own Groq API key on the Integrity tab. Without it, new files, tables and intrusion events are detected and reported exactly as before — the AI only adds an opinion next to a finding.

= What exactly is sent to Groq? =
Metadata for the single finding being reviewed: for a file, its relative path, extension, directory, size, modification time and location flags; for an intrusion event, the outcome, layer, action, target, target-type hints, whether a user was attached, role, hour of day and an HMAC-SHA256 hash of the IP address. Query-string values named token, key, nonce, password, pass or auth are redacted. File contents, POST bodies, database rows, usernames, passwords, raw IP addresses and site content are never sent.

= What happens if Groq is unreachable or the key stops working? =
Nothing is lost. Every AI request fails open: alerts remain exactly as they were, the review stays pending, and the AI card shows the exact error. A batch stops at the first quota, key, model or rate-limit error instead of retrying the rest, and requests pause for 90 seconds after HTTP 429.

= Can the AI delete, quarantine or dismiss a finding? =
No. Reviews are advisory. Nothing is deleted, quarantined, blocked or dismissed because of a review. The optional "Auto-explain high-confidence benign files" setting only marks a file as explained at the confidence threshold you choose; Dismiss and Delete still require your click, and File watch never deletes anything by itself.

= Which Groq model is used, and does it cost anything? =
The plugin uses your own Groq account and key. With **Model** set to Automatic it asks Groq which free models the key can use and picks one of those; you can also select a model explicitly. The plugin limits itself to 100 requests per day by default and caches every review, so re-opening a page does not spend new requests. Any usage limits or costs set by Groq on your account still apply.

== External services ==

This plugin can connect to two external services. Both are optional and off by default, and each is used only while the corresponding feature is on: AbuseIPDB for IP intelligence and Groq for AI-assisted false-positive filtering.

= AbuseIPDB =

AbuseIPDB provides an IP reputation and geolocation look-up for the site-wide IP reputation block and the login country check, only when those features are switched on. The visitor's IP address and your AbuseIPDB API key are sent when a protected request is checked. No other data is sent. Lookups are rate-limited and cached; if a lookup fails, the request is allowed (fail-open) and the failure is logged.

This service is provided by "AbuseIPDB LLC".

* Terms of use: https://www.abuseipdb.com/legal
* Privacy policy: https://www.abuseipdb.com/privacy

= Groq =

Groq provides the hosted language model behind the optional AI false-positive filtering feature, used only after you paste your own Groq API key on the Integrity tab and enable AI triage. The plugin author does not run a proxy, hold a shared key, or receive the data.

Groq runs an inference service for open language models. The plugin sends metadata about one finding and receives a JSON review: verdict, confidence, risk level and a one-sentence reason, stored beside the finding. No result is required for the site to work; if a request fails, the finding stays as it was and the failure is logged (fail-open).

Data sent: your API key in the request header, plus the metadata described in the AI section above — for a new file, the relative path, extension, directory, size, modification time and location flags; for an intrusion event, the outcome, layer, action, target (150 characters, secret query values redacted), target hints, user/role flags, hour of day and an HMAC-SHA256 hash of the IP address. No file contents, POST bodies, database rows, usernames, passwords, raw IP addresses or other site content are sent. Calls stop at 100 per day by default and pause after HTTP 429.

This service is provided by "Groq LLC".

* Terms of use: https://console.groq.com/docs/legal/services-agreement
* Privacy policy: https://groq.com/privacy-policy
* API keys: https://console.groq.com/keys

== Changelog ==

= 1.0.53 =
* Fixed an infinite recursion in the database query filter. Reading the protection state consults the database mirror, and that read was itself passing back through the SQL firewall; with a cold options cache every level issued the same SELECT until the request exhausted memory and the PHP error log filled. The state is now read once per request and guarded against re-entry, so the firewall can no longer call itself. Sites with the database write lock switched on should update.

= 1.0.52 =
* Automatic backups are now configurable. On the Snapshot tab you can choose daily, weekly (a specific weekday), monthly (a specific day of the month, including "last day") or any combination of calendar weekdays. Every run happens at 03:23 in the site's own timezone.
* Automatic backups can be switched off from the same card. Turning them off keeps the snapshots already stored.
* Added "Delete automatic backups", which removes only the automatic snapshots and leaves the current recovery snapshot and every named snapshot untouched.
* The schedule is stored in the signed state file, and the cron event is re-armed automatically if it is ever removed. Existing daily schedules keep working and are converted on the next admin page view.

= 1.0.51 =
* Added AI-assisted filtering for new file changes and intrusion log events via Groq (metadata only, opt-in, fail-open). New files are reviewed automatically during the scan; intrusion events are reviewed on demand, with a background pass that still labels routine noise without spending an API call.
* Intrusion events the plugin can judge without a model are now labelled as noise automatically: blocked WordPress cron scheduling and blocked writes to cron, recently_activated or transient options, plus new files that a recorded core, plugin, theme or translation update explains. A webshell-style file name is never explained away by an update.
* The intrusion log now has a "Show AI review" button on each unreviewed event and a "Review pending events on this page" button, and the AI card offers an Intrusion review mode: On demand (default) or Automatic. The AI review request itself now also tells the model whether the target is a URL, a path or an identifier, whether it is a static asset, and whether it sits in plugins, themes or uploads.
* AI triage now stops at the first quota, key, model or rate-limit error instead of retrying the rest of the batch, pauses calls for 90 seconds after HTTP 429, and writes one warning per distinct failure per 30 minutes with the API error in the message, so a failing key no longer floods the Security Log with identical rows.
* The AI model is picked automatically from the free models the Groq account actually has access to, and the selected model is honoured when one is chosen manually.
* Test Connection now validates the API key against Groq's model list and tests only models available to the account, so a retired model id no longer produces an unexplained HTTP 404.
* Fixed HTTP 400 "Failed to validate JSON" with reasoning models such as openai/gpt-oss-120b: the connection test no longer caps the reply at 10 tokens, reasoning effort is lowered for those models, and both the test and triage retry once without strict JSON mode if Groq rejects the generation. Every prompt now contains the word JSON, which Groq requires in JSON mode, and the "must contain the word 'json'" rejection is retried the same way.
* Fixed AI triage never running: the background job and "Triage pending now" aborted on an internal property access, so no file or event ever received a review. Triage also no longer re-reviews the same newest events on every run.
* The Intrusions tab now renders the AI Review cell (verdict, confidence, reason) instead of an empty column, and the New files cards on the Integrity tab and WordPress dashboard show the AI verdict once triage has run.
* AI triage failures are no longer silent: the AI card shows whether triage is on, whether a key is saved, the last triage run, the next scheduled run and the last error, and both tabs explain why a finding is still pending (AI off, no key, or the exact API error). "Triage pending now" reports the error instead of claiming there was nothing to review.
* Fixed the AI key appearing unconfigured after saving, keys left double-encoded by earlier builds now read as "not configured" instead of sending garbage to Groq, and the AI test buttons work.
* AI reviews now carry protection context: a BLOCKED write (including WordPress's own cron and option updates) is treated as the protection working, not as an attack, so those events are labelled noise or low risk with confidence capped at 70. The AI is no longer allowed to invent users, accounts, IPs, plugins, CVEs or file contents it was not given.
* File reviews now report a risk level and an action hint, and old reviews are refreshed automatically: bumping the review version makes the next triage run replace labels produced by earlier prompts.
* Intrusion reviews now show the risk level and the suggested action (no action needed, review, investigate now) next to the verdict.
* New files are now AI-reviewed during the scan that finds them (up to three per scan), so the alert table and the notification email carry the verdict instead of "Pending triage". The scheduled triage still reviews the rest and retries failures.
* Notification emails now wait about two minutes and re-check update causes before sending. Files written while a theme or plugin update is still copying are therefore explained by the completed update instead of being emailed as a possible intrusion.
* On the Integrity tab, files explained by an update no longer show "Pending triage" in the AI review column, and unexplained files are listed above the explained ones.
* Redesigned the Integrity tab: settings and watch status now sit side by side with file, table and finding totals, the new-file and new-table alerts use full-width tables with the file name, relative folder, cause and AI verdict in separate columns, and the integrity, quarantine, cleanup and AI controls are grouped into clearly titled cards. Paths inside the installation are shown relative to the site root so long absolute paths no longer dominate the table.

= 1.0.49 =
* Fixed the new-file alert overlapping the Cause/Action columns on the Dashboard and Integrity tabs: file paths in alert tables contain no spaces, so they could not wrap and stretched the table. Paths now break inside their own cell, including in the wp-admin notice and the WordPress dashboard widget.

= 1.0.48 =
* Fixed snapshot restore leaving the site with "One or more database tables are unavailable. The database may need to be repaired." Every table is now emptied and refilled inside a transaction (InnoDB), every inserted row is checked, the restored options table must contain a non-empty siteurl, and any failure rolls the database back instead of being reported as a successful restore. The repair page could never fix this because the missing row was siteurl itself.
* Snapshots now store the real CREATE TABLE statement for every table. The previous code wrote only the table name into each schema file, so a table that had been deleted could never be recreated.
* Snapshot creation now refuses to save an incomplete backup: it verifies that every row dump decodes, that the row counts match, and that siteurl is present.
* Extra files are now actually removed during a restore. The whole web root (not just .php/.txt) and wp-content drop-ins are covered, anything not in the snapshot is moved to the quarantine folder, and files that cannot be moved are reported instead of silently skipped.
* Extra database tables are dumped to a restore-audit folder and then dropped, with each DROP checked. Tables present in the snapshot but missing from the site are recreated from the stored schema.
* Restore is refused while protection or the Database/Filesystem write lock is on. Those locks were silently blocking the DROP/CREATE and file writes a restore needs, which is why extras survived and tables came back empty. Turn both off before restoring.

= 1.0.47 =
* Dashboard layout pass to match the approved design: a wider left column, roomier cards and table rows, pastel hero stat tiles, card-style pending items with numbered circles, and the Save menu setting button moved into the Plugins menu card header.
* Integrity now sits on the second navigation row beside Miners, Intrusions, Security Tests, Security Logs and Recovery.

= 1.0.46 =
* Each unexplained file alert now has a direct Delete button beside Dismiss, on the Dashboard card and the Integrity tab. Delete removes the file from disk after an explicit confirmation, then clears the alert and its snapshot entry so a file recreated at the same path is reported again. Only a path that still matches a stored alert and sits inside the WordPress installation can be deleted.
* Rearranged the Dashboard into two widget columns: the score, file watch, points, protection summary and layer table on the left; the Plugins menu, turn-off card, pending items, quick actions, tier chooser and recent activity on the right.
* New-file and new-table action rows keep their buttons aligned and wrap cleanly on narrow screens.

= 1.0.45 =
* New-file and new-table notifications now report only changes that nothing explains. Files and tables added by a plugin, theme, WordPress core or translation update stay listed on the Integrity tab with their cause, but no longer trigger dashboard notices or emails.
* A plugin or theme installed or updated outside WordPress (FTP, cPanel, a host-side updater) is now recognised by comparing plugin, theme and core versions between scans, so its files are not reported as unexplained.
* Alerts recorded before an update event existed are reclassified once the event arrives, and when this version first runs, existing alerts that live inside an installed plugin or theme directory are marked as explained.
* Email digests list only unexplained paths and state how many other files or tables were explained by an update.
* A bulk plugin update can no longer push an unexplained file out of the bounded alert list.

= 1.0.44 =
* Added a new-table watch alongside the new-file watch. Each scan compares the database table list with a signed baseline and reports tables that were not there before.
* Every new table is classified: a WordPress core table, created by a recent plugin or theme update, matching an installed plugin, or not explained. Unexplained tables are also recorded as DETECTED in the Intrusion log.
* Table alerts appear in the dashboard widget, on the plugin dashboard and on the Integrity tab, and are emailed in their own digest (capped at 100 tables).
* File and table notifications now have a Dismiss button per row, plus Dismiss all, on the dashboard, the WordPress dashboard widget and the Integrity tab.
* The first scan after updating records the table baseline, so tables already present are not reported.

= 1.0.43 =
* Email delivery: notification messages now use a sender on the site's own domain and set the administrator address as Reply-To, so shared-host mail filters stop rejecting them.
* A failed send is no longer silent. The reason reported by the mailer is stored, written to the log, and shown on the Dashboard and Integrity tabs next to the last attempt. The Send test email button now reports that same reason.
* Added a Dashboard switch for the Plugins menu. The Plugins screen can stay visible while protection is on, for reference. Plugin activation, deactivation, updates, deletion, installs and the code editors remain blocked.
* Bulk plugin actions (activate, deactivate, delete, update selected) and their action2 variants are now blocked explicitly.
* When the Plugins screen is visible, its per-plugin Activate/Deactivate/Delete/Edit links are removed so the screen offers no action that ends in a block page.
* New installations default to a 15-minute scan interval; existing installations keep their saved value.

= 1.0.42 =
* Fixed new-file alerts appearing to do nothing. The watch now records its baseline at activation instead of on the first admin page view, runs every five minutes through WP-Cron with a configurable interval, and rescans when the plugin screen is opened (at most once a minute).
* The plugin dashboard now always shows the new-file watch state: last scan, next automatic scan, files watched, email recipients, whether the last email was delivered, and a Scan now button. The WordPress dashboard widget also has Scan now.
* Findings are shown as a wp-admin notice on every admin screen, not only inside the plugin page.
* Added a Send test email button and a visible last-email result so a broken server mail setup no longer looks like "nothing was found".
* Reduced automatic scan interval from one hour to 15 minutes (selectable from 5 minutes to 6 hours) and replaced the hourly cron event with a five-minute recurrence.
* A watch that cannot write its snapshot now logs a CRITICAL entry instead of silently re-baselining on every scan.

= 1.0.41 =
* Fixed the plugin page opening blank on a fresh install. The first-run tour is now drawn in place instead of redirecting: WordPress has already sent the admin header when a menu callback runs, so the redirect could not be issued and ended the request with an empty content area.
* A page that fails while rendering now shows the error and records it in the plugin log instead of ending blank.
* Hardened the protected-administrator list against a malformed legacy value that would have failed every admin page before it could render.

= 1.0.40 =
* Added the new-file watch: the whole WordPress installation is scanned on a schedule, and every file that was not present before is reported with its full path, detection time and size, on the dashboard and by email.
* Each new-file alert states whether a WordPress core, plugin, theme or translation update recorded by the upgrader explains it, or whether no update does.
* Database and filesystem write protection are now manual Dashboard switches. No protection tier turns either of them on, and changing tiers leaves them exactly as they were.
* The database write lock is always available and reports partial when only the SQL firewall can be enforced; the filesystem lock refuses cleanly on hosts that cannot change file permissions.
* The protection score, status banner and documentation now reflect the manual locks; integrity points require a verified baseline.

= 1.0.37 =
* Maintenance release addressing WordPress.org plugin review feedback. No feature or behaviour changes.
* Admin stylesheet is now loaded with wp_enqueue_style instead of a printed raw style block.
* Theme and plugin headers are read with get_file_data() instead of file_get_contents().
* The AbuseIPDB external service is now documented, with links to its terms and privacy policy.
* Runtime, state and recovery paths now use wp_upload_dir() and WPMU_PLUGIN_DIR for custom and multisite layouts.
* Removed the global automatic-update filters; automatic updates are left to WordPress.
* Removed the automatic mu-plugin installer; the optional MU bootstrap is a manual copy.
* The miner-guard output buffer is now always closed.
* The top-level admin menu is placed lower (position 100).
* Remaining request inputs are sanitised and validated; output is escaped.

= 1.0.36 =
* Email verification code now appears as an inline field on the login form — no page refresh, the whole two-factor flow stays on one screen.
* Resend is throttled to once a minute and five codes per quarter hour; a failed delivery keeps the login blocked on purpose so the mailer cannot fail open.
* Codes are probed in the background on submit, with a clear error on the form when the code is wrong.

= 1.0.35 =
* Added email verification codes (Two-Factor): administrators can be required to enter a six-digit code emailed to them after the account password. Passkey-covered accounts skip the code — either factor alone satisfies the login.

= 1.0.34 =
* Allowed writes now defer to the SQL firewall's enforced rule server-side, so a server-level write block is verified against the same rule that actually runs.

= 1.0.0 =
* Initial release.

== Upgrade Notice ==

= 1.0.53 =
* Fixes an infinite recursion in the database query filter that could exhaust memory and flood the PHP error log while the database write lock was on. Recommended update.

= 1.0.52 =
* Adds a configurable automatic backup schedule (daily, weekly, monthly or selected calendar days), an off switch, and a one-click way to delete stored automatic backups without touching the current recovery snapshot or your named snapshots. Recommended update.

= 1.0.51 =
* Adds optional AI-assisted false-positive filtering using your own Groq API key: new files are reviewed as they are found, intrusion events can be reviewed on demand or automatically, and every verdict appears beside the finding. Also adds a redesigned Integrity tab and fixes the AI triage, notification timing and layout issues reported after 1.0.49. AI triage is off until you add a key; detection and protection behave as before without it. Recommended update.

= 1.0.49 =
* Stops long file paths in the new-file alerts from overlapping the neighbouring columns on the Dashboard and Integrity tabs. Recommended update.

= 1.0.48 =
* Fixes snapshot restore leaving the database without a siteurl (WordPress then shows "One or more database tables are unavailable") and failing to remove extra files and tables. Restore now verifies every row and rolls back on failure, and it must be run with protection and both write locks off. Create a fresh snapshot after updating. Recommended update.

= 1.0.47 =
* Polishes the Dashboard layout and spacing to match the approved design, and moves Integrity to the second navigation row. No functional changes. Recommended update.

= 1.0.46 =
* Adds a Delete button to each unexplained file alert and rearranges the Dashboard into two balanced widget columns. Delete asks for confirmation and only touches a file that still matches a stored alert inside the WordPress installation. Recommended update.

= 1.0.45 =
* Stops legitimate plugin, theme and WordPress updates from appearing in new-file notifications. Only files and tables that no update or installed plugin explains are reported; explained changes remain visible on the Integrity tab. Recommended update.

= 1.0.44 =
* Adds detection of new database tables with the same update-aware classification and email/dashboard alerts as new files, plus a Dismiss button on each notification. The first scan records the baseline; existing tables are not reported. Recommended update.

= 1.0.43 =
* Fixes new-file notification emails not arriving: site-domain sender, Reply-To, and a visible mailer error on failure. Adds a Dashboard option to keep the Plugins menu visible while protection stays enforced. Recommended update.

= 1.0.42 =
* Makes new-file detection prompt and visible: five-minute cron, a scan when the plugin screen opens, always-visible watch status, a Scan now button, admin-wide notices and a test-email control. Recommended update.

= 1.0.41 =
* Fixes the plugin page opening blank on a fresh install. Updating is safe; settings and protection state are untouched.

= 1.0.40 =
* Adds new-file detection with email and dashboard alerts, and moves database/filesystem write protection to manual switches. Database grants and file permissions are no longer changed by choosing a tier.

= 1.0.37 =
* Maintenance release for WordPress.org review compliance. No behaviour changes; updating is safe.
* If you already use the two-factor email code, nothing changes: the code field stays inline on the login form.