UNPKG

ya-express-ntlm

Version:
96 lines 3.5 kB
import { blue, lBlue, reset, rs, yellow } from 'af-color'; import { debugNtlmLdapProxy } from '../debug'; import { NTLMProxyStub } from './NTLMProxyStub'; import { NTLMProxy } from './NTLMProxy'; const PROXY_LIVE_TIME_MILLIS = 60000; const cache = {}; const connectToProxy = async (rsn, id, messageType1) => { const strategy = rsn.options.getStrategy(rsn); if (strategy === 'NTLM_STUB') { const proxy = new NTLMProxyStub(id); const messageType2Buf = await proxy.negotiate(messageType1); return { proxy, messageType2Buf }; } let proxy = proxyCache.getProxy(id); const tryProxy = async (isNewProxy) => { if (proxy) { try { const messageType2Buf = await proxy.negotiate(messageType1); if (messageType2Buf) { return { proxy, messageType2Buf, isNewProxy }; } } catch (err) { proxy.close(); } } }; let result = await tryProxy(); if (result) { return result; } const tlsOptions = rsn.options.getTlsOptions(rsn); const controllers = rsn.options.getDomainControllers(rsn); for (let i = 0; i < controllers.length; i++) { const ldapServer = new URL(controllers[i]); const decodedPath = decodeURI(ldapServer.pathname || ''); debugNtlmLdapProxy(`Choose LDAP server ${blue}${ldapServer.host}${reset}${decodedPath ? ` using base DN "${decodedPath}"` : ''}`); proxy = new NTLMProxy({ id, host: ldapServer.hostname, port: ldapServer.port, tlsOptions, }); result = await tryProxy(true); if (result) { return result; } } throw new Error(`None of the Domain Controllers are available: ${JSON.stringify(controllers)}`); }; export class ProxyCache { clean() { Object.entries(cache).forEach(([id, cachedProxy]) => { if (cachedProxy.expire < Date.now()) { this.remove(id, true); } }); proxyCache.info('clean'); } remove(id, byTimeout) { const cachedProxy = cache[id]; if (cachedProxy) { const { proxy } = cachedProxy; proxy.close(); delete cache[id]; debugNtlmLdapProxy(`Deleted proxy from cache${byTimeout ? ' by timeout' : ''}: id: ${lBlue}${id}${rs} / ${proxy.coloredAddress}`); } } async addOrReplace(rsn, id, messageType1) { const { proxy, messageType2Buf, isNewProxy } = await connectToProxy(rsn, id, messageType1); debugNtlmLdapProxy(`${isNewProxy ? 'Inserted proxy to' : 'Used proxy from'} cache: id: ${yellow}${id}${rs} / ${proxy.coloredAddress}`); cache[id] = { proxy, expire: Date.now() + PROXY_LIVE_TIME_MILLIS }; return messageType2Buf.toString('base64'); } getProxy(id) { return cache[id]?.proxy; } changeId(oldId, newId) { const cachedProxy = cache[oldId]; if (cachedProxy) { cache[newId] = cachedProxy; cachedProxy.proxy.id = newId; } } info(from = '') { const { length } = Object.keys(cache); if (length) { debugNtlmLdapProxy(`[${from}] In cache ${Object.keys(cache).length} LDAP proxy connections`); } } } export const proxyCache = new ProxyCache(); setInterval(() => { proxyCache.clean(); }, 30000); //# sourceMappingURL=ProxyCache.js.map