Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions source/controlers/rss.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { AddMessageKey, MContext, TNextFn } from '../types/ctx';
import { isNone } from '../types/option';
import { decodeUrl, encodeUrl } from '../utils/urlencode';
import sanitize from '../utils/sanitize';
import escapeHtml from '../utils/escape-html';

export async function sub(ctx: MContext, next: TNextFn): Promise<void> {
const { feedUrl, chat, lang } = ctx.state;
Expand Down Expand Up @@ -89,16 +90,19 @@ export async function rss(
builder.push(`<strong>${i18n[lang]['SUB_LIST']}</strong>`);
if (raw) {
feeds.forEach((feed) => {
const url = feed.url.trim();
// Raw mode: show title, then URL as both href and visible link text
builder.push(
`${sanitize(feed.feed_title)}: <a href="${encodeUrl(
feed.url.trim()
)}">${decodeUrl(feed.url.trim())}</a>`
`${sanitize(feed.feed_title)}: <a href="${escapeHtml(
encodeUrl(url)
)}">${escapeHtml(decodeUrl(url))}</a>`
);
});
} else {
feeds.forEach((feed) => {
// Normal mode: title is link text, URL is href
builder.push(
`<a href="${encodeUrl(feed.url.trim())}">${sanitize(
`<a href="${escapeHtml(encodeUrl(feed.url.trim()))}">${sanitize(
feed.feed_title
)}</a>`
);
Expand Down Expand Up @@ -148,10 +152,11 @@ export async function viewAll(ctx: MContext, next: TNextFn): Promise<void> {
feeds.forEach((feed) => {
const url = feed.url.trim();
const title = sanitize(feed.feed_title);
const subscriberCount = feed.sub_count;
builder.push(
`<a href="${encodeUrl(url)}">${title}</a> ${
`<a href="${escapeHtml(encodeUrl(url))}">${title}</a> ${
i18n[lang]['NUMBER_OF_SUBSCRIBER']
}: ${feed.sub_count}`
}: ${subscriberCount}`
);
});
ctx.state.replyText = builder.join('\n');
Expand Down
5 changes: 4 additions & 1 deletion source/middlewares/import-from-opml.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import errors from '../utils/errors';
import { sub } from '../proxies/rss-feed';
import i18n from '../i18n';
import { MContext, TNextFn } from '../types/ctx';
import sanitize from '../utils/sanitize';
import escapeHtml from '../utils/escape-html';

const getOutlines = async function (data: string): Promise<Outline[]> {
const { outlines } = await transform(data, {
Expand Down Expand Up @@ -42,7 +44,8 @@ export default async (ctx: MContext, next: TNextFn): Promise<void> => {
);
let text = `<strong>${i18n[lang]['IMPORT_SUCCESS']}</strong>`;
outlines.forEach((outline) => {
text += `\n<a href="${outline.xmlUrl}">${outline.text}</a>`;
// URL is escaped for href, title text is sanitized for display
text += `\n<a href="${escapeHtml(outline.xmlUrl)}">${sanitize(outline.text)}</a>`;
});
if (text.length > 4096) {
text = `<strong>${i18n[lang]['IMPORT_SUCCESS']}</strong>\n`;
Expand Down
6 changes: 4 additions & 2 deletions source/middlewares/sub-multi-url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { isSome } from '../types/option';
import { Feed } from '../types/feed';
import { parseString } from '../parser/parse';
import { decodeUrl, encodeUrl } from '../utils/urlencode';
import sanitize from '../utils/sanitize';
import escapeHtml from '../utils/escape-html';

export default async (
ctx: MContext & AddMessageKey<'text', string>,
Expand Down Expand Up @@ -56,9 +58,9 @@ export default async (
if (e.message !== 'ALREADY_SUB')
throw errors.newCtrlErr('DB_ERROR');
}
// encodeURL because it is decoded
// URL is percent-encoded for href, title is sanitized for display
builder.push(
`<a href="${encodeUrl(feed.url)}">${feed.feed_title}</a>`
`<a href="${escapeHtml(encodeUrl(feed.url))}">${sanitize(feed.feed_title)}</a>`
);
});
if (builder.length > 1) {
Expand Down
15 changes: 15 additions & 0 deletions source/utils/escape-html.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { escapeHTML } from 'fast-escape-html';

/**
* Escape HTML special characters for raw data in Telegram HTML messages.
* Use this for URLs, identifiers, and data that must preserve exact formatting.
*
* Escapes: &, <, >, ", and ' characters
* Preserves: all whitespace (including newlines and multiple spaces)
*
* For titles and content text, use sanitize() instead, which also cleans
* whitespace by removing newlines and collapsing multiple spaces.
*/
export default function escapeHtml(s: string): string {
return escapeHTML(s);
}
8 changes: 5 additions & 3 deletions source/utils/send.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
} from '../proxies/subscribes';
import logger from './logger';
import sanitize from './sanitize';
import escapeHtml from './escape-html';
import { config } from '../config';
import { Telegraf, Context } from 'telegraf';
import { Feed, FeedItem } from '../types/feed';
Expand Down Expand Up @@ -177,9 +178,10 @@ const send = async (
const userId = subscribe.user_id;
let text = `<b>${sanitize(feed.feed_title)}</b>`;
feedItems.forEach(function (item) {
text += `\n<a href="${item.link.trim()}">${
sanitize(item.title) || item.link.trim()
}</a>`;
// Escape URLs for href attribute; sanitize title, or escape URL as fallback text
const link = escapeHtml(item.link.trim());
const title = sanitize(item.title) || link;
text += `\n<a href="${link}">${title}</a>`;
});
try {
await sendMessageWithLimit(bot, userId, text, {
Expand Down
67 changes: 67 additions & 0 deletions test/escape-html.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import escapeHtml from '../source/utils/escape-html';

describe('escapeHtml utility', () => {
describe('escapes HTML special characters', () => {
test('escapes ampersand', () => {
expect(escapeHtml('a & b')).toBe('a &amp; b');
});

test('escapes less-than', () => {
expect(escapeHtml('a < b')).toBe('a &lt; b');
});

test('escapes greater-than', () => {
expect(escapeHtml('a > b')).toBe('a &gt; b');
});

test('escapes double quotes', () => {
expect(escapeHtml('"quote"')).toBe('&quot;quote&quot;');
});

test('escapes single quotes', () => {
expect(escapeHtml("it's")).toBe('it&#39;s');
});

test('escapes all special characters together', () => {
expect(escapeHtml('Tech <Daily> & "News"')).toBe(
'Tech &lt;Daily&gt; &amp; &quot;News&quot;'
);
});
});

describe('preserves whitespace and formatting', () => {
test('preserves whitespace', () => {
expect(escapeHtml(' spaces ')).toBe(' spaces ');
expect(escapeHtml('\n\n')).toBe('\n\n');
expect(escapeHtml('a\nb\nc')).toBe('a\nb\nc');
});

test('preserves Chinese characters', () => {
expect(escapeHtml('技术新闻')).toBe('技术新闻');
expect(escapeHtml('技术 & 新闻')).toBe('技术 &amp; 新闻');
});
});

describe('edge cases', () => {
test('handles empty string', () => {
expect(escapeHtml('')).toBe('');
});

test('handles string without special characters', () => {
const plain = 'Plain text 123';
expect(escapeHtml(plain)).toBe(plain);
});

test('handles URLs with query parameters', () => {
expect(escapeHtml('https://example.com/?a=1&b=2')).toBe(
'https://example.com/?a=1&amp;b=2'
);
});

test('handles HTML-like strings', () => {
expect(escapeHtml('<script>alert("xss")</script>')).toBe(
'&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;'
);
});
});
});
Loading
Loading