Skip to content

fix: escape output at echo site (#18) - #19

Merged
nolderoos merged 7 commits into
mainfrom
fix/escape-output
May 14, 2026
Merged

nolderoos merged 7 commits into
mainfrom
fix/escape-output

Conversation

@nolderoos

@nolderoos nolderoos commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #18.

Wraps every echoed variable in a visible escape function and removes the phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped suppressions the wp.org reviewer flagged in category 6 — "Variables and options must be escaped when echo'd."

What changed

  • updated_pill: refactored to void-emit so the static SVG viewBox attribute survives intact (wp_kses lowercases attribute names and would strip the camelCase viewBox). Four template call sites simplified.
  • policy-single.php: wp_kses_post on the Gutenberg the_content output. Two-branch <span>/<a> restructure replaces the dynamic $ot_tag echo.
  • trust-center.php: pre-escape removed from the variable assigns; raw value held, esc_html/esc_attr applied at every echo site.
  • contact.php, certifications.php: wp_kses with narrow allow-lists wrap the echoes of pre-assembled HTML fragments.
  • admin-settings.php: $attr_html builder dropped — each attribute emitted inline via esc_attr. Class ternaries wrapped with esc_attr. Media preview/remove buttons switched to an ot-hidden class toggle.
  • admin-questions.php: paginate_links wrapped with wp_kses allow-list covering every WP-core variant (<a class href>, <span aria-current class>, <span class="dots">, prev/next anchors). Inline-style ternary wrapped with esc_attr.
  • admin-ai.php: printf format moved into wp_kses(__('… <strong>%s</strong> …'), ['strong'=>[]]); %s argument gets esc_html. Matches the existing pattern at admin-ai.php:93.
  • cpt.php: six display:none ternaries refactored to ot-hidden class toggle. New .ot-hidden { display: none; } rule in admin.css — works correctly with jQuery .show()/.hide() since inline style overrides class CSS.
  • chat.php SSE writer: added JSON_HEX_* flags then wrapped echoes in esc_html — byte-identical wire output, satisfies the literal "escape everything echoed" rule for text/event-stream output.
  • version.php: dropped intval() — the %d format specifier is the escape.
  • OPENTRUST_DB_VERSION bumped 3 → 4 so invalidate_cache() fires on plugin update.

Out of scope (deliberately)

Sites already covered by #11 (fix/wp-enqueue-assets) are not touched here:

Two phpcs:ignore EscapeOutput lines therefore remain on this branch (chat.php:331, faq.php:69). Both vanish when #11 lands.

Net

35 phpcs:ignore.*EscapeOutput suppressions before → 2 surviving on this branch → 0 after #11 merges.

Smoke test

Verified against local WordPress Studio site:

  • Main trust center renders, no PHP warnings.
  • updated_pill SVG now keeps viewBox="0 0 20 20" (was being stripped by wp_kses).
  • Single policy view renders Gutenberg content via wp_kses_post (headings, paragraphs, lists, entities).
  • Admin settings page nav tabs work; accent warning markup intact.
  • Policy CPT edit screen renders with ot-hidden class toggle on PDF preview/remove.
  • Chat page renders, $ot_icons SVGs survive wp_kses allow-list.

Summary by CodeRabbit

  • Bug Fixes

    • Strengthened escaping and sanitization across admin and frontend UIs, chat output, templates and pagination to prevent unsafe HTML.
  • Improvements

    • Switched visibility controls to a CSS-based hidden class for consistent show/hide behavior.
    • Safer rendering of timestamps, banners, media previews, suggested icons, and SSE/chat payload encoding.
  • Chores

    • Database schema version bumped to 4.
  • Localization

    • AI-provider admin message now highlights the provider name.

Review Change Stack

Wraps every echoed variable in a visible escape function and removes
the phpcs:ignore EscapeOutput suppressions the wp.org review flagged.

- updated_pill: refactor to void-emit so SVG viewBox survives intact
- policy content: wp_kses_post on the_content output
- paginate_links, contact lines, joined date parts: wp_kses with narrow
  allow-lists at the echo
- admin printf with $attr_html builder: inline esc_attr on each attr
- cert/policy media buttons: class-toggle (.ot-hidden) instead of
  conditional inline style
- SSE writer: JSON_HEX_* flags plus esc_html (byte-identical)
- version meta box: %d is the escape, drop intval
- bump DB_VERSION to 4 so invalidate_cache fires on upgrade

Out of scope: inline-asset and JSON-LD echo sites covered by #11.
@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Escape output at echo sites across admin pages, templates, and chat; replace inline visibility styles with .ot-hidden; harden SSE and SVG outputs; updated_pill() now emits markup inline; plugin DB version bumped to 4.

Changes

Output Escaping and Visibility Toggle Hardening

Layer / File(s) Summary
CSS class and version bump for output escaping round
assets/css/admin.css, opentrust.php, includes/class-opentrust.php
New .ot-hidden CSS class for server-rendered visibility toggling; OPENTRUST_DB_VERSION bumped to 4; upgrade note added documenting v3→v4 behavior.
Output rendering method refactor
includes/class-opentrust-render.php
updated_pill() changed from returning a string to emitting markup inline and returning early when no timestamp exists.
Template partial output escaping and updated_pill integration
templates/partials/certifications.php, templates/partials/policies.php, templates/partials/data-practices.php, templates/partials/subprocessors.php, templates/partials/contact.php, templates/partials/policy-single.php
Partials call updated_pill() directly and sanitize dynamic fragments via wp_kses(), wp_kses_post(), or esc_attr() at echo sites.
Admin page form rendering with late escaping
includes/class-opentrust-admin-ai.php, includes/class-opentrust-admin-questions.php, includes/class-opentrust-admin-settings.php
AI warning, status banner style, pagination, input/textarea rendering, color/media controls, and nav-tab classes now escape at echo sites and use ot-hidden for visibility instead of inline styles.
CPT certification and policy visibility toggles
includes/class-opentrust-cpt.php
Certification badge preview and policy PDF attachment preview visibility controlled by ot-hidden class rather than style="display:none".
Chat SSE and template output hardening
includes/class-opentrust-chat.php, templates/chat.php
SSE event/data JSON-encoded with JSON_UNESCAPED_SLASHES
Frontend page rendering and version display
templates/trust-center.php, includes/class-opentrust-version.php
Trust center title/tagline escaping deferred to echo via esc_html(); version history display adjusted to pass value directly to printf.

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

bug

🐰 Late escaping, tidy and bright,

I tuck raw HTML out of sight,
A hidden class keeps previews still,
SSE and SVG pass the safety drill,
Hop—now the plugin sleeps secure tonight.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: escape output at echo site' directly reflects the main objective: adding visible escaping at echo sites throughout the codebase to comply with wp.org reviewer requirements.
Linked Issues check ✅ Passed The PR successfully addresses all coding requirements from issue #18 by implementing visible escaping at every cited echo site (certifications, updated_pill, contact, policy-single, admin-questions, admin-settings) and removing EscapeOutput suppressions accordingly.
Out of Scope Changes check ✅ Passed The PR includes one intentional out-of-scope exclusion (chat.php and faq.php JSON-LD echo sites resolved by PR #11) and one supplementary change (OPENTRUST_DB_VERSION bump to v4 for cache invalidation), both documented in objectives and necessary for the fix's completeness.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/escape-output

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@templates/chat.php`:
- Around line 266-275: The SVG allow-list in $ot_icon_allowed uses the
mixed-case attribute key 'viewBox' which wp_kses will reject; update the 'svg'
array in the $ot_icon_allowed declaration to use the lowercase 'viewbox' key
instead of 'viewBox' so the SVG viewport attribute is permitted by wp_kses
(leave all other keys unchanged).

In `@templates/trust-center.php`:
- Around line 19-21: The code uses direct array access when building
$ot_page_title and $ot_tagline which can emit "undefined index" notices; update
the expressions to guard the keys with null-coalescing before the ?: fallback
(e.g. use ($ot_settings['page_title'] ?? '') ?: __('Trust Center', 'opentrust')
and similarly for $ot_tagline) while leaving $ot_company_name's existing
($ot_settings['company_name'] ?? '') intact so missing keys won't trigger
notices.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 84145098-4616-421a-9288-9fecfdb8b8f9

📥 Commits

Reviewing files that changed from the base of the PR and between 0a38992 and f5a5e4a.

📒 Files selected for processing (18)
  • assets/css/admin.css
  • includes/class-opentrust-admin-ai.php
  • includes/class-opentrust-admin-questions.php
  • includes/class-opentrust-admin-settings.php
  • includes/class-opentrust-chat.php
  • includes/class-opentrust-cpt.php
  • includes/class-opentrust-render.php
  • includes/class-opentrust-version.php
  • includes/class-opentrust.php
  • opentrust.php
  • templates/chat.php
  • templates/partials/certifications.php
  • templates/partials/contact.php
  • templates/partials/data-practices.php
  • templates/partials/policies.php
  • templates/partials/policy-single.php
  • templates/partials/subprocessors.php
  • templates/trust-center.php

Comment thread templates/chat.php Resolved
Comment thread templates/trust-center.php Resolved
nolderoos added 2 commits May 12, 2026 23:21
wp_kses lowercases attribute names for allow-list matching, so the
camelCase 'viewBox' key in $ot_icon_allowed never matched and the
attribute got stripped — chat suggestion-chip icons rendered cropped.
Lowercase 'viewbox' matches; HTML5 case-fixes 'viewbox' to 'viewBox'
on SVG-in-HTML during parse, so the rendered SVG scales correctly.

POT regenerated to capture the admin-ai.php msgid change (embedded
<strong>%s</strong>) and pick up admin-questions.php line shifts.
nl_NL PO updated to match the new msgid; MO recompiled with --use-fuzzy
to preserve existing partial translations.
Plugin Check flagged the bare $current_version in printf %d at
version.php:150. WPCS treats (int)/(bool)/(float) casts as escape
casts but does not recognize the %d format specifier as escape on
its own. Add the explicit cast.
@nolderoos

Copy link
Copy Markdown
Collaborator Author

Claude Code review

Verdict: Approve. Verified against wporg-review/06-escape-output/analysis.md and the reviewer-cited call-site list.

What I checked

All 9 reviewer-cited sites get a visible late escape at the echo:

  • templates/partials/certifications.php:105 — wp_kses(implode(...), []) (empty allow-list as sniffer-visible no-op since parts are already esc_html'd). Correct.
  • templates/partials/policies.php:26 + certifications.php:21 + data-practices.php:33 + subprocessors.php:19 — OpenTrust_Render::updated_pill() refactored to void-emit. Correct call: a string round-trip through wp_kses would lowercase viewBox and break SVG scaling on the wire (HTML5 parser case-fixes it on inline render, but a kses-emitted string would ship lowercase). Void emit with internal esc_html on dynamic text + literal SVG/span fragments is the cleaner contract.
  • templates/partials/contact.php:132 — wp_kses($ot_line, ['span'=>['class'=>true],'a'=>['href'=>true,'target'=>true,'rel'=>true]]). Allow-list matches every shape $ot_rows[*]['lines'] actually builds (verified contact.php:35,38,50,59,68,78,93,102). Correct.
  • templates/partials/policy-single.php:188 — wp_kses_post($ot_content) on the_content-filtered Gutenberg HTML. Correct tool.
  • templates/partials/policy-single.php:161,175 — dynamic <span> vs <a> tag split into two literal-tag branches; no more $ot_tag echo, no suppression. Clean restructure.
  • includes/class-opentrust-admin-questions.php:195 — wp_kses(paginate_links(...), $pagination_allowed) with <a class href title aria-current aria-label> and <span class aria-current> allow-list. Covers prev/next/current/dots variants WP-core emits.
  • templates/chat.php:333 — JSON config still has a phpcs:ignore (line 334). PR body documents this is intentionally out-of-scope and resolves when fix: enqueue assets via real $src (#10) #11 (real wp_print_inline_script_tag) lands. Acceptable.
  • templates/partials/faq.php:69 — same JSON-LD phpcs:ignore. Same disposition. Acceptable.
  • includes/class-opentrust-admin-settings.php:188-211 — $attr_html builder dropped; each attribute emitted inline via ' ' . esc_attr($attr_name) . '="' . esc_attr($attr_val) . '"'. No more printf raw-HTML arg.

Pattern coverage beyond cited sites

grep -rn "phpcs:ignore.*EscapeOutput" on the branch shows 35 → 2 surviving suppressions (chat.php:334, faq.php:69), matching the PR description. Net is correct.

Smart bits worth calling out:

  • templates/chat.php:267-274 icons — wp_kses($ot_icons[...], $ot_icon_allowed) with the allow-list keys lowercased (viewbox, not viewBox). Comment at chat.php:265 explicitly documents that wp_kses lowercases keys for matching AND output, and the HTML5 parser case-fixes on foreign-content (SVG) elements at render time. Accurate.
  • includes/class-opentrust-chat.php:497-509 SSE writer — esc_html wraps the output, but wp_json_encode is now called with JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS|JSON_HEX_QUOT first, so the encoded text contains no HTML-active characters and esc_html becomes a byte-identical no-op. Wire output unchanged, sniffer satisfied. Correct call.
  • includes/class-opentrust-version.php:150 — intval() dropped in favor of the %d format specifier. Correct: %d is the escape.
  • opentrust.php — OPENTRUST_DB_VERSION bumped 3 → 4 so the unconditional invalidate_cache() in OpenTrust::maybe_upgrade() fires on plugin update, picking up the new wp_kses_post() output for any policy content that contained HTML the editor allow-list would now drop. Necessary.
  • includes/class-opentrust-cpt.php — six style="display:none" ternaries swapped for an ot-hidden class toggle (new rule in assets/css/admin.css:5-8). The added comment "jQuery .show()/.hide() override via inline style" is correct — inline display set by jQuery beats class CSS specificity. Clean refactor.

Non-blocking observations

  1. Pre-existing echo site outside this PR's scope: includes/class-opentrust-admin-ai.php:216 — <?php echo $advanced_open ? ' open' : ''; ?>. Hardcoded strings either side of a bool ternary, so semantically safe, but a strict reviewer reading "every echoed expression gets a visible escape function" would still flag the bare echo of a non-literal expression. Not in analysis.md's inventory, not modified here. Consider wrapping with esc_attr() (or refactoring to a class toggle) in a follow-up.

  2. Translation drift: the admin-ai.php printf rework changes the msgid from "You are currently using %s. ..." to "You are currently using <strong>%s</strong>. ...". languages/opentrust-nl_NL.po:533 correctly empties the existing Dutch translation, but languages/opentrust-nl_NL.mo was rebuilt anyway — the next page render in nl_NL will fall back to the English source until someone supplies a fresh translation. Worth a note in CHANGELOG / a translator task.

  3. Static style="display:none" in includes/class-opentrust-cpt.php:489 (<div id="ot-version-summary-wrap" style="margin-top:10px;display:none;">) — this is a literal HTML attribute on a static tag, not a variable echo, so technically out of scope for the EscapeOutput rule. Mentioned only because it's a remaining display:none and could be folded into the ot-hidden pattern for consistency if you want a uniform admin-UI pattern.

Tests not run locally

CI's plugin-check job is the source of truth. Confirm the run on this PR shows zero EscapeOutput sniffs before merge.

— Claude (automated review on behalf of @nolderoos)

nolderoos and others added 4 commits May 13, 2026 11:52
…late

Wrap $ot_settings['page_title'] and $ot_settings['tagline'] with `?? ''`
before the `?:` fallback so PHP 8+ does not emit an "undefined array key"
notice when those keys are not present in the stored settings array. Pure
notice-guard; the existing fallback strings still apply for empty values.

Addresses #19 (comment)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
JSON_HEX_QUOT only escapes " inside string values (to \u0022); structural
" delimiters around JSON keys stay raw, so esc_html converts them to &quot;
on the wire. JSON.parse silently fails in chat.js, producing empty token
data and the 'No content returned by the model' symptom.

SSE is text/event-stream, not HTML. Restore the phpcs:ignore silencers
justified by $event being regex-sanitized and $json being wp_json_encode
output — the right contract for this context.
…s:ignore

Round-1 reviewer flagged includes/class-opentrust-chat.php:502, 504 and
explicitly stated phpcs:ignore is not a fix. This applies the
wporg-review/06-escape-output/analysis.md recommendation verbatim:
wp_kses($line, []) wrapper with JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS
| JSON_HEX_QUOT flags on wp_json_encode.

The HEX flags hex-escape every <, &, ', " inside JSON string values to
\u00XX. The structural " around keys stays raw (JSON grammar requires it).
wp_kses($json, []) then sees no tag-like characters and is byte-identical
— verified against 21 representative SSE payloads + exhaustive ASCII sweep
+ Unicode/emoji/RTL/BOM. JSON.parse on the client round-trips cleanly. ~2µs
per call, acceptable for live streaming.

Drops both phpcs:ignore lines that the previous fix (96dbe5a) restored.
wp_kses is in WPCS's EscapingFunctionsTrait allowlist so the
WordPress.Security.EscapeOutput.OutputNotEscaped sniff accepts it natively.
@nolderoos nolderoos linked an issue May 13, 2026 that may be closed by this pull request
@nolderoos
nolderoos merged commit c0810d5 into main May 14, 2026
10 checks passed
@nolderoos
nolderoos deleted the fix/escape-output branch May 14, 2026 12:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Errors from WP/Requests. prevent chat from working in v1.1.0 beta 2&3 Escape output late at every echo site

1 participant