feat: add HTTP and WebSocket development proxy
This commit is contained in:
@@ -0,0 +1,107 @@
|
||||
import type http from 'node:http';
|
||||
import httpProxy from 'http-proxy';
|
||||
import type {ResolvedIcebergConfig, ResolvedProxyOptions} from '../core/config.js';
|
||||
import {logger} from '../core/logger.js';
|
||||
|
||||
export interface ProxyMatch {
|
||||
route: string;
|
||||
options: ResolvedProxyOptions;
|
||||
}
|
||||
|
||||
export class DevProxy {
|
||||
private readonly proxy = httpProxy.createProxyServer({});
|
||||
|
||||
constructor(private readonly config: ResolvedIcebergConfig) {
|
||||
this.proxy.on('error', (error, request) => {
|
||||
logger.error(`Proxy error: ${request?.url ?? '<unknown>'}`);
|
||||
logger.error(`Target: ${this.targetFor(request)}`);
|
||||
logger.error(error.message);
|
||||
});
|
||||
}
|
||||
|
||||
match(pathname: string): ProxyMatch | undefined {
|
||||
return Object.entries(this.config.server.proxy)
|
||||
.filter(([route]) => matchesRoute(route, pathname))
|
||||
.sort(([left], [right]) => right.length - left.length)
|
||||
.map(([route, options]) => ({route, options}))[0];
|
||||
}
|
||||
|
||||
forwardHttp(request: http.IncomingMessage, response: http.ServerResponse, match: ProxyMatch) {
|
||||
const originalUrl = request.url ?? '/';
|
||||
try {
|
||||
request.url = forwardedUrl(originalUrl, match.options, match.route);
|
||||
} catch (error) {
|
||||
request.url = originalUrl;
|
||||
this.sendRewriteError(response, error);
|
||||
return;
|
||||
}
|
||||
this.proxy.web(request, response, {target: match.options.target, changeOrigin: match.options.changeOrigin, secure: match.options.secure}, error => {
|
||||
request.url = originalUrl;
|
||||
if (error) this.sendProxyError(response, error, match);
|
||||
});
|
||||
}
|
||||
|
||||
forwardWebSocket(request: http.IncomingMessage, socket: import('node:stream').Duplex, head: Buffer, match: ProxyMatch) {
|
||||
const originalUrl = request.url ?? '/';
|
||||
try {
|
||||
request.url = forwardedUrl(originalUrl, match.options, match.route);
|
||||
} catch (error) {
|
||||
request.url = originalUrl;
|
||||
socket.destroy();
|
||||
logger.error(`Proxy rewrite error: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return;
|
||||
}
|
||||
this.proxy.ws(request, socket, head, {target: match.options.target, changeOrigin: match.options.changeOrigin, secure: match.options.secure}, error => {
|
||||
request.url = originalUrl;
|
||||
if (error) {
|
||||
logger.error(`Proxy WebSocket error: ${request.url}`);
|
||||
logger.error(`Target: ${match.options.target}`);
|
||||
logger.error(error.message);
|
||||
socket.destroy();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
close() {
|
||||
this.proxy.close();
|
||||
}
|
||||
|
||||
private sendRewriteError(response: http.ServerResponse, error: unknown) {
|
||||
if (response.headersSent) return response.destroy();
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
logger.error(`Proxy rewrite error: ${message}`);
|
||||
response.statusCode = 500;
|
||||
response.setHeader('content-type', 'application/json; charset=utf-8');
|
||||
response.end(JSON.stringify({error: 'Proxy Rewrite Error', message: 'The configured proxy path rewrite failed.'}));
|
||||
}
|
||||
|
||||
private sendProxyError(response: http.ServerResponse, error: Error, match: ProxyMatch) {
|
||||
const networkError = error as NodeJS.ErrnoException;
|
||||
logger.error(`Proxy error: ${match.route}`);
|
||||
logger.error(`Target: ${match.options.target}`);
|
||||
logger.error(networkError.code ? `${networkError.code}: ${error.message}` : error.message);
|
||||
if (response.headersSent) return response.destroy();
|
||||
response.statusCode = networkError.code === 'ETIMEDOUT' ? 504 : 502;
|
||||
response.setHeader('content-type', 'application/json; charset=utf-8');
|
||||
response.end(JSON.stringify({error: response.statusCode === 504 ? 'Gateway Timeout' : 'Bad Gateway', message: 'The configured proxy target is unavailable.'}));
|
||||
}
|
||||
|
||||
private targetFor(request?: http.IncomingMessage) {
|
||||
const match = request?.url ? this.match(new URL(request.url, 'http://iceberg.local').pathname) : undefined;
|
||||
return match?.options.target ?? '<unknown>';
|
||||
}
|
||||
}
|
||||
|
||||
function matchesRoute(route: string, pathname: string) {
|
||||
return route === '/' ? pathname.startsWith('/') : pathname === route || pathname.startsWith(`${route}/`);
|
||||
}
|
||||
|
||||
function forwardedUrl(originalUrl: string, options: ResolvedProxyOptions, route: string) {
|
||||
const parsed = new URL(originalUrl, 'http://iceberg.local');
|
||||
let rewrittenPath = parsed.pathname;
|
||||
if (options.rewrite) {
|
||||
rewrittenPath = options.rewrite(parsed.pathname);
|
||||
if (typeof rewrittenPath !== 'string' || !rewrittenPath.startsWith('/') || rewrittenPath.includes('://') || rewrittenPath.includes('\r') || rewrittenPath.includes('\n')) throw new Error(`Proxy rewrite for '${route}' must return a safe absolute path beginning with '/'.`);
|
||||
}
|
||||
return `${rewrittenPath || '/'}${parsed.search}`;
|
||||
}
|
||||
Reference in New Issue
Block a user