forked from Shared/esg
381 lines
12 KiB
TypeScript
381 lines
12 KiB
TypeScript
import axios, {
|
|
AxiosError,
|
|
AxiosInstance,
|
|
AxiosRequestConfig,
|
|
CreateAxiosDefaults,
|
|
InternalAxiosRequestConfig,
|
|
} from 'axios';
|
|
import { Logger } from '@nestjs/common';
|
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
import type { Agent as HttpAgent } from 'http';
|
|
|
|
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
|
const { SocksProxyAgent } = require('socks-proxy-agent');
|
|
|
|
const outboundHttpLogger = new Logger('OutboundHTTP');
|
|
|
|
export interface OutboundRequestTrace {
|
|
method: string;
|
|
url: string;
|
|
requestHeaders: Record<string, string>;
|
|
requestBody?: unknown;
|
|
status?: number;
|
|
responseBody?: unknown;
|
|
error?: string;
|
|
durationMs?: number;
|
|
curl: string;
|
|
}
|
|
|
|
const outboundTraceStorage = new AsyncLocalStorage<OutboundRequestTrace[]>();
|
|
const traceInterceptorsInstalled = new WeakSet<object>();
|
|
|
|
let cachedSocksAgents: { httpAgent: HttpAgent; httpsAgent: HttpAgent } | undefined;
|
|
let outboundHttpDebugInstalled = false;
|
|
|
|
function getOutboundProxyUrl(): string | undefined {
|
|
const value = process.env.OUTBOUND_PROXY?.trim();
|
|
return value || undefined;
|
|
}
|
|
|
|
export function isOutboundHttpDebugEnabled(): boolean {
|
|
return process.env.OUTBOUND_HTTP_DEBUG === 'true';
|
|
}
|
|
|
|
function isSocksProxy(proxyUrl: string): boolean {
|
|
return /^socks/i.test(proxyUrl);
|
|
}
|
|
|
|
function getSocksAgents(proxyUrl: string): { httpAgent: HttpAgent; httpsAgent: HttpAgent } {
|
|
if (!cachedSocksAgents) {
|
|
const agent = new SocksProxyAgent(proxyUrl);
|
|
cachedSocksAgents = { httpAgent: agent, httpsAgent: agent };
|
|
}
|
|
return cachedSocksAgents;
|
|
}
|
|
|
|
function truncate(value: string, max = 800): string {
|
|
return value.length <= max ? value : `${value.slice(0, max)}...(truncated)`;
|
|
}
|
|
|
|
function truncateTrace(value: string, max = 12000): string {
|
|
return value.length <= max ? value : `${value.slice(0, max)}...(truncated)`;
|
|
}
|
|
|
|
function redactTraceValue(value: unknown): unknown {
|
|
if (typeof value === 'string') {
|
|
return truncateTrace(
|
|
value
|
|
.replace(/(<(?:\w+:)?(?:Password|ClientSecret|AccessToken|RefreshToken)[^>]*>)[^<]*(<\/(?:\w+:)?(?:Password|ClientSecret|AccessToken|RefreshToken)>)/gi, '$1REDACTED$2')
|
|
.replace(/((?:password|client_secret|access_token|refresh_token)=)[^&\s]*/gi, '$1<REDACTED>')
|
|
.replace(/((?:"|')?(?:password|client_secret|access_token|refresh_token|authorization)(?:"|')?\s*:\s*)("[^"]*"|'[^']*')/gi, '$1"<REDACTED>"'),
|
|
);
|
|
}
|
|
if (value === undefined || value === null || typeof value !== 'object') return value;
|
|
if (typeof URLSearchParams !== 'undefined' && value instanceof URLSearchParams) {
|
|
return truncateTrace(
|
|
value
|
|
.toString()
|
|
.replace(/((?:password|client_secret|access_token|refresh_token)=)[^&\s]*/gi, '$1<REDACTED>'),
|
|
);
|
|
}
|
|
if (Buffer.isBuffer(value)) return truncateTrace(value.toString('utf8'));
|
|
if (Array.isArray(value)) return value.map((item) => redactTraceValue(item));
|
|
|
|
return Object.fromEntries(
|
|
Object.entries(value as Record<string, unknown>).map(([key, item]) => [
|
|
key,
|
|
/password|secret|authorization|token|client_secret/i.test(key)
|
|
? '<REDACTED>'
|
|
: redactTraceValue(item),
|
|
]),
|
|
);
|
|
}
|
|
|
|
function toTraceString(value: unknown): string {
|
|
if (typeof value === 'string') return truncateTrace(value);
|
|
try {
|
|
return truncateTrace(JSON.stringify(value));
|
|
} catch {
|
|
return truncateTrace(String(value));
|
|
}
|
|
}
|
|
|
|
function shellQuote(value: string): string {
|
|
return `'${value.replace(/'/g, `'\\''`)}'`;
|
|
}
|
|
|
|
function toHeaderRecord(headers: unknown): Record<string, string> {
|
|
const source =
|
|
headers && typeof headers === 'object' && 'toJSON' in headers && typeof headers.toJSON === 'function'
|
|
? headers.toJSON()
|
|
: headers;
|
|
if (!source || typeof source !== 'object') return {};
|
|
|
|
return Object.fromEntries(
|
|
Object.entries(source as Record<string, unknown>)
|
|
.filter(([key]) => !/^(host|content-length|user-agent|accept-encoding)$/i.test(key))
|
|
.map(([key, value]) => [
|
|
key,
|
|
/authorization|password|secret|token/i.test(key) ? '<REDACTED>' : String(value),
|
|
]),
|
|
);
|
|
}
|
|
|
|
function buildCurl(
|
|
method: string,
|
|
url: string,
|
|
headers: Record<string, string>,
|
|
body: unknown,
|
|
): string {
|
|
const parts = [`curl --request ${method}`, shellQuote(url)];
|
|
for (const [key, value] of Object.entries(headers)) {
|
|
parts.push(`--header ${shellQuote(`${key}: ${value}`)}`);
|
|
}
|
|
if (body !== undefined) {
|
|
parts.push(`--data-raw ${shellQuote(toTraceString(body))}`);
|
|
}
|
|
return parts.join(' \\\n ');
|
|
}
|
|
|
|
export function runWithOutboundTrace<T>(
|
|
trace: OutboundRequestTrace[],
|
|
callback: () => Promise<T>,
|
|
): Promise<T> {
|
|
return outboundTraceStorage.run(trace, callback);
|
|
}
|
|
|
|
function sanitizeForLog(data: unknown): string {
|
|
if (data === undefined || data === null) {
|
|
return String(data);
|
|
}
|
|
|
|
if (typeof data === 'string') {
|
|
return truncate(
|
|
data
|
|
.replace(/(<(?:\w+:)?Password[^>]*>)[^<]*(<\/(?:\w+:)?Password>)/gi, '$1***$2')
|
|
.replace(/password=[^&]*/gi, 'password=***')
|
|
.replace(/("password"\s*:\s*")[^"]*"/gi, '$1***"'),
|
|
);
|
|
}
|
|
|
|
if (typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) {
|
|
return truncate(data.toString('utf8').replace(/password=[^&\r\n]*/gi, 'password=***'));
|
|
}
|
|
|
|
try {
|
|
const serialized = JSON.stringify(data, (key, value) => {
|
|
if (/password|secret|authorization|token|refresh/i.test(key)) {
|
|
return '***';
|
|
}
|
|
return value;
|
|
});
|
|
return truncate(serialized);
|
|
} catch {
|
|
return truncate(String(data));
|
|
}
|
|
}
|
|
|
|
function resolveRequestUrl(config: InternalAxiosRequestConfig): string {
|
|
const url = config.url ?? '';
|
|
if (/^https?:\/\//i.test(url)) {
|
|
return url;
|
|
}
|
|
|
|
const base = config.baseURL ?? '';
|
|
if (!base) {
|
|
return url;
|
|
}
|
|
|
|
return `${base.replace(/\/$/, '')}/${url.replace(/^\//, '')}`;
|
|
}
|
|
|
|
function resolveTraceUrl(config: InternalAxiosRequestConfig): string {
|
|
const url = resolveRequestUrl(config);
|
|
if (!config.params || typeof config.params !== 'object') return url;
|
|
try {
|
|
const parsed = new URL(url);
|
|
for (const [key, value] of Object.entries(config.params as Record<string, unknown>)) {
|
|
if (Array.isArray(value)) value.forEach((item) => parsed.searchParams.append(key, String(item)));
|
|
else if (value !== undefined && value !== null) parsed.searchParams.set(key, String(value));
|
|
}
|
|
return parsed.toString();
|
|
} catch {
|
|
return url;
|
|
}
|
|
}
|
|
|
|
function logOutboundRequest(config: InternalAxiosRequestConfig): void {
|
|
const method = (config.method ?? 'GET').toUpperCase();
|
|
const url = resolveRequestUrl(config);
|
|
outboundHttpLogger.log(`→ ${method} ${url}`);
|
|
|
|
if (config.params) {
|
|
outboundHttpLogger.log(` query=${sanitizeForLog(config.params)}`);
|
|
}
|
|
if (config.data !== undefined) {
|
|
outboundHttpLogger.log(` body=${sanitizeForLog(config.data)}`);
|
|
}
|
|
if (config.headers?.SOAPAction) {
|
|
outboundHttpLogger.log(` SOAPAction=${String(config.headers.SOAPAction)}`);
|
|
}
|
|
}
|
|
|
|
function logOutboundResponse(response: {
|
|
config: InternalAxiosRequestConfig;
|
|
status: number;
|
|
data: unknown;
|
|
}): void {
|
|
const start = (response.config as InternalAxiosRequestConfig & { _outboundStart?: number })
|
|
._outboundStart;
|
|
const durationMs = start ? Date.now() - start : undefined;
|
|
const method = (response.config.method ?? 'GET').toUpperCase();
|
|
const url = resolveRequestUrl(response.config);
|
|
|
|
outboundHttpLogger.log(
|
|
`← ${response.status} ${method} ${url}${durationMs !== undefined ? ` (${durationMs}ms)` : ''}`,
|
|
);
|
|
outboundHttpLogger.log(` response=${sanitizeForLog(response.data)}`);
|
|
}
|
|
|
|
function logOutboundError(error: AxiosError): void {
|
|
const config = error.config;
|
|
if (!config) {
|
|
outboundHttpLogger.error(`← FAILED | ${error.message}`);
|
|
return;
|
|
}
|
|
|
|
const start = (config as InternalAxiosRequestConfig & { _outboundStart?: number })._outboundStart;
|
|
const durationMs = start ? Date.now() - start : undefined;
|
|
const method = (config.method ?? 'GET').toUpperCase();
|
|
const url = resolveRequestUrl(config);
|
|
|
|
outboundHttpLogger.error(
|
|
`← FAILED ${method} ${url}${durationMs !== undefined ? ` (${durationMs}ms)` : ''} | status=${error.response?.status ?? 'N/A'} | ${error.message}`,
|
|
);
|
|
if (error.response?.data !== undefined) {
|
|
outboundHttpLogger.error(` response=${sanitizeForLog(error.response.data)}`);
|
|
}
|
|
}
|
|
|
|
export function installOutboundHttpDebugInterceptors(): void {
|
|
if (outboundHttpDebugInstalled) {
|
|
return;
|
|
}
|
|
|
|
outboundHttpDebugInstalled = true;
|
|
if (isOutboundHttpDebugEnabled()) {
|
|
outboundHttpLogger.log('Outbound HTTP debug logging enabled (OUTBOUND_HTTP_DEBUG=true)');
|
|
}
|
|
|
|
installOutboundHttpTraceInterceptors(axios);
|
|
}
|
|
|
|
function installOutboundHttpTraceInterceptors(instance: AxiosInstance): void {
|
|
if (traceInterceptorsInstalled.has(instance)) return;
|
|
traceInterceptorsInstalled.add(instance);
|
|
|
|
instance.interceptors.request.use((config) => {
|
|
(config as InternalAxiosRequestConfig & { _outboundStart?: number })._outboundStart =
|
|
Date.now();
|
|
if (isOutboundHttpDebugEnabled()) logOutboundRequest(config);
|
|
const trace = outboundTraceStorage.getStore();
|
|
if (trace) {
|
|
const requestHeaders = toHeaderRecord(config.headers);
|
|
const requestBody = redactTraceValue(config.data);
|
|
const item: OutboundRequestTrace = {
|
|
method: (config.method ?? 'GET').toUpperCase(),
|
|
url: resolveTraceUrl(config),
|
|
requestHeaders,
|
|
requestBody,
|
|
curl: buildCurl((config.method ?? 'GET').toUpperCase(), resolveTraceUrl(config), requestHeaders, requestBody),
|
|
};
|
|
(config as InternalAxiosRequestConfig & { _outboundTrace?: OutboundRequestTrace })._outboundTrace = item;
|
|
trace.push(item);
|
|
}
|
|
return config;
|
|
});
|
|
|
|
instance.interceptors.response.use(
|
|
(response) => {
|
|
if (isOutboundHttpDebugEnabled()) logOutboundResponse(response);
|
|
const trace = (response.config as InternalAxiosRequestConfig & { _outboundTrace?: OutboundRequestTrace })._outboundTrace;
|
|
if (trace) {
|
|
trace.status = response.status;
|
|
trace.responseBody = redactTraceValue(response.data);
|
|
const start = (response.config as InternalAxiosRequestConfig & { _outboundStart?: number })._outboundStart;
|
|
trace.durationMs = start ? Date.now() - start : undefined;
|
|
}
|
|
return response;
|
|
},
|
|
(error: AxiosError) => {
|
|
if (isOutboundHttpDebugEnabled()) logOutboundError(error);
|
|
const config = error.config as (InternalAxiosRequestConfig & { _outboundTrace?: OutboundRequestTrace; _outboundStart?: number }) | undefined;
|
|
const trace = config?._outboundTrace;
|
|
if (trace) {
|
|
trace.status = error.response?.status;
|
|
trace.responseBody = redactTraceValue(error.response?.data);
|
|
trace.error = error.message;
|
|
trace.durationMs = config?._outboundStart ? Date.now() - config._outboundStart : undefined;
|
|
}
|
|
return Promise.reject(error);
|
|
},
|
|
);
|
|
}
|
|
|
|
installOutboundHttpDebugInterceptors();
|
|
|
|
/**
|
|
* Axios defaults for outbound provider calls.
|
|
* Set OUTBOUND_PROXY to route traffic through an SSH tunnel (e.g. Termius SOCKS on 6565).
|
|
*/
|
|
export function getOutboundAxiosDefaults(): AxiosRequestConfig {
|
|
const proxyUrl = getOutboundProxyUrl();
|
|
if (!proxyUrl) {
|
|
return {};
|
|
}
|
|
|
|
if (isSocksProxy(proxyUrl)) {
|
|
const agents = getSocksAgents(proxyUrl);
|
|
return {
|
|
httpAgent: agents.httpAgent,
|
|
httpsAgent: agents.httpsAgent,
|
|
proxy: false,
|
|
};
|
|
}
|
|
|
|
const parsed = new URL(proxyUrl);
|
|
const defaultPort = parsed.protocol === 'https:' ? 443 : 80;
|
|
|
|
return {
|
|
proxy: {
|
|
protocol: parsed.protocol.replace(':', ''),
|
|
host: parsed.hostname,
|
|
port: Number(parsed.port || defaultPort),
|
|
},
|
|
};
|
|
}
|
|
|
|
export function mergeOutboundAxiosConfig(config: AxiosRequestConfig = {}): AxiosRequestConfig {
|
|
const outbound = getOutboundAxiosDefaults();
|
|
|
|
return {
|
|
...outbound,
|
|
...config,
|
|
httpAgent: config.httpAgent ?? outbound.httpAgent,
|
|
httpsAgent: config.httpsAgent ?? outbound.httpsAgent,
|
|
};
|
|
}
|
|
|
|
export function createOutboundAxiosInstance(config: CreateAxiosDefaults = {}): AxiosInstance {
|
|
const outbound = getOutboundAxiosDefaults();
|
|
|
|
const instance = axios.create({
|
|
...config,
|
|
httpAgent: config.httpAgent ?? outbound.httpAgent,
|
|
httpsAgent: config.httpsAgent ?? outbound.httpsAgent,
|
|
proxy: config.proxy ?? outbound.proxy,
|
|
});
|
|
installOutboundHttpTraceInterceptors(instance);
|
|
return instance;
|
|
}
|