T-3: M0.4 Purge hardcoded proxy credential + fix IB collection typo

This commit is contained in:
Studio 2026-11-27 10:51:13 -05:00
parent 39f6f1fdfe
commit 36489a1e91
9 changed files with 415 additions and 20 deletions

View file

@ -1,5 +1,5 @@
import type { IServiceContainer } from '@stock-bot/services';
import { IB_CONFIG } from '../shared/config';
import { IB_CONFIG, getIbProxyUrl } from '../shared/config';
import { fetchSession } from './fetch-session.action';
export async function fetchExchanges(services: IServiceContainer): Promise<unknown[] | null> {
@ -33,11 +33,13 @@ export async function fetchExchanges(services: IServiceContainer): Promise<unkno
headerCount: Object.keys(requestHeaders).length,
});
// Use fetch with proxy configuration
const proxy = getIbProxyUrl();
// Use fetch with optional proxy configuration
const response = await fetch(exchangeUrl, {
method: 'GET',
headers: requestHeaders,
proxy: IB_CONFIG.DEFAULT_PROXY,
...(proxy ? { proxy } : {}),
});
if (!response.ok) {

View file

@ -1,11 +1,12 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { requireServices } from '@stock-bot/services';
import { IB_CONFIG } from '../shared/config';
import { IB_CONFIG, getIbProxyUrl } from '../shared/config';
export async function fetchSession(
services: IServiceContainer
): Promise<Record<string, string> | undefined> {
try {
const proxy = getIbProxyUrl();
const { browser } = requireServices(services, 'browser');
await browser.initialize({
headless: true,
@ -16,9 +17,9 @@ export async function fetchSession(
const { page } = await browser.createPageWithProxy(
IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_PAGE,
IB_CONFIG.DEFAULT_PROXY
proxy
);
services.logger.info('✅ Page created with proxy');
services.logger.info('✅ Page created', { usingProxy: Boolean(proxy) });
const headersPromise = new Promise<Record<string, string> | undefined>(resolve => {
let resolved = false;

View file

@ -1,6 +1,6 @@
import type { IServiceContainer } from '@stock-bot/handlers';
import { requireServices } from '@stock-bot/services';
import { IB_CONFIG } from '../shared/config';
import { IB_CONFIG, getIbProxyUrl } from '../shared/config';
import { fetchSession } from './fetch-session.action';
export async function fetchSymbols(services: IServiceContainer): Promise<unknown[] | null> {
@ -38,11 +38,13 @@ export async function fetchSymbols(services: IServiceContainer): Promise<unknown
sortField: 'symbol',
};
const proxy = getIbProxyUrl();
// Get Summary
const summaryResponse = await fetch(IB_CONFIG.BASE_URL + IB_CONFIG.SUMMARY_API, {
method: 'POST',
headers: requestHeaders,
proxy: IB_CONFIG.DEFAULT_PROXY,
...(proxy ? { proxy } : {}),
body: JSON.stringify(requestBody),
});
@ -72,7 +74,7 @@ export async function fetchSymbols(services: IServiceContainer): Promise<unknown
const symbolsResponse = fetch(IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_API, {
method: 'POST',
headers: requestHeaders,
proxy: IB_CONFIG.DEFAULT_PROXY,
...(proxy ? { proxy } : {}),
body: JSON.stringify(requestBody),
});
symbolPromises.push(symbolsResponse);
@ -105,7 +107,7 @@ export async function fetchSymbols(services: IServiceContainer): Promise<unknown
services.logger.info('✅ IB symbols fetched successfully, saving to DB...', {
totalSymbols: symbols.length,
});
await requireServices(services, 'mongodb').mongodb.batchUpsert('ib_symbols', symbols, [
await requireServices(services, 'mongodb').mongodb.batchUpsert('ibSymbols', symbols, [
'symbol',
'exchangeId',
]);

View file

@ -0,0 +1,207 @@
import { afterEach, describe, expect, mock, test } from 'bun:test';
import type { IServiceContainer } from '@stock-bot/services';
import { fetchExchanges } from './actions/fetch-exchanges.action';
import { fetchSession } from './actions/fetch-session.action';
import { fetchSymbols } from './actions/fetch-symbols.action';
import { IB_CONFIG, getIbProxyUrl } from './shared/config';
const buildProxyUrl = (scheme = 'http', user = 'ib-user', pass = 'ib-secret', host = 'proxy.test:8080') =>
`${scheme}://${user}:${pass}@${host}`;
const originalEnvProxy = process.env['IB_PROXY_URL'];
const originalFetch = globalThis.fetch;
afterEach(() => {
if (originalEnvProxy === undefined) {
delete process.env['IB_PROXY_URL'];
} else {
process.env['IB_PROXY_URL'] = originalEnvProxy;
}
globalThis.fetch = originalFetch;
});
function createMockServices() {
const logs: Array<{ level: string; message: string; meta?: unknown }> = [];
const createPageWithProxy = mock(async (_url: string, _proxy?: string) => {
let networkHandler: ((event: { url: string; type: string; headers: Record<string, string> }) => void) | undefined;
const locator = () => ({
waitFor: mock(async () => {}),
click: mock(async () => {
networkHandler?.({
type: 'request',
url: `${IB_CONFIG.BASE_URL}${IB_CONFIG.SUMMARY_API}`,
headers: { cookie: 'ib-session=1' },
});
}),
first() {
return this;
},
});
return {
contextId: 'ctx-test',
page: {
onNetworkEvent: mock(
(handler: (event: { url: string; type: string; headers: Record<string, string> }) => void) => {
networkHandler = handler;
}
),
waitForLoadState: mock(async () => {}),
locator,
close: mock(async () => {}),
},
};
});
const batchUpsert = mock(async (_collection: string, _docs: unknown[], _keys: string[]) => {});
const services = {
logger: {
info: (message: string, meta?: unknown) => logs.push({ level: 'info', message, meta }),
warn: (message: string, meta?: unknown) => logs.push({ level: 'warn', message, meta }),
error: (message: string, meta?: unknown) => logs.push({ level: 'error', message, meta }),
debug: (message: string, meta?: unknown) => logs.push({ level: 'debug', message, meta }),
},
browser: {
initialize: mock(async () => {}),
createPageWithProxy,
},
mongodb: {
batchUpsert,
},
} as unknown as IServiceContainer;
return { services, logs, createPageWithProxy, batchUpsert };
}
describe('IB config and proxy handling', () => {
test('IB_CONFIG has no DEFAULT_PROXY and getIbProxyUrl validates env safely', () => {
expect('DEFAULT_PROXY' in IB_CONFIG).toBe(false);
expect(getIbProxyUrl({})).toBeUndefined();
expect(getIbProxyUrl({ IB_PROXY_URL: ' ' })).toBeUndefined();
const httpProxy = buildProxyUrl('http');
const httpsProxy = buildProxyUrl('https');
expect(getIbProxyUrl({ IB_PROXY_URL: ` ${httpProxy} ` })).toBe(httpProxy);
expect(getIbProxyUrl({ IB_PROXY_URL: httpsProxy })).toBe(httpsProxy);
const invalidSecret = buildProxyUrl('socks5', 'leaked-user', 'leaked-pass', 'proxy.test:1080');
for (const bad of ['not-a-url', invalidSecret, 'ftp://u:p@proxy.test:21']) {
let caught: Error | undefined;
try {
getIbProxyUrl({ IB_PROXY_URL: bad });
} catch (error) {
caught = error as Error;
}
expect(caught).toBeInstanceOf(Error);
expect(caught?.message).toBe('IB_PROXY_URL must be a valid http(s) URL');
expect(caught?.message).not.toContain('leaked-pass');
expect(caught?.message).not.toContain('leaked-user');
}
});
test('fetchSession forwards IB_PROXY_URL when set, omits when unset, and never logs the proxy URL', async () => {
const proxyUrl = buildProxyUrl('http', 'session-user', 'session-secret', 'proxy.test:8080');
process.env['IB_PROXY_URL'] = proxyUrl;
const withProxy = createMockServices();
const headersWithProxy = await fetchSession(withProxy.services);
expect(headersWithProxy).toEqual({ cookie: 'ib-session=1' });
expect(withProxy.createPageWithProxy).toHaveBeenCalledWith(
IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_PAGE,
proxyUrl
);
expect(withProxy.logs).toContainEqual({
level: 'info',
message: '✅ Page created',
meta: { usingProxy: true },
});
expect(JSON.stringify(withProxy.logs)).not.toContain('session-secret');
expect(JSON.stringify(withProxy.logs)).not.toContain('session-user');
delete process.env['IB_PROXY_URL'];
const withoutProxy = createMockServices();
const headersWithoutProxy = await fetchSession(withoutProxy.services);
expect(headersWithoutProxy).toEqual({ cookie: 'ib-session=1' });
expect(withoutProxy.createPageWithProxy).toHaveBeenCalledWith(
IB_CONFIG.BASE_URL + IB_CONFIG.PRODUCTS_PAGE,
undefined
);
expect(withoutProxy.logs).toContainEqual({
level: 'info',
message: '✅ Page created',
meta: { usingProxy: false },
});
});
test('fetchExchanges forwards proxy when set and omits proxy option when unset', async () => {
const proxyUrl = buildProxyUrl('https', 'ex-user', 'ex-secret', 'proxy.test:8443');
const capturedOptions: Array<Record<string, unknown>> = [];
globalThis.fetch = mock(async (_url: string | URL | Request, init?: RequestInit) => {
capturedOptions.push((init ?? {}) as Record<string, unknown>);
return new Response(JSON.stringify({ exchanges: [{ id: 'NASDAQ', country_code: 'US' }] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}) as unknown as typeof fetch;
process.env['IB_PROXY_URL'] = proxyUrl;
const withProxy = createMockServices();
const res1 = await fetchExchanges(withProxy.services);
expect(res1).toEqual([{ id: 'NASDAQ', country_code: 'US' }]);
expect(capturedOptions[0]?.['proxy']).toBe(proxyUrl);
expect(JSON.stringify(withProxy.logs)).not.toContain('ex-secret');
delete process.env['IB_PROXY_URL'];
const withoutProxy = createMockServices();
const res2 = await fetchExchanges(withoutProxy.services);
expect(res2).toEqual([{ id: 'NASDAQ', country_code: 'US' }]);
expect('proxy' in (capturedOptions[1] ?? {})).toBe(false);
});
test('fetchSymbols forwards/omits proxy and writes to ibSymbols collection', async () => {
const proxyUrl = buildProxyUrl('http', 'sym-user', 'sym-secret', 'proxy.test:8080');
const capturedOptions: Array<Record<string, unknown>> = [];
const sampleSymbols = [{ symbol: 'AAPL', exchangeId: 'NASDAQ' }];
globalThis.fetch = mock(async (url: string | URL | Request, init?: RequestInit) => {
capturedOptions.push((init ?? {}) as Record<string, unknown>);
const urlStr = String(url);
if (urlStr.includes(IB_CONFIG.SUMMARY_API)) {
return new Response(JSON.stringify([{ totalCount: 1 }]), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}
return new Response(JSON.stringify({ products: sampleSymbols }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
}) as unknown as typeof fetch;
process.env['IB_PROXY_URL'] = proxyUrl;
const withProxy = createMockServices();
const symbols1 = await fetchSymbols(withProxy.services);
expect(symbols1).toEqual(sampleSymbols);
expect(capturedOptions[0]?.['proxy']).toBe(proxyUrl);
expect(capturedOptions[1]?.['proxy']).toBe(proxyUrl);
expect(withProxy.batchUpsert).toHaveBeenCalledWith('ibSymbols', sampleSymbols, [
'symbol',
'exchangeId',
]);
expect(JSON.stringify(withProxy.logs)).not.toContain('sym-secret');
capturedOptions.length = 0;
delete process.env['IB_PROXY_URL'];
const withoutProxy = createMockServices();
const symbols2 = await fetchSymbols(withoutProxy.services);
expect(symbols2).toEqual(sampleSymbols);
expect('proxy' in (capturedOptions[0] ?? {})).toBe(false);
expect('proxy' in (capturedOptions[1] ?? {})).toBe(false);
expect(withoutProxy.batchUpsert).toHaveBeenCalledWith('ibSymbols', sampleSymbols, [
'symbol',
'exchangeId',
]);
});
});

View file

@ -16,8 +16,29 @@ export const IB_CONFIG = {
HEADERS_TIMEOUT: 30000,
// API configuration
DEFAULT_PROXY: 'http://doimvbnb-US-rotate:w5fpiwrb9895@p.webshare.io:80',
PAGE_SIZE: 500,
PRODUCT_COUNTRIES: ['CA', 'US'],
PRODUCT_TYPES: ['STK'],
};
const INVALID_IB_PROXY_URL_ERROR = 'IB_PROXY_URL must be a valid http(s) URL';
export function getIbProxyUrl(env: NodeJS.ProcessEnv = process.env): string | undefined {
const raw = env['IB_PROXY_URL']?.trim();
if (!raw) {
return undefined;
}
let parsed: URL;
try {
parsed = new URL(raw);
} catch {
throw new Error(INVALID_IB_PROXY_URL_ERROR);
}
if ((parsed.protocol !== 'http:' && parsed.protocol !== 'https:') || !parsed.hostname) {
throw new Error(INVALID_IB_PROXY_URL_ERROR);
}
return raw;
}