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
89 changes: 88 additions & 1 deletion src/clients/upnp-client.test.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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(
'<manufacturer>TestCorp</manufacturer>',
'<friendlyName>华为路由AX3</friendlyName><manufacturer>华为 技术</manufacturer>'
).replace(
'<modelName>Test</modelName>',
'<modelName>WS7100-15📡</modelName>'
)
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({
Expand Down Expand Up @@ -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)
Expand Down
5 changes: 5 additions & 0 deletions src/clients/upnp-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
66 changes: 65 additions & 1 deletion src/codecs/device-desc-parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,40 @@ const VALID_DESC = `<?xml version="1.0"?>
</root>`

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)
Expand Down Expand Up @@ -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)
Expand All @@ -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 = `<?xml version="1.0"?><root>${'<x/>'.repeat(30000)}</root>`
const r = parseDeviceDescription(huge)
Expand Down
15 changes: 15 additions & 0 deletions src/codecs/ssdp-codec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/codecs/ssdp-codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
27 changes: 27 additions & 0 deletions src/codecs/xml-parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(`<root name="${text}"> \t\r\n${text} \t\r\n</root>`)
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('<root a="1" b="two"/>')
expect(r.ok).toBe(true)
Expand Down Expand Up @@ -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}<root/>`,
`<root/>${space}`,
`<?xml version="1.0"?>${space}<root/>`,
]) {
expect(parseXml(xml)).toEqual({
ok: false,
error: NatErrorCode.ParseError,
detail: 'text outside root element',
})
}
}
)

it('rejects XXE', () => {
const xxe =
'<?xml version="1.0"?><!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]><root>&xxe;</root>'
Expand Down
6 changes: 4 additions & 2 deletions src/codecs/xml-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
tokenizeXml,
XmlTokenType,
} from './xml-tokenizer.js'
import { trimXmlWhitespace } from './xml-whitespace.js'

export interface XmlElement {
name: string
Expand Down Expand Up @@ -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
Expand All @@ -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)
}

Expand Down
Loading
Loading