auth-server-helper/lib/KeyStore.ts

63 lines
1.6 KiB
TypeScript
Raw Normal View History

/*
* 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
*/
2020-12-06 21:06:40 +01:00
import { create_salt } from '@sapphirecode/crypto-helper';
2021-01-06 11:15:56 +01:00
interface Key {
key: string;
valid_until: number;
timeout: NodeJS.Timeout;
}
2020-12-06 21:06:40 +01:00
class KeyStore {
2021-01-06 11:15:56 +01:00
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);
}
2020-12-06 21:06:40 +01:00
public get_key (iat: number, valid_for = 0): string {
2021-01-06 11:15:56 +01:00
const index = Math.floor (iat / 60)
2020-12-06 21:06:40 +01:00
.toFixed (0);
2021-01-06 11:15:56 +01:00
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;
}
2020-12-06 21:06:40 +01:00
if (valid_for !== 0) {
2021-01-06 11:15:56 +01:00
if ((iat + 1) * 1000 < (new Date)
2020-12-06 21:29:11 +01:00
.getTime ())
throw new Error ('cannot create already expired keys');
2021-01-06 11:15:56 +01:00
this._keys[index] = {
key: create_salt (),
timeout: this.set_timeout (index, valid_for),
valid_until
};
return this._keys[index].key;
2020-12-06 21:06:40 +01:00
}
throw new Error ('key could not be found');
}
}
const ks: KeyStore = (new KeyStore);
export default ks;
2021-01-05 22:10:41 +01:00
export { KeyStore };