Security News
GitHub Removes Malicious Pull Requests Targeting Open Source Repositories
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
@mswjs/interceptors
Advanced tools
The @mswjs/interceptors package is a library for intercepting and mutating outgoing HTTP/HTTPS requests and WebSocket connections. It is primarily used for testing purposes, allowing developers to create mock servers and intercept network requests to return custom responses without having to alter the actual network infrastructure.
Intercepting HTTP/HTTPS requests
This feature allows you to intercept outgoing HTTP/HTTPS requests and return custom responses. The code sample demonstrates how to set up an interceptor for HTTP requests and provide a custom response with a mocked JSON body.
const { createInterceptor } = require('@mswjs/interceptors');
const { interceptClientRequest } = createInterceptor({
modules: [require('@mswjs/interceptors/lib/interceptors/http')],
resolver(request) {
return {
status: 200,
body: JSON.stringify({ mocked: true }),
};
},
});
interceptClientRequest();
Intercepting WebSocket connections
This feature enables the interception of WebSocket connections, allowing you to monitor or mock WebSocket events. The code sample shows how to set up an interceptor for WebSocket connections and log the intercepted events.
const { createInterceptor } = require('@mswjs/interceptors');
const { interceptClientRequest } = createInterceptor({
modules: [require('@mswjs/interceptors/lib/interceptors/ws')],
resolver(event) {
console.log('Intercepted WebSocket:', event);
},
});
interceptClientRequest();
Nock is a popular HTTP server mocking and expectations library for Node.js. It allows you to intercept HTTP requests and provide predefined responses. Compared to @mswjs/interceptors, nock is focused solely on HTTP/HTTPS and does not handle WebSocket connections.
Sinon is a testing library that provides standalone test spies, stubs, and mocks for JavaScript. It includes the ability to fake XMLHttpRequest and server responses, which is similar to the HTTP interception feature of @mswjs/interceptors. However, Sinon's focus is broader, encompassing various aspects of test doubles, not just network interception.
Mock-socket is a library that mocks WebSockets for front-end testing. It allows you to test WebSocket connections without an actual server. While @mswjs/interceptors can intercept WebSocket connections, mock-socket specializes in providing a WebSocket environment for testing purposes.
@mswjs/interceptors
Low-level HTTP/HTTPS/XHR/fetch request interception library.
Intercepts any requests issued by:
http.get
/http.request
https.get
/https.request
XMLHttpRequest
fetch
request
, node-fetch
, etc.)While there are a lot of network communication mocking libraries, they tend to use request interception as an implementation detail, giving you a high-level API that includes request matching, timeouts, retries, and so forth.
This library is a strip-to-bone implementation that provides as little abstraction as possible to execute arbitrary logic upon any request. It's primarily designed as an underlying component for high-level API mocking solutions such as Mock Service Worker.
As interception is often combined with request route matching, some libraries can determine whether a request should be mocked before it actually happens. This approach is not suitable for this library, as it rather intercepts all requests and then let's you decide which ones should be mocked. This affects the level at which interception happens, and also the way mocked/original responses are constructed, in comparison to other solutions.
This library monkey-patches the following native modules:
http.get
/http.request
https.get
/https.request
XMLHttpRequest
fetch
Once patched, it provisions the interception of requests and normalizes them to something called isomorphic request instances. That normalization ensures the same request handling for the consumer of the library, while requests originating from different modules may differ internally.
In its mocking phase, this library accepts an isomorphic response instance that describes a module-agnostic mocked response. This allows you to respond to requests issued by different modules using the same response instance.
npm install @mswjs/interceptors
createInterceptor(options: CreateInterceptorOptions)
import { createInterceptor } from '@mswjs/interceptors'
import nodeInterceptors from '@mswjs/interceptors/lib/presets/node'
const interceptor = createInterceptor({
modules: nodeInterceptors,
resolver(request, ref) {
// Optionally, return a mocked response.
},
})
Using the
/presets/node
interceptors preset is the recommended way to ensure all requests get intercepted, regardless of their origin.
This library utilizes a concept of interceptors–functions that patch necessary modules, handle mocked responses, and restore patched modules.
List of interceptors:
/interceptors/ClientRequest
/interceptors/XMLHttpRequest
/interceptors/fetch
To use a single, or multiple interceptors, import and provide them to the RequestInterceptor
constructor.
import { createInterceptor } from '@mswjs/interceptors'
import { interceptXMLHttpRequest } from '@mswjs/interceptors/lib/interceptors/XMLHttpRequest'
// This `interceptor` instance would handle only XMLHttpRequest,
// ignoring requests issued via `http`/`https` modules.
const interceptor = new createInterceptor({
modules: [interceptXMLHttpRequest],
})
Interceptors are crucial in leveraging environment-specific module overrides. Certain environments (i.e. React Native) do not have access to native Node.js modules (like
http
). Importing such modules raises an exception, and must be avoided.
.apply(): void
Applies module patches and enables interception of the requests.
interceptor.apply()
.on(event, listener): boolean
Adds an event listener to one of the following supported events:
request
, whenever a new request happens.response
, whenever a request library responds to a request.interceptor.on('request', (request) => {
console.log('[%s] %s', request.method, request.url.toString())
})
.restore(): void
Restores all patched modules and stops intercepting future requests.
interceptor.restore()
The following libraries were used as an inspiration to write this low-level API:
FAQs
Low-level HTTP/HTTPS/XHR/fetch request interception library.
The npm package @mswjs/interceptors receives a total of 2,365,375 weekly downloads. As such, @mswjs/interceptors popularity was classified as popular.
We found that @mswjs/interceptors demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
GitHub removed 27 malicious pull requests attempting to inject harmful code across multiple open source repositories, in another round of low-effort attacks.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.