auth-server-helper/lib/Blacklist.ts
Timo Hocker e80e3f9a94
Some checks failed
continuous-integration/drone/push Build is failing
improve debug, redis storage structure
2022-08-15 17:33:25 +02:00

85 lines
2.2 KiB
TypeScript

/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of Auth-Server-Helper which is released under MIT.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, December 2020
*/
import { debug } from './debug';
const logger = debug ('blacklist');
interface Signature {
hash: string;
iat: number;
}
class Blacklist {
private _signatures: Signature[];
public constructor () {
this._signatures = [];
}
public clear (before: number = Number.POSITIVE_INFINITY): void {
logger.extend ('clear') ('clearing blacklist');
for (let i = this._signatures.length - 1; i >= 0; i--) {
if (this._signatures[i].iat < before)
this.remove_signature (i);
}
}
public add_signature (hash: string): void {
logger.extend ('add_signature') ('blacklisting signature %s', hash);
this._signatures.push ({ iat: Date.now (), hash });
}
public remove_signature (signature: number | string): void {
const log = logger.extend ('remove_signature');
log ('removing signature from blacklist %s', signature);
if (typeof signature === 'string') {
log ('received string, searching through signatures');
for (let i = this._signatures.length - 1; i >= 0; i--) {
if (this._signatures[i].hash === signature)
this._signatures.splice (i, 1);
}
}
else {
log ('received index, removing at index');
this._signatures.splice (signature, 1);
}
}
public is_valid (hash: string): boolean {
const log = logger.extend ('is_valid');
log ('checking signature for blacklist entry %s', hash);
for (const sig of this._signatures) {
if (sig.hash === hash) {
log ('found matching blacklist entry');
return false;
}
}
log ('signature is not blacklisted');
return true;
}
public export_blacklist (): Signature[] {
logger.extend ('export_blacklist') ('exporting blacklist');
return this._signatures;
}
public import_blacklist (data: Signature[]): void {
logger.extend ('import_blacklist') (
'importing %d blacklist entries',
data.length
);
this._signatures.push (...data);
}
}
const bl = (new Blacklist);
export { Blacklist };
export default bl;