Skip to content

Commit

Permalink
harden protocol decode
Browse files Browse the repository at this point in the history
  • Loading branch information
heapwolf committed Dec 21, 2023
1 parent 0d29340 commit 5e993e5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 18 deletions.
2 changes: 1 addition & 1 deletion api/stream-relay/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ export class Cache {

// follow the chain to get the buffers in order
const bufs = [...source.values()]
.filter(p => p.previousId.toString('hex') === previous.packetId.toString('hex'))
.filter(p => Buffer.from(p.previousId).toString('hex') === Buffer.from(previous.packetId).toString('hex'))
.sort((a, b) => a.index - b.index)

if (!indexes || bufs.length < indexes) return null
Expand Down
40 changes: 23 additions & 17 deletions api/stream-relay/packets.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,27 +200,33 @@ export const decode = buf => {
for (const [k, spec] of Object.entries(PACKET_SPEC)) {
o[k] = spec.default

if (spec.encoding === 'number') {
const method = getMethod('read', spec.bytes, spec.signed)
o[k] = buf[method](offset)
offset += spec.bytes
continue
}
try {
if (spec.encoding === 'number') {
const method = getMethod('read', spec.bytes, spec.signed)
o[k] = buf[method](offset)
offset += spec.bytes
continue
}

const size = buf.readUInt16BE(offset)
offset += SIZE
let value = buf.slice(offset, offset + size)
offset += size
const size = buf.readUInt16BE(offset)
offset += SIZE
let value = buf.slice(offset, offset + size)
offset += size

if (spec.encoding === 'hex') value = Buffer.from(value, 'hex')
if (spec.encoding === 'base64') value = Buffer.from(value, 'base64')
if (spec.encoding === 'utf8') value = value.toString()
if (spec.bytes && size > spec.bytes) return null

if (k === 'message' && isEncodedAsJSON(o)) {
try { value = JSON.parse(value.toString()) } catch {}
}
if (spec.encoding === 'hex') value = Buffer.from(value, 'hex')
if (spec.encoding === 'base64') value = Buffer.from(value, 'base64')
if (spec.encoding === 'utf8') value = value.toString()

if (k === 'message' && isEncodedAsJSON(o)) {
try { value = JSON.parse(value.toString()) } catch {}
}

o[k] = value
o[k] = value
} catch (err) {
return null // completely bail
}
}

return o
Expand Down

0 comments on commit 5e993e5

Please sign in to comment.