From 38d3017ad9e561f01b303735b9a1cd2c6d0242f3 Mon Sep 17 00:00:00 2001 From: EJ Bensing Date: Wed, 9 Sep 2026 11:18:37 -0400 Subject: [PATCH] Drop libxmljs, fix XML injection bugs, modernize for Node 20+ libxmljs 0.15.x has four open advisories, one critical, and npm reports "No fix available" for every published version (GHSA-773h-w45w-f2f9, GHSA-mg49-jqgw-gcj6, GHSA-6433-x5p4-8jc7, GHSA-jv72-59wq-8rxm). The package was last published in Oct 2023 and needs a node-gyp/libxml2 native build against a NAN release pinned to the Node 4 era, so bumping the version -- what every previous update to this repo did -- cannot fix it. Build the feed XML directly instead; node-rss now has zero dependencies and `npm audit` is clean. Taking over serialization surfaced three injection bugs in our own code: - CDATA breakout: title and description are CDATA-wrapped, and a `]]>` in either terminated the section early, injecting arbitrary XML into the feed. The sequence is now split across two sections. - Unvalidated element names: keys from `options`/`fields` became tag names verbatim, so a key like `x> --- .github/workflows/ci.yml | 42 ++++++ .gitignore | 1 + LICENSE | 21 +++ README.md | 77 ++++++++--- examples/simple.js | 10 +- lib/node-rss.js | 279 ++++++++++++++++++++++++++++----------- package-lock.json | 16 +++ package.json | 34 +++-- test/node-rss.test.js | 243 ++++++++++++++++++++++++++++++++++ 9 files changed, 618 insertions(+), 105 deletions(-) create mode 100644 .github/workflows/ci.yml create mode 100644 LICENSE create mode 100644 package-lock.json create mode 100644 test/node-rss.test.js diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f767a62 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,42 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + node-version: ['20', '22', '24'] + name: node ${{ matrix.node-version }} + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + + # node-rss has no runtime or dev dependencies, so this only verifies + # that the lockfile and package.json agree. + - run: npm ci + + - run: npm test + + audit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: '24' + + - run: npm audit --audit-level=low diff --git a/.gitignore b/.gitignore index 92b3909..18e80f4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ node_modules/ npm-debug.log *.swp +*.tgz diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..11077e7 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2012-2026 EJ Bensing + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 6235940..5194470 100644 --- a/README.md +++ b/README.md @@ -10,19 +10,17 @@ None of the other node.js RSS modules that I could find supported the flexibilit npm install node-rss -## Dependencies +## Requirements -Update (6/18/2015): This step should no longer be necessary. - -node-rss uses the libxmljs library to construct the actual feed. -Unfortunately, some of the features of the library that are needed are only available in the current master branch. You will need to download the libxmljs source, compile, and install it yourself. Fortunately, this is fairly straight forward. https://github.com/polotek/libxmljs/ - -You will also need to have the libxml2 AND libxml2-dev packages installed on your system. +Node.js 20 or newer. node-rss has **no dependencies** - it builds the feed XML +directly, so there is no native module to compile and nothing to install beyond +the package itself. ## Usage ```javascript // this exposes two methods: createNewFeed and getFeedXML - var rss = require('node-rss'); + const rss = require('node-rss'); + // ESM works too: import { createNewFeed, getFeedXML } from 'node-rss'; // first we create a "feed" object that will define your feed // method signature: function createNewFeed(title, link, desc, author, feedLink, options) @@ -32,7 +30,7 @@ You will also need to have the libxml2 AND libxml2-dev packages installed on you // author : author of the feed // feedLink : link to the feed // options : additional options, explained below - var feed = rss.createNewFeed('Blog Most Recent', 'http://someurl.com/', + const feed = rss.createNewFeed('Blog Most Recent', 'http://someurl.com/', 'Most recent blog entries from blog', 'EJ Bensing', 'http://someurl.com/rss/MostRecent.xml', @@ -46,7 +44,7 @@ You will also need to have the libxml2 AND libxml2-dev packages installed on you //next, we need to add some items to the feed // create some dummy data to loop over... - var blogs = [ + const blogs = [ {title: 'blog post 1', url : 'http://someurl.com/blog1', pubDate : new Date(), description: 'this is a description' }, {title: 'blog post 2', url : 'http://someurl.com/blog2', pubDate : new Date(), description: 'this is a description' }, {title: 'blog post 3', url : 'http://someurl.com/blog3', pubDate : new Date(), description: 'this is a description' }, @@ -65,12 +63,12 @@ You will also need to have the libxml2 AND libxml2-dev packages installed on you // description : description of item // fields : functions exactly like the "options" parameter of createNewFeed, // allows the user to add arbitrary tags to an item - blogs.forEach(function (blog) { + for (const blog of blogs) { feed.addNewItem(blog.title, blog.url, blog.pubDate, blog.description, {}); - }); + } // now to get the XML simply call the getFeedXML function - var xmlString = rss.getFeedXML(feed); + const xmlString = rss.getFeedXML(feed); ``` ## Other @@ -78,19 +76,66 @@ The "feed" object has a defaults property. Inside this is a dictionary of defaul cdata : a list of tag names whose content should be "escaped" in CDATA tags -## tests +`pubDate` and `lastBuildDate` accept a `Date` and are written as RFC-1123 +strings, which is the format RSS readers expect. + +## Escaping and validation + +node-rss escapes everything it writes, so feed content taken from user input +cannot break out of the document: + +- text is XML-escaped, and CDATA-wrapped content has any `]]>` sequence split + so it cannot terminate the section early +- attribute values additionally escape quotes and literal newlines +- characters that XML 1.0 cannot represent (most control characters, unpaired + surrogates) are stripped +- tag names come from your option/field keys, and an element name cannot be + escaped - so a key that is not a valid XML name is rejected with an error, + as are keys that would overwrite the feed API (`items`, `defaults`, + `feedLink`, `addNewItem`) or the prototype chain (`__proto__`, `constructor`, + `prototype`) -In the process of building these... +## Tests + + npm test + +The suite runs on the built-in `node:test` runner, so there is nothing to install. ## TODO - - add tests - add support for attributes on custom tags - add some express.js middleware - ?? give me suggestions +## License + +MIT - see [LICENSE](LICENSE). + ## Change log +Version 2.0.0 + + **Breaking:** requires Node.js 20 or newer. + + - Removed the libxmljs dependency. It carried unpatched critical + advisories (GHSA-773h-w45w-f2f9, GHSA-mg49-jqgw-gcj6, + GHSA-6433-x5p4-8jc7, GHSA-jv72-59wq-8rxm) with no fixed version + available, and it requires a node-gyp/libxml2 native build against a + release pinned to the Node 4 era. The feed XML is now built directly, + so node-rss has zero dependencies. + - Fixed a CDATA injection: a `]]>` sequence in a title or description + could terminate the CDATA section early and inject arbitrary XML. + - Custom tag names are now validated as XML names instead of being + written verbatim, and keys that would clobber the feed API or the + prototype chain are rejected. + - Characters that XML cannot represent are stripped instead of producing + a malformed document. + - `Date` values are written as RFC-1123 (matching `lastBuildDate`) rather + than JavaScript's default date string, which is not valid in RSS. + - Added a test suite and CI across Node 20, 22 and 24. + - Relicensed under MIT and added the missing LICENSE file. Previous + releases declared a bare "BSD" with no license text included. + Version 1.0.5 - Updated libxml version to 0.15.x to support node.js 4.x (Thanks @dhendo) diff --git a/examples/simple.js b/examples/simple.js index 85ea56c..4fac898 100644 --- a/examples/simple.js +++ b/examples/simple.js @@ -1,4 +1,4 @@ -var rss = require('./../lib/node-rss.js'); +const rss = require('../lib/node-rss.js'); // create the feed object @@ -8,13 +8,13 @@ var rss = require('./../lib/node-rss.js'); // arg[3] : Author // arg[4] : Link to Feed // arg[5] : Options -var feed = rss.createNewFeed('Blog Most Recent', 'http://someurl.com/', +const feed = rss.createNewFeed('Blog Most Recent', 'http://someurl.com/', 'Most recent blog entries from blog', 'EJ Bensing', 'http://someurl.com/rss/MostRecent.xml', {'CustomTag' : 'This is a custom tag under the channel tag!' }); // create some dummy data to loop over... -var blogs = [ +const blogs = [ {title: 'blog post 1', url : 'http://someurl.com/blog1', pubDate : new Date(), description: 'this is a description' }, {title: 'blog post 2', url : 'http://someurl.com/blog2', pubDate : new Date(), description: 'this is a description' }, {title: 'blog post 3', url : 'http://someurl.com/blog3', pubDate : new Date(), description: 'this is a description' }, @@ -24,9 +24,9 @@ var blogs = [ ]; // add some items to the feed -blogs.forEach(function (blog) { +for (const blog of blogs) { feed.addNewItem(blog.title, blog.url, blog.pubDate, blog.description, {}); -}); +} // get the actual XML for the feed console.log("RSS Content: %s", rss.getFeedXML(feed)); diff --git a/lib/node-rss.js b/lib/node-rss.js index 26981f4..57c8c16 100644 --- a/lib/node-rss.js +++ b/lib/node-rss.js @@ -1,84 +1,211 @@ - +'use strict'; + /** - * this is an RSS module for node. - **/ - -var libxml = require('libxmljs'); - - - // this function will return a "Feed" object, which can then have items added to it -exports.createNewFeed = function (title, link, desc, author, feedLink, options) { - var feed = {}; - feed.title = title; - feed.link = link; - feed.description = desc; - feed.defaults = { author: author, cdata : ['description', 'title'] }; - feed.items = []; - feed.language = 'en-US'; - feed.feedLink = feedLink; - for (var opt in options) { - feed[opt] = options[opt]; + * node-rss - a simple, dependency-free RSS 2.0 feed builder for node.js + */ + +// Properties on a feed object that describe the feed itself rather than a +// channel element, and so are never serialized as XML nodes. +const RESERVED_FEED_KEYS = new Set(['items', 'defaults', 'feedLink', 'addNewItem']); + +// Keys that must never be copied from caller-supplied option/field objects, +// because assigning them mutates the prototype chain instead of the object. +const POLLUTING_KEYS = new Set(['__proto__', 'constructor', 'prototype']); + +// XML 1.0 Name, limited to an optional namespace prefix plus a local name. +// Element names come from caller-supplied object keys, so they are validated +// rather than escaped: there is no way to escape an illegal element name. +const XML_NAME = /^[A-Za-z_][A-Za-z0-9_.-]*(?::[A-Za-z_][A-Za-z0-9_.-]*)?$/; + +// Characters that are not legal anywhere in an XML 1.0 document. These cannot +// be escaped, only dropped, so they are stripped before serialization. +/* eslint-disable-next-line no-control-regex */ +const ILLEGAL_XML_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\uFFFE\uFFFF]/g; + +// Surrogate code units that are not part of a valid pair are likewise illegal. +const LONE_SURROGATES = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?/g, '>'); +} + +function escapeAttr(str) { + return escapeText(str) + .replace(/"/g, '"') + .replace(/\t/g, ' ') + .replace(/\n/g, ' ') + .replace(/\r/g, ' '); +} + +// A CDATA section ends at the first `]]>`, so content containing that sequence +// would otherwise break out of the section and inject arbitrary markup. Split +// the sequence across two sections to neutralize it. +function escapeCdata(str) { + return str.replace(/]]>/g, ']]]]>'); +} + +function assertValidName(name) { + if (!XML_NAME.test(name)) { + throw new Error(`node-rss: "${name}" is not a valid XML element name`); + } + return name; +} + +// Serialize one element. `cdata` selects CDATA-wrapped text over escaped text. +function renderElement(name, value, useCdata, depth, attrs) { + const pad = INDENT.repeat(depth); + let open = `<${assertValidName(name)}`; + for (const [attrName, attrValue] of Object.entries(attrs || {})) { + open += ` ${assertValidName(attrName)}="${escapeAttr(toText(attrValue))}"`; + } + + const text = toText(value); + if (text === '') { + return `${pad}${open}/>\n`; + } + const body = useCdata ? `` : escapeText(text); + return `${pad}${open}>${body}\n`; +} + +// Copy caller-supplied tags onto a target object, refusing keys that would +// clobber the feed/item API or poison the prototype chain. +function assignCustomFields(target, source, reserved) { + if (!source || typeof source !== 'object') { + return target; + } + for (const key of Object.keys(source)) { + if (POLLUTING_KEYS.has(key)) { + throw new Error(`node-rss: "${key}" is not an allowed tag name`); + } + if (reserved.has(key)) { + throw new Error(`node-rss: "${key}" is reserved and cannot be used as a tag name`); } + assertValidName(key); + target[key] = source[key]; + } + return target; +} + +/** + * Create a feed object that items can be added to. + * + * @param {string} title title of the feed + * @param {string} link link to the website + * @param {string} desc description of the feed + * @param {string} author author of the feed + * @param {string} feedLink link to the feed itself + * @param {Object} [options] additional channel-level tags, as key/value pairs + * @returns {Object} the feed + */ +exports.createNewFeed = function createNewFeed(title, link, desc, author, feedLink, options) { + const feed = { + title, + link, + description: desc, + defaults: { author, cdata: ['description', 'title'] }, + items: [], + language: 'en-US', + feedLink, + }; - feed.addNewItem = function (itemTitle, itemLink, pubDate, description, fields) { - var item = { - title: itemTitle, - link: itemLink, - pubDate: pubDate, - description: description, - guid: itemLink, - author: this.defaults.author - }; - for (var field in fields) { - item[field] = fields[field]; - } - - this.items.push(item); - }; - - return feed; + // Non-enumerable so it is not mistaken for a channel tag, while still + // being callable exactly as before. + Object.defineProperty(feed, 'addNewItem', { + enumerable: false, + writable: true, + configurable: true, + value: function addNewItem(itemTitle, itemLink, pubDate, description, fields) { + const item = { + title: itemTitle, + link: itemLink, + pubDate, + description, + guid: itemLink, + author: this.defaults.author, + }; + assignCustomFields(item, fields, new Set()); + this.items.push(item); + return item; + }, + }); + + assignCustomFields(feed, options, RESERVED_FEED_KEYS); + + return feed; }; -exports.getFeedXML = function (feed) { - var doc = new libxml.Document("1.0", "utf-8"); - var root = doc.node('rss'); - var rssNodeProps = { - 'xmlns:content': 'http://purl.org/rss/1.0/modules/content/', - 'xmlns:wfw': 'http://wellformedweb.org/CommentAPI/', - 'xmlns:dc': 'http://purl.org/dc/elements/1.1/', - 'xmlns:atom': 'http://www.w3.org/2005/Atom', - 'xmlns:sy': 'http://purl.org/rss/1.0/modules/syndication/', - 'xmlns:slash': 'http://purl.org/rss/1.0/modules/slash/' - }; - root.attr({ 'version': '2.0' }); - for (var i in rssNodeProps) { - root.attr(i, rssNodeProps[i]); +/** + * Serialize a feed object to an RSS 2.0 XML string. + * + * @param {Object} feed a feed built by createNewFeed + * @returns {string} the feed XML + */ +exports.getFeedXML = function getFeedXML(feed) { + if (!feed || typeof feed !== 'object') { + throw new TypeError('node-rss: getFeedXML requires a feed object'); + } + + const defaults = feed.defaults || {}; + const cdataTags = new Set(Array.isArray(defaults.cdata) ? defaults.cdata : []); + const items = Array.isArray(feed.items) ? feed.items : []; + + const rssAttrs = { + version: '2.0', + 'xmlns:content': 'http://purl.org/rss/1.0/modules/content/', + 'xmlns:wfw': 'http://wellformedweb.org/CommentAPI/', + 'xmlns:dc': 'http://purl.org/dc/elements/1.1/', + 'xmlns:atom': 'http://www.w3.org/2005/Atom', + 'xmlns:sy': 'http://purl.org/rss/1.0/modules/syndication/', + 'xmlns:slash': 'http://purl.org/rss/1.0/modules/slash/', + }; + + let xml = '\n\n'; + + for (const key of Object.keys(feed)) { + if (RESERVED_FEED_KEYS.has(key)) { + continue; } - var channel = root.node('channel'); - for (var nd in feed) { - if (nd != 'items' && nd != 'defaults' && nd != 'feedLink' && nd != 'addNewItem') { - if (feed.defaults.cdata.indexOf(nd) == -1) { - channel.node(nd, feed[nd]); - } else { - channel.node(nd).cdata(feed[nd]); - } - } + xml += renderElement(key, feed[key], cdataTags.has(key), 2); + } + + xml += renderElement('atom:link', null, false, 2, { + href: feed.feedLink, + rel: 'self', + type: 'application/rss+xml', + }); + xml += renderElement('lastBuildDate', new Date(), false, 2); + + for (const item of items) { + xml += INDENT.repeat(2) + '\n'; + for (const key of Object.keys(item)) { + xml += renderElement(key, item[key], cdataTags.has(key), 3); } - var aLink = channel.node('atom:link'); - aLink.attr({ href: feed.feedLink, rel: 'self', type: 'application/rss+xml' }); - var now = new Date(); - channel.node('lastBuildDate', now.toUTCString()); - - feed.items.forEach(function (item) { - var itemNode = channel.node('item'); - - for (var nd in item) { - if (feed.defaults.cdata.indexOf(nd) == -1) { - itemNode.node(nd, item[nd]); - } else { - itemNode.node(nd).cdata(item[nd]); - } - } - }); - return doc.toString(); + xml += INDENT.repeat(2) + '\n'; + } + + xml += INDENT + '\n\n'; + return xml; }; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..cea24a8 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,16 @@ +{ + "name": "node-rss", + "version": "2.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "node-rss", + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } + } + } +} diff --git a/package.json b/package.json index fb69b13..d77f2de 100644 --- a/package.json +++ b/package.json @@ -1,21 +1,39 @@ { "name": "node-rss", - "version": "1.0.5", - "description": "Node.js package for efficently creating RSS feeds", + "version": "2.0.0", + "description": "Node.js package for efficiently creating RSS feeds", "main": "lib/node-rss.js", + "type": "commonjs", + "exports": { + ".": "./lib/node-rss.js", + "./lib/*": "./lib/*" + }, + "files": [ + "lib", + "README.md", + "LICENSE" + ], + "engines": { + "node": ">=20.0.0" + }, "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" + "test": "node --test" }, "repository": { "type": "git", - "url": "https://github.com/ebensing/node-rss" + "url": "git+https://github.com/ebensing/node-rss.git" }, - "dependencies" : { - "libxmljs" : "0.15.x" + "bugs": { + "url": "https://github.com/ebensing/node-rss/issues" }, + "homepage": "https://github.com/ebensing/node-rss#readme", "keywords": [ - "rss" + "rss", + "feed", + "xml", + "atom", + "syndication" ], "author": "EJ Bensing", - "license": "BSD" + "license": "MIT" } diff --git a/test/node-rss.test.js b/test/node-rss.test.js new file mode 100644 index 0000000..57e18ba --- /dev/null +++ b/test/node-rss.test.js @@ -0,0 +1,243 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const rss = require('../lib/node-rss.js'); + +function makeFeed(options) { + return rss.createNewFeed( + 'Blog Most Recent', + 'http://someurl.com/', + 'Most recent blog entries', + 'EJ Bensing', + 'http://someurl.com/rss/MostRecent.xml', + options + ); +} + +test('createNewFeed populates the documented defaults', () => { + const feed = makeFeed(); + + assert.equal(feed.title, 'Blog Most Recent'); + assert.equal(feed.link, 'http://someurl.com/'); + assert.equal(feed.description, 'Most recent blog entries'); + assert.equal(feed.feedLink, 'http://someurl.com/rss/MostRecent.xml'); + assert.equal(feed.language, 'en-US'); + assert.equal(feed.defaults.author, 'EJ Bensing'); + assert.deepEqual(feed.defaults.cdata, ['description', 'title']); + assert.deepEqual(feed.items, []); + assert.equal(typeof feed.addNewItem, 'function'); +}); + +test('addNewItem records an item with the feed author as a default', () => { + const feed = makeFeed(); + const when = new Date('2026-01-02T03:04:05Z'); + feed.addNewItem('post 1', 'http://someurl.com/1', when, 'a description'); + + assert.equal(feed.items.length, 1); + assert.deepEqual(feed.items[0], { + title: 'post 1', + link: 'http://someurl.com/1', + pubDate: when, + description: 'a description', + guid: 'http://someurl.com/1', + author: 'EJ Bensing', + }); +}); + +test('getFeedXML produces a well-formed RSS 2.0 document', () => { + const feed = makeFeed(); + feed.addNewItem('post 1', 'http://someurl.com/1', new Date(), 'a description'); + const xml = rss.getFeedXML(feed); + + assert.match(xml, /^<\?xml version="1\.0" encoding="utf-8"\?>\n/); + assert.match(xml, //); + assert.match( + xml, + // + ); + assert.match(xml, /[^<]+<\/lastBuildDate>/); + assert.match(xml, /<\/channel>\n<\/rss>\n$/); + + // Every opened tag is closed exactly once. + const opened = xml.match(/<([A-Za-z][\w:.-]*)(?=[\s>/])/g).length; + const closed = xml.match(/<\/[A-Za-z][\w:.-]*>/g).length; + const selfClosed = xml.match(/\/>/g).length; + assert.equal(opened, closed + selfClosed); +}); + +test('feed-level bookkeeping properties are not serialized as tags', () => { + const xml = rss.getFeedXML(makeFeed()); + + assert.doesNotMatch(xml, / { + const feed = makeFeed(); + feed.addNewItem('post & one', 'http://someurl.com/?a=1&b=2', new Date(), 'x'); + const xml = rss.getFeedXML(feed); + + // title and description are in defaults.cdata + assert.match(xml, /<!\[CDATA\[post & <b>one<\/b>\]\]><\/title>/); + // link is not, so its ampersand must be escaped + assert.match(xml, /<link>http:\/\/someurl\.com\/\?a=1&b=2<\/link>/); +}); + +test('markup in non-cdata text is escaped rather than injected', () => { + const feed = makeFeed(); + feed.addNewItem('t', 'http://x/', new Date(), 'd', { + 'content:encoded': '</item><item><title>injected', + }); + const xml = rss.getFeedXML(feed); + + assert.match(xml, /<\/item><item>/); + assert.equal(xml.match(//g).length, 1); + assert.doesNotMatch(xml, /injected<\/title>/); +}); + +test('a CDATA-terminating sequence cannot break out of its section', () => { + const feed = makeFeed(); + feed.addNewItem('t', 'http://x/', new Date(), 'safe]]><script>alert(1)</script>'); + const xml = rss.getFeedXML(feed); + + // The payload stays inside CDATA: the raw `]]>` is split, so no bare + // `<script>` element ever appears in the document. + assert.doesNotMatch(xml, /\]\]><script>/); + assert.match(xml, /safe\]\]\]\]><!\[CDATA\[><script>/); + + // The payload created no extra elements: description tags stay balanced + // (one on the channel, one on the item) and no <script> element exists. + assert.equal(xml.match(/<description>/g).length, 2); + assert.equal(xml.match(/<\/description>/g).length, 2); + assert.equal(xml.match(/<item>/g).length, 1); +}); + +test('quotes and newlines in attribute values are escaped', () => { + const feed = rss.createNewFeed( + 't', + 'http://x/', + 'd', + 'a', + 'http://x/feed.xml" onload="alert(1)' + ); + const xml = rss.getFeedXML(feed); + + assert.match(xml, /href="http:\/\/x\/feed\.xml" onload="alert\(1\)"/); + assert.doesNotMatch(xml, /onload="alert/); +}); + +test('Date values are serialized as RFC-1123, which RSS requires', () => { + const feed = makeFeed(); + const when = new Date('2026-01-02T03:04:05Z'); + feed.addNewItem('t', 'http://x/', when, 'd'); + const xml = rss.getFeedXML(feed); + + assert.match(xml, /<pubDate>Fri, 02 Jan 2026 03:04:05 GMT<\/pubDate>/); +}); + +test('an invalid Date serializes as empty rather than "Invalid Date"', () => { + const feed = makeFeed(); + feed.addNewItem('t', 'http://x/', new Date('nope'), 'd'); + const xml = rss.getFeedXML(feed); + + assert.match(xml, /<pubDate\/>/); + assert.doesNotMatch(xml, /Invalid Date/); +}); + +test('characters that XML cannot represent are stripped', () => { + const illegal = [0x00, 0x08, 0x0b, 0x0c, 0x1f, 0xfffe, 0xffff] + .map((code) => String.fromCharCode(code)) + .join(''); + + const feed = makeFeed(); + feed.addNewItem('t', 'http://x/', new Date(), `bad${illegal}data`, { + // Tab, newline and carriage return are legal XML and must survive. + note: 'tab\there\nand\rmore', + }); + const xml = rss.getFeedXML(feed); + + assert.match(xml, /<!\[CDATA\[baddata\]\]>/); + assert.match(xml, /<note>tab\there\nand\rmore<\/note>/); + for (const char of illegal) { + assert.equal(xml.includes(char), false); + } +}); + +test('unpaired surrogates are stripped but valid pairs survive', () => { + const feed = makeFeed(); + feed.addNewItem('t', 'http://x/', new Date(), 'lone\uD800ok\uDC00 pair\u{1F600}'); + const xml = rss.getFeedXML(feed); + + assert.match(xml, /loneok pair\u{1F600}/u); + assert.equal(xml.includes('\uD800'), false); +}); + +test('custom channel tags and item fields are emitted', () => { + const feed = makeFeed({ CustomTag: 'a custom channel tag', 'dc:creator': 'someone' }); + feed.addNewItem('t', 'http://x/', new Date(), 'd', { category: 'news' }); + const xml = rss.getFeedXML(feed); + + assert.match(xml, /<CustomTag>a custom channel tag<\/CustomTag>/); + assert.match(xml, /<dc:creator>someone<\/dc:creator>/); + assert.match(xml, /<category>news<\/category>/); +}); + +test('tag names that are not valid XML names are rejected', () => { + for (const bad of ['bad name', 'bad>name', '1leading', 'a:b:c', '<script>', '']) { + assert.throws( + () => makeFeed({ [bad]: 'x' }), + /not a valid XML element name/, + `expected ${JSON.stringify(bad)} to be rejected` + ); + } +}); + +test('prototype-polluting keys are rejected', () => { + assert.throws( + () => makeFeed(JSON.parse('{"__proto__": "x"}')), + /not an allowed tag name/ + ); + assert.throws(() => makeFeed({ constructor: 'x' }), /not an allowed tag name/); + + const feed = makeFeed(); + assert.throws( + () => feed.addNewItem('t', 'http://x/', new Date(), 'd', JSON.parse('{"prototype": "x"}')), + /not an allowed tag name/ + ); + assert.equal({}.x, undefined); +}); + +test('options cannot clobber the feed API', () => { + for (const key of ['items', 'defaults', 'feedLink', 'addNewItem']) { + assert.throws(() => makeFeed({ [key]: 'x' }), /is reserved/, `expected ${key} to be rejected`); + } +}); + +test('inherited properties on option objects are ignored', () => { + const parent = { inherited: 'should not appear' }; + const options = Object.create(parent); + options.own = 'should appear'; + const xml = rss.getFeedXML(makeFeed(options)); + + assert.match(xml, /<own>should appear<\/own>/); + assert.doesNotMatch(xml, /inherited/); +}); + +test('getFeedXML rejects non-feed input', () => { + for (const bad of [undefined, null, 'nope', 42]) { + assert.throws(() => rss.getFeedXML(bad), TypeError); + } +}); + +test('getFeedXML tolerates a feed with no items or defaults', () => { + const xml = rss.getFeedXML({ title: 'bare' }); + + assert.match(xml, /<title>bare<\/title>/); + assert.match(xml, /<\/channel>\n<\/rss>\n$/); +});