UNPKG

@linkedmink/passport-mutual-key-challenge

Version:

Implements a Passport strategy to authenticate the public key of a user by issuing a dynamic generated challenge

75 lines 3.13 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.MessageVerifier = void 0; const crypto_1 = __importDefault(require("crypto")); const TypeCheck_1 = require("./Helpers/TypeCheck"); class MessageVerifier { constructor(key, options) { this.options = options; if ((0, TypeCheck_1.isFunction)(key)) { this.key = key; } else { this.key = (0, TypeCheck_1.isKeyObject)(key) ? key : crypto_1.default.createPrivateKey(key); } } async decryptAndVerify(pubKey, data) { const key = await this.serverKey(); const decrypted = crypto_1.default.privateDecrypt(this.encryptOptions(key), data.message); const isVerified = crypto_1.default.verify(this.options.hashAlgorithm, decrypted, this.verifyOptions(pubKey), data.signature); return isVerified ? decrypted : null; } async encryptAndSign(pubKey, data) { const key = await this.serverKey(); const message = crypto_1.default.publicEncrypt(this.encryptOptions(pubKey), data); const signature = crypto_1.default.sign(this.options.hashAlgorithm, data, this.signOptions(key)); return { message, signature }; } async verify(pubKey, data) { const key = await this.serverKey(); return crypto_1.default.verify(this.options.hashAlgorithm, data.message, this.verifyOptions(pubKey), data.signature); } async sign(data) { const key = await this.serverKey(); const signature = crypto_1.default.sign(this.options.hashAlgorithm, data, this.signOptions(key)); return { message: data, signature }; } hash(data) { return crypto_1.default.createHash(this.options.hashAlgorithm).update(data).digest("base64"); } getNonce() { return crypto_1.default.randomBytes(this.options.nonceSize); } signOptions(key) { return { key: (0, TypeCheck_1.isKeyObject)(key) ? key : crypto_1.default.createPrivateKey(key), padding: this.options.signaturePadding, }; } verifyOptions(key) { return { key: (0, TypeCheck_1.isKeyObject)(key) ? key : crypto_1.default.createPublicKey(key), padding: this.options.signaturePadding, }; } encryptOptions(key) { return { key, oaepHash: this.options.hashAlgorithm, padding: this.options.messagePadding, }; } async serverKey() { if ((0, TypeCheck_1.isKeyObject)(this.key)) { return this.key; } const keyResult = this.key(); const keyLike = (0, TypeCheck_1.isPromise)(keyResult) ? await keyResult : keyResult; return (0, TypeCheck_1.isKeyObject)(keyLike) ? keyLike : crypto_1.default.createPrivateKey(keyLike); } } exports.MessageVerifier = MessageVerifier; //# sourceMappingURL=MessageVerifier.js.map