auth-server-helper/lib/KeyStore.ts

39 lines
1015 B
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';
class KeyStore {
private _keys: Record<string, string> = {};
public get_key (iat: number, valid_for = 0): string {
const key = Math.floor (iat / 60)
.toFixed (0);
if (typeof this._keys[key] === 'string')
return this._keys[key];
if (valid_for !== 0) {
2020-12-06 21:29:11 +01:00
if ((iat + valid_for) * 1000 < (new Date)
.getTime ())
throw new Error ('cannot create already expired keys');
2020-12-06 21:06:40 +01:00
this._keys[key] = create_salt ();
setTimeout (() => {
delete this._keys[key];
}, (valid_for + 5) * 1000);
return this._keys[key];
}
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 };