2020-10-03 05:47:04 -07:00
|
|
|
import buildDebug from 'debug';
|
2023-10-07 16:23:04 +02:00
|
|
|
import jwt, { SignOptions } from 'jsonwebtoken';
|
2020-10-03 05:47:04 -07:00
|
|
|
|
2023-10-07 16:23:04 +02:00
|
|
|
import { RemoteUser } from '@verdaccio/types';
|
|
|
|
|
|
|
|
export type SignOptionsSignature = Pick<SignOptions, 'algorithm' | 'expiresIn' | 'notBefore'>;
|
2020-10-03 05:47:04 -07:00
|
|
|
|
|
|
|
const debug = buildDebug('verdaccio:auth:token:jwt');
|
|
|
|
/**
|
|
|
|
* Sign the payload and return JWT
|
|
|
|
* https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback
|
|
|
|
* @param payload
|
|
|
|
* @param secretOrPrivateKey
|
|
|
|
* @param options
|
|
|
|
*/
|
|
|
|
export async function signPayload(
|
|
|
|
payload: RemoteUser,
|
|
|
|
secretOrPrivateKey: string,
|
2023-10-07 16:23:04 +02:00
|
|
|
options: SignOptionsSignature = {}
|
2020-10-03 05:47:04 -07:00
|
|
|
): Promise<string> {
|
2023-10-07 16:23:04 +02:00
|
|
|
return new Promise(function (resolve, reject) {
|
2020-10-03 05:47:04 -07:00
|
|
|
debug('sign jwt token');
|
2023-10-07 16:23:04 +02:00
|
|
|
jwt.sign(
|
2020-10-03 05:47:04 -07:00
|
|
|
payload,
|
2023-10-07 16:23:04 +02:00
|
|
|
secretOrPrivateKey, // FIXME: upgrade to the latest library and types
|
2020-10-03 05:47:04 -07:00
|
|
|
{
|
|
|
|
// 1 === 1ms (one millisecond)
|
|
|
|
notBefore: '1', // Make sure the time will not rollback :)
|
|
|
|
...options,
|
|
|
|
},
|
2023-10-07 16:23:04 +02:00
|
|
|
(error, token) => {
|
|
|
|
if (error) {
|
|
|
|
debug('error on sign jwt token %s', error.message);
|
|
|
|
return reject(error);
|
|
|
|
}
|
|
|
|
debug('signed jwt token successfully');
|
|
|
|
return resolve(token as string);
|
2020-10-03 05:47:04 -07:00
|
|
|
}
|
|
|
|
);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function verifyPayload(token: string, secretOrPrivateKey: string): RemoteUser {
|
2023-12-31 14:34:29 +01:00
|
|
|
debug('verifying jwt token');
|
2022-02-15 22:18:20 +01:00
|
|
|
return jwt.verify(token, secretOrPrivateKey) as RemoteUser;
|
2020-10-03 05:47:04 -07:00
|
|
|
}
|