UNPKG

expresscheckout-nodejs

Version:

Juspay's official expresscheckout-nodejs sdk

71 lines 2.62 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = __importDefault(require("crypto")); const Utils_js_1 = __importDefault(require("./Utils.js")); const JuspayCryptoError_js_1 = __importDefault(require("./JuspayCryptoError.js")); function sign(claims, keyId, privateKey) { try { const signer = crypto_1.default.createSign('RSA-SHA256'); const signatureHeader = '{"alg":"RS256","kid":"' + keyId + '"}'; const header = Utils_js_1.default.encodeBase64Url(signatureHeader); const payload = Utils_js_1.default.encodeBase64Url(claims); const data = `${header}.${payload}`; signer.update(data); const signedBuffer = signer.sign(privateKey); const signed = Utils_js_1.default.encodeBase64UrlFromBuffer(signedBuffer); return { header, payload, signature: signed, }; } catch (error) { throw new JuspayCryptoError_js_1.default(error); } } // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any function verify(signed, publicKey) { try { let data; if (typeof signed == 'string') { try { data = JSON.parse(signed); } catch (error) { const signedParts = signed.split('.'); if (signedParts.length != 3) { throw new JuspayCryptoError_js_1.default('Signature Illformed', 'SignedPayloadIllformed'); } data = { header: signedParts[0], payload: signedParts[1], signature: signedParts[3], }; } } else { data = signed; } const verifier = crypto_1.default.createVerify('RSA-SHA256'); const protect = `${data.header}.${data.payload}`; verifier.update(protect); const isVerified = verifier.verify(publicKey, data.signature, 'base64'); if (isVerified) { return Utils_js_1.default.decodeBase64Url(data.payload); } else { throw new JuspayCryptoError_js_1.default('Signature verification failed', 'SignatureValidationFailed'); } } catch (error) { throw new JuspayCryptoError_js_1.default(error); } } exports.default = { sign, verify, }; //# sourceMappingURL=JWS.js.map