diff --git a/sign.js b/sign.js index e0242c5..d6f8755 100644 --- a/sign.js +++ b/sign.js @@ -20,7 +20,7 @@ var sign_options_schema = { subject: { isValid: isString, message: '"subject" must be a string' }, jwtid: { isValid: isString, message: '"jwtid" must be a string' }, noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, - keyid: { isValid: isString, message: '"keyid" must be a string' }, + keyid: { isValid: isString, message: '"keyid" must be a string' } }; var registered_claims_schema = { @@ -29,16 +29,16 @@ var registered_claims_schema = { nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } }; -function validate(schema, unknown, object) { +function validate(schema, allowUnknown, object, parameterName) { if (!isPlainObject(object)) { - throw new Error('Expected object'); + throw new Error('Expected "' + parameterName + '" to be a plain object.'); } Object.keys(object) .forEach(function(key) { var validator = schema[key]; if (!validator) { - if (!unknown) { - throw new Error('"' + key + '" is not allowed'); + if (!allowUnknown) { + throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); } return; } @@ -48,6 +48,14 @@ function validate(schema, unknown, object) { }); } +function validateOptions(options) { + return validate(sign_options_schema, false, options, 'options'); +} + +function validatePayload(payload) { + return validate(registered_claims_schema, true, payload, 'payload'); +} + var options_to_payload = { 'audience': 'aud', 'issuer': 'iss', @@ -97,7 +105,7 @@ module.exports = function (payload, secretOrPrivateKey, options, callback) { return failure(new Error('payload is required')); } else if (isObjectPayload) { try { - validate(registered_claims_schema, true, payload); + validatePayload(payload); } catch (error) { return failure(error); @@ -122,7 +130,7 @@ module.exports = function (payload, secretOrPrivateKey, options, callback) { } try { - validate(sign_options_schema, false, options); + validateOptions(options); } catch (error) { return failure(error);