Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: consolidate XML-entity decoders into shared server/lib/xmlEntities.js (#1876)

[._.]/ Adam Eivya492727ab23b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 923209f1c3..fe77a529ca 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -55,3 +55,4 @@
- **Dropped the `sax` dependency from the Apple Health XML importer** — the 500MB-export streaming path now uses a self-contained ~190-line `Record` parser (`server/services/appleHealthXmlParser.js`) that splits the byte stream on `<Record>` tag boundaries and parses attributes with a quote-aware scan, preserving the prior backpressure (caller pauses the source stream) and error-skip (malformed records dropped, not fatal) behavior. Per the PortOS "write small helpers yourself" policy; covered by new unit + chunk-boundary tests. Partial-ships the `sax` half of #1824; the client `three-fenestra` shader replacement is tracked separately. (#1824)
- **[issue-1837] On-disk JSON writes are now crash-safe across ~50 service/route files** — ~73 persistence sites used a raw `writeFile(path, JSON.stringify(data, null, 2))`, which truncates the JSON file if the process crashes mid-write (leaving an unparseable half-record on disk). Each was swapped to the canonical `atomicWrite` helper (`server/lib/fileUtils.js`), which writes to a temp file and atomically renames it over the target so readers never see a partial write. Covers brain storage, run/agent metadata, decision log, meatspace (calendar/alcohol/nicotine/health/post), mortal-loom store, identity goals, image/video sidecars, GitHub/Google/Obsidian configs, taste/usage/genome/epigenetic stores, and the scaffolding routes. Sites that intentionally append a trailing newline keep their exact byte output (passed as a pre-stringified string), and `videoGen/local.js`'s `{ flag: 'wx' }` exclusive-create write is left as-is (atomicWrite can't replicate exclusive-create). (#1837)
- **[issue-1846] Replaced vacuous inline-copy tests with coverage of real production logic** — `subAgentSpawner.test.js` had four `describe` blocks that re-implemented production logic inline and tested the copies, so the real code could regress while the suite stayed green: an inline `ERROR_PATTERNS`/`categorizeError`, an inline `resolveFailedTaskStatus` (which omitted the `MAX_TOTAL_SPAWNS` short-circuit and `compaction` metadata that the real `resolveFailedTaskUpdate` has), and stub `exitCodeMessages`/`buildSpawnArgs` literals exported from no production module. The error-classification and retry-decision blocks now live in `agentErrorAnalysis.test.js` against the real exported `ERROR_PATTERNS` (via `analyzeAgentFailure`) and a new pure `resolveFailedTaskDecision` helper extracted from `resolveFailedTaskUpdate` (the async wrapper delegates to it and just stamps timestamps + creates the investigation task — behavior-preserving); the exit-code block is replaced by a new `agentRunTracking.test.js` covering the real `extractErrorFromOutput` mapping; and the redundant spawn-args stub is dropped since `agentCliSpawning.test.js` already covers the real `buildCliSpawnConfig`. The genuine imported-helper tests (`isTruthyMeta`/`isFalsyMeta`/`applyAppWorktreeDefault`) are kept. (#1846)
+- **[issue-1876] Consolidated four private XML-entity decoders into a shared `server/lib/xmlEntities.js`** — `decodeXmlEntities`/`decodeEntities`/inline `stripHtml` had drifted into near-identical copies across `appleHealthXmlParser.js`, `claudeChangelog.js`, `pinterestFeed.js`, `feeds.js`, and `messageGmailSync.js`, so an entity-handling fix had to be applied in up to five places. The most complete implementation (named + decimal `&#NN;` + hex `&#xNN;` via a single double-decode-safe pass, out-of-range-tolerant) is promoted to a shared, barrel-registered helper that also takes an optional extra-named-entity map (`{ nbsp: ' ', zwnj: '' }`) for the mail-specific entities Gmail's HTML-to-text needs; every call site now imports it. Behavior-preserving (each site's existing tests pass on the shared single-pass decoder); covered by a new `xmlEntities.test.js`. (#1876)
diff --git a/server/lib/README.md b/server/lib/README.md
index a4e7cec82d..25d60119c5 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -182,6 +182,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
|---|---|
| `jsonExtract.js` | Pull JSON blocks out of LLM responses. |
| `taskParser.js` | Parse `TASKS.md` format. |
+| `xmlEntities.js` | Shared dependency-free XML/HTML entity decoder. `decodeXmlEntities(str, extraEntities?)` — single-pass (double-decode-safe) decode of the five predefined named entities + decimal/hex numeric refs, with an optional caller-supplied extra-entity map (e.g. `{ nbsp: ' ', zwnj: '' }`). Unknown/out-of-range refs left untouched. Used by the Apple Health XML parser, Claude changelog feed, Pinterest RSS, generic feeds, and Gmail HTML-to-text. |
## Curated static data
diff --git a/server/lib/index.js b/server/lib/index.js
index a99ca861d0..6f474f9512 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -164,6 +164,7 @@ export * from './vectorMath.js';
// === Extraction & parsing ===
export * from './jsonExtract.js';
export * from './taskParser.js';
+export * from './xmlEntities.js';
// === Curated static data ===
export * from './curatedGenomeMarkers.js';
diff --git a/server/lib/pinterestFeed.js b/server/lib/pinterestFeed.js
index f7fada1ad8..d50d15b1e3 100644
--- a/server/lib/pinterestFeed.js
+++ b/server/lib/pinterestFeed.js
@@ -14,6 +14,8 @@
* the download/persist orchestration in `services/moodBoard/pinterest.js`.
*/
+import { decodeXmlEntities } from './xmlEntities.js';
+
import { ServerError } from './errorHandler.js';
// Explicit allow-list of Pinterest's REGISTRABLE domains. A registrable-label
@@ -95,10 +97,10 @@ export function normalizePinterestFeedUrl(input) {
// Minimal HTML-entity decode for URLs/titles pulled out of the feed (the
// feed escapes `&` as `&amp;` inside attribute values, which would corrupt an
-// image URL's query string if left encoded).
+// image URL's query string if left encoded). Trims, like the rest of the feed
+// extractors. Numeric refs (`&#39;`, `&#039;`) are handled by the shared decoder.
const decodeEntities = (s) => (typeof s === 'string'
- ? s.replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
- .replace(/&quot;/g, '"').replace(/&#0?39;/g, "'").trim()
+ ? decodeXmlEntities(s).trim()
: s);
// Non-greedy single-tag text extractor (CDATA-aware). Mirrors feeds.js's
@@ -111,10 +113,7 @@ const extractTag = (xml, tag) => {
return m ? m[1].trim() : '';
};
-const stripHtml = (html) => html
- .replace(/<[^>]+>/g, ' ')
- .replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
- .replace(/&quot;/g, '"').replace(/&#0?39;/g, "'")
+const stripHtml = (html) => decodeXmlEntities(html.replace(/<[^>]+>/g, ' '))
.replace(/\s+/g, ' ')
.trim();
diff --git a/server/lib/xmlEntities.js b/server/lib/xmlEntities.js
new file mode 100644
index 0000000000..dba9fab6b5
--- /dev/null
+++ b/server/lib/xmlEntities.js
@@ -0,0 +1,61 @@
+/**
+ * Shared XML / HTML entity decoder.
+ *
+ * A single dependency-free decoder for the entity references that appear in the
+ * various feeds and exports PortOS parses (Apple Health `export.xml`, GitHub
+ * release Atom feeds, Pinterest/RSS/Atom feeds, Gmail HTML bodies). It replaces
+ * what used to be four near-identical private copies (issue #1876).
+ *
+ * Handles, in a single left-to-right pass:
+ * - the five predefined named entities (`&amp;` `&lt;` `&gt;` `&quot;` `&apos;`)
+ * - decimal numeric refs (`&#NN;`)
+ * - hex numeric refs (`&#xNN;` / `&#XNN;`)
+ * - any extra named entities supplied by the caller (e.g. `&nbsp;`, `&zwnj;`)
+ *
+ * Single-pass is intentionally double-decode-safe: because `&amp;` is consumed
+ * in the same scan as everything else, a literal `&amp;lt;` in the source
+ * decodes to `&lt;` (not `<`) — the scanner does not re-examine the `&` it just
+ * emitted. Unknown entities and out-of-range numeric code points are left
+ * untouched rather than dropped or thrown on, so one malformed reference can't
+ * corrupt or abort the surrounding parse.
+ */
+
+const NAMED_ENTITIES = {
+ amp: '&',
+ lt: '<',
+ gt: '>',
+ quot: '"',
+ apos: "'",
+};
+
+const ENTITY_RE = /&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z][a-zA-Z0-9]*);/g;
+
+/**
+ * Decode the XML/HTML entities in a string.
+ *
+ * @param {string} str - Raw text that may contain entity references.
+ * @param {Object<string,string>} [extraEntities] - Optional extra named-entity
+ * map (without the surrounding `&`/`;`), merged on top of the predefined five.
+ * Lets callers decode feed-specific entities such as `{ nbsp: ' ', zwnj: '' }`
+ * while sharing the numeric-reference and double-decode handling.
+ * @returns {string} Decoded string. Non-strings and entity-free input are
+ * returned unchanged.
+ */
+export function decodeXmlEntities(str, extraEntities) {
+ if (typeof str !== 'string' || str.indexOf('&') === -1) return str;
+ return str.replace(ENTITY_RE, (match, code) => {
+ if (code[0] === '#') {
+ const cp = code[1] === 'x' || code[1] === 'X'
+ ? parseInt(code.slice(2), 16)
+ : parseInt(code.slice(1), 10);
+ // Leave out-of-range / non-Unicode code points untouched — String
+ // .fromCodePoint throws a RangeError for cp < 0 or > 0x10FFFF. A malformed
+ // numeric entity in one record must not fail the whole parse/import.
+ return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : match;
+ }
+ if (extraEntities && Object.prototype.hasOwnProperty.call(extraEntities, code)) {
+ return extraEntities[code];
+ }
+ return NAMED_ENTITIES[code] ?? match;
+ });
+}
diff --git a/server/lib/xmlEntities.test.js b/server/lib/xmlEntities.test.js
new file mode 100644
index 0000000000..a652218920
--- /dev/null
+++ b/server/lib/xmlEntities.test.js
@@ -0,0 +1,57 @@
+import { describe, it, expect } from 'vitest';
+import { decodeXmlEntities } from './xmlEntities.js';
+
+describe('decodeXmlEntities', () => {
+ it('returns the input unchanged when there are no entities', () => {
+ expect(decodeXmlEntities('plain text')).toBe('plain text');
+ expect(decodeXmlEntities('')).toBe('');
+ });
+
+ it('returns non-strings unchanged', () => {
+ expect(decodeXmlEntities(undefined)).toBe(undefined);
+ expect(decodeXmlEntities(null)).toBe(null);
+ expect(decodeXmlEntities(42)).toBe(42);
+ });
+
+ it('decodes the five predefined named entities', () => {
+ expect(decodeXmlEntities('A &amp; B')).toBe('A & B');
+ expect(decodeXmlEntities('&lt;tag&gt;')).toBe('<tag>');
+ expect(decodeXmlEntities('say &quot;hi&quot;')).toBe('say "hi"');
+ expect(decodeXmlEntities('it&apos;s')).toBe("it's");
+ });
+
+ it('decodes decimal numeric references', () => {
+ expect(decodeXmlEntities('&#39;')).toBe("'");
+ expect(decodeXmlEntities('&#039;')).toBe("'"); // leading-zero form
+ expect(decodeXmlEntities('caf&#233;')).toBe('café');
+ });
+
+ it('decodes hex numeric references (XML-conformant lowercase x)', () => {
+ expect(decodeXmlEntities('caf&#xe9;')).toBe('café');
+ expect(decodeXmlEntities('&#x1F600;')).toBe(String.fromCodePoint(0x1f600)); // emoji, multi-byte
+ });
+
+ it('leaves unknown named entities untouched', () => {
+ expect(decodeXmlEntities('&bogus;')).toBe('&bogus;');
+ expect(decodeXmlEntities('&nbsp;')).toBe('&nbsp;'); // not predefined without extras
+ });
+
+ it('does not throw and leaves out-of-range numeric references untouched', () => {
+ expect(() => decodeXmlEntities('&#999999999999;')).not.toThrow();
+ expect(decodeXmlEntities('&#999999999999;')).toBe('&#999999999999;');
+ expect(decodeXmlEntities('&#x110000;')).toBe('&#x110000;'); // just past U+10FFFF
+ expect(decodeXmlEntities('&#x10FFFF;')).toBe(String.fromCodePoint(0x10ffff)); // max valid
+ });
+
+ it('is double-decode safe in a single pass (&amp;lt; → &lt;, not <)', () => {
+ expect(decodeXmlEntities('&amp;lt;')).toBe('&lt;');
+ expect(decodeXmlEntities('a &amp;amp; b')).toBe('a &amp; b');
+ });
+
+ it('applies caller-supplied extra named entities, including empty-string targets', () => {
+ expect(decodeXmlEntities('one&nbsp;two', { nbsp: ' ' })).toBe('one two');
+ expect(decodeXmlEntities('zero&zwnj;width', { zwnj: '' })).toBe('zerowidth');
+ // extras compose with the predefined set in one pass
+ expect(decodeXmlEntities('a&nbsp;&amp;&nbsp;b', { nbsp: ' ' })).toBe('a & b');
+ });
+});
diff --git a/server/services/appleHealthXmlParser.js b/server/services/appleHealthXmlParser.js
index 7e099557f2..16a4de6d4c 100644
--- a/server/services/appleHealthXmlParser.js
+++ b/server/services/appleHealthXmlParser.js
@@ -18,6 +18,7 @@
import { Writable } from 'stream';
import { StringDecoder } from 'string_decoder';
+import { decodeXmlEntities } from '../lib/xmlEntities.js';
const RECORD_TAG = '<Record';
@@ -28,37 +29,11 @@ const RECORD_TAG = '<Record';
// preserving the "skip the bad record, keep importing" contract sax provided.
const MAX_OPEN_TAG = 64 * 1024;
-const NAMED_ENTITIES = {
- amp: '&',
- lt: '<',
- gt: '>',
- quot: '"',
- apos: "'",
-};
-
-/**
- * Decode the XML entities that can appear in attribute values (named + numeric).
- * Apple Health source/device names occasionally carry `&amp;` and friends.
- *
- * @param {string} str - Raw attribute value
- * @returns {string} Decoded value (unchanged if it contains no entities)
- */
-export function decodeXmlEntities(str) {
- if (!str || str.indexOf('&') === -1) return str;
- return str.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z][a-zA-Z0-9]*);/g, (match, code) => {
- if (code[0] === '#') {
- const cp = code[1] === 'x' || code[1] === 'X'
- ? parseInt(code.slice(2), 16)
- : parseInt(code.slice(1), 10);
- // Leave out-of-range / non-Unicode code points untouched — String
- // .fromCodePoint throws a RangeError for cp < 0 or > 0x10FFFF, which,
- // running inside the stream's synchronous write, would reject the entire
- // import. A malformed entity in one record must not fail the whole upload.
- return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : match;
- }
- return NAMED_ENTITIES[code] ?? match;
- });
-}
+// Apple Health source/device names occasionally carry `&amp;` and friends. The
+// decoder lives in the shared `server/lib/xmlEntities.js` (named + decimal/hex
+// numeric, double-decode-safe, out-of-range-tolerant); re-exported here because
+// this module's tests and callers reference `decodeXmlEntities` by this path.
+export { decodeXmlEntities };
const ATTR_RE = /([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
diff --git a/server/services/claudeChangelog.js b/server/services/claudeChangelog.js
index 891373c1de..821498bd73 100644
--- a/server/services/claudeChangelog.js
+++ b/server/services/claudeChangelog.js
@@ -9,6 +9,7 @@
import { join } from 'path'
import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js'
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
+import { decodeXmlEntities } from '../lib/xmlEntities.js'
const FEED_URL = 'https://github.com/anthropics/claude-code/releases.atom'
const STATE_FILE = join(PATHS.data, 'claude-changelog.json')
@@ -22,18 +23,9 @@ const defaultState = () => ({
entries: []
})
-// Decode the five XML predefined entities (the only ones a text feed uses
-// outside CDATA). `&amp;` is intentionally last so a literal "&amp;lt;" in the
-// source decodes to "&lt;" rather than being double-decoded to "<".
-function decodeXmlEntities(s) {
- return s
- .replace(/&lt;/g, '<')
- .replace(/&gt;/g, '>')
- .replace(/&quot;/g, '"')
- .replace(/&#39;/g, "'")
- .replace(/&apos;/g, "'")
- .replace(/&amp;/g, '&')
-}
+// Entity decoding is the shared `server/lib/xmlEntities.js` single-pass decoder
+// (named + numeric). It is double-decode-safe — a literal "&amp;lt;" decodes to
+// "&lt;", not "<" — which preserves the guard this feed used to chain manually.
// Pull the first <tag>…</tag> text from an <entry> block. CDATA-wrapped
// content (GitHub wraps release notes in <![CDATA[…]]>) is returned verbatim;
diff --git a/server/services/feeds.js b/server/services/feeds.js
index 8d18025a54..1e0dad5343 100644
--- a/server/services/feeds.js
+++ b/server/services/feeds.js
@@ -14,6 +14,7 @@ import dns from 'dns/promises';
import net from 'net';
import { PATHS, createCachedStore } from '../lib/fileUtils.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
+import { decodeXmlEntities } from '../lib/xmlEntities.js';
const FEEDS_FILE = join(PATHS.data, 'feeds.json');
const MAX_ITEMS_PER_FEED = 100;
@@ -80,7 +81,7 @@ const extractAtomLink = (xml) => {
/**
* Strip HTML tags from a string for plain text display.
*/
-const stripHtml = (html) => html.replace(/<[^>]+>/g, '').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").trim();
+const stripHtml = (html) => decodeXmlEntities(html.replace(/<[^>]+>/g, '')).trim();
/**
* Parse RSS 2.0 feed XML into normalized items.
diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.js
index 45da46eb03..4881bc736c 100644
--- a/server/services/messageGmailSync.js
+++ b/server/services/messageGmailSync.js
@@ -7,6 +7,7 @@ import { gmail } from '@googleapis/gmail';
import { v4 as uuidv4 } from '../lib/uuid.js';
import crypto from 'crypto';
import { getAuthenticatedClient } from './googleAuth.js';
+import { decodeXmlEntities } from '../lib/xmlEntities.js';
function makeExternalId(gmailId) {
return 'api-gmail-' + crypto.createHash('md5').update(gmailId).digest('hex').slice(0, 12);
@@ -27,7 +28,7 @@ function decodeBase64Url(str) {
* Convert HTML to readable plain text by stripping style/script/head blocks, then tags.
*/
function htmlToText(html) {
- return html
+ const stripped = html
.replace(/<head\b[^>]*>[\s\S]*?<\/head>/gi, '')
.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '')
.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')
@@ -36,14 +37,10 @@ function htmlToText(html) {
.replace(/<\/div>/gi, '\n')
.replace(/<\/tr>/gi, '\n')
.replace(/<\/li>/gi, '\n')
- .replace(/<[^>]*>/g, '')
- .replace(/&nbsp;/g, ' ')
- .replace(/&amp;/g, '&')
- .replace(/&lt;/g, '<')
- .replace(/&gt;/g, '>')
- .replace(/&quot;/g, '"')
- .replace(/&#39;/g, "'")
- .replace(/&zwnj;/g, '')
+ .replace(/<[^>]*>/g, '');
+ // Shared decoder handles the named + numeric entities; `&nbsp;`/`&zwnj;` are
+ // mail-specific so they're passed as extra entities (space / zero-width strip).
+ return decodeXmlEntities(stripped, { nbsp: ' ', zwnj: '' })
.replace(/\n{3,}/g, '\n\n')
.replace(/[ \t]+/g, ' ')
.trim();