@kikiutils/nitro-session
Version:
Easy-to-use nitro session.
49 lines (46 loc) • 1.8 kB
JavaScript
import { Buffer } from 'node:buffer';
import { AesCiphers } from 'node-ciphers';
class CookieOrHeaderDataHandler {
#cipher;
constructor(options) {
const aesModeToCipherClassMap = {
cbc: AesCiphers.Cbc,
cfb: AesCiphers.Cfb,
cfb1: AesCiphers.Cfb1,
cfb8: AesCiphers.Cfb8,
ctr: AesCiphers.Ctr,
ofb: AesCiphers.Ofb,
};
if (options?.encryptionMode && !aesModeToCipherClassMap[options.encryptionMode]) {
throw new Error(`Invalid cookie/header data encryption mode: ${options.encryptionMode}`);
}
if (!options?.key)
throw new Error('No cookie/header data encryption key provided');
const isKeyLengthValid = [
16,
24,
32,
].includes(Buffer.from(options.key, options.encodingOptions?.key).byteLength);
if (!isKeyLengthValid)
throw new Error('Invalid cookie/header data encryption key length');
this.#cipher = new aesModeToCipherClassMap[options.encryptionMode || 'ctr'](options.key, Object.assign({
decryptInput: 'base64',
encryptOutput: 'base64',
iv: 'base64',
}, options.encodingOptions));
}
delete(_) { }
get(_, token) {
const separatorIndex = token.lastIndexOf(':');
if (separatorIndex === -1)
return;
return this.#cipher.decryptToJson(token.slice(0, separatorIndex), token.slice(separatorIndex + 1));
}
setOrProcessAndGetToken(_, data) {
const encryptResult = this.#cipher.encryptJson(data);
if (encryptResult)
return `${encryptResult.data}:${encryptResult.iv}`;
}
}
export { CookieOrHeaderDataHandler };
//# sourceMappingURL=cookie-or-header.mjs.map