=== WP CodeScout Connector ===
Contributors: codescout
Tags: rest api, ai agent, remote management, developer tools, connector
Requires at least: 6.0
Tested up to: 6.8
Requires PHP: 7.4
Stable tag: 1.5.2
License: GPLv2 or later
License URI: https://www.gnu.org/licenses/gpl-2.0.html

Secure remote execution bridge that lets the Code Scout AI agent inspect and operate this WordPress site. No AI logic inside — the intelligence stays in Code Scout.

== Description ==

WP CodeScout Connector exposes a tightly controlled REST API (`/wp-json/codescout/v1/`) that allows the external Code Scout AI agent to:

* **Discover** the environment: WordPress version, plugins, themes, custom post types, taxonomies, REST routes, database tables — all dynamic, nothing hardcoded.
* **Operate files** with strict path validation: read, search, write (atomic), move, delete. `wp-config.php` and `.htaccess` are always protected; core directories are write-blocked by default; PHP files cannot be created in uploads.
* **Query the database** through `$wpdb` with server-side statement classification (READ / WRITE / DESTRUCTIVE), single-statement enforcement, `WHERE`-clause requirements and result caps. Transactions run inside one request.
* **Manage plugins and themes**: list, activate, deactivate, install (wordpress.org or uploaded zip with malware scanning and a full upload log), update, delete (destructive), scaffold new plugins and child themes.
* **Manage content generically**: any post type, taxonomy, term, user (with full user meta and bulk operations), media item, comment, option and post meta — including page-builder data such as Elementor's `_elementor_data`, stored with correct array types.
* **Run guarded PHP code** using the official functions of every installed plugin, and manage persistent code snippets (PHP / CSS / JS) with automatic fatal recovery (Safe Mode).
* **Get notified**: signed outbound webhooks for publishes, registrations, orders, comments and fatal errors, plus custom events.
* **Maintain the site**: one-click cache purge (Elementor, object cache, popular plugins), serialized-safe search & replace with dry-run, WP-CLI bridge, content export/import between sites, binary file uploads and a full site report digest.
* **Schedule automation**: named tasks (code or hook chains) on one-off, interval, daily or cron-expression schedules — scheduled through the official wp-cron APIs, with automatic failure disabling and a full run history.
* **Explore any plugin's API surface** statically — classes, methods, hooks, tables, options — before touching it.
* **Diagnose**: PHP/server health, WordPress debug status, debug-log tails and recent failures, so the agent can debug without the user pasting logs.
* **Snapshot and restore**: targeted file/table backups with explicit, non-automatic restore.
* **Trigger hooks and internal REST routes** that are already registered — never arbitrary code.

Every operation is permission-gated server-side, audit-logged, rate-limited and authenticated with a bearer token that is stored only as a hash and shown exactly once.

