Skip to content

Commit

Permalink
fix(sign): fix sign parameters type and usage
Browse files Browse the repository at this point in the history
The payload and signOptions parameters have incorrect type checking,
therefore possibly breaking the jsonwebtoken source code
passing invalid payload and sign options.
Scenario: if "expiresIn" has been set in the nestjs module and uses payload
as a string, it'll break the code, because jsonwebtoken does not allow the use
of "expiresIn" option with a string payload.
In order to solve the problem, it is necessary predict the developer's behavior using types.
Also throw an error in case of incorrect use of the sign method of the JwtService class.
  • Loading branch information
hender-hs committed Mar 24, 2023
1 parent 5d44e13 commit bea5df3
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions lib/jwt.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ export class JwtService {
private readonly options: JwtModuleOptions = {}
) {}

sign(
payload: string,
options?: Omit<JwtSignOptions, keyof jwt.SignOptions>
): string;
sign(payload: Buffer | object, options?: JwtSignOptions): string;
sign(payload: string | Buffer | object, options?: JwtSignOptions): string {
const signOptions = this.mergeJwtOptions(
{ ...options },
Expand All @@ -30,9 +35,29 @@ export class JwtService {
JwtSecretRequestType.SIGN
);

const allowedSignOptKeys = ['secret', 'privateKey'];
const signOptKeys = Object.keys(signOptions);
if (
typeof payload === 'string' &&
signOptKeys.some((k) => !allowedSignOptKeys.includes(k))
) {
throw new Error(
'Not allowed payload as string with these sign options: ' +
signOptKeys.join(', ')
);
}

return jwt.sign(payload, secret, signOptions);
}

signAsync(
payload: string,
options?: Omit<JwtSignOptions, keyof jwt.SignOptions>
): Promise<string>;
signAsync(
payload: Buffer | object,
options?: JwtSignOptions
): Promise<string>;
signAsync(
payload: string | Buffer | object,
options?: JwtSignOptions
Expand All @@ -48,6 +73,18 @@ export class JwtService {
JwtSecretRequestType.SIGN
);

const allowedSignOptKeys = ['secret', 'privateKey'];
const signOptKeys = Object.keys(signOptions);
if (
typeof payload === 'string' &&
signOptKeys.some((k) => !allowedSignOptKeys.includes(k))
) {
throw new Error(
'Not allowed payload as string with these sign options: ' +
signOptKeys.join(', ')
);
}

return new Promise((resolve, reject) =>
jwt.sign(payload, secret, signOptions, (err, encoded) =>
err ? reject(err) : resolve(encoded)
Expand Down

0 comments on commit bea5df3

Please sign in to comment.