UNPKG

jwt-fp

Version:

A wrapper on top of jsonwebtoken package that uses data structures from fp-ts

69 lines (68 loc) 2.67 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Either_1 = require("fp-ts/lib/Either"); var t = require("io-ts"); var PathReporter_1 = require("io-ts/lib/PathReporter"); var jwt = require("jsonwebtoken"); var SignPayload = t.intersection([ t.partial({ exp: t.number, iat: t.number, nbf: t.number, }), t.interface({ data: t.object, }), ]); var VerifyPayload = t.intersection([ t.partial({ exp: t.number, nbf: t.number, }), t.interface({ data: t.object, iat: t.number, }), ]); var jsonwebtoken_1 = require("jsonwebtoken"); exports.TokenExpiredError = jsonwebtoken_1.TokenExpiredError; exports.JsonWebTokenError = jsonwebtoken_1.JsonWebTokenError; exports.NotBeforeError = jsonwebtoken_1.NotBeforeError; /** * Sign the given payload into a JSON Web Token string * @param {SignPayload} payload - Payload to sign, could be an literal, buffer or string * @param {String|Buffer} secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. * @param {ISignOptions} [options] - Options for the signature * @returns {String} The JSON Web Token string */ exports.sign = function (payload, secretOrPrivateKey, options) { return jwt.sign(payload, secretOrPrivateKey, options); }; /** * Verify given token using a secret or a public key to get a decoded token * @param {String} token - JWT string to verify * @param {String|Buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. * @param {VerifyOptions} [options] - Options for the verification * @returns {Either<VerifyError, string>} Either an error or the decoded string. */ exports.verify = function (token, secretOrPublicKey, options) { try { var decodedToken = jwt.verify(token, secretOrPublicKey, options); var decodedPayload_1 = VerifyPayload.decode(decodedToken); return Either_1.mapLeft(function () { return new jwt.JsonWebTokenError(PathReporter_1.PathReporter.report(decodedPayload_1).join(', ')); })(decodedPayload_1); } catch (err) { if (exports.isVerifyError(err)) { return Either_1.left(err); } return Either_1.left(new jwt.JsonWebTokenError(err.message, err)); } }; /** * Returns `true` if err is a `VerifyError`, `false` otherwise * @param {Error} err * @returns {Boolean} Whether err is a `VerifyError` or not */ exports.isVerifyError = function (err) { return err instanceof jwt.TokenExpiredError || err instanceof jwt.JsonWebTokenError || err instanceof jwt.NotBeforeError; };