From fe2805f93975377d1d59fc6419e435b4d355b859 Mon Sep 17 00:00:00 2001 From: ej-shafran Date: Fri, 3 Nov 2023 14:27:14 +0200 Subject: [PATCH] fix: `validator.isValid is not a function` for certain objects Objects with keys like `valueOf`, `toString`, and `__proto__` cause a `TypeError` to be raised when calling `jwt.sign`. This is because the key technically does exist on the `schema` param of `validate`, when checked with `if (schema[key]) {}`. Using `Object.prototype.hasOwnProperty` solves the issue. --- sign.js | 4 ++-- test/issue_945.tests.js | 12 ++++++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) create mode 100644 test/issue_945.tests.js diff --git a/sign.js b/sign.js index 82bf526..96a7799 100644 --- a/sign.js +++ b/sign.js @@ -45,13 +45,13 @@ function validate(schema, allowUnknown, object, parameterName) { } Object.keys(object) .forEach(function(key) { - const validator = schema[key]; - if (!validator) { + if (!Object.prototype.hasOwnProperty.call(schema, key)) { if (!allowUnknown) { throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); } return; } + const validator = schema[key]; if (!validator.isValid(object[key])) { throw new Error(validator.message); } diff --git a/test/issue_945.tests.js b/test/issue_945.tests.js new file mode 100644 index 0000000..bb24c45 --- /dev/null +++ b/test/issue_945.tests.js @@ -0,0 +1,12 @@ +const jwt = require(".."); + +const KEY = "any_key"; + +describe("issue 945 - validator.isValid is not a function", () => { + it("should work", () => { + jwt.sign({ hasOwnProperty: null }, KEY); + jwt.sign({ valueOf: null }, KEY); + jwt.sign({ toString: null }, KEY); + jwt.sign({ __proto__: null }, KEY); + }); +});