@inngest/middleware-encryption
Version:
E2E encryption middleware for Inngest.
54 lines (53 loc) • 1.98 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AESEncryptionService = void 0;
const aes_js_1 = __importDefault(require("crypto-js/aes.js"));
const enc_utf8_js_1 = __importDefault(require("crypto-js/enc-utf8.js"));
/**
* The AES encryption service used by the encryption middleware.
*
* This service uses AES encryption to encrypt and decrypt data. It supports
* multiple keys, so that you can rotate keys without breaking existing
* encrypted data.
*
* It was the method used before the default encryption service using LibSodium
* was added, and is still used internally for decrypting data to ensure
* compatibility with older versions.
*/
class AESEncryptionService {
constructor(key) {
this.identifier = "inngest/aes";
if (!key) {
throw new Error("Missing encryption key(s) in encryption middleware");
}
const keys = (Array.isArray(key) ? key : [key])
.map((s) => s.trim())
.filter(Boolean);
if (!keys.length) {
throw new Error("Missing encryption key(s) in encryption middleware");
}
this.keys = keys;
}
encrypt(value) {
return aes_js_1.default.encrypt(JSON.stringify(value), this.keys[0]).toString();
}
decrypt(value) {
let err;
for (const key of this.keys) {
try {
const decrypted = aes_js_1.default.decrypt(value, key).toString(enc_utf8_js_1.default);
return JSON.parse(decrypted);
}
catch (decryptionError) {
err = decryptionError;
continue;
}
}
throw (err ||
new Error("Unable to decrypt value; no keys were able to decrypt it"));
}
}
exports.AESEncryptionService = AESEncryptionService;