Notes/src/services/protected_session.ts

83 lines
2.0 KiB
TypeScript
Raw Normal View History

"use strict";
2024-02-16 23:09:59 +02:00
import log = require('./log');
import dataEncryptionService = require('./encryption/data_encryption');
2024-02-16 23:09:59 +02:00
let dataKey: Buffer | null = null;
2024-02-16 23:09:59 +02:00
function setDataKey(decryptedDataKey: Buffer) {
dataKey = Buffer.from(decryptedDataKey);
}
function getDataKey() {
return dataKey;
}
function resetDataKey() {
dataKey = null;
}
function isProtectedSessionAvailable() {
return !!dataKey;
}
2024-02-16 23:09:59 +02:00
function encrypt(plainText: string | Buffer) {
const dataKey = getDataKey();
if (plainText === null || dataKey === null) {
return null;
}
2024-02-16 23:09:59 +02:00
return dataEncryptionService.encrypt(dataKey, plainText);
}
function decrypt(cipherText: string | Buffer): Buffer | null {
2024-02-16 23:09:59 +02:00
const dataKey = getDataKey();
if (cipherText === null || dataKey === null) {
return null;
}
return dataEncryptionService.decrypt(dataKey, cipherText) || null;
}
function decryptString(cipherText: string): string | null {
2024-02-16 23:09:59 +02:00
const dataKey = getDataKey();
if (dataKey === null) {
return null;
}
return dataEncryptionService.decryptString(dataKey, cipherText);
2019-11-02 07:50:23 +01:00
}
2024-02-16 23:09:59 +02:00
let lastProtectedSessionOperationDate: number | null = null;
function touchProtectedSession() {
if (isProtectedSessionAvailable()) {
lastProtectedSessionOperationDate = Date.now();
}
}
function checkProtectedSessionExpiration() {
const options = require('./options.js');
const protectedSessionTimeout = options.getOptionInt('protectedSessionTimeout');
if (isProtectedSessionAvailable()
&& lastProtectedSessionOperationDate
&& Date.now() - lastProtectedSessionOperationDate > protectedSessionTimeout * 1000) {
resetDataKey();
log.info("Expiring protected session");
require('./ws.js').reloadFrontend("leaving protected session");
}
}
export = {
setDataKey,
resetDataKey,
isProtectedSessionAvailable,
encrypt,
decrypt,
2019-11-02 07:50:23 +01:00
decryptString,
touchProtectedSession,
checkProtectedSessionExpiration
2020-06-15 17:56:53 +02:00
};