Registry / auth-security / oauth2-mock-server

oauth2-mock-server

JSON →
library8.2.2jsnpmunverified

oauth2-mock-server is a JavaScript/TypeScript library designed to provide a configurable OAuth2/OpenID Connect server for automated testing and development purposes. It allows developers to simulate an OAuth2 provider to issue verifiable access tokens without needing a full-fledged identity provider, making it ideal for unit and integration tests. The library supports various OAuth2 grant types, including Client Credentials, Resource Owner Password Credentials, Authorization Code (with PKCE), and Refresh Token grants. It also supports multiple JWK formats for signing tokens (RSA, EC, EdDSA). The current stable version is 8.2.2, with recent releases indicating an active maintenance and development cadence focused on dependency updates, minor feature additions, and bug fixes. A key differentiator is its programmatic control via event emitters for customizing server behavior, allowing for specific test scenarios, such as modifying token expiration or adding custom claims. It is explicitly not intended for production use due to a lack of full feature parity and security hardening.

npm install oauth2-mock-server
INSTALL
IMPORT
SIG · OAUTH2-MOCK-SERVER
O
oauth2-mock-server
auth-securityjavascriptv8.2.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

OAuth2Server
import { OAuth2Server } from 'oauth2-mock-server';
const { OAuth2Server } = require('oauth2-mock-server');
The library switched to 'Universal' ESM in v8.0.0. While CommonJS `require()` is supported for specific Node.js versions (>=20.19, >=22.12), using `import` is the recommended and more robust approach for modern projects. Avoid `import OAuth2Server from '...'`.
HttpServer, OAuth2Service
import { HttpServer, OAuth2Service } from 'oauth2-mock-server';
const { HttpServer } = require('oauth2-mock-server');
These classes were exported starting from v8.1.0. Adhere to ESM import rules since v8.0.0. The CommonJS `require()` pattern is subject to the same compatibility constraints as `OAuth2Server`.
TokenRequestIncomingMessage
import type { TokenRequestIncomingMessage } from 'oauth2-mock-server';
import { TokenRequestIncomingMessage } from 'oauth2-mock-server';
This is a TypeScript type, use `import type` for proper type-only imports to prevent bundling issues and ensure type stripping. This type was exported starting from v8.2.0.

This quickstart demonstrates how to initialize, configure, and operate the `oauth2-mock-server`. It shows how to generate cryptographic keys, start the server on a dynamic port, build JWTs programmatically, and apply customization hooks to modify token claims before signing, simulating an OAuth2 flow for testing purposes.

import { OAuth2Server } from 'oauth2-mock-server'; import axios from 'axios'; async function runMockServerExample() { let server = new OAuth2Server(); // Generate a new RSA key and add it to the keystore await server.issuer.keys.generate('RS256'); // Start the server on a free port, typically a high port for testing // using 0 lets the OS pick a free port, then get the port from server.port await server.start(0, 'localhost'); const port = server.port; console.log('Mock OAuth2 Server started on port:', port); console.log('Issuer URL:', server.issuer.url); // -> http://localhost:PORT // --- Example: Build a token and use it --- try { let token = await server.issuer.buildToken(); console.log('Generated JWT:', token); // Call a remote API with the token (this part won't actually work without a real API) // For demonstration, let's just log what would happen const exampleApiUrl = 'https://api.example.com/secure-data'; console.log(`Attempting to call ${exampleApiUrl} with Bearer token...`); // In a real test, you'd point this to your application's protected endpoint // and your application would validate this token against the mock server's JWKS endpoint. // const response = await axios.get(exampleApiUrl, { // headers: { // authorization: `Bearer ${token}`, // }, // }); // console.log('API Response (simulated):', response.data); // --- Example: Customize next token signing --- server.once('beforeTokenSigning', (modifiedToken) => { console.log('Modifying next token: Adding custom claim "test_claim".'); modifiedToken.payload.test_claim = 'custom_value'; modifiedToken.payload.exp = Math.floor(Date.now() / 1000) + 60; // Make it expire in 60s }); let customToken = await server.issuer.buildToken(); console.log('Generated custom JWT:', customToken); // You would typically decode and assert properties of customToken here in a test. } catch (error) { console.error('Error during mock server operation:', error); } finally { // Stop the server console.log('Stopping mock server...'); await server.stop(); console.log('Mock server stopped.'); } } runMockServerExample();
Debug
Known issues
breakingNode.js 18 is no longer supported since v8.0.0. The package now requires Node.js ^20.19 || ^22.12 || ^24.
fix
Upgrade your Node.js environment to a supported version (20.19+, 22.12+, or 24+).
affects: >=8.0.0
breakingVersion 8.0.0 switched to 'Universal' ESM. While CommonJS `require()` is technically supported for specific Node.js versions (20.19+, 22.12+), it is generally recommended to migrate your project to use ES modules (`import` statements) to avoid potential compatibility issues and leverage modern JavaScript module loading.
fix
Ensure your project is configured for ES modules (e.g., `'type': 'module'` in `package.json` and using `import` statements), or confirm your Node.js version is within the range that supports the CJS fallback.
affects: >=8.0.0
gotchaThis tool is explicitly *not* intended to be used as a production-grade OAuth 2 server. It lacks many features and security hardening required for a proper implementation and should only be used for development or testing purposes.
fix
Do not deploy `oauth2-mock-server` in production environments. Use a robust, production-ready OAuth2/OIDC provider instead.
affects: >=1.0.0
gotchaBefore the mock server can issue tokens, you must explicitly generate or add cryptographic keys to its keystore. Failing to do so will result in runtime errors when attempting to build or sign tokens.
fix
Call `await server.issuer.keys.generate('RS256')` (or another supported algorithm) or `await server.issuer.keys.add(yourJwk)` after initializing `OAuth2Server` and before starting the server or building tokens.
affects: >=1.0.0
Errors
Common errors & fixes
ERR_REQUIRE_ESM: require() of ES Module ... not supported.
Attempting to `require()` the `oauth2-mock-server` package in a CommonJS context on an unsupported Node.js version or when the project's module configuration conflicts with its 'Universal' ESM design.
fix
Update your Node.js version to ^20.19 || ^22.12 || ^24, or configure your project to use ES Modules by adding `'type': 'module'` to your `package.json` and using `import` statements.
Error: listen EADDRINUSE: address already in use :::8080
The specified port (e.g., 8080) that you are trying to start the `OAuth2Server` on is already being used by another process on your system.
fix
Choose an alternative port for `server.start(port, 'localhost')`, or set the port to `0` to have the operating system automatically assign a free port (e.g., `await server.start(0, 'localhost')`). Ensure previous instances of the server are properly stopped.
Error: No signing keys available. Generate one with server.issuer.keys.generate() or add one with server.issuer.keys.add().
The `OAuth2Server` instance requires at least one cryptographic key (JWK) to sign tokens, but no keys have been provided or generated.
fix
Before making requests to token endpoints or programmatically building tokens, ensure you call `await server.issuer.keys.generate('RS256')` or `await server.issuer.keys.add(yourJwk)` to populate the server's keystore.
Upgrade
Version history
8.2.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
7 hits · last 30 days
node
6
OpenAI (training)
1
Resources
oauth2-mock-server — npm install oauth2-mock-server · libregistry