diff --git a/src/api.js b/src/api.js index 3fcd945..3c93e7a 100644 --- a/src/api.js +++ b/src/api.js @@ -12,6 +12,9 @@ import { InfluxDB, Point } from '@influxdata/influxdb-client' const debug = createDebug('app:api') +// const vtClient = new VTApi(process.env.VT_API_KEY) +const vtClient = process.env.VT_API_KEY ? new VTApi(process.env.VT_API_KEY) : null + const redisUrl = process.env.REDIS_URL || 'redis://redis:6379' console.log(`REDIS_URL: ${redisUrl}`) // NOTE: Increase connectTimeout for Render, consider using reconnectStrategy... @@ -210,12 +213,11 @@ export async function getVTStats(hash) { return cached } debug(`-- CACHE MISS: ${key}`) - const vt = new VTApi(process.env.VT_API_KEY) let stats, epoch, data if (hash.endsWith('==')) { debug('DEPRECATED - getAnalysis') // TODO: Deprecated try { - data = await vt.getAnalysis(hash) + data = await vtClient.getAnalysis(hash) } catch (error) { await cacheError(key, `Error ${error.status}`) } @@ -224,7 +226,7 @@ export async function getVTStats(hash) { epoch = data?.data?.attributes?.date } else { try { - data = await vt.getReport(hash) + data = await vtClient.getReport(hash) } catch (error) { await cacheError(key, `Error ${error.status}`) } diff --git a/src/virustotal.js b/src/virustotal.js index 290ea70..adf6e6b 100644 --- a/src/virustotal.js +++ b/src/virustotal.js @@ -5,13 +5,28 @@ const debug = createDebug('app:api') export class VTApi { /** - * GitHub Api - * @param {string} token + * VirusTotal API + * @param {string} tokens - CSV of API tokens */ - constructor(token) { + constructor(tokens) { + this.tokens = tokens + .split(',') + .map((t) => t.trim()) + .filter(Boolean) + // debug('this.tokens:', this.tokens) + console.log(`Loaded ${this.tokens.length} VT API Keys`) + + this.idx = 0 + this.client = axios.create({ baseURL: 'https://www.virustotal.com/api/v3/', - headers: { 'X-APIKey': token }, + }) + + this.client.interceptors.request.use((config) => { + config.headers['X-APIKey'] = this.tokens[this.idx] + this.idx = (this.idx + 1) % this.tokens.length + debug('Using token index %d/%d', this.idx, this.tokens.length) + return config }) }