diff --git a/src/clients/upnp-client.test.ts b/src/clients/upnp-client.test.ts
index 25869f0..d7d80cf 100644
--- a/src/clients/upnp-client.test.ts
+++ b/src/clients/upnp-client.test.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import { tick } from '../__test__/utils.js'
import {
SSDP_IGD_V1_ST,
@@ -224,6 +224,46 @@ describe('UpnpClient.discover', () => {
}
})
+ it('discovers a gateway with Huawei AX3 Unicode metadata (issue #5)', async () => {
+ const body = VALID_DEVICE_XML.replace(
+ 'TestCorp',
+ '华为路由AX3华为 技术'
+ ).replace(
+ 'Test',
+ 'WS7100-15📡'
+ )
+ http.history
+ .expect({
+ method: 'GET',
+ host: '192.168.3.1',
+ port: 37215,
+ path: '/upnpdev.xml',
+ })
+ .reply({ statusCode: 200, body })
+
+ const pending = client.discover({ timeoutMs: 2000 })
+ await tick()
+ udpFactory.sockets[0]!.emitMessage(
+ buildSsdpResponse('http://192.168.3.1:37215/upnpdev.xml'),
+ { address: '192.168.3.1', port: 1900, size: 0 }
+ )
+
+ expect(await pending).toEqual({
+ ok: true,
+ value: {
+ gatewayIp: '192.168.3.1',
+ controlHost: '192.168.3.1',
+ controlPort: 37215,
+ controlUrl: '/ctl/IPConn',
+ serviceType: 'urn:schemas-upnp-org:service:WANIPConnection:1',
+ manufacturer: '华为 技术',
+ modelName: 'WS7100-15📡',
+ },
+ })
+ expect(http.history.calls).toHaveLength(1)
+ expect(udpFactory.sockets[0]!.closed).toBe(true)
+ })
+
it('stops accepting responses after first valid gateway', async () => {
http.history
.expect({
@@ -310,6 +350,53 @@ describe('UpnpClient.discover', () => {
expect(http.history.calls).toHaveLength(0)
})
+ it('ignores an unescaped space in LOCATION and discovers the next gateway', async () => {
+ http.history
+ .expect({ method: 'GET', host: '192.168.1.1', port: 80, path: '/desc' })
+ .reply({ statusCode: 200, body: VALID_DEVICE_XML })
+ const pending = client.discover({ timeoutMs: 1000 })
+ await tick()
+ const socket = udpFactory.sockets[0]!
+ const remote = { address: '192.168.1.1', port: 1900, size: 0 }
+ socket.emitMessage(buildSsdpResponse('http://192.168.1.1/a b'), remote)
+ await tick()
+ socket.emitMessage(buildSsdpResponse('http://192.168.1.1/desc'), remote)
+
+ expect((await pending).ok).toBe(true)
+ expect(http.history.calls).toHaveLength(1)
+ expect(http.history.calls[0]?.path).toBe('/desc')
+ expect(socket.closed).toBe(true)
+ })
+
+ it.each(['throw', 'reject'] as const)(
+ 'continues discovery after an HTTP transport %s',
+ async (failure) => {
+ const request = vi.spyOn(http.client, 'request')
+ const error = new Error('HTTP request setup failed')
+ if (failure === 'throw') {
+ request.mockImplementationOnce(() => {
+ throw error
+ })
+ } else {
+ request.mockRejectedValueOnce(error)
+ }
+ http.history
+ .expect({ method: 'GET', host: '192.168.1.1', port: 80, path: '/desc' })
+ .reply({ statusCode: 200, body: VALID_DEVICE_XML })
+ const pending = client.discover({ timeoutMs: 1000 })
+ await tick()
+ const socket = udpFactory.sockets[0]!
+ const remote = { address: '192.168.1.1', port: 1900, size: 0 }
+ socket.emitMessage(buildSsdpResponse('http://192.168.1.1/failed'), remote)
+ await tick()
+ socket.emitMessage(buildSsdpResponse('http://192.168.1.1/desc'), remote)
+
+ expect((await pending).ok).toBe(true)
+ expect(request).toHaveBeenCalledTimes(2)
+ expect(socket.closed).toBe(true)
+ }
+ )
+
it('times out when no valid response received', async () => {
const r = await client.discover({ timeoutMs: 50 })
expect(r.ok).toBe(false)
diff --git a/src/clients/upnp-client.ts b/src/clients/upnp-client.ts
index 8b0ebf2..bfb9196 100644
--- a/src/clients/upnp-client.ts
+++ b/src/clients/upnp-client.ts
@@ -200,6 +200,11 @@ export class UpnpClient {
modelName: desc.value.modelName,
}
await settle(parseOk(found))
+ } catch (error) {
+ // UDP listeners are not awaited. Keep an unexpected transport
+ // rejection from becoming an unhandled rejection, and try the
+ // next response within the existing discovery budget.
+ log.warn({ err: error }, 'device description fetch failed')
} finally {
processingResponse = false
}
diff --git a/src/codecs/device-desc-parser.test.ts b/src/codecs/device-desc-parser.test.ts
index 0834cd0..7c2721c 100644
--- a/src/codecs/device-desc-parser.test.ts
+++ b/src/codecs/device-desc-parser.test.ts
@@ -34,6 +34,40 @@ const VALID_DESC = `
`
describe('parseDeviceDescription happy path', () => {
+ it('parses the Huawei AX3 Unicode friendlyName regression (issue #5)', () => {
+ const xml = VALID_DESC.replace('Test Router', '华为路由AX3')
+ .replace('TP-LINK', 'Huawei Technologies Co., Ltd.')
+ .replace('AX73', 'WS7100-15')
+ expect(parseDeviceDescription(xml)).toEqual({
+ ok: true,
+ value: {
+ friendlyName: '华为路由AX3',
+ manufacturer: 'Huawei Technologies Co., Ltd.',
+ modelName: 'WS7100-15',
+ services: [
+ {
+ serviceType: 'urn:schemas-upnp-org:service:WANIPConnection:1',
+ controlUrl: '/ctl/IPConn',
+ },
+ ],
+ },
+ })
+ })
+
+ it('preserves Unicode in all device metadata, including surrogate pairs', () => {
+ const xml = VALID_DESC.replace('Test Router', '\u00a0路由器📡\u3000')
+ .replace('TP-LINK', '华为 技术')
+ .replace('AX73', '型号\u{20000}')
+ const r = parseDeviceDescription(xml)
+ expect(r.ok).toBe(true)
+ if (r.ok) {
+ expect(r.value.friendlyName).toBe('\u00a0路由器📡\u3000')
+ expect(r.value.manufacturer).toBe('华为 技术')
+ expect(r.value.modelName).toBe('型号\u{20000}')
+ expect(r.value.services).toHaveLength(1)
+ }
+ })
+
it('extracts manufacturer and model', () => {
const r = parseDeviceDescription(VALID_DESC)
expect(r.ok).toBe(true)
@@ -69,6 +103,23 @@ describe('parseDeviceDescription happy path', () => {
})
describe('parseDeviceDescription security', () => {
+ it.each([
+ '\u0000',
+ '\u000b',
+ '\u007f',
+ '\u0085',
+ '\ufffe',
+ '\ud800',
+ '\udc00',
+ '\udc00\ud800',
+ ])('rejects invalid characters or surrogates %j in friendlyName', (value) => {
+ const r = parseDeviceDescription(
+ VALID_DESC.replace('Test Router', `华为${value}AX3`)
+ )
+ expect(r.ok).toBe(false)
+ if (!r.ok) expect(r.error).toBe(NatErrorCode.SecurityViolation)
+ })
+
it('rejects relative path with ..', () => {
const xml = VALID_DESC.replace('/ctl/IPConn', '/ctl/../../../secret')
const r = parseDeviceDescription(xml)
@@ -91,9 +142,22 @@ describe('parseDeviceDescription security', () => {
it('rejects controlURL with non-ASCII', () => {
const xml = VALID_DESC.replace('/ctl/IPConn', '/ctl/ä')
const r = parseDeviceDescription(xml)
- expect(r.ok).toBe(false)
+ expect(r).toEqual({
+ ok: false,
+ error: NatErrorCode.SecurityViolation,
+ detail: 'controlURL has disallowed byte',
+ })
})
+ it.each(['\u00a0/ctl/IPConn', '/ctl/IPConn\u3000'])(
+ 'does not trim Unicode whitespace out of controlURL %j',
+ (value) => {
+ const r = parseDeviceDescription(VALID_DESC.replace('/ctl/IPConn', value))
+ expect(r.ok).toBe(false)
+ if (!r.ok) expect(r.error).toBe(NatErrorCode.SecurityViolation)
+ }
+ )
+
it('rejects descriptions exceeding size', () => {
const huge = `${''.repeat(30000)}`
const r = parseDeviceDescription(huge)
diff --git a/src/codecs/ssdp-codec.test.ts b/src/codecs/ssdp-codec.test.ts
index 7a36096..d73dbfc 100644
--- a/src/codecs/ssdp-codec.test.ts
+++ b/src/codecs/ssdp-codec.test.ts
@@ -334,6 +334,21 @@ describe('validateLocationUrl additional branches', () => {
})
describe('validateLocationUrl direct call', () => {
+ it('rejects unescaped spaces in the request path', () => {
+ expect(validateLocationUrl('http://192.168.1.1/a b')).toEqual({
+ ok: false,
+ error: NatErrorCode.SecurityViolation,
+ detail: 'path contains disallowed byte',
+ })
+ })
+
+ it('preserves percent-encoded spaces in the request path', () => {
+ expect(validateLocationUrl('http://192.168.1.1/a%20b')).toEqual({
+ ok: true,
+ value: { host: '192.168.1.1', port: 80, path: '/a%20b' },
+ })
+ })
+
it('rejects path containing disallowed byte (direct call bypasses byte scanner)', () => {
// validateLocationUrl is exported — call it directly with a URL whose path
// contains a control character that would be blocked by parseMSearchResponse
diff --git a/src/codecs/ssdp-codec.ts b/src/codecs/ssdp-codec.ts
index 86003bd..2296c1a 100644
--- a/src/codecs/ssdp-codec.ts
+++ b/src/codecs/ssdp-codec.ts
@@ -172,7 +172,7 @@ export function validateLocationUrl(url: string): ParseResult<{
for (let i = 0; i < path.length; i++) {
const c = path.charCodeAt(i)
- if (c < 0x20 || c > 0x7e) {
+ if (c <= 0x20 || c > 0x7e) {
return parseErr(
NatErrorCode.SecurityViolation,
'path contains disallowed byte'
diff --git a/src/codecs/xml-parser.test.ts b/src/codecs/xml-parser.test.ts
index 4f82e2b..453cf70 100644
--- a/src/codecs/xml-parser.test.ts
+++ b/src/codecs/xml-parser.test.ts
@@ -19,6 +19,16 @@ describe('parseXml happy path', () => {
if (r.ok) expect(r.value.text).toBe('hello')
})
+ it('trims XML whitespace while preserving Unicode text and attributes', () => {
+ const text = '\u00a0华为📡\u3000'
+ const r = parseXml(` \t\r\n${text} \t\r\n`)
+ expect(r.ok).toBe(true)
+ if (r.ok) {
+ expect(r.value.text).toBe(text)
+ expect(r.value.attrs.name).toBe(text)
+ }
+ })
+
it('parses attributes', () => {
const r = parseXml('')
expect(r.ok).toBe(true)
@@ -89,6 +99,23 @@ describe('parseXml limits', () => {
})
describe('parseXml security', () => {
+ it.each(['\u00a0', '\u2003', '\u2028', '\u3000'])(
+ 'rejects non-XML whitespace %j outside the root',
+ (space) => {
+ for (const xml of [
+ `${space}`,
+ `${space}`,
+ `${space}`,
+ ]) {
+ expect(parseXml(xml)).toEqual({
+ ok: false,
+ error: NatErrorCode.ParseError,
+ detail: 'text outside root element',
+ })
+ }
+ }
+ )
+
it('rejects XXE', () => {
const xxe =
']>&xxe;'
diff --git a/src/codecs/xml-parser.ts b/src/codecs/xml-parser.ts
index 6665f49..81399bc 100644
--- a/src/codecs/xml-parser.ts
+++ b/src/codecs/xml-parser.ts
@@ -5,6 +5,7 @@ import {
tokenizeXml,
XmlTokenType,
} from './xml-tokenizer.js'
+import { trimXmlWhitespace } from './xml-whitespace.js'
export interface XmlElement {
name: string
@@ -81,7 +82,7 @@ export function parseXml(
}
} else {
if (stack.length === 0) {
- if (token.value.trim().length > 0) {
+ if (/[^ \t\r\n]/.test(token.value)) {
return parseErr(NatErrorCode.ParseError, 'text outside root element')
}
continue
@@ -102,7 +103,8 @@ export function parseXml(
}
function trimTextRecursively(el: XmlElement): void {
- el.text = el.text.trim()
+ // Trim XML S only, preserving Unicode characters such as NBSP in data.
+ el.text = trimXmlWhitespace(el.text)
for (const child of el.children) trimTextRecursively(child)
}
diff --git a/src/codecs/xml-tokenizer.test.ts b/src/codecs/xml-tokenizer.test.ts
index 1b7b114..d959755 100644
--- a/src/codecs/xml-tokenizer.test.ts
+++ b/src/codecs/xml-tokenizer.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'
import { NatErrorCode } from '../errors.js'
import { tokenizeXml, XmlTokenType } from './xml-tokenizer.js'
-describe('xml-tokenizer byte-level safety', () => {
+describe('xml-tokenizer character safety', () => {
it('rejects input exceeding max size', () => {
const xml = `${'x'.repeat(64 * 1024)}`
const r = tokenizeXml(xml, { maxSize: 1024 })
@@ -11,16 +11,159 @@ describe('xml-tokenizer byte-level safety', () => {
if (!r.ok) expect(r.error).toBe(NatErrorCode.SecurityViolation)
})
- it('rejects non-ASCII bytes', () => {
- const xml = '\u00e9'
- const r = tokenizeXml(xml)
- expect(r.ok).toBe(false)
+ it('enforces the UTF-8 byte budget for Unicode input', () => {
+ const xml = '华为📡'
+ const byteLength = Buffer.byteLength(xml, 'utf-8')
+ expect(byteLength).toBeGreaterThan(xml.length)
+ expect(tokenizeXml(xml, { maxSize: byteLength }).ok).toBe(true)
+ expect(tokenizeXml(xml, { maxSize: byteLength - 1 })).toEqual({
+ ok: false,
+ error: NatErrorCode.SecurityViolation,
+ detail: 'xml exceeds max size',
+ })
+ })
+
+ it.each([
+ '华为路由AX3',
+ 'Café e\u0301 日本語 العربية',
+ ...[
+ 0x20, 0x7e, 0xa0, 0xd7ff, 0xe000, 0xfdd0, 0xfffd, 0x10000, 0x1f4e1,
+ 0x1fffe, 0x20000, 0x10ffff,
+ ].map((code) => String.fromCodePoint(code)),
+ ])('preserves valid Unicode %j in text and attribute values', (value) => {
+ const r = tokenizeXml(`${value}`)
+ expect(r).toEqual({
+ ok: true,
+ value: [
+ {
+ type: XmlTokenType.StartTag,
+ name: 'a',
+ attrs: [{ name: 'name', value }],
+ selfClosing: false,
+ },
+ { type: XmlTokenType.Text, value },
+ { type: XmlTokenType.EndTag, name: 'a' },
+ ],
+ })
+ })
+
+ it.each([
+ ...Array.from({ length: 0x20 }, (_, code) => code).filter(
+ (code) => code !== 0x09 && code !== 0x0a && code !== 0x0d
+ ),
+ ...Array.from({ length: 0x21 }, (_, offset) => 0x7f + offset),
+ ])('rejects control code point %i in text and attributes', (code) => {
+ const value = String.fromCharCode(code)
+ for (const xml of [`${value}`, ``]) {
+ expect(tokenizeXml(xml)).toEqual({
+ ok: false,
+ error: NatErrorCode.SecurityViolation,
+ detail: 'disallowed control char',
+ })
+ }
})
- it('rejects control characters (except \\t \\n \\r)', () => {
- const xml = '\u0001'
+ it.each([0xfffe, 0xffff])('rejects invalid XML code point %i', (code) => {
+ const value = String.fromCharCode(code)
+ for (const xml of [`${value}`, ``]) {
+ expect(tokenizeXml(xml)).toEqual({
+ ok: false,
+ error: NatErrorCode.SecurityViolation,
+ detail: 'invalid XML character',
+ })
+ }
+ })
+
+ it.each([
+ '\ud800',
+ '\udbff',
+ '\udc00',
+ '\udfff',
+ '\ud800x',
+ '\ud800\ud800',
+ '\udc00\ud800',
+ '\udc00\udc00',
+ '\ud800\udc00\udc00',
+ ])('rejects unpaired or malformed surrogates %j', (value) => {
+ // Include end-of-input so a high surrogate cannot read past the string.
+ for (const xml of [
+ `${value}`,
+ ``,
+ `${value}`,
+ ]) {
+ expect(tokenizeXml(xml)).toEqual({
+ ok: false,
+ error: NatErrorCode.SecurityViolation,
+ detail: 'unpaired surrogate',
+ })
+ }
+ })
+
+ it.each([
+ '<华为/>',
+ '',
+ '华为>',
+ '',
+ '',
+ '',
+ '',
+ '',
+ ])('keeps element and attribute names ASCII-only: %s', (xml) => {
+ expect(tokenizeXml(xml).ok).toBe(false)
+ })
+
+ it.each([
+ '\u00a0',
+ '\u1680',
+ '\u2003',
+ '\u2028',
+ '\u2029',
+ '\u202f',
+ '\u3000',
+ '\ufeff',
+ ])('rejects non-XML whitespace %j in markup', (space) => {
+ for (const xml of [
+ `<${space}a/>`,
+ ``,
+ ``,
+ ``,
+ ``,
+ ``,
+ `${space}a>`,
+ ]) {
+ expect(tokenizeXml(xml).ok).toBe(false)
+ }
+ })
+
+ it.each([
+ '华为',
+ '',
+ '',
+ '',
+ '',
+ '华为华',
+ '华为华',
+ '',
+ ])('keeps unsafe constructs forbidden with Unicode: %s', (xml) => {
const r = tokenizeXml(xml)
expect(r.ok).toBe(false)
+ if (!r.ok) expect(r.error).toBe(NatErrorCode.SecurityViolation)
+ })
+
+ it('decodes only standard entities alongside Unicode', () => {
+ const r = tokenizeXml(
+ '华为<>&"'📡'
+ )
+ expect(r.ok).toBe(true)
+ if (r.ok) {
+ expect(r.value[0]).toMatchObject({
+ attrs: [{ name: 'name', value: '华为&📡' }],
+ })
+ expect(r.value[1]).toEqual({
+ type: XmlTokenType.Text,
+ value: `华为<>&"'📡`,
+ })
+ }
})
it('accepts \\t \\n \\r', () => {
diff --git a/src/codecs/xml-tokenizer.ts b/src/codecs/xml-tokenizer.ts
index 1057077..41483fa 100644
--- a/src/codecs/xml-tokenizer.ts
+++ b/src/codecs/xml-tokenizer.ts
@@ -1,5 +1,6 @@
import { NatErrorCode } from '../errors.js'
import { type ParseResult, parseErr, parseOk } from './parse-result.js'
+import { trimXmlWhitespace } from './xml-whitespace.js'
export const DEFAULT_XML_MAX_SIZE = 64 * 1024
export const XML_MAX_TAG_NAME_LENGTH = 64
@@ -43,12 +44,15 @@ const ALLOWED_ENTITIES: Record = {
apos: "'",
}
-function isAllowedByte(code: number): boolean {
+// XML 1.0 Fifth Edition, production [2] (Char).
+function isXmlChar(code: number): boolean {
return (
- (code >= 0x20 && code <= 0x7e) ||
code === 0x09 ||
code === 0x0a ||
- code === 0x0d
+ code === 0x0d ||
+ (code >= 0x20 && code <= 0xd7ff) ||
+ (code >= 0xe000 && code <= 0xfffd) ||
+ (code >= 0x10000 && code <= 0x10ffff)
)
}
@@ -66,18 +70,31 @@ export function tokenizeXml(
): ParseResult {
const maxSize = options.maxSize ?? DEFAULT_XML_MAX_SIZE
- if (xml.length > maxSize) {
+ // Keep the original byte budget now that one character may span many bytes.
+ if (xml.length > maxSize || Buffer.byteLength(xml, 'utf-8') > maxSize) {
return parseErr(NatErrorCode.SecurityViolation, 'xml exceeds max size')
}
for (let i = 0; i < xml.length; i++) {
- const code = xml.charCodeAt(i)
- if (code > 0x7e) {
- return parseErr(NatErrorCode.SecurityViolation, 'non-ASCII byte')
+ // codePointAt combines valid UTF-16 pairs, but leaves lone surrogates
+ // in 0xD800..0xDFFF, which the XML Char ranges exclude.
+ const code = xml.codePointAt(i) ?? 0
+ if (!isXmlChar(code)) {
+ return parseErr(
+ NatErrorCode.SecurityViolation,
+ code < 0x20
+ ? 'disallowed control char'
+ : code >= 0xd800 && code <= 0xdfff
+ ? 'unpaired surrogate'
+ : 'invalid XML character'
+ )
}
- if (!isAllowedByte(code)) {
+ // Preserve the existing ban on DEL/C1 controls, even though XML 1.0
+ // permits them. Unicode support applies to text and attribute values.
+ if (code >= 0x7f && code <= 0x9f) {
return parseErr(NatErrorCode.SecurityViolation, 'disallowed control char')
}
+ if (code > 0xffff) i++
}
const tokens: XmlToken[] = []
@@ -89,7 +106,7 @@ export function tokenizeXml(
return parseErr(NatErrorCode.ParseError, 'unterminated XML declaration')
}
i = end + 2
- while (i < xml.length && /\s/.test(xml[i] ?? '')) i++
+ while (i < xml.length && /[ \t\r\n]/.test(xml[i] ?? '')) i++
}
while (i < xml.length) {
@@ -123,7 +140,7 @@ export function tokenizeXml(
if (close < 0) {
return parseErr(NatErrorCode.ParseError, 'unterminated end tag')
}
- const name = xml.slice(i + 2, close).trim()
+ const name = trimXmlWhitespace(xml.slice(i + 2, close))
if (!validateName(name)) {
return parseErr(NatErrorCode.SecurityViolation, 'invalid tag name')
}
@@ -176,7 +193,9 @@ function validateName(name: string): boolean {
function parseStartTag(
body: string
): ParseResult> {
- const trimmed = body.trim()
+ // XML S is only space, tab, CR and LF; JS \s/trim also accept Unicode
+ // characters that must not become tag or attribute separators.
+ const trimmed = trimXmlWhitespace(body)
let p = 0
const nameMatch = /^([A-Za-z_][A-Za-z0-9_:\-.]*)/.exec(trimmed.slice(p))
if (!nameMatch) return parseErr(NatErrorCode.ParseError, 'missing tag name')
@@ -188,7 +207,7 @@ function parseStartTag(
const attrs: Array<{ name: string; value: string }> = []
while (p < trimmed.length) {
- while (p < trimmed.length && /\s/.test(trimmed[p] ?? '')) p++
+ while (p < trimmed.length && /[ \t\r\n]/.test(trimmed[p] ?? '')) p++
if (p >= trimmed.length) break
const attrNameMatch = /^([A-Za-z_][A-Za-z0-9_:\-.]*)/.exec(trimmed.slice(p))
@@ -201,7 +220,7 @@ function parseStartTag(
}
p += attrName.length
- while (p < trimmed.length && /\s/.test(trimmed[p] ?? '')) p++
+ while (p < trimmed.length && /[ \t\r\n]/.test(trimmed[p] ?? '')) p++
if (trimmed[p] !== '=') {
return parseErr(
NatErrorCode.ParseError,
@@ -209,7 +228,7 @@ function parseStartTag(
)
}
p++
- while (p < trimmed.length && /\s/.test(trimmed[p] ?? '')) p++
+ while (p < trimmed.length && /[ \t\r\n]/.test(trimmed[p] ?? '')) p++
if (trimmed[p] !== '"') {
return parseErr(
NatErrorCode.SecurityViolation,
diff --git a/src/codecs/xml-whitespace.integration.test.ts b/src/codecs/xml-whitespace.integration.test.ts
new file mode 100644
index 0000000..4b20633
--- /dev/null
+++ b/src/codecs/xml-whitespace.integration.test.ts
@@ -0,0 +1,37 @@
+import { spawnSync } from 'node:child_process'
+import { describe, expect, it } from 'vitest'
+
+describe('XML whitespace processing budget', () => {
+ it('handles long interior whitespace without blocking on quadratic trimming', () => {
+ // A subprocess timeout can interrupt a synchronous parser regression.
+ // Vitest's in-process timeout cannot interrupt a blocked event loop.
+ const parserUrl = new URL('./xml-parser.ts', import.meta.url).href
+ const tokenizerUrl = new URL('./xml-tokenizer.ts', import.meta.url).href
+ const result = spawnSync(
+ process.execPath,
+ [
+ '--import',
+ 'tsx',
+ '--input-type=module',
+ '-e',
+ `
+ import assert from 'node:assert/strict'
+ import { parseXml } from ${JSON.stringify(parserUrl)}
+ import { tokenizeXml } from ${JSON.stringify(tokenizerUrl)}
+ const gap = ' '.repeat(60000)
+ const tag = ''
+ const text = 'x' + (' '.repeat(1000) + '').repeat(60) + 'x'
+ for (let i = 0; i < 10; i++) {
+ assert.equal(tokenizeXml(tag).ok, true)
+ const parsed = parseXml(text)
+ assert.equal(parsed.ok, true)
+ assert.equal(parsed.value.text, 'x' + gap + 'x')
+ }
+ `,
+ ],
+ { encoding: 'utf-8', timeout: 5000 }
+ )
+ expect(result.error).toBeUndefined()
+ expect(result.status, result.stderr).toBe(0)
+ }, 10_000)
+})
diff --git a/src/codecs/xml-whitespace.ts b/src/codecs/xml-whitespace.ts
new file mode 100644
index 0000000..cb71c36
--- /dev/null
+++ b/src/codecs/xml-whitespace.ts
@@ -0,0 +1,12 @@
+function isXmlWhitespace(code: number): boolean {
+ return code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d
+}
+
+/** Trim XML S in linear time, preserving every other Unicode character. */
+export function trimXmlWhitespace(value: string): string {
+ let start = 0
+ let end = value.length
+ while (start < end && isXmlWhitespace(value.charCodeAt(start))) start++
+ while (end > start && isXmlWhitespace(value.charCodeAt(end - 1))) end--
+ return value.slice(start, end)
+}
diff --git a/src/net/http-client.ts b/src/net/http-client.ts
index 8ae2d29..d9c896e 100644
--- a/src/net/http-client.ts
+++ b/src/net/http-client.ts
@@ -1,3 +1,4 @@
+import { isUtf8 } from 'node:buffer'
import http from 'node:http'
import {
isIpv4String,
@@ -58,58 +59,82 @@ export class NodeHttpClient implements HttpClient {
resolve(r)
}
- const req = http.request(
- {
- method: input.method,
- host: input.host,
- port: input.port,
- path: input.path,
- headers: input.headers ?? {},
- // Prevent any hostname resolution path by omitting 'lookup' and passing only literal IP
- family: 4,
- },
- (res) => {
- const status = res.statusCode ?? 0
- // Reject 3xx as protocol error — never follow redirects
- if (status >= 300 && status < 400) {
- res.destroy()
- return settle(
- parseErr(
- NatErrorCode.SecurityViolation,
- `unexpected redirect: ${status}`
- )
- )
- }
- let bytes = 0
- const chunks: Buffer[] = []
- res.on('data', (chunk: Buffer) => {
- bytes += chunk.length
- if (bytes > HTTP_MAX_RESPONSE_SIZE) {
+ let req: http.ClientRequest
+ try {
+ req = http.request(
+ {
+ method: input.method,
+ host: input.host,
+ port: input.port,
+ path: input.path,
+ headers: input.headers ?? {},
+ // Prevent any hostname resolution path by omitting 'lookup' and passing only literal IP
+ family: 4,
+ },
+ (res) => {
+ const status = res.statusCode ?? 0
+ // Reject 3xx as protocol error — never follow redirects
+ if (status >= 300 && status < 400) {
res.destroy()
return settle(
parseErr(
NatErrorCode.SecurityViolation,
- 'http response too large'
+ `unexpected redirect: ${status}`
)
)
}
- chunks.push(chunk)
- })
- res.on('end', () => {
- const body = Buffer.concat(chunks).toString('utf-8')
- const headers: Record = {}
- for (const [k, v] of Object.entries(res.headers)) {
- headers[k.toLowerCase()] = Array.isArray(v)
- ? v.join(',')
- : (v ?? '')
- }
- settle(parseOk({ statusCode: status, headers, body }))
- })
- res.on('error', (e) =>
- settle(parseErr(NatErrorCode.ParseError, e.message))
+ let bytes = 0
+ const chunks: Buffer[] = []
+ res.on('data', (chunk: Buffer) => {
+ bytes += chunk.length
+ if (bytes > HTTP_MAX_RESPONSE_SIZE) {
+ res.destroy()
+ return settle(
+ parseErr(
+ NatErrorCode.SecurityViolation,
+ 'http response too large'
+ )
+ )
+ }
+ chunks.push(chunk)
+ })
+ res.on('end', () => {
+ const rawBody = Buffer.concat(chunks)
+ // Validate before decoding: toString replaces malformed UTF-8
+ // with U+FFFD, hiding invalid sequences from the XML codec.
+ if (!isUtf8(rawBody)) {
+ return settle(
+ parseErr(
+ NatErrorCode.SecurityViolation,
+ 'invalid UTF-8 response'
+ )
+ )
+ }
+ const body = rawBody.toString('utf-8')
+ const headers: Record = {}
+ for (const [k, v] of Object.entries(res.headers)) {
+ headers[k.toLowerCase()] = Array.isArray(v)
+ ? v.join(',')
+ : (v ?? '')
+ }
+ settle(parseOk({ statusCode: status, headers, body }))
+ })
+ res.on('error', (e) =>
+ settle(parseErr(NatErrorCode.ParseError, e.message))
+ )
+ }
+ )
+ } catch (error) {
+ settle(
+ parseErr(
+ NatErrorCode.ParseError,
+ error instanceof Error
+ ? error.message
+ : 'HTTP request creation failed'
)
- }
- )
+ )
+ return
+ }
req.setTimeout(timeoutMs, () => {
req.destroy()
diff --git a/src/net/node-http-client.test.ts b/src/net/node-http-client.test.ts
index bf2f2db..03acb5f 100644
--- a/src/net/node-http-client.test.ts
+++ b/src/net/node-http-client.test.ts
@@ -148,6 +148,109 @@ describe('NodeHttpClient', () => {
})
})
+ it('returns a parse error when creating the HTTP request throws', async () => {
+ requestMock.mockImplementationOnce(() => {
+ throw new TypeError('Request path contains unescaped characters')
+ })
+
+ await expect(
+ new NodeHttpClient().request({
+ method: 'GET',
+ host: '192.168.1.1',
+ port: 80,
+ path: '/invalid path',
+ })
+ ).resolves.toEqual({
+ ok: false,
+ error: NatErrorCode.ParseError,
+ detail: 'Request path contains unescaped characters',
+ })
+ })
+
+ it('preserves UTF-8 device text split across HTTP chunks', async () => {
+ const pendingRequest = primeRequest()
+ const pending = new NodeHttpClient().request({
+ method: 'GET',
+ host: '192.168.3.1',
+ port: 37215,
+ path: '/upnpdev.xml',
+ })
+ const response = new FakeResponse(200, {
+ 'content-type': 'text/xml; charset="utf-8"',
+ })
+ pendingRequest.respond(response)
+ const body = '华为路由AX3📡'
+ // Splitting at every byte covers boundaries within multibyte characters.
+ for (const byte of Buffer.from(body, 'utf-8'))
+ response.emit('data', Buffer.from([byte]))
+ response.emit('end')
+
+ await expect(pending).resolves.toMatchObject({ ok: true, value: { body } })
+ })
+
+ it('preserves a legitimately encoded Unicode replacement character', async () => {
+ const pendingRequest = primeRequest()
+ const pending = new NodeHttpClient().request({
+ method: 'GET',
+ host: '192.168.3.1',
+ port: 37215,
+ path: '/upnpdev.xml',
+ })
+ const response = new FakeResponse(200)
+ pendingRequest.respond(response)
+ const body = '华为\ufffd📡'
+ response.emit('data', Buffer.from(body, 'utf-8'))
+ response.emit('end')
+
+ await expect(pending).resolves.toMatchObject({ ok: true, value: { body } })
+ })
+
+ const invalidUtf8: Array<[string, number[]]> = [
+ ['isolated continuation byte', [0x80]],
+ ['invalid leading byte', [0xff]],
+ ['truncated multibyte sequence', [0xe4, 0xb8]],
+ ['high surrogate', [0xed, 0xa0, 0x80]],
+ ['low surrogate', [0xed, 0xb0, 0x80]],
+ ['CESU-8 surrogate pair', [0xed, 0xa0, 0xbd, 0xed, 0xb3, 0xa1]],
+ ['code point above U+10FFFF', [0xf4, 0x90, 0x80, 0x80]],
+ ['overlong NUL', [0xc0, 0x80]],
+ ['overlong markup delimiter', [0xe0, 0x80, 0xbc]],
+ ]
+
+ it.each(invalidUtf8)(
+ 'rejects UTF-8 %s before decoding',
+ async (_name, bytes) => {
+ // The outcome must not depend on boundaries inside a multibyte sequence.
+ for (const split of [false, true]) {
+ const pendingRequest = primeRequest()
+ const pending = new NodeHttpClient().request({
+ method: 'GET',
+ host: '192.168.3.1',
+ port: 37215,
+ path: '/upnpdev.xml',
+ })
+ const response = new FakeResponse(200, {
+ 'content-type': 'text/xml; charset="utf-8"',
+ })
+ pendingRequest.respond(response)
+ response.emit('data', Buffer.from('华为'))
+ if (split) {
+ for (const byte of bytes) response.emit('data', Buffer.from([byte]))
+ } else {
+ response.emit('data', Buffer.from(bytes))
+ }
+ response.emit('data', Buffer.from(''))
+ response.emit('end')
+
+ await expect(pending).resolves.toEqual({
+ ok: false,
+ error: NatErrorCode.SecurityViolation,
+ detail: 'invalid UTF-8 response',
+ })
+ }
+ }
+ )
+
it('rejects redirects without following them', async () => {
const pendingRequest = primeRequest()
const resultPromise = new NodeHttpClient().request({
diff --git a/tests/docker/hostile/hostile_server.py b/tests/docker/hostile/hostile_server.py
index a72e068..fb6951a 100644
--- a/tests/docker/hostile/hostile_server.py
+++ b/tests/docker/hostile/hostile_server.py
@@ -15,6 +15,19 @@
]>
&lol3;"""
+UNICODE_DEVICE = """
+
+华为路由AX3📡
+华为 技术WS7100-15
+
+urn:schemas-upnp-org:service:WANIPConnection:1
+/ctl/IPConn
+""".encode("utf-8")
+
+# UTF-8 must never encode surrogate code points. Decoding with replacement
+# would hide this error from the XML character validator.
+INVALID_UTF8_DEVICE = UNICODE_DEVICE.replace("📡".encode("utf-8"), b"\xed\xa0\x80")
+
REDIRECT_TO_EXTERNAL = None # signals 302 handler
class HostileHandler(BaseHTTPRequestHandler):
@@ -24,6 +37,10 @@ def do_GET(self):
body = XXE_PAYLOAD
elif self.path.endswith("/bomb"):
body = BILLION_LAUGHS
+ elif self.path.endswith("/unicode"):
+ body = UNICODE_DEVICE
+ elif self.path.endswith("/invalid-utf8"):
+ body = INVALID_UTF8_DEVICE
elif self.path.endswith("/huge"):
body = b"x" * (200 * 1024) # 200KB, exceeds SOAP + device-desc caps
elif self.path.endswith("/redirect"):
diff --git a/tests/integration/nat-docker.test.ts b/tests/integration/nat-docker.test.ts
index 4dd62f4..ede4b77 100644
--- a/tests/integration/nat-docker.test.ts
+++ b/tests/integration/nat-docker.test.ts
@@ -1,8 +1,10 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import {
+ NatErrorCode,
nodeHttpClient,
nodeUdpSocketFactory,
PmpPcpClient,
+ parseDeviceDescription,
parseXml,
UpnpClient,
} from '../../src/index.js'
@@ -75,6 +77,48 @@ describe.skipIf(SKIP)('NAT docker matrix', () => {
})
describe('Hostile router', () => {
+ it('preserves Unicode device metadata over HTTP', async () => {
+ const res = await nodeHttpClient.request({
+ method: 'GET',
+ host: await containerIp('hostile'),
+ port: 49154,
+ path: '/unicode',
+ timeoutMs: 3000,
+ })
+ expect(res.ok).toBe(true)
+ if (res.ok) {
+ expect(parseDeviceDescription(res.value.body)).toEqual({
+ ok: true,
+ value: {
+ friendlyName: '华为路由AX3📡',
+ manufacturer: '华为 技术',
+ modelName: 'WS7100-15',
+ services: [
+ {
+ serviceType: 'urn:schemas-upnp-org:service:WANIPConnection:1',
+ controlUrl: '/ctl/IPConn',
+ },
+ ],
+ },
+ })
+ }
+ })
+
+ it('rejects malformed UTF-8 before it reaches the XML parser', async () => {
+ const res = await nodeHttpClient.request({
+ method: 'GET',
+ host: await containerIp('hostile'),
+ port: 49154,
+ path: '/invalid-utf8',
+ timeoutMs: 3000,
+ })
+ expect(res).toEqual({
+ ok: false,
+ error: NatErrorCode.SecurityViolation,
+ detail: 'invalid UTF-8 response',
+ })
+ })
+
// nodeHttpClient's SSRF guard admits only private/link-local hosts, so
// 127.0.0.1:published-port is unreachable by design — always target the
// container's RFC1918 bridge address.