Skip to content

Render notification templates with fixed templates and escaped locals - #2250

Merged
fengkx merged 5 commits into
masterfrom
cursor/fix-template-injection-460b
Oct 22, 2026
Merged

fengkx merged 5 commits into
masterfrom
cursor/fix-template-injection-460b

Conversation

@fengkx

@fengkx fengkx commented Oct 22, 2026 •

Copy link
Copy Markdown
Owner

Summary

This PR updates error and feed-change notification message rendering to use fixed EJS template sources with all feed-controlled data passed as escaped locals. This prevents feed data from injecting arbitrary Telegram HTML markup or malformed tags.

Scope: This PR addresses error notifications (ERROR_MANY_TIME) and feed URL change notifications (isChangeFeedUrl). Other Telegram HTML outputs (normal feed items, subscription confirmations, RSS list) are out of scope for this PR and will be addressed separately if needed.

Changes

Notification Template Construction

  • Created source/utils/notification-messages.ts with message builder functions:

    • buildErrorNotification() - constructs error notification templates and locals
    • buildFeedChangeNotification() - constructs feed URL change templates and locals
  • Updated source/index.ts to use the builder functions:

    • ERROR_MANY_TIME path now calls buildErrorNotification()
    • isChangeFeedUrl path now calls buildFeedChangeNotification()

HTML Entity Decoding in Feed Discovery

  • Created source/utils/html-entities.ts to decode HTML entities from href attributes
  • Updated findFeed() in source/utils/feed.ts to decode entities before URL parsing
  • Prevents double-escaping when entity-encoded URLs (e.g., href="...?a=1&b=2") flow through to notifications

Template Rendering

  • All feed-controlled data (titles, URLs, error messages, new feed URLs) is passed as EJS locals
  • Data is rendered with escaped output (<%= %>) to prevent injection of Telegram HTML
  • HTML markup that belongs to the template itself (e.g., <a href="..."> tags) remains literal in the template source

Extended send() Function

  • Added optional templateLocals parameter to pass untrusted data safely
  • Template locals are merged with i18n translations at render time

Behavior Changes

Escaping of Special Characters

Feed titles, URLs, and error messages now have HTML special characters escaped in error and feed-change notifications:

  • < becomes &lt;
  • > becomes &gt;
  • & becomes &amp;
  • " becomes &#34;
  • ' becomes &#39;

Before: Feed title Tech News <Daily> & Updates would render with raw HTML
After: Title renders as Tech News &lt;Daily&gt; &amp; Updates (displays literally in Telegram)

Literal EJS Delimiter Preservation

Feed titles or URLs containing literal <% or %> text are now preserved:

Before: Title Use <%= variable %> might cause rendering issues
After: Title renders as Use &lt;%= variable %&gt; (displays literally)

Plain Input Compatibility

Plain feed titles without special characters render byte-identically to the previous implementation.

Testing

Test Coverage (13 test suites, 76 tests)

Notification Security Tests (11 tests in template-injection.spec.ts):

  • Full-text assertions for messages with &, quotes, <> in all positions
  • Tests verify href attribute, link text, new-feed list items, and trailing repeated URL
  • Tests use production buildErrorNotification() and buildFeedChangeNotification() functions
  • Chinese language test with special characters and i18n text
  • Any change from <%= %> to <%- %> in any output position will fail at least one test

