diff --git a/lib/utils/escape-filter-value.js b/lib/utils/escape-filter-value.js index 62808e7..48a2d25 100644 --- a/lib/utils/escape-filter-value.js +++ b/lib/utils/escape-filter-value.js @@ -27,22 +27,22 @@ function escapeFilterValue (toEscape) { } function escapeBuffer (buf) { + const bufLen = buf.byteLength let result = '' for (let i = 0; i < buf.length; i += 1) { if (buf[i] >= 0xc0 && buf[i] <= 0xdf) { // Represents the first byte in a 2-byte UTF-8 character. - result += '\\' + buf[i].toString(16) + '\\' + buf[i + 1].toString(16) + result += '\\' + buf[i].toString(16) + if (i < (bufLen - 1)) { result += '\\' + buf[i + 1].toString(16).padStart(2, '0') } // Only add second byte if exist in buffer i += 1 continue } if (buf[i] >= 0xe0 && buf[i] <= 0xef) { // Represents the first byte in a 3-byte UTF-8 character. - result += [ - '\\', buf[i].toString(16), - '\\', buf[i + 1].toString(16), - '\\', buf[i + 2].toString(16) - ].join('') + result += '\\' + buf[i].toString(16) + if (i < (bufLen - 1)) { result += '\\' + buf[i + 1].toString(16).padStart(2, '0') } // Only add second byte if exist in buffer + if (i < (bufLen - 2)) { result += '\\' + buf[i + 2].toString(16).padStart(2, '0') } // Only add third byte if exist in buffer i += 2 continue } diff --git a/lib/utils/escape-filter-value.test.js b/lib/utils/escape-filter-value.test.js index e7ac53d..468064c 100644 --- a/lib/utils/escape-filter-value.test.js +++ b/lib/utils/escape-filter-value.test.js @@ -83,3 +83,15 @@ tap.test('leaves encoded characters intact', async t => { t.equal(result, expected[i]) } }) + +tap.test('handle start of two byte utf-8 character at end of buffer', async t => { + const input = Buffer.from([0x30, 0xc2]) + const expected = '0\\c2' + t.equal(escapeFilterValue(input), expected) +}) + +tap.test('handle start of three byte utf-8 character at end of buffer', async t => { + const input = Buffer.from([0x30, 0xe2]) + const expected = '0\\e2' + t.equal(escapeFilterValue(input), expected) +})