**This plugin contains no AI logic, no LLM calls and no prompts.** It is a generic, secure execution bridge; all reasoning happens inside Code Scout (https://codescout.online/).

== Security model ==

* Credential: cryptographically random token, hashed with `wp_hash_password`, rotatable, revocable, associated with a named administrator account.
* Transport: `Authorization: Bearer` header (or `X-CodeScout-Token` for hosts that strip the header). Never a query parameter. HTTPS strongly recommended.
* Brute force: 5 failed attempts per IP triggers a 15-minute lockout, plus a second counter of 20 failed attempts per connection ID across all IPs (so rotating source IPs does not bypass it); all failures are audit-logged.
* SQL hardening: MySQL versioned comments (`/*!...*/`, which MySQL executes) are rejected outright, and forbidden-construct checks run against the raw statement so guards cannot be hidden in comments. String literals are stripped before structural checks, so a `WHERE` inside a quoted string cannot satisfy the WHERE requirement.
* Permissions: 16 granular capabilities, enforced server-side. A separate master switch gates destructive operations (delete plugin/theme/user, permanent media/comment deletion, DROP/TRUNCATE, bulk deletions, full restores, PHP code execution).
* Protected options: `siteurl`, `home`, `admin_email`, user roles, plugin lists and connector config cannot be changed through the generic options endpoint — closing a token-revival path via password-reset email interception.
* Rate limits: separate budgets for general, file, database, backup and HTTP operations.
* Audit log: every request is recorded (operation, target, status, IP) and inspectable in the admin.
* Secrets never leave the server: no salts, no DB credentials, no plaintext tokens in any response; user password hashes are redacted in query results, and backup dumps are sanitized (password hashes plus credential-like option/meta values are written as `[redacted]`).
* Backup storage: unguessable random folder IDs under `wp-content/uploads/codescout-backups/`, protected with an `.htaccess` deny rule. On Nginx (which ignores `.htaccess`) add a matching deny block on your server; the random IDs and sanitized dumps act as the second layer.
* SSRF protection: outbound HTTP is restricted to an explicit host allow-list, private IPs are blocked after DNS resolution (for both the HTTP proxy and remote media fetches) and redirects are disabled.
* Multisite: connections are scoped to the site that generated them; table access is limited to that blog plus global tables.

== Installation ==

1. Upload the `wp-codescout-connector` folder to `/wp-content/plugins/` (or install the zip).
2. Activate the plugin through the 'Plugins' menu.
3. Open the new **Code Scout** menu in the admin sidebar.
4. Click **Generate New Credential**, copy the token (shown once), and enter the endpoint URL + connection ID + token into Code Scout.
5. Enable the permissions Code Scout needs for your task. Start with read-only permissions and grant write access deliberately.

== Frequently Asked Questions ==

= Can the connector survive a fatal error in another plugin? =

The connector is deliberately lightweight and independent, but no plugin can respond if WordPress or PHP itself fails to boot. The diagnostics endpoint clearly distinguishes connector, third-party, WordPress-bootstrap and server failures for every case it can observe.

= Can Code Scout edit wp-config.php? =

No. `wp-config.php` and `.htaccess` are hard-blocked for reading and writing, along with core root files and (by default) `wp-admin/` / `wp-includes/`. Database credentials are never exposed.

= Does the token get stored in plain text? =

Never. Only a bcrypt/argon2 hash is stored. The token is displayed exactly once at generation time; "Regenerate" rotates it.

= Can Code Scout read the audit log of its own operations? =

Yes, through `/audit` with the Diagnostics permission — transparency helps the agent verify its own work.

= Does it work on shared hosting? =

Yes. It needs only standard PHP/WordPress capabilities: no SSH, no cron daemons, no Node.js, no root. Heavy operations (backups, restores) are chunked and bounded, and transactions are scoped to a single request.

== Changelog ==

= 1.5.2 =
* New: built-in official update system. The Plugins screen checks the CodeScout update endpoint on load and installs new versions directly from WordPress.

= 1.5.1 =
* Fix (found in live testing): REST args declared with `type: array` rejected JSON objects on current WordPress versions ("params is not of type array"), breaking /rest/do-request with object params, /webhooks/trigger payloads, task hook chains and several bulk endpoints. All 17 such arguments are now type-free; handlers still validate server-side.
* Fix: Plugin Explorer now prioritizes the API surface within its scan cap - root plugin files and includes/src/classes directories are scanned before vendor libraries and tests, so classes like WC_Product are found in large plugins such as WooCommerce.
* Fix: admin UI - "Recent runs" and "WordPress cron" cards on the Tasks screen no longer clip their titles; settings save buttons no longer sit inside a stray bordered box.
* Verified live on a production site (WordPress 7.1.3, PHP 8.2, Elementor 4.3.4, WooCommerce 11.1.2): code execution, Elementor cache purge, WooCommerce product creation with nested meta via WC_Product_Simple, meta arrays stored as real arrays, snippet/task lifecycles, search-replace dry run, export/import, binary upload, reports, cron bridge.

= 1.5.0 =
* New: outbound webhooks — the site notifies Code Scout the moment something happens (post_published, post_deleted, user_registered, user_deleted, comment_posted, order_created, order_status_changed, fatal_error) plus any custom event via POST /webhooks/trigger. Deliveries are HMAC-signed, sent through wp-cron, retried up to 3 times with backoff, and URLs pass the same SSRF guard and host allow-list as every other outbound call.
* New: one-click cache purge (POST /cache/purge) — Elementor generated CSS, object cache and popular cache plugins (WP Rocket, LiteSpeed, WP Super Cache, W3TC, WP Fastest Cache, Autoptimize), reporting exactly what was found and cleared.
* New: WP-CLI bridge (POST /cli/run) — runs wp commands when the administrator configured a wp binary path and the host allows proc_open; every argument is escapeshellarg'd (no shell metacharacters), output is capped, and availability is announced honestly in features.wp_cli. Requires execute_code + destructive.
* New: serialized-safe search & replace (POST /database/search-replace) — dry_run by default, mandatory backup of affected tables before real runs, per-value unserialize/replace/reserialize so option arrays and builder data survive; object-bearing values are skipped for safety; 5000-row cap.
* New: content export/import (GET /content/export, POST /content/import) — move pages, posts and builder templates between sites with meta (credential-like keys excluded) and terms; import always creates new posts and returns an old-to-new ID map.
* New: binary file upload (POST /files/upload) — fonts, zips and other assets via base64 with the same path guards as /files/write and the higher upload_max_bytes cap.
* New: site report digest (GET /reports/digest) — updates, health, last-24h activity, failing tasks/snippets, approvals and backup state in one response, plus an optional daily email to the administrator (daily_report setting).
* 35 new unit tests covering webhook events, CLI tokenizing, serialized replacement edges (objects, b:0, lengths) and the report renderer.

= 1.4.0 =
* New: optional HMAC request signing — with "Require HMAC signatures" enabled, every request must carry X-CodeScout-Timestamp + X-CodeScout-Signature (HMAC-SHA256 over timestamp.body with the connection signing secret, 5-minute window, single-use replay guard). A stolen bearer token alone becomes useless. Off by default; credentials created in 1.4.0+ ship with a signing secret, older ones need one rotation.
* New: multiple connections — the administrator can issue additional tokens (each with its own label, linked admin, permission map, optional expiry and optional IP allow-list), pause/resume or revoke them separately, and edit any connection permissions from the same panel. The legacy primary connection and every existing client keep working unchanged.
* New: temporary permissions — any capability can carry an expiry timestamp (datetime field next to each permission). Expired grants are rejected server-side and shown as disabled in /capabilities.
* New: approval mode — destructive operations return HTTP 202 "pending" and wait for the administrator; the agent polls GET /approvals/get, receives a one-time token (15 minutes, bound to the route) and re-sends with X-CodeScout-Approval. Pending items appear as an admin notice + dashboard card with approve/reject actions and an email is sent for each queue event.
* New: tamper-evident audit log — every entry commits to its predecessor (prev_hash/row_hash, SHA-256). A "Verify chain" button on the activity log walks the chain and reports the exact broken entry; "Export page" downloads the log as JSON; legacy rows are backfilled on upgrade.
* New: per-connection IP allow-list, credential expiry (rejections: ip_not_allowed / token_expired) and an emergency kill switch that disables every connection at once (with email confirmation).
* New: optional email alert on every successful destructive operation (off by default).
* 28 new unit tests covering temporary grants, chain math, signature verification (stale/wrong/foreign/replayed) and connection lifecycle.

= 1.3.0 =
* New: scheduled tasks system — named units of automation (guarded PHP code or hook chains) with four schedule types: one-off, interval (min 5 min), daily at HH:MM (site time) and full 5-field cron expressions (including steps, ranges, lists and the dom/dow OR rule).
* New: scheduling runs on the official wp_schedule_* APIs via a self-healing 5-minute master sweep — the `cron` option is never written directly. Per-task overlap locks prevent doubled runs; each sweep is bounded to 10 due tasks.
* New: task API (`/tasks` CRUD, `/tasks/set-enabled`, `/tasks/run-now`, `/tasks/runs`) gated by the execute_code permission; run-now additionally requires the destructive switch.
* New: wp-cron bridge — `GET /cron/events` lists the site's scheduled events (with wp-cron health), `POST /cron/event/run` fires an event immediately, `POST /cron/event/delete` unschedules it.
* New: automatic failure handling — a task failing 3 times in a row is disabled and the administrator is emailed; one-shot tasks complete themselves; run history (status, output, errors, duration) is stored for 30 days.
* New: "Tasks" admin page — task table with schedules and next runs, recent run history, wp-cron health and event list, and a master switch for scheduled execution.
* Full unit coverage for the cron parser and next-run math (timezone-safe, UTC).

= 1.2.0 =
* New: plugin and theme installation from a zip archive (`/plugins/upload`, `/themes/upload`) — base64 or any URL, SSRF-guarded, size-capped. Requires the matching manage permission plus the destructive switch.
* New: malware heuristics scan on every extracted package (eval, obfuscation chains, superglobal includes, /e regexp...). Activation is blocked while findings exist unless explicitly overridden; findings travel in the response and the log.
* New: complete upload log (`codescout_uploads` table + `/uploads-log` + admin "Upload Log" page): source, SHA-256 checksum, size, scan findings, activation status and errors for every package that lands on disk — wordpress.org installs are recorded too.
* New: full user meta support (`GET/POST /content/user-meta`) with escalation-path protection (`{prefix}_capabilities`, user levels, session tokens always blocked) — makes LMS student flags and any plugin's user attributes manageable.
* New: bulk user operations (`POST /content/users/bulk`): delete, re-role or set meta for up to 100 users at once, with the same escalation guards.
* Fix: meta arrays are now stored as real (serialized) arrays instead of JSON strings — Elementor page settings, display conditions for headers/footers, and plugin meta read back correctly. The legacy behaviour stays available via `value_format: "json_string"`.
* Fix: the internal REST proxy passes nested arrays through untouched — WooCommerce product creation with `images`, `categories`, `attributes` and `meta_data` now works through `/rest/do-request`.
* Fix: option updates accept real scalars (int/bool/null) and arrays from JSON bodies, and the single-element-array flattening bug is fixed. New `merge: true` parameter deep-merges an array into the existing option (theme mods, plugin settings) without clobbering the rest.
* Change: the hard-coded blocked-options list is now two tiers — connector config and auth secrets are always locked, while the sensitive list (siteurl, home, roles, active_plugins, cron...) is admin-editable in the settings.
* New: `upload_max_bytes` setting (default 50 MB) and expanded `features` map in `/capabilities`.

= 1.1.0 =
* New: guarded PHP code execution (`POST /code/execute`) behind the new `execute_code` permission + the destructive switch. The agent can now use the official functions of any plugin (Tutor LMS enrolment, Elementor cache regeneration, WooCommerce products, language packs, rewrite flushes...) instead of fragile direct table writes. Output is captured and capped, warnings/notices are collected, catchable errors return structured data, and the full code is stored in the audit log payload.
* New: Plugin Explorer (`GET /plugins/explore`) — a static source scan mapping any installed plugin's classes, methods and signatures, functions, hooks, post types, taxonomies, custom tables, options and constants without executing anything, so the agent can learn an unfamiliar plugin's API surface safely.
* New: snippets manager — persistent PHP / CSS / JS snippets in their own database table with REST CRUD (`/snippets/*`), scoped execution (front/admin/both), and a "Snippets" admin page showing status and last errors.
* New: Safe Mode — a fatal in executed code or a snippet deactivates the snippet automatically, engages Safe Mode (blocks further execution) and emails the administrator. Includes an emergency recovery link that deactivates every snippet from outside wp-admin.
* New: `features` map in `/capabilities` and `safe_mode` state in `/connect` and `/diagnostics`, so the agent can adapt to the installed connector version without version comparisons.
* Audit log gains a `payload` column storing full executed code for forensics (excluded from list responses).
* Schema upgrades run lazily on admin/REST hits (no re-activation needed after update). Snippets are removed on uninstall.

= 1.0.1 =
* Fix: token modal could appear on page load (CSS `display:flex` overrode the `hidden` attribute) and the "Done" button appeared to re-open it after reload.
* Fix: AJAX failures are now surfaced in an alert with the server's actual response instead of failing silently.
* Security hardening after audit: reject MySQL versioned comments in SQL queries (guards cannot be hidden inside `/*!...*/`), run forbidden-construct checks against the raw statement, strip string literals before structural checks.
* Security hardening: block `admin_email` / `new_admin_email` via the generic options endpoint; per-connection failure counter (20 across all IPs) in addition to the per-IP lockout; media and comment permanent deletion now require the destructive switch; reject DDL inside transactions (MySQL implicitly commits it); credential-like meta keys are blocked on the meta endpoint too; backup folders use unguessable random IDs and dumps are sanitized (password hashes and credential-like option/meta values are redacted); backup restores validate dump columns against the live table; private-IP check added to remote media fetches; unguessable backup folder IDs; file listing is capped.
* Fix: removed a double-unslash on REST parameters that could corrupt file content containing backslash escape sequences.
* UI: buttons disable while their AJAX request is in flight.

= 1.0.0 =
* Initial release: authentication, permission system, filesystem/database/plugin/theme/content endpoints, discovery, diagnostics, targeted backups, audit logging, rate limiting, SSRF-guarded HTTP proxy, hook execution and internal REST dispatch.
