File size: 13,739 Bytes
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
4942106
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a81b95
 
 
 
 
 
 
 
 
 
 
 
4942106
 
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4942106
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4942106
 
 
 
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4942106
5a81b95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4942106
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
/**
 * useLiveData - Universal hook for live data fetching in widgets
 * 
 * Features:
 * - Automatic polling with configurable intervals
 * - WebSocket subscriptions for real-time updates
 * - Source recommendations with user-triggerable fetch
 * - Caching and error handling
 * - Connection state tracking
 */

import { useState, useEffect, useCallback, useRef } from 'react';

// Dynamic API base - use environment variable or HuggingFace Spaces URL in production
const getApiBase = () => {
    // Check for Vite environment variable first
    if (typeof import.meta !== 'undefined' && import.meta.env?.VITE_API_URL) {
        return `${import.meta.env.VITE_API_URL}/api`;
    }
    // Production default: HuggingFace Spaces backend
    if (typeof window !== 'undefined' && window.location.hostname !== 'localhost') {
        return 'https://kraft102-widgettdc-api.hf.space/api';
    }
    // Development default
    return 'http://localhost:3001/api';
};

const getWsBase = () => {
    // Check for Vite environment variable first
    if (typeof import.meta !== 'undefined' && import.meta.env?.VITE_WS_URL) {
        return import.meta.env.VITE_WS_URL;
    }
    // Production default: HuggingFace Spaces backend
    if (typeof window !== 'undefined' && window.location.hostname !== 'localhost') {
        return 'wss://kraft102-widgettdc-api.hf.space';
    }
    // Development default
    return 'ws://localhost:3001';
};

const API_BASE = getApiBase();
const WS_BASE = getWsBase();

// Source types that widgets can request
export type DataSourceType =
    | 'hyperlog'          // Real-time events
    | 'alerts'            // System alerts
    | 'autonomousStats'   // Autonomous agent stats
    | 'sourcesHealth'     // Data source health
    | 'decisionHistory'   // AI decisions log
    | 'knowledge'         // Knowledge graph data
    | 'systemHealth'      // System services health
    | 'metrics'           // Platform metrics
    | 'osint'             // External OSINT feeds (future)
    | 'threatIntel'       // Threat intelligence (future)
    | 'email';            // Email inbox data

// Recommended external sources that can be fetched on demand
export interface RecommendedSource {
    id: string;
    name: string;
    description: string;
    category: 'osint' | 'threatIntel' | 'social' | 'internal';
    endpoint?: string;
    requiresApproval: boolean;
    isAvailable: boolean;
}

interface UseLiveDataOptions<T> {
    sourceType: DataSourceType;
    pollInterval?: number;           // ms, 0 = no polling
    wsEvents?: string[];             // WebSocket event types to subscribe
    transform?: (data: any) => T;    // Transform raw API data
    enabled?: boolean;               // Enable/disable fetching
}

interface UseLiveDataResult<T> {
    data: T | null;
    isLoading: boolean;
    error: string | null;
    lastUpdated: Date | null;
    refresh: () => Promise<void>;
    connectionStatus: 'connected' | 'connecting' | 'disconnected';
    recommendedSources: RecommendedSource[];
    fetchRecommendedSource: (sourceId: string) => Promise<void>;
}

// API endpoint mapping
const sourceEndpoints: Record<DataSourceType, string> = {
    hyperlog: '/hyper/events',
    alerts: '/mcp/autonomous/alerts',
    autonomousStats: '/mcp/autonomous/stats',
    sourcesHealth: '/mcp/autonomous/sources',
    decisionHistory: '/mcp/autonomous/decisions',
    knowledge: '/knowledge/compile',
    systemHealth: '/health',
    metrics: '/sys/metrics',
    osint: '/acquisition/osint',
    threatIntel: '/acquisition/threats',
    email: '/email/inbox',
};

