import axios, { AxiosInstance } from 'axios'; import { ImmuneSignal } from './protocol'; import { HiveScrubber } from './scrubber'; import chalk from 'chalk'; /** * THE HIVE GATEWAY * Connects the local Rigstate instance to the Global Hive Mind (rigstate.com). */ export class HiveGateway { private client: AxiosInstance; private enabled: boolean; private lastSignalTime: number = 0; private readonly MIN_INTERVAL_MS = 5000; // Throttle: Max 1 signal per 5s constructor(baseUrl: string, token?: string) { this.enabled = !!token; if (!this.enabled) { console.log(chalk.dim('⚠️ Hive Gateway disabled (No Token provided). Running in localized mode.')); } this.client = axios.create({ baseURL: baseUrl, headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json', 'X-Rigstate-Client': 'CLI-0.2.0' }, timeout: 5000 }); } /** * Transmit an Immune Signal to the Hive. * Includes Pre-Flight Scrubbing and Throttling. */ public async transmit(signal: ImmuneSignal): Promise { if (!this.enabled) return false; // 1. THROTTLE CHECK const now = Date.now(); if (now - this.lastSignalTime < this.MIN_INTERVAL_MS) { console.warn(chalk.yellow('⏳ Hive Gateway Throttled. Signal dropped to preventing spam.')); return false; } // 2. SCRUBBER VERIFICATION (Double Check) // Even if Frank ran it, we run it again here at the edge. const scrubResult = HiveScrubber.scrub(signal.ruleContent); if (scrubResult.riskScore > 20) { console.error(chalk.red(`🛑 HIVE BLOCKED: Signal contains sensitive data (Risk: ${scrubResult.riskScore})`)); return false; } // 3. TRANSMISSION try { console.log(chalk.blue(`📡 Uplinking to Hive... [${signal.vector}]`)); // Using the scrubbed content just to be 100% safe const payload = { ...signal, ruleContent: scrubResult.sanitizedContent }; await this.client.post('/signal', payload); this.lastSignalTime = now; console.log(chalk.green('✅ Signal Received by Hive Core. Knowledge Shared.')); return true; } catch (error: any) { console.error(chalk.red(`❌ Hive Transmission Failed: ${error.message}`)); return false; } } }