Skip to content

Commit

Permalink
Don't throw unhandled exception if invalid json in buffer (#11)
Browse files Browse the repository at this point in the history
* fix: dont throw unhandled exception on invalid json in buffer

* chore: lint

* test: add invalid json test case
  • Loading branch information
daniandl committed Jan 5, 2022
1 parent 2070e01 commit 07ae645
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
9 changes: 8 additions & 1 deletion index.js
Expand Up @@ -42,7 +42,14 @@ const verify = (secret, token, remoteip = null, sitekey = null) => {
response
.on('error', reject)
.on('data', (chunk) => buffer += chunk)
.on('end', () => resolve(JSON.parse(buffer)))
.on('end', () => {
try {
const json = JSON.parse(buffer);
resolve(json);
} catch (error) {
reject(error);
}
});
});

request.on('error', reject);
Expand Down
14 changes: 13 additions & 1 deletion test/index.js
Expand Up @@ -72,13 +72,25 @@ describe('hCaptcha', function () {
.catch(done.fail);
});

it('throws on invalid json response', function (done) {
nock('https://hcaptcha.com')
.post('/siteverify', 'secret=mysecret&response=token')
.reply(200, '<html lang="en">...');
verify(secret, token)
.then(done.fail)
.catch(error => {
assert.strictEqual(error.message, 'Unexpected token < in JSON at position 0')
done()
});
});

it('throws on http failure', function (done) {
nock('https://hcaptcha.com')
.post('/siteverify', 'secret=mysecret&response=token')
.replyWithError('failboat');
verify(secret, token)
.then(done.fail)
.catch(() => done())
.catch(() => done());
});
});
});

0 comments on commit 07ae645

Please sign in to comment.