This commit is contained in:
@ -7,26 +7,50 @@
|
||||
|
||||
import { create_salt } from '@sapphirecode/crypto-helper';
|
||||
|
||||
interface Key {
|
||||
key: string;
|
||||
valid_until: number;
|
||||
timeout: NodeJS.Timeout;
|
||||
}
|
||||
|
||||
class KeyStore {
|
||||
private _keys: Record<string, string> = {};
|
||||
private _keys: Record<string, Key> = {};
|
||||
|
||||
private set_timeout (index: string, valid_for: number): NodeJS.Timeout {
|
||||
return setTimeout (() => {
|
||||
delete this._keys[index];
|
||||
}, (valid_for + 5) * 1000);
|
||||
}
|
||||
|
||||
public get_key (iat: number, valid_for = 0): string {
|
||||
const key = Math.floor (iat / 60)
|
||||
const index = Math.floor (iat / 60)
|
||||
.toFixed (0);
|
||||
|
||||
if (typeof this._keys[key] === 'string')
|
||||
return this._keys[key];
|
||||
const valid_until = (new Date)
|
||||
.getTime () + (valid_for * 1000);
|
||||
|
||||
if (typeof this._keys[index] !== 'undefined') {
|
||||
const key = this._keys[index];
|
||||
if (valid_for !== 0 && key.valid_until < valid_until) {
|
||||
clearTimeout (key.timeout);
|
||||
key.timeout = this.set_timeout (index, valid_for);
|
||||
key.valid_until = valid_until;
|
||||
}
|
||||
return key.key;
|
||||
}
|
||||
|
||||
if (valid_for !== 0) {
|
||||
if ((iat + valid_for) * 1000 < (new Date)
|
||||
if ((iat + 1) * 1000 < (new Date)
|
||||
.getTime ())
|
||||
throw new Error ('cannot create already expired keys');
|
||||
|
||||
this._keys[key] = create_salt ();
|
||||
setTimeout (() => {
|
||||
delete this._keys[key];
|
||||
}, (valid_for + 5) * 1000);
|
||||
return this._keys[key];
|
||||
this._keys[index] = {
|
||||
key: create_salt (),
|
||||
timeout: this.set_timeout (index, valid_for),
|
||||
valid_until
|
||||
};
|
||||
|
||||
return this._keys[index].key;
|
||||
}
|
||||
|
||||
throw new Error ('key could not be found');
|
||||
|
Reference in New Issue
Block a user