feat: Passwordless cross-device authentication

- Arkitektur: docs/auth/passwordless-architecture.md
- Backend: iom/quixzoom-auth-service/ (FastAPI + Redis)
- Webb: quixzoom-market-pages/se/login/ (QR-kod + polling)
- App: iom/quixzoom-app/src/features/auth/ (push + deep links)

Flöde: QR-kod → app-godkännande → webb-inloggad
This commit is contained in:
Bernt
2026-07-07 07:11:50 +00:00
parent 4aa984ad74
commit 6989a98d75
61843 changed files with 5491611 additions and 872231 deletions
+3
View File
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Options } from './types.js';
export declare function verifyConfig<TReq extends http.IncomingMessage, TRes extends http.ServerResponse>(options: Options<TReq, TRes>): void;
+6
View File
@@ -0,0 +1,6 @@
import { HttpProxyMiddlewareError } from './errors.js';
export function verifyConfig(options) {
if (!options.target && !options.router) {
throw new HttpProxyMiddlewareError('[HPM] Missing "target" option. Example: {target: "http://www.example.org"}', 'ERR_CONFIG_FACTORY_TARGET_MISSING');
}
}
+5
View File
@@ -0,0 +1,5 @@
import createDebug from 'debug';
/**
* Debug instance with the given namespace: http-proxy-middleware
*/
export declare const Debug: createDebug.Debugger;
+5
View File
@@ -0,0 +1,5 @@
import createDebug from 'debug';
/**
* Debug instance with the given namespace: http-proxy-middleware
*/
export const Debug = createDebug('http-proxy-middleware');
+4
View File
@@ -0,0 +1,4 @@
export declare class HttpProxyMiddlewareError extends Error {
code: string;
constructor(message: string, code: string);
}
+15
View File
@@ -0,0 +1,15 @@
export class HttpProxyMiddlewareError extends Error {
code;
constructor(message, code) {
super(message);
// add custom `code` property
// so this can be used in src/plugins/default/error-response-plugin.ts to determine the status code to return
this.code = code;
// set the correct name for the error class
this.name = this.constructor.name;
// maintain proper stack trace (V8 environments)
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
}
+28
View File
@@ -0,0 +1,28 @@
import type { HttpBindings } from '@hono/node-server';
import type { MiddlewareHandler } from 'hono';
import { type Options } from './index.js';
/**
* Creates a Hono middleware that proxies requests using http-proxy-middleware.
*
* @remarks
* This middleware requires Hono to be running on Node.js via `@hono/node-server`.
* It uses `c.env.incoming` and `c.env.outgoing` which are only available with `HttpBindings`.
*
* @experimental This API is experimental and may change without a major version bump.
*
* @example
* ```ts
* import { serve } from '@hono/node-server';
* import { Hono } from 'hono';
* import { createHonoProxyMiddleware } from 'http-proxy-middleware/hono';
*
* const app = new Hono();
* app.use('/api', createHonoProxyMiddleware({ target: 'http://example.com', changeOrigin: true }));
* serve(app);
* ```
*
* @since 4.0.0
*/
export declare function createHonoProxyMiddleware(options: Options): MiddlewareHandler<{
Bindings: HttpBindings;
}>;
+45
View File
@@ -0,0 +1,45 @@
import { createProxyMiddleware } from './index.js';
import { getLogger } from './logger.js';
/**
* Creates a Hono middleware that proxies requests using http-proxy-middleware.
*
* @remarks
* This middleware requires Hono to be running on Node.js via `@hono/node-server`.
* It uses `c.env.incoming` and `c.env.outgoing` which are only available with `HttpBindings`.
*
* @experimental This API is experimental and may change without a major version bump.
*
* @example
* ```ts
* import { serve } from '@hono/node-server';
* import { Hono } from 'hono';
* import { createHonoProxyMiddleware } from 'http-proxy-middleware/hono';
*
* const app = new Hono();
* app.use('/api', createHonoProxyMiddleware({ target: 'http://example.com', changeOrigin: true }));
* serve(app);
* ```
*
* @since 4.0.0
*/
export function createHonoProxyMiddleware(options) {
const proxy = createProxyMiddleware(options);
const logger = getLogger(options);
return (c, next) => {
return new Promise((resolve, reject) => {
proxy(c.env.incoming, c.env.outgoing, (err) => {
if (err) {
reject(err);
}
else {
resolve();
}
});
})
.then(() => next())
.catch((err) => {
logger.error('Proxy error:', err);
return c.text('Proxy Error', 500);
});
};
}
+79
View File
@@ -0,0 +1,79 @@
import type * as http from 'node:http';
import type { NextFunction, Options, RequestHandler } from './types.js';
/**
* Create proxy middleware for Express-like servers. ([list of servers with examples](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md))
*
* @example Basic proxy to a single target.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* changeOrigin: true,
* });
* ```
*
* @example Proxy only matching paths and rewrite the forwarded path.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://localhost:3000',
* pathFilter: '/api',
* pathRewrite: {
* '^/api/': '/',
* },
* });
* ```
*
* @example Native path rewrite by mounting at a route (alternative to `pathRewrite`).
* ```ts
* import express from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const app = express();
* app.use(
* '/users',
* createProxyMiddleware({
* target: 'http://jsonplaceholder.typicode.com/users',
* changeOrigin: true,
* }),
* );
* ```
*
* @example Use framework-specific request/response types (Express).
* ```ts
* import type { Request, Response } from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware<Request, Response>({
* target: 'http://www.example.org/api',
* changeOrigin: true,
* });
* ```
*
* @example Intercept and modify a proxied response body.
* ```ts
* import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* selfHandleResponse: true,
* on: {
* proxyRes: responseInterceptor(async (responseBuffer) => {
* const response = responseBuffer.toString('utf8');
* return response.replace('Hello', 'Goodbye');
* }),
* },
* });
* ```
*
* @see https://github.com/chimurai/http-proxy-middleware/
* @see https://github.com/chimurai/http-proxy-middleware/#basic-usage
* @see https://github.com/chimurai/http-proxy-middleware/#intercept-and-manipulate-responses
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md
*/
export declare function createProxyMiddleware<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse, TNext = NextFunction>(options: Options<TReq, TRes>): RequestHandler<TReq, TRes, TNext>;
+81
View File
@@ -0,0 +1,81 @@
import { HttpProxyMiddleware } from './http-proxy-middleware.js';
/**
* Create proxy middleware for Express-like servers. ([list of servers with examples](https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md))
*
* @example Basic proxy to a single target.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* changeOrigin: true,
* });
* ```
*
* @example Proxy only matching paths and rewrite the forwarded path.
* ```ts
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://localhost:3000',
* pathFilter: '/api',
* pathRewrite: {
* '^/api/': '/',
* },
* });
* ```
*
* @example Native path rewrite by mounting at a route (alternative to `pathRewrite`).
* ```ts
* import express from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const app = express();
* app.use(
* '/users',
* createProxyMiddleware({
* target: 'http://jsonplaceholder.typicode.com/users',
* changeOrigin: true,
* }),
* );
* ```
*
* @example Use framework-specific request/response types (Express).
* ```ts
* import type { Request, Response } from 'express';
* import { createProxyMiddleware } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware<Request, Response>({
* target: 'http://www.example.org/api',
* changeOrigin: true,
* });
* ```
*
* @example Intercept and modify a proxied response body.
* ```ts
* import { createProxyMiddleware, responseInterceptor } from 'http-proxy-middleware';
*
* const proxy = createProxyMiddleware({
* target: 'http://www.example.org',
* selfHandleResponse: true,
* on: {
* proxyRes: responseInterceptor(async (responseBuffer) => {
* const response = responseBuffer.toString('utf8');
* return response.replace('Hello', 'Goodbye');
* }),
* },
* });
* ```
*
* @see https://github.com/chimurai/http-proxy-middleware/
* @see https://github.com/chimurai/http-proxy-middleware/#basic-usage
* @see https://github.com/chimurai/http-proxy-middleware/#intercept-and-manipulate-responses
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/servers.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md
* @see https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/response-interceptor.md
*/
export function createProxyMiddleware(options) {
const { middleware } = new HttpProxyMiddleware(options);
return middleware;
}
+3
View File
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Options, Plugin } from './types.js';
export declare function getPlugins<TReq extends http.IncomingMessage, TRes extends http.ServerResponse>(options: Options<TReq, TRes>): Plugin<TReq, TRes>[];
+10
View File
@@ -0,0 +1,10 @@
import { debugProxyErrorsPlugin, errorResponsePlugin, loggerPlugin, proxyEventsPlugin, } from './plugins/default/index.js';
export function getPlugins(options) {
// don't load default errorResponsePlugin if user has specified their own
const maybeErrorResponsePlugin = options.on?.error ? [] : [errorResponsePlugin];
const defaultPlugins = options.ejectPlugins
? [] // no default plugins when ejecting
: [debugProxyErrorsPlugin, proxyEventsPlugin, loggerPlugin, ...maybeErrorResponsePlugin];
const userPlugins = options.plugins ?? [];
return [...defaultPlugins, ...userPlugins];
}
@@ -0,0 +1,12 @@
/**
* HPM_ERR_INVALID_MULTIPART prefixed error code will be used in
* [status-code.ts]({@link ../../status-code.ts}) to return status code 400.
*/
export declare const HPM_ERR_INVALID_MULTIPART = "HPM_ERR_INVALID_MULTIPART";
/**
* stringify FormData data
* @param contentType
* @param data
* @returns
*/
export declare function stringifyFormData(contentType: string, data: object): string;
@@ -0,0 +1,46 @@
import { HttpProxyMiddlewareError } from '../../errors.js';
const CR_OR_LF = /[\r\n]/;
/**
* HPM_ERR_INVALID_MULTIPART prefixed error code will be used in
* [status-code.ts]({@link ../../status-code.ts}) to return status code 400.
*/
export const HPM_ERR_INVALID_MULTIPART = 'HPM_ERR_INVALID_MULTIPART';
/**
* stringify FormData data
* @param contentType
* @param data
* @returns
*/
export function stringifyFormData(contentType, data) {
const boundary = getMultipartBoundary(contentType);
let str = '';
for (const [key, value] of Object.entries(data)) {
const normalizedKey = String(key);
const normalizedValue = String(value);
// Reject potentially dangerous sequences to prevent multipart header/body injection.
validateMultipartField(normalizedKey, normalizedValue, boundary);
str += `--${boundary}\r\nContent-Disposition: form-data; name="${escapeMultipartFieldName(normalizedKey)}"\r\n\r\n${normalizedValue}\r\n`;
}
return str;
}
function getMultipartBoundary(contentType) {
const boundaryMatch = /(?:^|;)\s*boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
// Keep backward-compatible behavior when boundary is omitted: fall back to legacy extraction.
const boundary = (boundaryMatch?.[1] ?? boundaryMatch?.[2] ?? contentType).trim();
if (!boundary || CR_OR_LF.test(boundary)) {
throw new HttpProxyMiddlewareError('[HPM] invalid multipart boundary detected.', `${HPM_ERR_INVALID_MULTIPART}_BOUNDARY`);
}
return boundary;
}
function validateMultipartField(fieldName, fieldValue, boundary) {
const boundaryDelimiter = `--${boundary}`;
if (CR_OR_LF.test(fieldName)) {
throw new HttpProxyMiddlewareError(`[HPM] invalid multipart field name "${fieldName}" detected.`, `${HPM_ERR_INVALID_MULTIPART}_FIELD_NAME`);
}
if (CR_OR_LF.test(fieldValue) || fieldValue.includes(boundaryDelimiter)) {
throw new HttpProxyMiddlewareError(`[HPM] invalid multipart field value for "${fieldName}" detected.`, `${HPM_ERR_INVALID_MULTIPART}_FIELD_VALUE`);
}
}
function escapeMultipartFieldName(fieldName) {
return fieldName.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
+22
View File
@@ -0,0 +1,22 @@
import type * as http from 'node:http';
export type BodyParserLikeRequest = http.IncomingMessage & {
body?: any;
};
/**
* Fix proxied body if bodyParser is involved.
*
* @example
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* on: {
* proxyReq: fixRequestBody,
* }
* });
* ```
*
* Alternative solution without using `fixRequestBody()`: put `http-proxy-middleware` before `bodyParser` in the middleware stack.
*
* @see {@link https://github.com/chimurai/http-proxy-middleware/issues/40 Github issue #40 - POST request body is not proxied}
*/
export declare function fixRequestBody<TReq extends BodyParserLikeRequest = BodyParserLikeRequest>(proxyReq: http.ClientRequest, req: TReq): void;
+78
View File
@@ -0,0 +1,78 @@
import * as querystring from 'node:querystring';
import * as zlib from 'node:zlib';
import { stringifyFormData } from './fix-request-body-utils/stringify-form-data.js';
/**
* Fix proxied body if bodyParser is involved.
*
* @example
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* on: {
* proxyReq: fixRequestBody,
* }
* });
* ```
*
* Alternative solution without using `fixRequestBody()`: put `http-proxy-middleware` before `bodyParser` in the middleware stack.
*
* @see {@link https://github.com/chimurai/http-proxy-middleware/issues/40 Github issue #40 - POST request body is not proxied}
*/
export function fixRequestBody(proxyReq, req) {
// skip fixRequestBody() when req.readableLength not 0 (bodyParser failure)
if (req.readableLength !== 0) {
return;
}
const requestBody = req.body;
if (!requestBody) {
return;
}
const contentType = proxyReq.getHeader('Content-Type');
if (!contentType) {
return;
}
const writeBody = (bodyData) => {
let proxyData = bodyData;
const contentEncoding = String(proxyReq.getHeader('Content-Encoding')).toLowerCase();
switch (contentEncoding) {
case 'br':
proxyData = zlib.brotliCompressSync(proxyData);
break;
case 'deflate':
proxyData = zlib.deflateSync(proxyData);
break;
case 'gzip':
proxyData = zlib.gzipSync(proxyData);
break;
case 'zstd':
proxyData = zlib.zstdCompressSync(proxyData);
break;
}
proxyReq.setHeader('Content-Length', Buffer.byteLength(proxyData));
proxyReq.write(proxyData);
};
try {
// Use if-elseif to prevent multiple writeBody/setHeader calls:
// Error: "Cannot set headers after they are sent to the client"
if (contentType.includes('application/json') || contentType.includes('+json')) {
writeBody(JSON.stringify(requestBody));
}
else if (contentType.includes('application/x-www-form-urlencoded')) {
writeBody(querystring.stringify(requestBody));
}
else if (contentType.includes('multipart/form-data')) {
writeBody(stringifyFormData(contentType, requestBody));
}
else if (contentType.includes('text/plain')) {
writeBody(requestBody);
}
}
catch (error) {
// proxyReq listeners run outside the middleware try/catch path; re-throwing here can bubble as
// an unhandled exception in consumers, so destroy() is used to fail closed through proxy error handling.
proxyReq.destroy(toError(error));
}
}
function toError(error) {
return error instanceof Error ? error : new Error(String(error));
}
+1
View File
@@ -0,0 +1 @@
export * from './public.js';
+1
View File
@@ -0,0 +1 @@
export * from './public.js';
+2
View File
@@ -0,0 +1,2 @@
export { responseInterceptor } from './response-interceptor.js';
export { fixRequestBody } from './fix-request-body.js';
+2
View File
@@ -0,0 +1,2 @@
export { responseInterceptor } from './response-interceptor.js';
export { fixRequestBody } from './fix-request-body.js';
@@ -0,0 +1,27 @@
import type * as http from 'node:http';
type Interceptor<TReq = http.IncomingMessage, TRes = http.ServerResponse> = (buffer: Buffer, proxyRes: http.IncomingMessage, req: TReq, res: TRes) => Promise<Buffer | string>;
/**
* Intercept responses from upstream.
* Automatically decompress (deflate, gzip, brotli, zstd).
* Give developer the opportunity to modify intercepted Buffer and http.ServerResponse
*
* NOTE: must set options.selfHandleResponse=true (prevent automatic call of res.end())
*
* @example
*
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* selfHandleResponse: true, // MUST set selfHandleResponse=true
* on: {
* proxyRes: responseInterceptor(async (buffer, proxyRes, req, res) => {
* // modify intercepted buffer and return modified buffer
* const modifiedBuffer = Buffer.from(buffer.toString().replace(/Example/g, 'Demo'), 'utf8');
* return modifiedBuffer;
* }),
* }
* });
* ```
*/
export declare function responseInterceptor<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(interceptor: Interceptor<TReq, TRes>): (proxyRes: http.IncomingMessage, req: TReq, res: TRes) => Promise<void>;
export {};
@@ -0,0 +1,145 @@
import * as zlib from 'node:zlib';
import { Debug } from '../debug.js';
import { getFunctionName } from '../utils/function.js';
const debug = Debug.extend('response-interceptor');
/**
* Intercept responses from upstream.
* Automatically decompress (deflate, gzip, brotli, zstd).
* Give developer the opportunity to modify intercepted Buffer and http.ServerResponse
*
* NOTE: must set options.selfHandleResponse=true (prevent automatic call of res.end())
*
* @example
*
* ```ts
* createProxyMiddleware({
* target: 'http://example.com',
* selfHandleResponse: true, // MUST set selfHandleResponse=true
* on: {
* proxyRes: responseInterceptor(async (buffer, proxyRes, req, res) => {
* // modify intercepted buffer and return modified buffer
* const modifiedBuffer = Buffer.from(buffer.toString().replace(/Example/g, 'Demo'), 'utf8');
* return modifiedBuffer;
* }),
* }
* });
* ```
*/
export function responseInterceptor(interceptor) {
return async function proxyResResponseInterceptor(proxyRes, req, res) {
debug('intercept proxy response');
const originalProxyRes = proxyRes;
const chunks = [];
let bufferLength = 0;
// Bodyless responses (HEAD, 1xx, 204, 304) must not be decompressed.
const contentEncoding = isBodylessResponse(proxyRes.statusCode, req.method)
? undefined
: proxyRes.headers['content-encoding'];
// decompress proxy response
const _proxyRes = decompress(proxyRes, contentEncoding);
// collect data chunks and concatenate once on end to avoid repeated full-buffer copies
_proxyRes.on('data', (chunk) => {
const chunkBuffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
chunks.push(chunkBuffer);
bufferLength += chunkBuffer.length; // precalculate Buffer length for slightly better performance on Buffer.concat()
});
_proxyRes.on('end', async () => {
const buffer = Buffer.concat(chunks, bufferLength);
chunks.length = 0; // clear chunks array
bufferLength = 0;
// copy original headers
copyHeaders(proxyRes, res);
// RFC 9110: HEAD and 1xx/204/304 responses do not include content.
// End the response after headers to avoid writing an invalid body.
if (isBodylessResponse(proxyRes.statusCode, req.method)) {
res.end();
return;
}
// call interceptor with intercepted response (buffer)
debug('call interceptor function: %s', getFunctionName(interceptor));
const interceptedBuffer = Buffer.from(await interceptor(buffer, originalProxyRes, req, res));
// set correct content-length (with double byte character support)
debug('set content-length: %s', Buffer.byteLength(interceptedBuffer));
// Buffered responses cannot preserve trailer framing.
// Remove trailer declaration (and transfer-encoding just in case) before setting content-length.
res.removeHeader('trailer');
res.removeHeader('transfer-encoding');
res.setHeader('content-length', Buffer.byteLength(interceptedBuffer));
debug('write intercepted response');
res.write(interceptedBuffer);
res.end();
});
_proxyRes.on('error', (error) => {
chunks.length = 0; // clear chunks array
bufferLength = 0;
res.end(`Error fetching proxied request: ${error.message}`);
});
};
}
function isBodylessResponse(statusCode, method) {
return (method?.toUpperCase() === 'HEAD' ||
(statusCode !== undefined &&
((statusCode >= 100 && statusCode < 200) || statusCode === 204 || statusCode === 304)));
}
/**
* Streaming decompression of proxy response
* source: https://github.com/apache/superset/blob/9773aba522e957ed9423045ca153219638a85d2f/superset-frontend/webpack.proxy-config.js#L116
*/
function decompress(proxyRes, contentEncoding) {
let _proxyRes = proxyRes;
let decompress;
switch (contentEncoding) {
case 'gzip':
decompress = zlib.createGunzip();
break;
case 'br':
decompress = zlib.createBrotliDecompress();
break;
case 'deflate':
decompress = zlib.createInflate();
break;
case 'zstd':
decompress = zlib.createZstdDecompress();
break;
default:
break;
}
if (decompress) {
debug(`decompress proxy response with 'content-encoding': %s`, contentEncoding);
_proxyRes.pipe(decompress);
_proxyRes = decompress;
}
return _proxyRes;
}
/**
* Copy original headers
* https://github.com/apache/superset/blob/9773aba522e957ed9423045ca153219638a85d2f/superset-frontend/webpack.proxy-config.js#L78
*/
function copyHeaders(originalResponse, response) {
debug('copy original response headers');
if (originalResponse.statusCode) {
response.statusCode = originalResponse.statusCode;
}
if (originalResponse.statusMessage) {
response.statusMessage = originalResponse.statusMessage;
}
if (response.setHeader) {
let keys = Object.keys(originalResponse.headers);
// ignore encoding/framing headers that are incompatible with buffered interception
keys = keys.filter((key) => !['content-encoding', 'transfer-encoding', 'trailer'].includes(key));
keys.forEach((key) => {
let value = originalResponse.headers[key];
if (key === 'set-cookie' && value) {
// remove cookie domain
value = Array.isArray(value) ? value : [value];
value = value.map((x) => x.replace(/Domain=[^;]+?/i, ''));
}
response.setHeader(key, value);
});
}
else {
if ('headers' in response) {
response.headers = originalResponse.headers;
}
}
}
+31
View File
@@ -0,0 +1,31 @@
import type * as http from 'node:http';
import type { Options, RequestHandler } from './types.js';
export declare class HttpProxyMiddleware<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> {
#private;
private wsInternalSubscribedServers;
private activeServers;
private proxyOptions;
private proxy;
private pathRewriter;
private logger;
constructor(options: Options<TReq, TRes>);
middleware: RequestHandler<TReq, TRes>;
private registerPlugins;
private catchUpgradeRequest;
private handleUpgrade;
/**
* Determine whether request should be proxied.
*/
private shouldProxy;
/**
* Apply option.router and option.pathRewrite
* Order matters:
* Router uses original path for routing;
* NOT the modified path, after it has been rewritten by pathRewrite
* @param {Object} req
* @return {Object} proxy options
*/
private prepareProxyRequest;
private applyRouter;
private applyPathRewrite;
}
+183
View File
@@ -0,0 +1,183 @@
import { createProxyServer } from 'httpxy';
import { verifyConfig } from './configuration.js';
import { Debug as debug } from './debug.js';
import { getPlugins } from './get-plugins.js';
import { getLogger } from './logger.js';
import { matchPathFilter } from './path-filter.js';
import { createPathRewriter } from './path-rewriter.js';
import { getTarget } from './router.js';
import { getFunctionName } from './utils/function.js';
import { normalizeIPv6LiteralTargets } from './utils/ipv6.js';
export class HttpProxyMiddleware {
wsInternalSubscribedServers = new WeakSet();
activeServers = new Set();
proxyOptions;
proxy;
pathRewriter;
logger;
constructor(options) {
verifyConfig(options);
this.proxyOptions = options;
this.logger = getLogger(options);
debug(`create proxy server`);
this.proxy = createProxyServer({});
this.registerPlugins(this.proxy, this.proxyOptions);
this.pathRewriter = createPathRewriter(this.proxyOptions.pathRewrite); // returns undefined when "pathRewrite" is not provided
// https://github.com/chimurai/http-proxy-middleware/issues/19
// expose function to upgrade externally
this.middleware.upgrade = (req, socket, head) => {
const server = this.#getServer(req);
if (server && !this.wsInternalSubscribedServers.has(server)) {
this.handleUpgrade(req, socket, head);
}
};
}
#getServer(req) {
return req.socket?.server;
}
// https://github.com/Microsoft/TypeScript/wiki/'this'-in-TypeScript#red-flags-for-this
middleware = (async (req, res, next) => {
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
let activeProxyOptions;
try {
// Preparation Phase: Apply router and path rewriter.
activeProxyOptions = await this.prepareProxyRequest(req, res);
// [Smoking Gun] httpxy is inconsistent with error handling:
// 1. If target is missing (here), it emits 'error' but returns a boolean (bypassing our catch/next).
// 2. If a network error occurs (in proxy.web), it rejects the promise but SKIPS emitting 'error'.
// We manually throw here to force Case 1 into the catch block so next(err) is called for Express.
if (!activeProxyOptions.target && !activeProxyOptions.forward) {
throw new Error('Must provide a proper URL as target');
}
}
catch (err) {
next?.(err);
return;
}
try {
// Proxying Phase: Handle the actual web request.
debug(`proxy request to target: %O`, activeProxyOptions.target);
await this.proxy.web(req, res, activeProxyOptions);
}
catch (err) {
// Manually emit 'error' event because httpxy's promise-based API does not emit it automatically.
// This is crucial for backward compatibility with HPM plugins (like error-response-plugin)
// and custom listeners registered via the 'on: { error: ... }' option.
this.proxy.emit('error', err, req, res, activeProxyOptions.target);
next?.(err);
}
}
else {
next?.();
}
/**
* Get the server object to subscribe to server events;
* 'upgrade' for websocket and 'close' for graceful shutdown
*/
const server = this.#getServer(req);
if (server && !this.activeServers.has(server)) {
debug('registering server close listener');
this.activeServers.add(server);
server.on('close', () => {
debug('server close signal received.');
this.activeServers.delete(server);
if (this.activeServers.size > 0) {
debug(`proxy server not closed: ${this.activeServers.size} server(s) still active`);
return;
}
else {
debug('closing proxy server');
this.proxy.close(() => debug('proxy server closed'));
}
});
}
if (this.proxyOptions.ws === true && server) {
// use initial request to access the server object to subscribe to http upgrade event
this.catchUpgradeRequest(server);
}
});
registerPlugins(proxy, options) {
const plugins = getPlugins(options);
plugins.forEach((plugin) => {
debug(`register plugin: "${getFunctionName(plugin)}"`);
plugin(proxy, options);
});
}
catchUpgradeRequest = (server) => {
if (!this.wsInternalSubscribedServers.has(server)) {
debug('subscribing to server upgrade event');
server.on('upgrade', this.handleUpgrade);
this.wsInternalSubscribedServers.add(server);
}
};
handleUpgrade = async (req, socket, head) => {
try {
if (this.shouldProxy(this.proxyOptions.pathFilter, req)) {
// No HTTP response object exists during WebSocket upgrades, so pass undefined.
const activeProxyOptions = await this.prepareProxyRequest(req, undefined);
await this.proxy.ws(req, socket, activeProxyOptions, head);
debug('server upgrade event received. Proxying WebSocket');
}
}
catch (err) {
// This error does not include the URL as the fourth argument as we won't
// have the URL if `this.prepareProxyRequest` throws an error.
this.proxy.emit('error', err, req, socket);
}
};
/**
* Determine whether request should be proxied.
*/
shouldProxy = (pathFilter, req) => {
try {
return matchPathFilter(pathFilter, req.url, req);
}
catch (err) {
debug('Error: matchPathFilter() called with request url: ', `"${req.url}"`);
this.logger.error(err);
return false;
}
};
/**
* Apply option.router and option.pathRewrite
* Order matters:
* Router uses original path for routing;
* NOT the modified path, after it has been rewritten by pathRewrite
* @param {Object} req
* @return {Object} proxy options
*/
prepareProxyRequest = async (req, res) => {
const newProxyOptions = Object.assign({}, this.proxyOptions);
// Apply in order:
// 1. option.router
// 2. option.pathRewrite
await this.applyRouter(req, res, newProxyOptions);
normalizeIPv6LiteralTargets(newProxyOptions);
await this.applyPathRewrite(req, res, this.pathRewriter, newProxyOptions);
return newProxyOptions;
};
// Modify option.target when router present.
applyRouter = async (req, res, options) => {
let newTarget;
if (options.router) {
newTarget = await getTarget(req, res, options);
if (newTarget) {
debug('router new target: "%s"', newTarget);
options.target = newTarget;
}
}
};
// rewrite path
applyPathRewrite = async (req, res, pathRewriter, options) => {
if (req.url && pathRewriter) {
const path = await pathRewriter(req.url, req, res, options);
if (typeof path === 'string') {
debug('pathRewrite new path: %s', path);
req.url = path;
}
else {
debug('pathRewrite: no rewritten path found: %s', req.url);
}
}
};
}
+10
View File
@@ -0,0 +1,10 @@
/**
* Hono-specific API entrypoint.
*
* This is intentionally published as a dedicated subpath (`http-proxy-middleware/hono`)
* so the root package types do not import `hono` / `@hono/node-server`.
*
* Keeping these exports out of the root entrypoint prevents non-Hono consumers from
* getting TypeScript module-resolution errors for optional Hono dependencies.
*/
export { createHonoProxyMiddleware } from './factory-hono.js';
+10
View File
@@ -0,0 +1,10 @@
/**
* Hono-specific API entrypoint.
*
* This is intentionally published as a dedicated subpath (`http-proxy-middleware/hono`)
* so the root package types do not import `hono` / `@hono/node-server`.
*
* Keeping these exports out of the root entrypoint prevents non-Hono consumers from
* getting TypeScript module-resolution errors for optional Hono dependencies.
*/
export { createHonoProxyMiddleware } from './factory-hono.js';
+4
View File
@@ -0,0 +1,4 @@
export * from './factory.js';
export * from './handlers/index.js';
export type { Plugin, Filter, Options, RequestHandler, OnProxyEvent } from './types.js';
export * from './plugins/index.js';
+3
View File
@@ -0,0 +1,3 @@
export * from './factory.js';
export * from './handlers/index.js';
export * from './plugins/index.js';
+2
View File
@@ -0,0 +1,2 @@
import type { Logger, Options } from './types.js';
export declare function getLogger(options: Options): Logger;
+21
View File
@@ -0,0 +1,21 @@
/**
* Compatibility matrix
*
| Library | log | info | warn | error | \<interpolation\> |
|----------|:------|:-------|:------|:--------|:------------------|
| console | ✅ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
| bunyan | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
| pino | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
| winston | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O)^1 |
| log4js | ❌ | ✅ | ✅ | ✅ | ✅ (%s %o %O) |
*
* ^1: https://github.com/winstonjs/winston#string-interpolation
*/
const noopLogger = {
info: () => { },
warn: () => { },
error: () => { },
};
export function getLogger(options) {
return options.logger || noopLogger;
}
+3
View File
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Filter } from './types.js';
export declare function matchPathFilter<TReq extends http.IncomingMessage = http.IncomingMessage>(pathFilter: Filter<TReq> | undefined, uri: string | undefined, req: http.IncomingMessage): boolean;
+76
View File
@@ -0,0 +1,76 @@
import isGlob from 'is-glob';
import micromatch from 'micromatch';
import { HttpProxyMiddlewareError } from './errors.js';
export function matchPathFilter(pathFilter = '/', uri, req) {
// single path
if (isStringPath(pathFilter)) {
return matchSingleStringPath(pathFilter, uri);
}
// single glob path
if (isGlobPath(pathFilter)) {
return matchSingleGlobPath(pathFilter, uri);
}
// multi path
if (Array.isArray(pathFilter)) {
if (pathFilter.every(isStringPath)) {
return matchMultiPath(pathFilter, uri);
}
if (pathFilter.every(isGlobPath)) {
return matchMultiGlobPath(pathFilter, uri);
}
throw new HttpProxyMiddlewareError('[HPM] Invalid pathFilter. Plain paths (e.g. "/api") can not be mixed with globs (e.g. "/api/**"). Expecting something like: ["/api", "/ajax"] or ["/api/**", "!**.html"].', 'HPM_INVALID_PATH_FILTER_ARRAY_CONFIG');
}
// custom matching
if (typeof pathFilter === 'function') {
const pathname = getUrlPathName(uri);
return Boolean(pathFilter(pathname, req));
}
throw new HttpProxyMiddlewareError('[HPM] Invalid pathFilter. Expecting something like: "/api" or ["/api", "/ajax"]', 'HPM_INVALID_PATH_FILTER_CONFIG');
}
/**
* @param {String} pathFilter '/api'
* @param {String} uri 'http://example.org/api/b/c/d.html'
* @return {Boolean}
*/
function matchSingleStringPath(pathFilter, uri) {
const pathname = getUrlPathName(uri);
return pathname?.indexOf(pathFilter) === 0;
}
function matchSingleGlobPath(pattern, uri) {
const pathname = getUrlPathName(uri);
const matches = micromatch([pathname], pattern);
return matches && matches.length > 0;
}
function matchMultiGlobPath(patternList, uri) {
return matchSingleGlobPath(patternList, uri);
}
/**
* @param {String} pathFilterList ['/api', '/ajax']
* @param {String} uri 'http://example.org/api/b/c/d.html'
* @return {Boolean}
*/
function matchMultiPath(pathFilterList, uri) {
let isMultiPath = false;
for (const context of pathFilterList) {
if (matchSingleStringPath(context, uri)) {
isMultiPath = true;
break;
}
}
return isMultiPath;
}
/**
* Parses URI and returns RFC 3986 path
*
* @param {String} uri from req.url
* @return {String} RFC 3986 path
*/
function getUrlPathName(uri) {
return uri && new URL(uri, 'http://0.0.0.0').pathname;
}
function isStringPath(pathFilter) {
return typeof pathFilter === 'string' && !isGlob(pathFilter);
}
function isGlobPath(pathFilter) {
return isGlob(pathFilter);
}
+6
View File
@@ -0,0 +1,6 @@
import type { IncomingMessage, ServerResponse } from 'node:http';
import type { PathRewriteConfig } from './types.js';
/**
* Create rewrite function, to cache parsed rewrite rules.
*/
export declare function createPathRewriter<TReq extends IncomingMessage = IncomingMessage, TRes extends ServerResponse = ServerResponse>(rewriteConfig: PathRewriteConfig<TReq, TRes> | undefined): ((path: string, req: TReq, res?: TRes | undefined, options?: import("./types.js").Options<TReq, TRes> | undefined) => string | undefined) | ((path: string, req: TReq, res?: TRes | undefined, options?: import("./types.js").Options<TReq, TRes> | undefined) => Promise<string | undefined>) | undefined;
+59
View File
@@ -0,0 +1,59 @@
import isPlainObject from 'is-plain-obj';
import { Debug } from './debug.js';
import { HttpProxyMiddlewareError } from './errors.js';
const debug = Debug.extend('path-rewriter');
/**
* Create rewrite function, to cache parsed rewrite rules.
*/
export function createPathRewriter(rewriteConfig) {
let rulesCache;
if (!isValidRewriteConfig(rewriteConfig)) {
return;
}
if (typeof rewriteConfig === 'function') {
const customRewriteFn = rewriteConfig;
return customRewriteFn;
}
else {
rulesCache = parsePathRewriteRules(rewriteConfig);
return rewritePath;
}
function rewritePath(path) {
let result = path;
for (const rule of rulesCache) {
if (rule.regex.test(path)) {
result = result.replace(rule.regex, rule.value);
debug('rewriting path from "%s" to "%s"', path, result);
break;
}
}
return result;
}
}
function isValidRewriteConfig(rewriteConfig) {
if (typeof rewriteConfig === 'function') {
return true;
}
else if (isPlainObject(rewriteConfig)) {
return Object.keys(rewriteConfig).length !== 0;
}
else if (rewriteConfig === undefined || rewriteConfig === null) {
return false;
}
else {
throw new HttpProxyMiddlewareError('[HPM] Invalid pathRewrite config. Expecting object with pathRewrite config or a rewrite function', 'HPM_INVALID_PATH_REWRITER_CONFIG');
}
}
function parsePathRewriteRules(rewriteConfig) {
const rules = [];
if (isPlainObject(rewriteConfig)) {
for (const [key, value] of Object.entries(rewriteConfig)) {
rules.push({
regex: new RegExp(key),
value: value,
});
debug('rewrite rule created: "%s" ~> "%s"', key, value);
}
}
return rules;
}
@@ -0,0 +1,6 @@
import type { Plugin } from '../../types.js';
/**
* Subscribe to {@link https://github.com/unjs/httpxy#events `httpxy` error events} to prevent server from crashing.
* Errors are logged with {@link https://www.npmjs.com/package/debug debug} library.
*/
export declare const debugProxyErrorsPlugin: Plugin;
@@ -0,0 +1,77 @@
import { styleText } from 'node:util';
import { Debug } from '../../debug.js';
import { definePlugin } from '../define-plugin.js';
const debug = Debug.extend('debug-proxy-errors-plugin');
const BODY_PARSER_ERROR_MESSAGE = `[HPM] Connection reset (ECONNRESET) detected with non-empty "req.body" [ERR_HPM.GH40].
This usually means that the POST request body (req.body) was already parsed before reaching the proxy.
When bodyParser runs first, it consumes the request stream, leaving the proxy unable to forward the body data to the target server.
How to fix this issue:
- Option 1: Place the proxy middleware before the bodyParser middleware.
- Option 2: Use 'fixRequestBody()' helper to fix this issue.
For more details, see: https://github.com/chimurai/http-proxy-middleware/issues/40\n`;
function hasParsedBody(req) {
return Boolean(req && req.method === 'POST' && 'body' in req && req.body);
}
/**
* Subscribe to {@link https://github.com/unjs/httpxy#events `httpxy` error events} to prevent server from crashing.
* Errors are logged with {@link https://www.npmjs.com/package/debug debug} library.
*/
export const debugProxyErrorsPlugin = definePlugin((proxyServer, options) => {
/**
* The old `http-proxy` doesn't handle any errors by default (https://github.com/http-party/node-http-proxy#listening-for-proxy-events)
* > We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.
* Subscribing to error event to prevent server from crashing
*/
proxyServer.on('error', (error, req, res, target) => {
debug(`httpxy error event: \n%O`, error);
// detect request body (when bodyParser used) and log an error message to help debugging
if (error.code === 'ECONNRESET' && hasParsedBody(req)) {
console.error(styleText('red', BODY_PARSER_ERROR_MESSAGE));
}
});
proxyServer.on('proxyReq', (proxyReq, req, socket) => {
socket.on('error', (error) => {
debug('Socket error in proxyReq event: \n%O', error);
});
});
/**
* Fix SSE close events
* @link https://github.com/chimurai/http-proxy-middleware/issues/678
* @link https://github.com/http-party/node-http-proxy/issues/1520#issue-877626125
*/
proxyServer.on('proxyRes', (proxyRes, req, res) => {
res.on('close', () => {
if (!res.writableEnded) {
debug('Destroying proxyRes in proxyRes close event');
proxyRes.destroy();
}
});
});
/**
* Fix crash when target server restarts
* https://github.com/chimurai/http-proxy-middleware/issues/476#issuecomment-746329030
* https://github.com/webpack/webpack-dev-server/issues/1642#issuecomment-790602225
*/
proxyServer.on('proxyReqWs', (proxyReq, req, socket) => {
socket.on('error', (error) => {
debug('Socket error in proxyReqWs event: \n%O', error);
});
});
proxyServer.on('open', (proxySocket) => {
proxySocket.on('error', (error) => {
debug('Socket error in open event: \n%O', error);
});
});
proxyServer.on('close', (req, socket, head) => {
socket.on('error', (error) => {
debug('Socket error in close event: \n%O', error);
});
});
// https://github.com/webpack/webpack-dev-server/issues/1642#issuecomment-1103136590
proxyServer.on('econnreset', (error, req, res, target) => {
debug(`httpxy econnreset event: \n%O`, error);
});
});
@@ -0,0 +1,2 @@
import type { Plugin } from '../../types.js';
export declare const errorResponsePlugin: Plugin;
@@ -0,0 +1,28 @@
import { getStatusCode } from '../../status-code.js';
import { sanitize } from '../../utils/sanitize.js';
import { definePlugin } from '../define-plugin.js';
function isResponseLike(obj) {
return obj && typeof obj.writeHead === 'function';
}
function isSocketLike(obj) {
return obj && typeof obj.write === 'function' && !('writeHead' in obj);
}
export const errorResponsePlugin = definePlugin((proxyServer, options) => {
proxyServer.on('error', (err, req, res, target) => {
// Re-throw error. Not recoverable since req & res are empty.
if (!req || !res) {
throw err; // "Error: Must provide a proper URL as target"
}
if (isResponseLike(res)) {
if (!res.headersSent) {
const statusCode = getStatusCode(err.code);
res.writeHead(statusCode);
}
const host = req.headers && req.headers.host;
res.end(`Error occurred while trying to proxy: ${sanitize(host)}${sanitize(req.url)}`);
}
else if (isSocketLike(res)) {
res.destroy();
}
});
});
+4
View File
@@ -0,0 +1,4 @@
export * from './debug-proxy-errors-plugin.js';
export * from './error-response-plugin.js';
export * from './logger-plugin.js';
export * from './proxy-events.js';
+4
View File
@@ -0,0 +1,4 @@
export * from './debug-proxy-errors-plugin.js';
export * from './error-response-plugin.js';
export * from './logger-plugin.js';
export * from './proxy-events.js';
@@ -0,0 +1,2 @@
import type { Plugin } from '../../types.js';
export declare const loggerPlugin: Plugin;
@@ -0,0 +1,57 @@
import { URL } from 'node:url';
import { getLogger } from '../../logger.js';
import { createUrl } from '../../utils/create-url.js';
import { getPort } from '../../utils/logger-plugin.js';
import { definePlugin } from '../define-plugin.js';
export const loggerPlugin = definePlugin((proxyServer, options) => {
const logger = getLogger(options);
proxyServer.on('error', (err, req, res, target) => {
const hostname = req?.headers?.host;
const requestHref = `${hostname}${req?.url}`;
const targetHref = `${target?.href}`; // target is undefined when websocket errors
const errorMessage = '[HPM] Error occurred while proxying request %s to %s [%s] (%s)';
const errReference = 'https://nodejs.org/api/errors.html#errors_common_system_errors'; // link to Node Common Systems Errors page
logger.error(errorMessage, requestHref, targetHref, err.code || err, errReference);
});
/**
* Log request and response
* @example
* ```shell
* [HPM] GET /users/ -> http://jsonplaceholder.typicode.com/users/ [304]
* ```
*/
proxyServer.on('proxyRes', (proxyRes, req, res) => {
// BrowserSync uses req.originalUrl
// Next.js doesn't have req.baseUrl
const originalUrl = req.originalUrl ?? `${req.baseUrl || ''}${req.url}`;
// construct targetUrl
let target;
try {
const port = getPort(proxyRes.req?.agent?.sockets);
const { protocol, host, path } = proxyRes.req;
target = createUrl({ protocol, host, port, path });
}
catch (err) {
// should not error. keeping fallback just in case
console.error('[HPM] Unexpected error while creating target URL', err);
// fallback to old implementation (less correct - without port)
target = new URL(options.target);
target.pathname = proxyRes.req.path;
}
const targetUrl = target.toString();
const exchange = `[HPM] ${req.method} ${originalUrl} -> ${targetUrl} [${proxyRes.statusCode}]`;
logger.info(exchange);
});
/**
* When client opens WebSocket connection
*/
proxyServer.on('open', (socket) => {
logger.info('[HPM] Client connected: %o', socket.address());
});
/**
* When client closes WebSocket connection
*/
proxyServer.on('close', (req, proxySocket, proxyHead) => {
logger.info('[HPM] Client disconnected: %o', proxySocket.address());
});
});
@@ -0,0 +1,22 @@
import type { Plugin } from '../../types.js';
/**
* Implements option.on object to subscribe to `httpxy` events.
*
* @example
* ```js
* createProxyMiddleware({
* on: {
* error: (error, req, res, target) => {},
* proxyReq: (proxyReq, req, res, options) => {},
* proxyReqWs: (proxyReq, req, socket, options) => {},
* proxyRes: (proxyRes, req, res) => {},
* open: (proxySocket) => {},
* close: (proxyRes, proxySocket, proxyHead) => {},
* start: (req, res, target) => {},
* end: (req, res, proxyRes) => {},
* econnreset: (error, req, res, target) => {},
* }
* });
* ```
*/
export declare const proxyEventsPlugin: Plugin;
@@ -0,0 +1,42 @@
import { Debug } from '../../debug.js';
import { getFunctionName } from '../../utils/function.js';
import { definePlugin } from '../define-plugin.js';
const debug = Debug.extend('proxy-events-plugin');
/**
* Implements option.on object to subscribe to `httpxy` events.
*
* @example
* ```js
* createProxyMiddleware({
* on: {
* error: (error, req, res, target) => {},
* proxyReq: (proxyReq, req, res, options) => {},
* proxyReqWs: (proxyReq, req, socket, options) => {},
* proxyRes: (proxyRes, req, res) => {},
* open: (proxySocket) => {},
* close: (proxyRes, proxySocket, proxyHead) => {},
* start: (req, res, target) => {},
* end: (req, res, proxyRes) => {},
* econnreset: (error, req, res, target) => {},
* }
* });
* ```
*/
export const proxyEventsPlugin = definePlugin((proxyServer, options) => {
if (!options.on) {
return;
}
// hoist variable here for better typing
let eventName;
// for in provide better typing than Object.entries()
for (eventName in options.on) {
if (Object.prototype.hasOwnProperty.call(options.on, eventName)) {
const handler = options.on[eventName];
if (!handler) {
continue;
}
debug(`register event handler: "${eventName}" -> "${getFunctionName(handler)}"`);
proxyServer.on(eventName, handler);
}
}
});
+25
View File
@@ -0,0 +1,25 @@
import type * as http from 'node:http';
import type { Plugin } from '../types.js';
/**
* Helper function to define a http-proxy-middleware plugin
* @see proxyServer {@link ProxyServer} - proxy server instance to which the plugin is being applied
* @see options {@link Options} - options object passed to `createProxyMiddleware`
*
* @example defining a plugin
* ```js
* export const myPlugin = definePlugin((proxyServer, options) => {
* // plugin implementation
* });
* ```
*
* @example using a plugin
* ```js
* createProxyMiddleware({
* target: 'http://example.com',
* plugins: [myPlugin],
* });
* ```
*
* @since 4.1.0
*/
export declare function definePlugin<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(fn: Plugin<TReq, TRes>): Plugin<TReq, TRes>;
+25
View File
@@ -0,0 +1,25 @@
/**
* Helper function to define a http-proxy-middleware plugin
* @see proxyServer {@link ProxyServer} - proxy server instance to which the plugin is being applied
* @see options {@link Options} - options object passed to `createProxyMiddleware`
*
* @example defining a plugin
* ```js
* export const myPlugin = definePlugin((proxyServer, options) => {
* // plugin implementation
* });
* ```
*
* @example using a plugin
* ```js
* createProxyMiddleware({
* target: 'http://example.com',
* plugins: [myPlugin],
* });
* ```
*
* @since 4.1.0
*/
export function definePlugin(fn) {
return fn;
}
+2
View File
@@ -0,0 +1,2 @@
export * from './define-plugin.js';
export * from './default/index.js';
+4
View File
@@ -0,0 +1,4 @@
// definePlugin()
export * from './define-plugin.js';
// default plugins
export * from './default/index.js';
+3
View File
@@ -0,0 +1,3 @@
import type * as http from 'node:http';
import type { Options } from './index.js';
export declare function getTarget<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(req: TReq, res: TRes | undefined, config: Options<TReq, TRes>): Promise<import("httpxy").ProxyTarget | undefined>;
+60
View File
@@ -0,0 +1,60 @@
import isPlainObject from 'is-plain-obj';
import { Debug } from './debug.js';
const debug = Debug.extend('router');
export async function getTarget(req, res, config) {
let newTarget;
const router = config.router;
if (isPlainObject(router)) {
newTarget = getTargetFromProxyTable(req, router);
}
else if (typeof router === 'function') {
newTarget = await router(req, res, config);
}
return newTarget;
}
function getTargetFromProxyTable(req, table) {
let result;
const host = req.headers.host ?? '';
const path = req.url ?? '';
for (const [key, value] of Object.entries(table)) {
if (containsPath(key)) {
if (isHostAndPathKey(key)) {
const [keyHost, keyPath] = splitHostAndPathKey(key);
// SECURITY: host+path keys must match exact host + path prefix.
if (host === keyHost && path.startsWith(keyPath)) {
// match 'localhost:3000/api'
result = value;
debug('match: "%s" -> "%s"', key, result);
break;
}
}
else {
if (path.startsWith(key)) {
// match '/api'
result = value;
debug('match: "%s" -> "%s"', key, result);
break;
}
}
}
else {
if (key === host) {
// match 'localhost:3000'
result = value;
debug('match: "%s" -> "%s"', host, result);
break;
}
}
}
return result;
}
function containsPath(v) {
return v.indexOf('/') > -1;
}
function isHostAndPathKey(v) {
return containsPath(v) && !v.startsWith('/');
}
function splitHostAndPathKey(v) {
const firstSlash = v.indexOf('/');
return [v.slice(0, firstSlash), v.slice(firstSlash)];
}
+1
View File
@@ -0,0 +1 @@
export declare function getStatusCode(errorCode: string): number;
+23
View File
@@ -0,0 +1,23 @@
export function getStatusCode(errorCode) {
let statusCode;
if (/HPE_INVALID/.test(errorCode)) {
statusCode = 502;
return statusCode;
}
if (/HPM_ERR_INVALID_MULTIPART_/.test(errorCode)) {
statusCode = 400;
return statusCode;
}
switch (errorCode) {
case 'ECONNRESET':
case 'ENOTFOUND':
case 'ECONNREFUSED':
case 'ETIMEDOUT':
statusCode = 504;
break;
default:
statusCode = 500;
break;
}
return statusCode;
}
+139
View File
@@ -0,0 +1,139 @@
/**
* Based on definition by DefinitelyTyped:
* https://github.com/DefinitelyTyped/DefinitelyTyped/blob/6f529c6c67a447190f86bfbf894d1061e41e07b7/types/http-proxy-middleware/index.d.ts
*/
import type * as http from 'node:http';
import type * as net from 'node:net';
import type { ProxyServer, ProxyServerOptions } from 'httpxy';
export type NextFunction<T = (err?: any) => void> = T;
export interface RequestHandler<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse, TNext = NextFunction> {
(req: TReq, res: TRes, next?: TNext): Promise<void>;
upgrade: (req: TReq, socket: net.Socket, head: Buffer) => void;
}
export type Filter<TReq extends http.IncomingMessage = http.IncomingMessage> = string | string[] | ((pathname: string, req: TReq) => boolean | string | RegExpMatchArray | null);
/**
* @see {@link https://github.com/chimurai/http-proxy-middleware/tree/master#defineplugin-helper `definePlugin()`} to define a http-proxy-middleware plugin.
*/
export interface Plugin<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> {
(proxyServer: ProxyServer<TReq, TRes>, options: Options<TReq, TRes>): void;
}
export interface OnProxyEvent<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> {
error?: (err: Error, req: TReq, res: TRes | net.Socket, target?: string | Partial<URL>) => void;
proxyReq?: (proxyReq: http.ClientRequest, req: TReq, res: TRes, options: ProxyServerOptions) => void;
proxyReqWs?: (proxyReq: http.ClientRequest, req: TReq, socket: net.Socket, options: ProxyServerOptions, head: any) => void;
proxyRes?: (proxyRes: TReq, req: TReq, res: TRes) => void | Promise<void>;
open?: (proxySocket: net.Socket) => void;
close?: (proxyRes: TReq, proxySocket: net.Socket, proxyHead: any) => void;
start?: (req: TReq, res: TRes, target: string | Partial<URL>) => void;
end?: (req: TReq, res: TRes, proxyRes: TReq) => void;
econnreset?: (err: Error, req: TReq, res: TRes, target: string | Partial<URL>) => void;
}
export type Logger = Pick<Console, 'info' | 'warn' | 'error'>;
export type PathRewriteConfig<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> = {
[regexp: string]: string;
} | ((path: string, req: TReq,
/** `res` is undefined in WebSocket upgrade flows. */
res?: TRes | undefined, options?: Options<TReq, TRes>) => string | undefined) | ((path: string, req: TReq,
/** `res` is undefined in WebSocket upgrade flows. */
res?: TRes | undefined, options?: Options<TReq, TRes>) => Promise<string | undefined>);
export interface Options<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse> extends ProxyServerOptions {
/**
* Narrow down requests to proxy or not.
* Filter on {@link http.IncomingMessage.url `pathname`} which is relative to the proxy's "mounting" point in the server.
* Or use the {@link http.IncomingMessage `req`} object for more complex filtering.
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathFilter.md
* @since v3.0.0
*/
pathFilter?: Filter<TReq>;
/**
* Modify request paths before requests are send to the target.
* @example
* ```js
* createProxyMiddleware({
* pathRewrite: {
* '^/api/old-path': '/api/new-path', // rewrite path
* }
* });
* ```
* @since v0.15.0
* @since v0.21.0 - support `async` function
* @since v4.1.0 - `res` and `options` parameters added to custom function
*
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/pathRewrite.md
*/
pathRewrite?: PathRewriteConfig<TReq, TRes>;
/**
* Access the internal `httpxy` server instance to customize behavior
*
* @example
* ```js
* createProxyMiddleware({
* plugins: [(proxyServer, options) => {
* proxyServer.on('error', (error, req, res) => {
* console.error(error);
* });
* }]
* });
* ```
* @link https://github.com/chimurai/http-proxy-middleware#plugins-array
* @since v3.0.0
*/
plugins?: Plugin<TReq, TRes>[];
/**
* Eject pre-configured plugins.
* NOTE: register your own error handlers to prevent server from crashing.
*
* @link https://github.com/chimurai/http-proxy-middleware#ejectplugins-boolean-default-false
* @since v3.0.0
*/
ejectPlugins?: boolean;
/**
* Listen to `httpxy` events
* @see {@link OnProxyEvent} for available events
* @example
* ```js
* createProxyMiddleware({
* on: {
* error: (error, req, res, target) => {
* console.error(error);
* }
* }
* });
* ```
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/proxy-events.md
* @since v3.0.0
*/
on?: OnProxyEvent<TReq, TRes>;
/**
* Dynamically set the {@link Options.target `options.target`}.
*
* @example
* ```js
* createProxyMiddleware({
* router: async (req, res, options) => {
* return 'http://127:0.0.1:3000';
* }
* });
* ```
*
* @since v0.16.0
* @since v4.1.0 - `res` and `options` parameters added to router function signature
*
* NOTE: `res` is undefined in WebSocket upgrade flows.
*
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/router.md
*/
router?: Record<string, ProxyServerOptions['target']> | ((req: TReq, res: TRes | undefined, options: Options<TReq, TRes>) => ProxyServerOptions['target']) | ((req: TReq, res: TRes | undefined, options: Options<TReq, TRes>) => Promise<ProxyServerOptions['target']>);
/**
* Log information from http-proxy-middleware
* @example
* ```js
* createProxyMiddleware({
* logger: console
* });
* ```
* @link https://github.com/chimurai/http-proxy-middleware/blob/master/recipes/logger.md
* @since v3.0.0
*/
logger?: Logger;
}
+1
View File
@@ -0,0 +1 @@
export {};
+9
View File
@@ -0,0 +1,9 @@
import { URL } from 'url';
type CreateUrlParams = {
protocol?: string;
host?: string;
port?: string;
path?: string;
};
export declare function createUrl({ protocol, host, port, path }: CreateUrlParams): URL;
export {};
+17
View File
@@ -0,0 +1,17 @@
import { URL } from 'url';
export function createUrl({ protocol, host, port, path }) {
// wrap IPv6 host in brackets
const ipv6Host = host?.includes(':') ? `[${host}]` : host;
// use fallback values to create a valid URL (protocol: 'undefined:', host: '[::]')
// nock v13 issue: protocol and host are undefined (https://github.com/chimurai/http-proxy-middleware/issues/1035)
// nock v14+ seems to return protocol and host correctly
const base = `${protocol || 'undefined:'}//${ipv6Host || '[::]'}`;
const url = new URL(base);
if (port) {
url.port = port;
}
if (path) {
url.pathname = path;
}
return url;
}
+1
View File
@@ -0,0 +1 @@
export declare function getFunctionName(fn: Function): string;
+4
View File
@@ -0,0 +1,4 @@
/* eslint-disable @typescript-eslint/no-unsafe-function-type */
export function getFunctionName(fn) {
return fn.name || '[anonymous Function]';
}
+20
View File
@@ -0,0 +1,20 @@
import type * as http from 'node:http';
import type { Options } from '../types.js';
/**
* Normalize bracketed IPv6 URL targets into unbracketed host options.
*
* RFC 2732 defines the URL syntax for literal IPv6 addresses as bracketed
* host references (for example `http://[::1]:8080/path` where host is
* `[::1]`).
*
* `httpxy` resolves bracketed hostnames (for example `[::1]`) via DNS,
* which can fail for IPv6 literals. This converts string/URL `target` and
* `forward` values into object form with `hostname: ::1` (brackets removed)
* so the address can be connected directly.
*
* Reference: RFC 2732, Section 2 (Literal IPv6 Address Format in URL's)
* https://www.ietf.org/rfc/rfc2732.txt
*
* The provided options object is mutated in place.
*/
export declare function normalizeIPv6LiteralTargets<TReq extends http.IncomingMessage = http.IncomingMessage, TRes extends http.ServerResponse = http.ServerResponse>(options: Options<TReq, TRes>): void;
+66
View File
@@ -0,0 +1,66 @@
import { Debug } from '../debug.js';
const debug = Debug.extend('ipv6');
/**
* Normalize bracketed IPv6 URL targets into unbracketed host options.
*
* RFC 2732 defines the URL syntax for literal IPv6 addresses as bracketed
* host references (for example `http://[::1]:8080/path` where host is
* `[::1]`).
*
* `httpxy` resolves bracketed hostnames (for example `[::1]`) via DNS,
* which can fail for IPv6 literals. This converts string/URL `target` and
* `forward` values into object form with `hostname: ::1` (brackets removed)
* so the address can be connected directly.
*
* Reference: RFC 2732, Section 2 (Literal IPv6 Address Format in URL's)
* https://www.ietf.org/rfc/rfc2732.txt
*
* The provided options object is mutated in place.
*/
export function normalizeIPv6LiteralTargets(options) {
options.target = normalizeIPv6ProxyTarget(options.target, 'target');
options.forward = normalizeIPv6ProxyTarget(options.forward, 'forward');
}
function normalizeIPv6ProxyTarget(target, optionName) {
const targetUrl = toTargetUrl(target);
if (targetUrl && isBracketedIPv6Hostname(targetUrl.hostname)) {
const normalizedHostname = normalizeIPv6DestinationHostname(stripBrackets(targetUrl.hostname));
debug('normalized IPv6 "%s" %s', optionName, target);
const auth = targetUrl.username || targetUrl.password
? `${targetUrl.username}:${targetUrl.password}`
: undefined;
return {
hostname: normalizedHostname,
auth,
pathname: targetUrl.pathname,
port: targetUrl.port,
protocol: targetUrl.protocol,
search: targetUrl.search,
};
}
return target;
}
function toTargetUrl(target) {
if (typeof target === 'string') {
return new URL(target);
}
if (target instanceof URL) {
return target;
}
return undefined;
}
function isBracketedIPv6Hostname(hostname) {
return hostname.startsWith('[') && hostname.endsWith(']');
}
function stripBrackets(hostname) {
return hostname.replace(/^\[|\]$/g, '');
}
function normalizeIPv6DestinationHostname(hostname) {
// The unspecified address (::) is not a routable destination for outbound client requests.
// Treat it as loopback so a target like http://[::]:port reaches local IPv6 listeners.
if (hostname === '::') {
debug('normalizing hostname unspecified IPv6 address (::) to loopback (::1)');
return '::1';
}
return hostname;
}
+7
View File
@@ -0,0 +1,7 @@
import type { Agent } from 'node:http';
export type Sockets = Pick<Agent, 'sockets'>;
/**
* Get port from target
* Using proxyRes.req.agent.sockets to determine the target port
*/
export declare function getPort(sockets?: Sockets): string | undefined;
+7
View File
@@ -0,0 +1,7 @@
/**
* Get port from target
* Using proxyRes.req.agent.sockets to determine the target port
*/
export function getPort(sockets) {
return Object.keys(sockets || {})?.[0]?.split(':')[1];
}
+1
View File
@@ -0,0 +1 @@
export declare function sanitize(input: string | undefined): string;
+3
View File
@@ -0,0 +1,3 @@
export function sanitize(input) {
return input?.replace(/[<>]/g, (i) => encodeURIComponent(i)) ?? '';
}