UNPKG

@piggly/fastify-chassis

Version:

An ESM/CommonJS toolkit to help you to do common operations in your back-end applications with Fastify and NodeJS.

70 lines 2.62 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.NonceTokenMiddleware = void 0; const events_1 = require("../events/index.js"); const errors_1 = require("../errors/index.js"); const utils_1 = require("../utils/index.js"); /** * Nonce token middleware. * * When method.from is body, will get the "param" * value from body. E.g: request.body[param]. * * When method.from is header, will get the "param" * value from header. E.g: request.headers[param]. * * When regenerate is set to true, then it will append * to reply header the "X-Nonce-Token" header with the * new nonce token that can be used to verify the request. * * The ttl is related to the nonce token expiration time * when regenerating the nonce token. * * If nonce token is invalid for any reason, it will: * - Publish UnauthorizedAccessEvent. * - Return InvalidNonceTokenError. * * Note: regenerated nonces will always be set in "X-Nonce-Token" header. * * @param {Object} method The method to get the nonce token. * @param {string} method.from The source of the nonce token. * @param {string} method.param The parameter name to get the nonce token. * @param {boolean} [method.regenerate] Whether to regenerate the nonce token. * @param {number} [method.ttl] The nonce token expiration time. * @param {Object} deps The dependencies. * @param {NonceTokenService} deps.NONCE_SERVICE The nonce token service. * @returns Callback function. * @since 7.0.0 * @author Caique Araujo <caique@piggly.com.br> */ const NonceTokenMiddleware = (method, deps) => (request, reply, done) => { const { from, param, regenerate = false, ttl = 3600 } = method; const { NONCE_SERVICE } = deps; const token = from === 'header' ? (0, utils_1.getHeaderValue)(request, param, '') : (request.body?.[param] ?? ''); if (!token) { events_1.UnauthorizedAccessEvent.publish(request); done(new errors_1.InvalidNonceTokenError()); return; } NONCE_SERVICE.verify(token, regenerate, ttl) .then(t => { if (t === undefined) { events_1.UnauthorizedAccessEvent.publish(request); done(new errors_1.InvalidNonceTokenError()); return; } if (regenerate) { reply.header('X-Nonce-Token', t); } done(); }) .catch(() => { events_1.UnauthorizedAccessEvent.publish(request); done(new errors_1.InvalidNonceTokenError()); return; }); }; exports.NonceTokenMiddleware = NonceTokenMiddleware; //# sourceMappingURL=NonceTokenMiddleware.js.map