From 8a264bfa582811fca624c46bb734219c7601a633 Mon Sep 17 00:00:00 2001 From: Timo Hocker Date: Sat, 19 Dec 2020 15:40:49 +0100 Subject: [PATCH] separate authority --- lib/Authority.ts | 66 ++++++++++++++++++++++++++++++++++++++++++++++++ lib/Gateway.ts | 14 ++-------- 2 files changed, 68 insertions(+), 12 deletions(-) create mode 100644 lib/Authority.ts diff --git a/lib/Authority.ts b/lib/Authority.ts new file mode 100644 index 0000000..14514eb --- /dev/null +++ b/lib/Authority.ts @@ -0,0 +1,66 @@ +import { + create_salt, + sign_object, + verify_signature_get_info +} from '@sapphirecode/crypto-helper'; +import keystore from './KeyStore'; +import blacklist from './Blacklist'; + +// eslint-disable-next-line no-shadow +type TokenType = 'access_token'|'refresh_token'|'part_token'|'none' + +interface VerificationResult { + authorized: boolean; + type: TokenType; + next_module: string; +} + +interface SignatureResult { + signature: string; + id: string; +} + +class Authority { + public verify (key: string): VerificationResult { + const result = { authorized: false, type: 'none', next_module: '' }; + const data = verify_signature_get_info ( + key, + (info) => keystore.get_key (info.iat / 1000), + (info) => info.valid_for * 1000 + ); + + if (data === null) + return result; + + result.type = data.type; + + if (!blacklist.is_valid (data.id)) + return result; + + result.authorized = result.type === 'access_token'; + result.next_module = data.obj; + + return result; + } + + public sign ( + type: TokenType, + valid_for: number, + next_module?: string + ): SignatureResult { + const time = Date.now (); + const key = keystore.get_key (time / 1000); + const attributes = { + id: create_salt (), + iat: time, + type, + valid_for + }; + const signature = sign_object (next_module, key, attributes); + return { id: attributes.id, signature }; + } +} + +const auth = (new Authority); + +export default auth; diff --git a/lib/Gateway.ts b/lib/Gateway.ts index f3e8561..9c41db9 100644 --- a/lib/Gateway.ts +++ b/lib/Gateway.ts @@ -5,10 +5,8 @@ * Created by Timo Hocker , December 2020 */ -import { verify_signature_get_info } from '@sapphirecode/crypto-helper'; import { run_regex } from '@sapphirecode/utilities'; -import keystore from './KeyStore'; -import blacklist from './Blacklist'; +import authority from './Authority'; type AnyFunc = (...args: unknown) => unknown; type Gateway = (req: Request, res: Response, next: AnyFunc) => Promise; @@ -63,15 +61,7 @@ class GatewayClass { if (auth === null) return false; - const data = verify_signature_get_info ( - auth, - (info) => keystore.get_key (info.iat), - (info) => info.valid_for * 1000 - ); - - return data !== null - && data.type === 'access_token' - && blacklist.is_valid (data.id); + return authority.verify (auth).authorized; } public process_request (