All files / modules/jose index.js

100% Statements 28/28
100% Branches 10/10
100% Functions 8/8
100% Lines 28/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214      6x 6x 6x           6x               6x                                               6x                                         6x             6x 1x                         6x 1x                                       6x 3x 2x   3x                           6x 3x                       6x 17x                                                       6x 29x                                 6x 2x 2x                       6x 2x 2x     6x                    
/**
 * @module jose
 */
const jose = require('jose');
const config = require("../../config").jose;
const fs = require("fs");
const {
    JWE, // JSON Web Encryption (JWE)
    JWK, // JSON Web Key (JWK)
    JWKS, // JSON Web Key Set (JWKS)
    JWT, // JSON Web Token (JWT)
} = jose;
 
/**
 * Import encryption key if user sessions are configured to be
 * preserved on reboot or synchronously generate an encryption
 * key with config-defined type and curve/size.
 */
const encKey = (
    process.env.PRESERVE_SESSIONS_ON_REBOOT === '1' ?
        /* istanbul ignore next */
        JWK.asKey({
            key: fs.readFileSync("./keys/enc.key"),
            format: "pem",
            passphrase: process.env.PRIVATE_KEY_PASSPHRASE,
        },
        {
            alg: config.alg,
            use: "enc",
        }) :
        JWK.generateSync(config.kty, config.crvOrSize, {
            alg: config.alg,
            use: "enc",
            key_ops: ["deriveKey"],
        })
);
 
/**
 * Import signing key if user sessions are configured to be
 * preserved on reboot or synchronously generate a signing
 * key with config-defined type and curve/size.
 */
const sigKey = (
    process.env.PRESERVE_SESSIONS_ON_REBOOT === '1' ?
        /* istanbul ignore next */
        JWK.asKey({
            key: fs.readFileSync("./keys/sig.key"),
            format: "pem",
            passphrase: process.env.PRIVATE_KEY_PASSPHRASE,
        },
        {
            use: "sig",
            alg: config.sigAlg,
        }) :
        JWK.generateSync(config.kty, config.crvOrSize, {
            alg: config.sigAlg,
            use: "sig",
            key_ops: ["sign", "verify"],
        })
);
 
/**
 * Initialise JSON Web Key Store
 */
const keystore = new JWKS.KeyStore(encKey, sigKey);
 
/**
 * Get the public key used for encryption-decryption
 * in Privacy-Enhanced Mail format
 * @return {object} enc public key in PEM format
 */
const getEncPubAsPEM = () => {
    return keystore.get({
        kty: config.kty,
        crv: config.crvOrSize,
        use: "enc",
        key_ops: ["deriveKey"],
    }).toPEM();
};
 
/**
 * Get the public key used for signing-verifying
 * in Privacy-Enhanced Mail format
 * @return {object} sig public key in PEM format
 */
const getSigPubAsPEM = () => {
    return keystore.get({
        kty: config.kty,
        crv: config.crvOrSize,
        use: "sig",
        key_ops: ["sign", "verify"],
    }).toPEM();
};
 
/**
 * Encrypt given cleartext with specified public
 * key and return the resulting JWE object as a string.
 * If no public key is provided by the recipient and
 * symmetric encryption is enabled, the JWT is symmetrically
 * encrypted by the server's key instead.
 * In case asymmetric encryption is enforced and the client
 * does not provide a public key, an error is thrown.
 * @param {string} cleartext
 * @param {object} pub JWK compatible public key of recipient
 * @return {string} JWE object as string
 */
const encrypt = (cleartext, pub) => {
    if (pub === undefined && process.env.SYMMETRIC_ENC_ENABLED === '1') {
        pub = encKey;
    };
    return JWE.encrypt(cleartext, JWK.asKey(pub),
        {
            enc: config.enc,
            alg: config.alg,
        });
};
 
/**
 * Decrypt given JWK object with owned
 * private key and return cleartext as a
 * utf8 string.
 * @param {string} jwe JWE object as string
 * @return {string} cleartext (utf8)
 */
const decrypt = (jwe) => {
    return JWE.decrypt(jwe, encKey, {
        complete: false,
    }).toString("utf8");
};
 
/**
 * Sign provided payload and return the
 * signed JWT.
 * @param {JSON} payload
 * @param {string} [exp=default] default expiry will be used if omitted
 * @return {string} signed JWT
 */
const sign = (payload, exp) => {
    return JWT.sign(payload, sigKey, {
        header: {
            typ: "JWT",
        },
        issuer: config.iss,
        audience: config.aud,
        kid: true,
        expiresIn: exp !== undefined ? exp : config.exp,
    });
};
 
/**
 * Verify provided JWT with given params and
 * the server's signing key.
 * The audience may also be optionally provided,
 * for instance when validating access to routes
 * with custom permissions. An example is when
 * an unauthenticated user wishes to reset their
 * password and have been granted access via a
 * reset token. In this case the aud="/reset".
 * If the audience param is left out, the default
 * configuration will be used.
 * @param {object} jwt JWT token
 * @param {string} [aud=default] default config will be used if omitted
 * @return {string} payload
 * @throws {JWSVerificationFailed} if JWT blacklisted
 * @throws {jose.errors} for failed verification
 */
const verify = (jwt, aud) => {
    return JWT.verify(jwt, sigKey, {
        audience: aud !== undefined ? aud : config.aud,
        complete: false,
        issuer: config.iss,
    });
};
 
/**
 * Sign provided payload with the server's private
 * key and asymmetrically encrypt the signed JWT by
 * the client provided public key.
 * This returns the encrypted JWE object as a string.
 * @param {JSON} payload
 * @param {object} pub client's pub used for encryption
 * @param {string} [exp=default] default expiry will be used if omitted
 * @return {string} JWE object as string
 */
const signAndEncrypt = (payload, pub, exp) => {
    const jwt = sign(payload, exp);
    return encrypt(jwt, pub);
};
 
/**
 * Decrypt given JWE with the server's encryption
 * key and verify resulting JWT with the server's
 * signing key. Returns the payload object if
 * successful.
 * @param {string} jwe JWE object as string
 * @param {string} [aud=default] default config will be used if omitted
 * @return {string} decrypted and verified payload
 */
const decryptAndVerify = (jwe, aud) => {
    const jwt = decrypt(jwe);
    return verify(jwt, aud);
};
 
module.exports = {
    getEncPubAsPEM,
    getSigPubAsPEM,
    encrypt,
    decrypt,
    sign,
    verify,
    signAndEncrypt,
    decryptAndVerify,
};