auth-server-helper/lib/Authority.ts
Timo Hocker 48afa73ae8
Some checks failed
continuous-integration/drone/push Build is failing
fix
2021-01-05 15:59:06 +01:00

104 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 {
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;
valid: boolean;
type: TokenType;
id: string;
next_module?: string;
data?: unknown;
error?: string;
}
interface SignatureResult {
signature: string;
id: string;
}
interface SignatureOptions
{
data?: unknown
next_module?: string
}
class Authority {
public verify (key: string): VerificationResult {
const result: VerificationResult = {
authorized: false,
valid: false,
type: 'none',
id: ''
};
const data = verify_signature_get_info (
key,
(info) => {
try {
return keystore.get_key (info.iat / 1000);
}
catch {
return '';
}
},
(info) => info.valid_for * 1000
);
if (data === null) {
result.error = 'invalid signature';
return result;
}
result.id = data.id;
result.type = data.type;
if (!blacklist.is_valid (data.id)) {
result.error = 'blacklisted';
return result;
}
result.valid = true;
result.authorized = result.type === 'access_token';
result.next_module = data.next_module;
result.data = data.obj;
return result;
}
public sign (
type: TokenType,
valid_for: number,
options?: SignatureOptions
): SignatureResult {
const time = Date.now ();
const key = keystore.get_key (time / 1000, valid_for);
const attributes = {
id: create_salt (),
iat: time,
type,
valid_for,
next_module: options?.next_module
};
const signature = sign_object (options?.data, key, attributes);
return { id: attributes.id, signature };
}
}
const auth = (new Authority);
export default auth;