forked from Shared/esg
moallem all endpoints working
This commit is contained in:
@@ -0,0 +1,222 @@
|
||||
import axios, {
|
||||
AxiosError,
|
||||
AxiosInstance,
|
||||
AxiosRequestConfig,
|
||||
CreateAxiosDefaults,
|
||||
InternalAxiosRequestConfig,
|
||||
} from 'axios';
|
||||
import { Logger } from '@nestjs/common';
|
||||
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');
|
||||
|
||||
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 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 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 (!isOutboundHttpDebugEnabled() || outboundHttpDebugInstalled) {
|
||||
return;
|
||||
}
|
||||
|
||||
outboundHttpDebugInstalled = true;
|
||||
outboundHttpLogger.log('Outbound HTTP debug logging enabled (OUTBOUND_HTTP_DEBUG=true)');
|
||||
|
||||
axios.interceptors.request.use((config) => {
|
||||
(config as InternalAxiosRequestConfig & { _outboundStart?: number })._outboundStart =
|
||||
Date.now();
|
||||
logOutboundRequest(config);
|
||||
return config;
|
||||
});
|
||||
|
||||
axios.interceptors.response.use(
|
||||
(response) => {
|
||||
logOutboundResponse(response);
|
||||
return response;
|
||||
},
|
||||
(error: AxiosError) => {
|
||||
logOutboundError(error);
|
||||
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();
|
||||
|
||||
return axios.create({
|
||||
...config,
|
||||
httpAgent: config.httpAgent ?? outbound.httpAgent,
|
||||
httpsAgent: config.httpsAgent ?? outbound.httpsAgent,
|
||||
proxy: config.proxy ?? outbound.proxy,
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user