feat(core): Enhanced JWT handling and key management

This commit is contained in:
2024-08-26 21:49:48 +02:00
parent 26655ff92e
commit b247630e0f
6 changed files with 5089 additions and 3988 deletions

View File

@@ -1,5 +1,8 @@
import * as plugins from './smartjwt.plugins.js';
// Define the IWithJwt interface with a constraint that T must be an object
export type IObjectWithJwt<T extends object> = T & { jwt: string };
/**
* A class to create and validate JWTs and their keys
*/
@@ -81,4 +84,33 @@ export class SmartJwt<T extends object = any> {
public async init() {
await this.createNewKeyPair();
}
public isObjectWithJwt<T extends object>(
object: unknown,
): object is IObjectWithJwt<T> {
return (
typeof object === 'object' &&
object !== null &&
'jwt' in object &&
typeof (object as IObjectWithJwt<T>).jwt === 'string'
);
}
public jwtObjectGuard = new plugins.smartguard.Guard(async (dataArg: IObjectWithJwt<any>) => {
const jwtData = this.verifyJWTAndGetData(dataArg.jwt);
// check all other properties wether they match with jwtData
for (const key in dataArg) {
if (key !== 'jwt') {
if (jwtData[key] !== dataArg[key]) {
return false;
}
}
}
return true;
}, {
name: 'jwtObjectGuard',
failedHint: 'is not a valid jwt object',
})
}