Skip to content

perf: Allow secret and publicKey options to be crypto.KeyObject (2x to 50x faster calls) #1971

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,16 @@ The `JwtModule` takes an `options` object:
- `verifyOptions` [read more](https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback)
- `secretOrPrivateKey` (DEPRECATED!) [read more](https://github.com/auth0/node-jsonwebtoken#jwtsignpayload-secretorprivatekey-options-callback)

For performance purposes, it is advised to pass instances of `KeyObject` to `secret`, `privateKey` and `publicKey` properties of this `options` object. These `KeyObject` can be generated with `createSecretKey()`, `createPrivateKey()` and `createPublicKey()` from Node.js `crypto` module. For example:

```typescript
import { createSecretKey } from 'crypto';

new JwtService({
secret: createSecretKey(Buffer.from('the secret key'))
});
```

## Support

Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
Expand Down
4 changes: 2 additions & 2 deletions lib/interfaces/jwt-module-options.interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ export enum JwtSecretRequestType {
export interface JwtModuleOptions {
global?: boolean;
signOptions?: jwt.SignOptions;
secret?: string | Buffer;
publicKey?: string | Buffer;
secret?: jwt.Secret;
Copy link
Member

@micalevisk micalevisk Jun 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

are you sure that we can still assign string or Buffer to these jwt.Secret fields? I didn't check the types nor the test suite

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we can use string or Buffer. See README of jsonwebtoken and code (here for example).

Tests in @nestjs/jwt already made sure that we can use a Buffer. No (non-mocked) tests used strings. I did not change that part.

publicKey?: jwt.Secret;
privateKey?: jwt.Secret;
/**
* @deprecated
Expand Down
75 changes: 75 additions & 0 deletions lib/jwt.service.spec.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
import {
createPrivateKey,
createPublicKey,
createSecretKey,
generateKeyPairSync,
KeyObject
} from 'crypto';
import { Test } from '@nestjs/testing';
import * as jwt from 'jsonwebtoken';
import {
Expand Down Expand Up @@ -152,6 +159,44 @@ describe('JwtService', () => {
});
});

describe('should allow KeyObject for privateKey and publicKey', () => {
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
});
const privKeyAsObject: KeyObject = createPrivateKey(privateKey);
const pubKeyAsObject: KeyObject = createPublicKey(publicKey);
const testPayload = { foo: 'bar' };

let jwtService: JwtService;

beforeEach(async () => {
jwtService = await setup({
privateKey: privKeyAsObject,
publicKey: pubKeyAsObject,
signOptions: { algorithm: 'RS256' }
});
verifySpy.mockRestore();
signSpy.mockRestore();
});

it('verifying should work', () => {
const token = jwtService.sign(testPayload);

expect(jwtService.verify(token)).toHaveProperty('foo', 'bar');
});

it('verifying (async) should work', () => {
const token = jwtService.sign(testPayload);

expect(jwtService.verifyAsync(token)).resolves.toHaveProperty(
'foo',
'bar'
);
});
});

describe('should use config.secretOrPrivateKey but warn about deprecation', () => {
let jwtService: JwtService;
let consoleWarnSpy: jest.SpyInstance;
Expand Down Expand Up @@ -226,6 +271,36 @@ describe('JwtService', () => {
});
});

describe('should allow KeyObject for secret', () => {
const secretB64: KeyObject = createSecretKey(
Buffer.from('ThisIsARandomSecret', 'base64')
);
const testPayload = { foo: 'bar' };

let jwtService: JwtService;

beforeEach(async () => {
jwtService = await setup({ secret: secretB64 });
verifySpy.mockRestore();
signSpy.mockRestore();
});

it('verifying should use base64 buffer key', () => {
const token = jwt.sign(testPayload, secretB64);

expect(jwtService.verify(token)).toHaveProperty('foo', 'bar');
});

it('verifying (async) should use base64 buffer key', async () => {
const token = jwt.sign(testPayload, secretB64);

await expect(jwtService.verifyAsync(token)).resolves.toHaveProperty(
'foo',
'bar'
);
});
});

describe('should use secret key from options', () => {
let jwtService: JwtService;
const testPayload: string = getRandomString();
Expand Down