Skip to content

Commit bea5df3

Browse files
committed
fix(sign): fix sign parameters type and usage
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.
1 parent 5d44e13 commit bea5df3

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

lib/jwt.service.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ export class JwtService {
1818
private readonly options: JwtModuleOptions = {}
1919
) {}
2020

21+
sign(
22+
payload: string,
23+
options?: Omit<JwtSignOptions, keyof jwt.SignOptions>
24+
): string;
25+
sign(payload: Buffer | object, options?: JwtSignOptions): string;
2126
sign(payload: string | Buffer | object, options?: JwtSignOptions): string {
2227
const signOptions = this.mergeJwtOptions(
2328
{ ...options },
@@ -30,9 +35,29 @@ export class JwtService {
3035
JwtSecretRequestType.SIGN
3136
);
3237

38+
const allowedSignOptKeys = ['secret', 'privateKey'];
39+
const signOptKeys = Object.keys(signOptions);
40+
if (
41+
typeof payload === 'string' &&
42+
signOptKeys.some((k) => !allowedSignOptKeys.includes(k))
43+
) {
44+
throw new Error(
45+
'Not allowed payload as string with these sign options: ' +
46+
signOptKeys.join(', ')
47+
);
48+
}
49+
3350
return jwt.sign(payload, secret, signOptions);
3451
}
3552

53+
signAsync(
54+
payload: string,
55+
options?: Omit<JwtSignOptions, keyof jwt.SignOptions>
56+
): Promise<string>;
57+
signAsync(
58+
payload: Buffer | object,
59+
options?: JwtSignOptions
60+
): Promise<string>;
3661
signAsync(
3762
payload: string | Buffer | object,
3863
options?: JwtSignOptions
@@ -48,6 +73,18 @@ export class JwtService {
4873
JwtSecretRequestType.SIGN
4974
);
5075

76+
const allowedSignOptKeys = ['secret', 'privateKey'];
77+
const signOptKeys = Object.keys(signOptions);
78+
if (
79+
typeof payload === 'string' &&
80+
signOptKeys.some((k) => !allowedSignOptKeys.includes(k))
81+
) {
82+
throw new Error(
83+
'Not allowed payload as string with these sign options: ' +
84+
signOptKeys.join(', ')
85+
);
86+
}
87+
5188
return new Promise((resolve, reject) =>
5289
jwt.sign(payload, secret, signOptions, (err, encoded) =>
5390
err ? reject(err) : resolve(encoded)

0 commit comments

Comments
 (0)