// Recommended sources per data type
const recommendedSourcesMap: Record<DataSourceType, RecommendedSource[]> = {
    hyperlog: [
        { id: 'syslog', name: 'System Logs', description: 'Local system event logs', category: 'internal', requiresApproval: false, isAvailable: true },
        { id: 'auditlog', name: 'Audit Trail', description: 'Security audit events', category: 'internal', requiresApproval: false, isAvailable: true },
    ],
    alerts: [
        { id: 'selfehealing', name: 'Self-Healing Alerts', description: 'Autonomous recovery events', category: 'internal', requiresApproval: false, isAvailable: true },
        { id: 'pattern-alerts', name: 'Pattern Detection', description: 'AI-detected anomalies', category: 'internal', requiresApproval: false, isAvailable: true },
    ],
    autonomousStats: [],
    sourcesHealth: [],
    decisionHistory: [],
    knowledge: [
        { id: 'neo4j-graph', name: 'Knowledge Graph', description: 'Neo4j entity relationships', category: 'internal', requiresApproval: false, isAvailable: true },
        { id: 'embeddings', name: 'Semantic Embeddings', description: 'Vector similarity search', category: 'internal', requiresApproval: false, isAvailable: true },
    ],
    systemHealth: [],
    metrics: [
        { id: 'prometheus', name: 'Prometheus Metrics', description: 'Time-series system metrics', category: 'internal', requiresApproval: false, isAvailable: false },
    ],
    osint: [
        { id: 'shodan', name: 'Shodan', description: 'Internet-connected device search', category: 'osint', requiresApproval: true, isAvailable: false },
        { id: 'virustotal', name: 'VirusTotal', description: 'File and URL analysis', category: 'threatIntel', requiresApproval: true, isAvailable: false },
        { id: 'abuseipdb', name: 'AbuseIPDB', description: 'IP reputation database', category: 'threatIntel', requiresApproval: true, isAvailable: false },
    ],
    threatIntel: [
        { id: 'otx', name: 'AlienVault OTX', description: 'Open Threat Exchange IOCs', category: 'threatIntel', requiresApproval: true, isAvailable: false },
        { id: 'mitre', name: 'MITRE ATT&CK', description: 'Adversary tactics & techniques', category: 'threatIntel', requiresApproval: false, isAvailable: true },
    ],
    email: [
        { id: 'outlook', name: 'Outlook/Office365', description: 'Microsoft email via IMAP', category: 'internal', requiresApproval: false, isAvailable: true },
        { id: 'gmail', name: 'Gmail', description: 'Google email via IMAP', category: 'internal', requiresApproval: false, isAvailable: true },
    ],
};