HTML Entity Decoding Tests (7 tests in html-entities.spec.ts):

  • Named entities (&amp;, &lt;, &gt;, &quot;, &apos;)
  • Numeric entities (decimal &#38;)
  • Hex entities (&#x26;)
  • Multiple entities in strings
  • URLs with entities

Feed Discovery Tests (6 tests in feed-discovery.spec.ts):

  • Entity-encoded URLs in HTML href attributes are properly decoded
  • Multiple feed types (RSS, Atom) with entities
  • Named, numeric, and hex entity support
  • Plain URLs pass through unchanged

Test Results

Test Suites: 17 passed, 17 total
Tests:       76 passed, 76 total

Build & Lint

✓ npm run build  # TypeScript compilation succeeds
✓ npm test       # All tests pass
✓ npm run lint   # ESLint, Prettier, lockfile-lint all pass

Technical Details

Why Escaped Output?

Using <%= %> (escaped) instead of <%- %> (raw) ensures feed data cannot inject:

  • Fake HTML links (<a href="malicious">)
  • Telegram formatting tags (<b>, <i>, <code>)
  • Malformed markup that causes Telegram to reject messages

HTML Entity Decoding Flow

  1. HTML contains href="https://example.com/rss?a=1&amp;b=2" (entity-encoded)
  2. findFeed() decodes: https://example.com/rss?a=1&b=2 (raw URL)
  3. URL stored in database as raw URL
  4. Notification builder passes raw URL as EJS local
  5. EJS escapes for Telegram HTML: https://example.com/rss?a=1&amp;b=2 (output)
  6. Result: Single escaping, no double-escaping

Template Construction Pattern

Fixed template source:

'<%= title %>: <a href="<%= url %>"><%= url %></a> <%=i18n["ERROR_MANY_TIME"]%> <%= errorMessage %>'

Data passed as locals:

{
    title: feed.feed_title,
    url: feed.url,
    errorMessage: error.message
}

This separation ensures data is never evaluated as template code.

Out of Scope

This PR's escaping guarantee is limited to error and feed-change notifications. The following Telegram HTML outputs are NOT changed by this PR:

  • Normal feed item links in send.ts (line ~174)
  • Subscription confirmation messages in sub-multi-url.ts
  • Import success messages in import-from-opml.ts
  • RSS list output in controlers/rss.ts

These may be addressed in future work if needed.

Commit History

  • cdba6e5 - Initial hardening with escaped locals
  • f1b9cb7 - Address Codex feedback on raw vs escaped output
  • fdc87a3 - Extract production functions, rewrite tests
  • 9048ac1 - Fix double-escaping, add comprehensive full-text tests

Files Changed

  • source/index.ts - Use builder functions for notifications
  • source/utils/notification-messages.ts - Message construction functions
  • source/utils/html-entities.ts - HTML entity decoder
  • source/utils/feed.ts - Decode entities in findFeed()
  • source/utils/send.ts - Added templateLocals parameter
  • test/template-injection.spec.ts - 11 comprehensive security tests
  • test/html-entities.spec.ts - 7 entity decoder tests
  • test/feed-discovery.spec.ts - 6 feed discovery tests
Open in Web Open in Cursor 

cursoragent and others added 3 commits October 22, 2026 04:02
- Pass untrusted data (feed titles, URLs, error messages) as EJS locals instead of concatenating into template source
- Add stripEjsDelimiters() function for defense-in-depth sanitization
- Apply EJS delimiter sanitization when storing feed titles
- Add comprehensive security tests covering template injection scenarios
- Update send() function to accept optional template locals parameter

This change prevents untrusted remote content from being evaluated as code when rendering error messages and feed change notifications.

Co-authored-by: fengkx <liangkx8237@gmail.com>
Key changes:
- Use <%- %> (raw/unescaped) instead of <%= %> for untrusted data to preserve original output behavior for benign inputs
- Pass entire new_feed array as local and loop in EJS template (no concatenation)
- Remove storage-time stripEjsDelimiters (inconsistent, breaks legitimate titles)
- Rewrite tests to use production code paths with DB/Telegram mocks
- Add regression guards that verify the fix works correctly
- Add benign input compatibility tests to ensure output remains identical

All template sources now use fixed strings with all untrusted data passed as locals.

Co-authored-by: fengkx <liangkx8237@gmail.com>
- Switch from <%- %> to <%= %> for all user/feed-controlled data
- Extract notification construction into testable functions
- Rewrite tests to use production message builders
- Remove executable code from tests (use inert HTML chars)
- Add full-text assertions for complete message verification

Behavior changes:
- HTML special characters (<, >, &, quotes) in feed titles, URLs, and error messages are now escaped
- Literal EJS delimiters in titles are preserved (not interpreted)
- Plain inputs without special characters render identically to before

Co-authored-by: fengkx <liangkx8237@gmail.com>
@cursor cursor Bot changed the title Security: Harden feed-title and error message rendering Render notification templates with fixed templates and escaped locals Oct 22, 2026
1. HTML entity decoding in feed discovery:
   - Created html-entities decoder for href attributes
   - findFeed() now decodes &amp; etc. before URL parsing
   - Prevents double-escaping in notification output

2. Comprehensive test coverage:
   - Full-text (toBe) assertions cover all escaped outputs
   - Tests verify href attribute, link text, list items, trailing URL
   - Added tests for &, quotes, <>, Chinese text in all positions
   - Any change from <%= to <%- will fail at least one test

3. Feed discovery tests:
   - Test entity decoding from HTML through to URL output
   - Cover named, numeric, and hex entities

Test results: 17 suites, 76 tests, all passed

Co-authored-by: fengkx <liangkx8237@gmail.com>
Refactoring for clarity - no behavior changes:

notification-messages.ts:
- Extract templates as named constants for readability
- Improve JSDoc with parameter descriptions
- Use clearer variable names (feedUrl vs feed_url)

html-entities.ts:
- Extract NAMED_ENTITIES as top-level constant
- Better file-level documentation explaining purpose
- Use descriptive parameter names (entityName, decimal, hexadecimal)
- Use nullish coalescing for cleaner fallback

feed.ts (findFeed):
- Extract href parsing into extractHref() helper function
- Convert chained map/filter to clear for loop with early continues
- Better variable names (linkTags, baseUrl)
- Add JSDoc for both functions

template-injection.spec.ts:
- Add createTestFeed() helper to reduce boilerplate
- More concise test descriptions
- Simplified mock setup
- Better test organization with clearer describe blocks

All tests pass (76/76), build clean, lint clean, behavior identical

Co-authored-by: fengkx <liangkx8237@gmail.com>
@fengkx
fengkx marked this pull request as ready for review October 22, 2026 07:54
@fengkx
fengkx merged commit 358ca54 into master Oct 22, 2026
6 checks passed
@fengkx fengkx mentioned this pull request Oct 22, 2026
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.

2 participants