@foal/core
Version:
Full-featured Node.js framework, with no complexity
37 lines (36 loc) • 1.39 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.verifySignedToken = verifySignedToken;
// std
const crypto_1 = require("crypto");
// FoalTS
const sign_token_util_1 = require("./sign-token.util");
/**
* Verify a base64-encoded (or base64url-encoded) signed token against a secret.
*
* Returns false if the token format is invalid or the signature does not match.
*
* Returns the token without its signature otherwise.
*
* @export
* @param {string} signedToken - The signed token
* @param {string} secret - The base64-encoded secret with which the token is supposed to have been signed with.
* @returns {(string|false)} - False or the unsigned token.
*/
function verifySignedToken(signedToken, secret) {
if (typeof signedToken !== 'string') {
return false;
}
const [unsignedToken, signature] = signedToken.split('.');
// signature is potentially undefined
if (signature === undefined) {
return false;
}
const expectedSignatureBuffer = (0, sign_token_util_1.sign)(unsignedToken, secret);
const actualSignatureBuffer = Buffer.alloc(expectedSignatureBuffer.length);
actualSignatureBuffer.write(signature, 0, actualSignatureBuffer.length, 'base64');
if ((0, crypto_1.timingSafeEqual)(expectedSignatureBuffer, actualSignatureBuffer)) {
return unsignedToken;
}
return false;
}