export function useLiveData<T = any>(options: UseLiveDataOptions<T>): UseLiveDataResult<T> {
    const {
        sourceType,
        pollInterval = 30000,
        wsEvents = [],
        transform,
        enabled = true,
    } = options;

    const [data, setData] = useState<T | null>(null);
    const [isLoading, setIsLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [lastUpdated, setLastUpdated] = useState<Date | null>(null);
    const [connectionStatus, setConnectionStatus] = useState<'connected' | 'connecting' | 'disconnected'>('connecting');
    const [recommendedSources, setRecommendedSources] = useState<RecommendedSource[]>(
        recommendedSourcesMap[sourceType] || []
    );

    const wsRef = useRef<WebSocket | null>(null);
    const pollRef = useRef<NodeJS.Timeout | null>(null);

    // Fetch data from API
    const fetchData = useCallback(async () => {
        if (!enabled) return;

        const endpoint = sourceEndpoints[sourceType];
        if (!endpoint) {
            setError(`Unknown source type: ${sourceType}`);
            setIsLoading(false);
            return;
        }

        try {
            const response = await fetch(`${API_BASE}${endpoint}`);

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const rawData = await response.json();
            const transformedData = transform ? transform(rawData) : rawData;

            setData(transformedData);
            setError(null);
            setLastUpdated(new Date());
            setConnectionStatus('connected');
        } catch (err: any) {
            console.error(`[useLiveData] ${sourceType} fetch error:`, err);
            setError(err.message || 'Failed to fetch data');
            setConnectionStatus('disconnected');
        } finally {
            setIsLoading(false);
        }
    }, [enabled, sourceType, transform]);

    // Refresh function
    const refresh = useCallback(async () => {
        setIsLoading(true);
        await fetchData();
    }, [fetchData]);

    // Fetch a recommended source (user-triggered)
    const fetchRecommendedSource = useCallback(async (sourceId: string) => {
        const source = recommendedSources.find(s => s.id === sourceId);
        if (!source) {
            console.warn(`Unknown source: ${sourceId}`);
            return;
        }

        try {
            // Call backend to enable/fetch this source
            const response = await fetch(`${API_BASE}/acquisition/enable-source`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    sourceId,
                    sourceName: source.name,
                    category: source.category,
                    requiresApproval: source.requiresApproval,
                }),
            });

            if (response.ok) {
                // Update source availability
                setRecommendedSources(prev =>
                    prev.map(s =>
                        s.id === sourceId ? { ...s, isAvailable: true } : s
                    )
                );
                // Refresh main data
                await refresh();
            } else {
                console.error(`Failed to enable source ${sourceId}`);
            }
        } catch (err) {
            console.error(`Error enabling source ${sourceId}:`, err);
        }
    }, [recommendedSources, refresh]);

    // Setup polling
    useEffect(() => {
        if (!enabled) return;

        fetchData();

        if (pollInterval > 0) {
            pollRef.current = setInterval(fetchData, pollInterval);
        }

        return () => {
            if (pollRef.current) {
                clearInterval(pollRef.current);
            }
        };
    }, [enabled, pollInterval, fetchData]);

    // Setup WebSocket subscription
    useEffect(() => {
        if (!enabled || wsEvents.length === 0) return;

        const wsUrl = `${WS_BASE}/mcp/ws`;

        try {
            wsRef.current = new WebSocket(wsUrl);

            wsRef.current.onopen = () => {
                setConnectionStatus('connected');
                // Subscribe to events
                wsRef.current?.send(JSON.stringify({
                    type: 'subscribe',
                    events: wsEvents,
                }));
            };

            wsRef.current.onmessage = (event) => {
                try {
                    const message = JSON.parse(event.data);
                    if (wsEvents.includes(message.type)) {
                        // Real-time update - refresh data
                        fetchData();
                    }
                } catch (err) {
                    console.warn('WebSocket message parse error:', err);
                }
            };

            wsRef.current.onclose = () => {
                setConnectionStatus('disconnected');
            };

            wsRef.current.onerror = () => {
                setConnectionStatus('disconnected');
            };
        } catch (err) {
            console.error('WebSocket connection error:', err);
            setConnectionStatus('disconnected');
        }

        return () => {
            if (wsRef.current) {
                wsRef.current.close();
            }
        };
    }, [enabled, wsEvents, fetchData]);

    return {
        data,
        isLoading,
        error,
        lastUpdated,
        refresh,
        connectionStatus,
        recommendedSources,
        fetchRecommendedSource,
    };
}

// Specialized hooks for common data types
export function useAlerts(pollInterval = 15000) {
    return useLiveData<any[]>({
        sourceType: 'alerts',
        pollInterval,
        wsEvents: ['system.alert', 'security.alert', 'failure:recorded'],
        transform: (data) => data.alerts || data.events || [],
    });
}

export function useHyperEvents(pollInterval = 10000) {
    return useLiveData({
        sourceType: 'hyperlog',
        pollInterval,
        wsEvents: ['agent.log', 'mcp.tool.executed'],
        transform: (data) => ({
            events: data.events || [],
            metrics: data.metrics || {},
        }),
    });
}

export function useSystemMetrics(pollInterval = 30000) {
    return useLiveData({
        sourceType: 'metrics',
        pollInterval,
        transform: (data) => ({
            cpu: data.cpu || 0,
            memory: data.memory || 0,
            uptime: data.uptime || 0,
            networkIn: data.network?.incoming || 0,
            networkOut: data.network?.outgoing || 0,
        }),
    });
}

export function useSourcesHealth(pollInterval = 20000) {
    return useLiveData({
        sourceType: 'sourcesHealth',
        pollInterval,
        wsEvents: ['source:health'],
        transform: (data) => data.sources || [],
    });
}

export function useDecisionHistory(pollInterval = 30000) {
    return useLiveData({
        sourceType: 'decisionHistory',
        pollInterval,
        wsEvents: ['decision:made'],
        transform: (data) => data.decisions || [],
    });
}

export function useEmailInbox(pollInterval = 60000) {
    return useLiveData({
        sourceType: 'email',
        pollInterval,
        wsEvents: ['email:refresh'],
        transform: (data) => ({
            emails: data.emails || [],
            unreadCount: data.unreadCount || 0,
            source: data.source || 'unknown',
            lastFetch: data.lastFetch || null,
        }),
    });
}