Spaces:
Paused
Paused
Download src/App.jsx from InvertedShu/osint-sm-tools: direct link, hf CLI and curl.
- Browser
- Download file 73.4 kB
-
https://huggingface.co/spaces/InvertedShu/osint-sm-tools/resolve/main/src/App.jsx
- Command line
-
hf download hf://spaces/InvertedShu/osint-sm-tools/src/App.jsx
-
curl -L -o App.jsx https://huggingface.co/spaces/InvertedShu/osint-sm-tools/resolve/main/src/App.jsx
73.4 kB
import React, { useState, useEffect, useRef } from 'react';
import { Api, TelegramClient } from 'telegram';
import { StringSession } from 'telegram/sessions';
import * as XLSX from 'xlsx';
import { Facebook, Twitter, Send, Instagram, Menu, X, Globe, Search, Database, FileText, Upload, Shield, Square, User, Users, Bell, ExternalLink } from 'lucide-react';
import InstagramSearch from './components/InstagramSearch';
import FacebookSearch from './components/FacebookSearch';
import XSearch from './components/XSearch';
import TikTokSearch from './components/TikTokSearch';
import { Music2 } from 'lucide-react';
import { getApiUrl } from './config';
// User must provide these in .env.local
const apiId = Number(import.meta.env.VITE_TELEGRAM_API_ID) || 0;
const apiHash = import.meta.env.VITE_TELEGRAM_API_HASH || "";
// Simple range expander in JS. Equivalent to Python's extend_search_patterns
function expandRange(pattern) {
const chars = [];
const regex = /([a-z0-9])-([a-z0-9])/gi;
let match;
while ((match = regex.exec(pattern)) !== null) {
const start = match[1].charCodeAt(0);
const end = match[2].charCodeAt(0);
for (let c = start; c <= end; c++) {
chars.push(String.fromCharCode(c));
}
}
return chars;
}
function expandSearchPatterns(terms) {
const expandedTerms = [];
for (const term of terms) {
const matches = [...term.matchAll(/\[([^\[\]]+)\]/g)];
if (matches.length === 0) {
expandedTerms.push(term);
continue;
}
const staticParts = [];
const dynamicCharSets = [];
let lastEnd = 0;
for (const match of matches) {
staticParts.push(term.slice(lastEnd, match.index));
const pattern = match[1];
const ranges = pattern.match(/[a-z0-9]-[a-z0-9]/gi);
const singles = pattern.replace(/[a-z0-9]-[a-z0-9]/gi, '');
const charset = ranges ? expandRange(pattern) : [];
charset.push(...singles.split(''));
dynamicCharSets.push(charset);
lastEnd = match.index + match[0].length;
}
staticParts.push(term.slice(lastEnd));
// Cartesian product
const cartesianProduct = (arr) => arr.reduce((a, b) =>
a.flatMap(d => b.map(e => [d, e].flat()))
);
// We handle the edge case where dynamicCharSets only has 1 array differently
const combos = dynamicCharSets.length === 1 ? dynamicCharSets[0].map(x => [x]) : cartesianProduct(dynamicCharSets);
for (const combo of combos) {
let newTerm = '';
for (let i = 0; i < staticParts.length; i++) {
newTerm += staticParts[i] + (combo[i] !== undefined ? combo[i] : '');
}
expandedTerms.push(newTerm);
}
}
return expandedTerms;
}
export default function App() {
const [client, setClient] = useState(null);
const [sessionString, setSessionString] = useState('');
const [step, setStep] = useState('phone'); // phone, code, dashboard
const [activeTab, setActiveTab] = useState(() => localStorage.getItem('lastActiveTab') || 'telegram');
const isRemote = !!import.meta.env.VITE_API_URL;
const [platformsAuth, setPlatformsAuth] = useState({
telegram: { status: false, detail: 'OFFLINE', updated: null },
facebook: { status: false, detail: 'MISSING', updated: null },
x: { status: false, detail: 'MISSING', updated: null },
instagram: { status: false, detail: 'MISSING', updated: null },
tiktok: { status: true, detail: 'PUBLIC_ACCESS', updated: 'LIVE' }
});
const [expansion, setExpansion] = useState('none');
const [localSearchTerm, setLocalSearchTerm] = useState('');
// Auth state
const [phone, setPhone] = useState('');
const [phoneCodeHash, setPhoneCodeHash] = useState('');
const [code, setCode] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
// Search state - Telegram
const [tgSearchTerm, setTgSearchTerm] = useState('');
const [tgResults, setTgResults] = useState([]);
const [isTgSearching, setIsTgSearching] = useState(false);
const [tgSearchMode, setTgSearchMode] = useState('none');
const [tgProgress, setTgProgress] = useState(null);
const [tgError, setTgError] = useState('');
// Search state - Instagram
const [igSearchTerm, setIgSearchTerm] = useState('');
const [igResults, setIgResults] = useState([]);
const [isIgSearching, setIsIgSearching] = useState(false);
const [igProgress, setIgProgress] = useState(null);
const [igError, setIgError] = useState('');
const [igSearchMode, setIgSearchMode] = useState('none');
// Search state - Facebook
const [fbSearchTerm, setFbSearchTerm] = useState('');
const [fbResults, setFbResults] = useState([]);
const [isFbSearching, setIsFbSearching] = useState(false);
const [fbError, setFbError] = useState('');
const [fbSearchTypes, setFbSearchTypes] = useState(['pages']);
const [fbSearchMode, setFbSearchMode] = useState('none');
const [fbProgress, setFbProgress] = useState(null);
const fbAbortControllerRef = useRef(null);
const [xSearchTerm, setXSearchTerm] = useState('');
const [xResults, setXResults] = useState([]);
const [isXSearching, setIsXSearching] = useState(false);
const [xError, setXError] = useState('');
const xAbortControllerRef = useRef(null);
const [xProgress, setXProgress] = useState(null);
// Search state - TikTok
const [ttSearchTerm, setTtSearchTerm] = useState('');
const [ttResults, setTtResults] = useState([]);
const [isTtSearching, setIsTtSearching] = useState(false);
const [ttError, setTtError] = useState('');
const [ttProgress, setTtProgress] = useState(null);
const ttAbortControllerRef = useRef(null);
const [isFirstAuthCheckDone, setIsFirstAuthCheckDone] = useState(false);
const checkAllAuth = async () => {
try {
const resp = await fetch(getApiUrl('/api/auth/status'));
if (resp.ok) {
const data = await resp.json();
const hasTg = !!localStorage.getItem('telegramSession');
setPlatformsAuth(prev => ({
...prev,
...data,
telegram: {
status: hasTg,
detail: hasTg ? 'SESSION_ID_FOUND' : 'OFFLINE',
updated: hasTg ? 'LIVE' : null
}
}));
}
} catch (e) {
console.error('[AUTH] Status check failed:', e);
} finally {
setIsFirstAuthCheckDone(true);
}
};
useEffect(() => {
localStorage.setItem('lastActiveTab', activeTab);
}, [activeTab]);
useEffect(() => {
checkAllAuth();
const interval = setInterval(checkAllAuth, 10000); // Poll every 10s
return () => clearInterval(interval);
}, []);
useEffect(() => {
if (activeTab === 'telegram') setLocalSearchTerm(tgSearchTerm);
else if (activeTab === 'instagram') setLocalSearchTerm(igSearchTerm);
else if (activeTab === 'facebook') setLocalSearchTerm(fbSearchTerm);
else if (activeTab === 'tiktok') setLocalSearchTerm(ttSearchTerm);
else setLocalSearchTerm(xSearchTerm);
}, [activeTab, tgSearchTerm, igSearchTerm, fbSearchTerm, ttSearchTerm, xSearchTerm]);
const stopFacebookSearch = () => {
if (fbAbortControllerRef.current) {
fbAbortControllerRef.current.abort();
fbAbortControllerRef.current = null;
}
};
const stopXSearch = () => {
if (xAbortControllerRef.current) {
xAbortControllerRef.current.abort();
xAbortControllerRef.current = null;
}
};
const stopTikTokSearch = () => {
if (ttAbortControllerRef.current) {
ttAbortControllerRef.current.abort();
ttAbortControllerRef.current = null;
}
};
// Auth state - Facebook
const [showFbAuth, setShowFbAuth] = useState(false);
const [fbAuthInput, setFbAuthInput] = useState(localStorage.getItem('fb_auth_input') || '');
const [isFbAuthenticating, setIsFbAuthenticating] = useState(false);
const [fbAuthError, setFbAuthError] = useState('');
const [fbAuthSuccess, setFbAuthSuccess] = useState(false);
// Auth state - Instagram
const [igAuthInput, setIgAuthInput] = useState(localStorage.getItem('ig_auth_input') || '');
useEffect(() => { localStorage.setItem('ig_auth_input', igAuthInput); }, [igAuthInput]);
const [igUsername, setIgUsername] = useState(localStorage.getItem('ig_username') || 'adarshs1780');
const [igPassword, setIgPassword] = useState(localStorage.getItem('ig_password') || '@J6Ku8HFTM3y,Af');
const [isIgAuthenticating, setIsIgAuthenticating] = useState(false);
const [igAuthError, setIgAuthError] = useState('');
const [showIgAuth, setShowIgAuth] = useState(false);
const [igAuthSuccess, setIgAuthSuccess] = useState(false);
// Auth state - X (Twitter)
const [showXAuth, setShowXAuth] = useState(false);
const [xAuthInput, setXAuthInput] = useState(localStorage.getItem('x_auth_input') || '');
const [isXAuthenticating, setIsXAuthenticating] = useState(false);
const [xAuthError, setXAuthError] = useState('');
const [xAuthSuccess, setXAuthSuccess] = useState(false);
// Sidebar state
const [sidebarOpen, setSidebarOpen] = useState(false);
useEffect(() => {
// Auto load session from localStorage
const savedSession = localStorage.getItem('telegramSession');
if (apiId && apiHash) {
if (savedSession) {
setSessionString(savedSession);
initClient(savedSession);
} else {
const initialSession = new StringSession("");
const tc = new TelegramClient(initialSession, apiId, apiHash, { connectionRetries: 5 });
setClient(tc);
}
} else {
console.warn("[TELEGRAM] Skipping initialization: API ID or Hash missing.");
}
}, []);
useEffect(() => {
localStorage.setItem('ig_username', igUsername);
localStorage.setItem('ig_password', igPassword);
localStorage.setItem('ig_auth_input', igAuthInput);
localStorage.setItem('fb_auth_input', fbAuthInput);
localStorage.setItem('x_auth_input', xAuthInput);
}, [igUsername, igPassword, igAuthInput, fbAuthInput, xAuthInput]);
const initClient = async (savedSession) => {
try {
setLoading(true);
const stringSession = new StringSession(savedSession);
const tc = new TelegramClient(stringSession, apiId, apiHash, {
connectionRetries: 5,
});
await tc.connect();
// Verify login is still valid
const isAuth = await tc.checkAuthorization();
if (isAuth) {
setClient(tc);
setStep('dashboard');
} else {
localStorage.removeItem('telegramSession');
if (apiId && apiHash) {
setClient(new TelegramClient(new StringSession(""), apiId, apiHash, { connectionRetries: 5 }));
}
setStep('phone');
}
} catch (err) {
console.error(err);
setError("Failed to init Telegram Client");
} finally {
setLoading(false);
}
};
const sendCode = async () => {
if (!client || !apiId || !apiHash) {
setError('Telegram API credentials missing. Please set them in environment variables.');
return;
}
try {
setError('');
setLoading(true);
await client.connect();
const result = await client.sendCode(
{
apiId: apiId,
apiHash: apiHash,
},
phone
);
setPhoneCodeHash(result.phoneCodeHash);
setStep('code');
} catch (err) {
console.error(err);
setError(err.message || 'Failed to send code.');
} finally {
setLoading(false);
}
};
const verifyCode = async () => {
try {
setError('');
setLoading(true);
await client.invoke(
new Api.auth.SignIn({
phoneNumber: phone,
phoneCodeHash: phoneCodeHash,
phoneCode: code,
})
);
const newSessionString = client.session.save();
localStorage.setItem('telegramSession', newSessionString);
setSessionString(newSessionString);
setStep('dashboard');
} catch (err) {
console.error(err);
setError(err.message || 'Verification failed. Password might be needed.');
} finally {
setLoading(false);
}
};
const clearAuthSessions = async () => {
if (!window.confirm("Are you sure you want to clear ALL stored session cookies (Instagram, Facebook, X)? This will log you out of these platforms locally and on the server.")) {
return;
}
setLoading(true);
try {
const resp = await fetch(getApiUrl('/api/auth/clear'), { method: 'POST' });
if (!resp.ok) throw new Error('Failed to clear sessions');
// Clear local inputs as well
localStorage.removeItem('fb_auth_input');
localStorage.removeItem('ig_auth_input');
localStorage.removeItem('x_auth_input');
setFbAuthInput('');
setIgAuthInput('');
setXAuthInput('');
// Refresh all auth statuses
await checkAllAuth();
} catch (err) {
setError(`Failed to clear sessions: ${err.message}`);
} finally {
setLoading(false);
}
};
const logout = async () => {
localStorage.removeItem('telegramSession');
setSessionString('');
setStep('phone');
if (client) await client.disconnect();
setTgResults([]);
// Setup fresh client
if (apiId && apiHash) {
setClient(new TelegramClient(new StringSession(""), apiId, apiHash, { connectionRetries: 5 }));
} else {
setClient(null);
}
};
const performSearch = async (term) => {
try {
const result = await client.invoke(
new Api.contacts.Search({
q: term,
limit: 50,
})
);
const bufferToBase64 = (buffer) => {
if (!buffer || buffer.length === 0) return null;
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return `data:image/jpeg;base64,${window.btoa(binary)}`;
};
const newResults = [];
for (const user of result.users) {
if (user.username) {
let image = null;
try {
const photoBuffer = await client.downloadProfilePhoto(user);
image = bufferToBase64(photoBuffer);
} catch (e) {
console.warn(`Failed to download photo for ${user.username}`, e);
}
newResults.push({
search_term: term,
type: 'user',
name: `${user.firstName || ''} ${user.lastName || ''}`.trim(),
username: user.username,
url: `https://t.me/${user.username}`,
image: image
});
}
}
for (const chat of result.chats) {
if (chat.username) {
let image = null;
try {
const photoBuffer = await client.downloadProfilePhoto(chat);
image = bufferToBase64(photoBuffer);
} catch (e) {
console.warn(`Failed to download photo for ${chat.username}`, e);
}
newResults.push({
search_term: term,
type: chat.broadcast ? 'channel' : 'group',
name: chat.title,
username: chat.username,
url: `https://t.me/${chat.username}`,
image: image
});
}
}
return newResults;
} catch (err) {
console.error(`Search failed for ${term}`, err);
return [];
}
};
const startSearch = async () => {
if (!tgSearchTerm) return;
let termsToProcess = [tgSearchTerm];
if (!tgSearchTerm.match(/\[.*?\]/)) {
if (tgSearchMode !== 'none') {
termsToProcess = [`${tgSearchTerm}[${tgSearchMode}]`];
}
}
const expandedTerms = expandSearchPatterns(termsToProcess);
const finalTerms = [...new Set([tgSearchTerm.replace(/\[.*?\]/, ''), ...expandedTerms])].filter(Boolean);
setIsTgSearching(true);
setTgResults([]);
setTgError('');
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const BATCH_SIZE = 3;
for (let i = 0; i < finalTerms.length; i += BATCH_SIZE) {
const chunk = finalTerms.slice(i, i + BATCH_SIZE);
setTgProgress(`Searching batch: ${chunk.join(', ')} (${Math.min(i + BATCH_SIZE, finalTerms.length)}/${finalTerms.length})`);
const results = await Promise.all(chunk.map(term => performSearch(term)));
// Merge and deduplicate
setTgResults(prev => {
const flat = [...prev, ...results.flat()];
return Array.from(new Map(flat.map(item => [item.url, item])).values());
});
if (i + BATCH_SIZE < finalTerms.length) {
await sleep(5000);
}
}
setIsTgSearching(false);
setTgProgress('Search Complete!');
};
const exportExcel = () => {
let dataToExport = [];
let fileName = '';
if (activeTab === 'telegram') {
if (tgResults.length === 0) return;
dataToExport = tgResults;
const baseTerm = tgSearchTerm.replace(/\[/g, '').replace(/\]/g, '') || 'results';
fileName = `telegram_search_${baseTerm}`;
} else if (activeTab === 'instagram') {
if (igResults.length === 0) return;
dataToExport = igResults.map(r => ({
'Full Name': r.user.full_name,
'Username': r.user.username,
'Profile URL': `https://www.instagram.com/${r.user.username}/`,
'Is Private': r.user.is_private ? 'Yes' : 'No',
'Is Verified': r.user.is_verified ? 'Yes' : 'No'
}));
fileName = `instagram_${igSearchTerm}`;
} else if (activeTab === 'facebook') {
if (fbResults.length === 0) return;
dataToExport = fbResults.map(r => {
const cleanUrl = r.url.replace('https://www.facebook.com/', '').replace('http://www.facebook.com/', '').split('?')[0].replace(/\/$/, '');
const fallbackUsername = cleanUrl.split('/').pop() || 'Facebook User';
return {
'Type': r.type.charAt(0).toUpperCase() + r.type.slice(1),
'Name': r.name || fallbackUsername,
'Profile URL': r.url,
'Search Term': r.term
};
});
fileName = `facebook_${fbSearchTerm}`;
} else if (activeTab === 'x') {
if (xResults.length === 0) return;
dataToExport = xResults.map(r => ({
'Name': r.name,
'Username': r.username,
'Profile URL': r.url,
'Bio': r.bio,
'Followers': r.followers,
'Following': r.following,
'Tweets': r.tweets,
'Verified': r.verified ? 'Yes' : 'No',
'Location': r.location,
'Website': r.website,
}));
fileName = `x_search_${xSearchTerm}`;
} else if (activeTab === 'tiktok') {
if (ttResults.length === 0) return;
dataToExport = ttResults.map(r => ({
'Username': r.username,
'Nickname': r.nickname,
'Profile URL': r.url,
}));
fileName = `tiktok_search_${ttSearchTerm}`;
} else {
return;
}
const ws = XLSX.utils.json_to_sheet(dataToExport);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, "Results");
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
XLSX.writeFile(wb, `${fileName}_${timestamp}.xlsx`);
};
const performInstagramSearch = async () => {
if (!igSearchTerm) return;
let patterns = [igSearchTerm];
if (!igSearchTerm.match(/\[.*?\]/)) {
if (igSearchMode !== 'none') {
patterns = [`${igSearchTerm}[${igSearchMode}]`];
}
}
const expanded = expandSearchPatterns(patterns);
const finalQueries = [...new Set([igSearchTerm.replace(/\[.*?\]/, ''), ...expanded])].filter(Boolean);
setIsIgSearching(true);
setIgResults([]);
setIgError('');
const sleep = (ms) => new Promise(r => setTimeout(r, ms));
const BATCH_SIZE = 2; // Strict limit for IG
const seen = new Set();
let combinedResults = [];
try {
for (let i = 0; i < finalQueries.length; i += BATCH_SIZE) {
const chunk = finalQueries.slice(i, i + BATCH_SIZE);
setIgProgress(`Searching IG batch: ${chunk.join(', ')} (${Math.min(i + BATCH_SIZE, finalQueries.length)}/${finalQueries.length})`);
const responses = await Promise.all(chunk.map(query =>
fetch(getApiUrl('/api/instagram/search'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query })
})
));
for (const resp of responses) {
if (resp.status === 401) {
throw new Error("Instagram authentication failed. Please update cookies in Dashboard.");
}
if (!resp.ok) continue;
const data = await resp.json();
if (data.users) {
data.users.forEach(u => {
if (!seen.has(u.user.username)) {
seen.add(u.user.username);
combinedResults.push(u);
}
});
}
}
setIgResults([...combinedResults]);
if (i + BATCH_SIZE < finalQueries.length) {
await sleep(5000); // Respect IG rate limits
}
}
setIgProgress(null);
} catch (err) {
if (err.message.includes('Instagram authentication failed')) {
setIgError("Authentication failed or missing cookies. Launching Instagram Login auto-configurator...");
setShowIgAuth(true);
} else {
setIgError(err.message);
}
setIgProgress(null);
} finally {
setIsIgSearching(false);
}
};
const launchFacebookAutoAuth = async () => {
if (isRemote) return;
setIsFbAuthenticating(true);
setFbAuthError('');
setFbAuthSuccess(false);
try {
const resp = await fetch(getApiUrl('/api/facebook/auth-launch'), { method: 'POST' });
const data = await resp.json();
if (!resp.ok || !data.success) throw new Error(data.error || 'Failed to authenticate');
setFbAuthSuccess(true);
setFbError('');
setTimeout(() => { setShowFbAuth(false); setFbAuthSuccess(false); }, 2000);
} catch (err) {
setFbAuthError(err.message);
} finally {
setIsFbAuthenticating(false);
}
};
const performFacebookSearch = async () => {
if (!fbSearchTerm) return;
setIsFbSearching(true);
setFbResults([]);
setFbError('');
fbAbortControllerRef.current = new AbortController();
try {
const resp = await fetch(getApiUrl('/api/facebook/search'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: fbSearchTerm, types: fbSearchTypes }),
signal: fbAbortControllerRef.current.signal
}).catch(err => {
if (err.name === 'AbortError') throw err;
throw new Error("Failed to connect to the backend server. Ensure 'npm run dev:all' is running.");
});
if (!resp.ok) {
if (resp.status === 401 || resp.status === 403) {
setFbError("Authentication failed. Please check your cookies in the configuration panel.");
setShowFbAuth(true);
return;
}
let msg = `Server error: ${resp.status}`;
try { const d = await resp.json(); msg = d.error || msg; } catch (e) { }
throw new Error(msg);
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
if (data.type === 'partial') {
setFbResults(prev => {
const existingIdx = prev.findIndex(x => x.url === data.data.url);
if (existingIdx !== -1) {
const existing = prev[existingIdx];
const incoming = data.data;
// Update if name is longer OR if incoming has an image and existing doesn't
if ((incoming.name && incoming.name.length > (existing.name || '').length) || (incoming.image && !existing.image)) {
const copy = [...prev];
copy[existingIdx] = { ...existing, ...incoming };
return copy;
}
return prev;
}
return [...prev, data.data];
});
} else if (data.type === 'error') {
throw new Error(data.error);
}
} catch (e) {
if (e.message !== "Unexpected end of JSON input" && !e.message.startsWith("Unexpected token")) {
throw e;
}
}
}
}
}
} catch (err) {
if (err.name === 'AbortError') {
const errorMsg = 'Search stopped by user.';
setFbError(errorMsg);
return;
}
if (err.message.includes('FACEBOOK_AUTH_EXPIRED') || err.message.includes('fb_cookies.json not found')) {
setFbError("Authentication expired or missing cookies. Launching Facebook Login auto-configurator...");
setShowFbAuth(true);
launchFacebookAutoAuth();
} else {
setFbError(err.message);
}
} finally {
setIsFbSearching(false);
}
};
const performFacebookDeepSearch = async () => {
if (!fbSearchTerm) return;
setIsFbSearching(true);
setFbResults([]);
setFbError('');
setFbProgress('Initializing Facebook deep search...');
fbAbortControllerRef.current = new AbortController();
try {
let charSet = [];
if (fbSearchMode === 'a-z') charSet = 'abcdefghijklmnopqrstuvwxyz'.split('');
else if (fbSearchMode === '0-9') charSet = '0123456789'.split('');
else if (fbSearchMode === 'a-z0-9') charSet = 'abcdefghijklmnopqrstuvwxyz0123456789'.split('');
const resultsMap = new Map();
const BATCH_SIZE = 2; // Keep low for browser sessions
for (let i = 0; i < charSet.length; i += BATCH_SIZE) {
if (fbAbortControllerRef.current.signal.aborted) break;
const chunk = charSet.slice(i, i + BATCH_SIZE);
setFbProgress(`Searching FB batch: ${chunk.join(', ')} (${Math.min(i + BATCH_SIZE, charSet.length)}/${charSet.length})`);
await Promise.all(chunk.map(async (char) => {
const currentQuery = `${fbSearchTerm} ${char}`;
try {
const resp = await fetch(getApiUrl('/api/facebook/search'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: currentQuery, types: fbSearchTypes }),
signal: fbAbortControllerRef.current.signal
});
if (!resp.ok) return;
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
if (data.type === 'partial') {
const item = data.data;
if (!resultsMap.has(item.url)) {
resultsMap.set(item.url, item);
setFbResults(Array.from(resultsMap.values()));
}
}
} catch (e) { }
}
}
}
} catch (e) {
if (e.name !== 'AbortError') console.error(`FB Error for ${char}:`, e);
}
}));
}
setFbProgress(null);
} catch (err) {
if (err.name === 'AbortError') {
setFbError('Search stopped by user.');
} else {
setFbError(err.message);
}
setFbProgress(null);
} finally {
setIsFbSearching(false);
}
};
const launchXAutoAuth = async () => {
setIsXAuthenticating(true);
setXAuthError('');
setXAuthSuccess(false);
try {
const resp = await fetch(getApiUrl('/api/x/auth-launch'), { method: 'POST' });
const data = await resp.json();
if (!resp.ok || !data.success) throw new Error(data.error || 'Failed to authenticate');
setXAuthSuccess(true);
setXError('');
setTimeout(() => { setShowXAuth(false); setXAuthSuccess(false); }, 2000);
} catch (err) {
setXAuthError(err.message);
} finally {
setIsXAuthenticating(false);
}
};
const performXSearch = async () => {
if (!xSearchTerm) return;
setIsXSearching(true);
setXResults([]);
setXError('');
setXProgress('Starting X (Twitter) search...');
xAbortControllerRef.current = new AbortController();
try {
const resp = await fetch(getApiUrl('/api/x/search'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: xSearchTerm }),
signal: xAbortControllerRef.current.signal
});
if (!resp.ok) {
let msg = 'Failed to search X (Twitter)';
try { const d = await resp.json(); msg = d.error || msg; } catch (e) { }
throw new Error(msg);
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
if (data.type === 'partial') {
setXResults(prev => {
const existingIdx = prev.findIndex(x => x.url === data.data.url);
if (existingIdx !== -1) {
// Update existing entry if more complete data arrives
const copy = [...prev];
copy[existingIdx] = { ...copy[existingIdx], ...data.data };
return copy;
}
return [...prev, data.data];
});
setXProgress(`Found ${xResults.length + 1} results for "${xSearchTerm}"...`);
} else if (data.type === 'progress') {
setXProgress(data.message);
} else if (data.type === 'error') {
throw new Error(data.error);
}
} catch (e) {
if (e.message !== "Unexpected end of JSON input" && !e.message.startsWith("Unexpected token")) {
throw e;
}
}
}
}
}
setXProgress(`Search complete! Found ${xResults.length} results.`);
} catch (err) {
if (err.name === 'AbortError') {
setXError('Search stopped by user.');
setXProgress(null);
return;
}
if (err.message.includes('X_AUTH_EXPIRED') || err.message.includes('x_cookies.json not found')) {
setXError("Authentication required for X (Twitter).");
setShowXAuth(true);
if (!isRemote) {
launchXAutoAuth();
}
} else {
setXError(err.message);
}
setXProgress(null);
} finally {
setIsXSearching(false);
}
};
const performTikTokSearch = async () => {
if (!ttSearchTerm) return;
setIsTtSearching(true);
setTtResults([]);
setTtError('');
setTtProgress('Starting TikTok search...');
ttAbortControllerRef.current = new AbortController();
try {
const resp = await fetch(getApiUrl('/api/tiktok/search'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query: ttSearchTerm }),
signal: ttAbortControllerRef.current.signal
});
if (!resp.ok) {
let msg = 'Failed to search TikTok';
try { const d = await resp.json(); msg = d.error || msg; } catch (e) { }
throw new Error(msg);
}
const reader = resp.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.slice(6));
if (data.type === 'partial') {
setTtResults(prev => {
if (prev.some(x => x.url === data.data.url)) return prev;
return [...prev, data.data];
});
} else if (data.type === 'progress') {
setTtProgress(data.data);
} else if (data.type === 'error') {
throw new Error(data.error);
}
} catch (e) {
if (e.message.includes('API credentials') || e.message.includes('TikTok') || e.message.includes('Navigation')) {
throw e; // Bubble up important errors
}
}
}
}
}
setTtProgress(null);
} catch (err) {
if (err.name === 'AbortError') {
setTtError('Search stopped by user.');
} else {
setTtError(err.message);
}
setTtProgress(null);
} finally {
setIsTtSearching(false);
}
};
const launchInstagramAutoAuth = async () => {
setIsIgAuthenticating(true);
setIgAuthError('');
setIgAuthSuccess(false);
try {
const resp = await fetch(getApiUrl('/api/instagram/auth-launch'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: igUsername, password: igPassword })
});
const data = await resp.json();
if (!resp.ok || !data.success) throw new Error(data.error || 'Failed to authenticate');
// The backend handles saving these; we just need to know it succeeded
setIgAuthSuccess(true);
setIgError('');
// Trigger instant status check
setTimeout(checkAllAuth, 500);
setTimeout(() => { setShowIgAuth(false); setIgAuthSuccess(false); }, 2000);
} catch (err) {
setIgAuthError(err.message);
} finally {
setIsIgAuthenticating(false);
}
};
const saveInstagramCookies = async () => {
if (!igAuthInput) {
setIgAuthError('Please paste the cookies JSON array.');
return;
}
setIsIgAuthenticating(true);
setIgAuthError('');
setIgAuthSuccess(false);
try {
let rawInput = igAuthInput.trim();
let allCookies;
try {
// First pass: try standard parse
allCookies = JSON.parse(rawInput);
// Second pass: if user pasted a JSON string wrapped in quotes (stringified JSON)
if (typeof allCookies === 'string') {
allCookies = JSON.parse(allCookies);
}
if (!Array.isArray(allCookies)) {
throw new Error('Input is valid JSON but not an array of cookies.');
}
} catch (e) {
if (e.message.includes('JSON but not an array')) throw e;
throw new Error(`JSON Error: Please ensure you paste a valid [ { ... } ] array. (${e.message})`);
}
const response = await fetch(getApiUrl('/api/instagram/save-cookies'), {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ allCookies })
});
if (!response.ok) {
let errorMsg = 'Failed to save cookies';
try {
const errData = await response.json();
errorMsg = errData.error || errorMsg;
} catch (e) { }
throw new Error(errorMsg);
}
setIgAuthSuccess(true);
setIgError(''); // Clear search errors if any
// Trigger instant status check
setTimeout(checkAllAuth, 100);
setTimeout(() => {
setShowIgAuth(false);
setIgAuthSuccess(false);
}, 2000);
} catch (err) {
setIgAuthError(err.message);
} finally {
setIsIgAuthenticating(false);
}
};
const saveFacebookCookies = async () => {
if (!fbAuthInput) {
setFbAuthError('Cookies data is required.');
return;
}
setIsFbAuthenticating(true);
setFbAuthError('');
setFbAuthSuccess(false);
try {
// Clean input (handle standard JSON format)
let cookies;
try {
cookies = JSON.parse(fbAuthInput);
} catch (e) {
throw new Error('Invalid JSON format for cookies.');
}
const response = await fetch(getApiUrl('/api/facebook/save-cookies'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cookies })
});
if (!response.ok) throw new Error('Failed to save Facebook cookies');
setFbAuthSuccess(true);
setTimeout(checkAllAuth, 500);
setTimeout(() => { setShowFbAuth(false); setFbAuthSuccess(false); }, 2000);
} catch (err) {
setFbAuthError(err.message);
} finally {
setIsFbAuthenticating(false);
}
};
const saveXCookies = async () => {
if (!xAuthInput) {
setXAuthError('Cookies data is required.');
return;
}
setIsXAuthenticating(true);
setXAuthError('');
setXAuthSuccess(false);
try {
const response = await fetch(getApiUrl('/api/x/save-cookies'), {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ cookies: xAuthInput })
});
if (!response.ok) throw new Error('Failed to save X cookies');
setXAuthSuccess(true);
setTimeout(checkAllAuth, 500);
setTimeout(() => { setShowXAuth(false); setXAuthSuccess(false); }, 2000);
} catch (err) {
setXAuthError(err.message);
} finally {
setIsXAuthenticating(false);
}
};
const LoginRequired = ({ platform, onLogin }) => {
const icons = {
telegram: <Send size={32} />,
facebook: <Facebook size={32} />,
x: <Twitter size={32} />,
instagram: <Instagram size={32} />
};
const colors = {
telegram: 'var(--p-telegram)',
facebook: 'var(--p-facebook)',
x: 'var(--text-bright)',
instagram: 'var(--p-instagram)'
};
return (
<div className="flex flex-col items-center justify-center py-16 px-4 bg-black/40 rounded-lg border border-dashed anim-fade-in" style={{ borderColor: 'var(--line)' }}>
<div className="mb-4 opacity-50" style={{ color: colors[platform] }}>
{icons[platform]}
</div>
<h3 className="text-lg font-bold mb-1 uppercase tracking-widest" style={{ color: 'var(--text-bright)' }}>Session Inactive</h3>
<p className="text-xs font-mono mb-6 text-center max-w-sm" style={{ color: 'var(--text-ghost)' }}>
System requires an active <span style={{ color: colors[platform] }}>{platform.toUpperCase()}</span> session to authorize search requests.
</p>
<button onClick={onLogin} className="btn-primary flex items-center gap-2 group">
<Shield size={14} className="group-hover:rotate-12 transition-transform" />
AUTHORIZE SESSION
</button>
</div>
);
};
const StatusBadge = ({ platform }) => {
const auth = platformsAuth[platform] || { status: false, detail: 'OFFLINE' };
if (platform === 'status') return null;
return (
<div className="flex items-center gap-2 ml-auto">
<div className={`flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[9px] font-mono border ${auth.status ? 'bg-green-500/5 border-green-500/20 text-green-500' : 'bg-red-500/5 border-red-500/20 text-red-400'}`}>
<div className={`w-1 h-1 rounded-full ${auth.status ? 'bg-green-500 shadow-[0_0_4px_rgba(34,197,94,0.5)]' : 'bg-red-500'}`} />
<span>{auth.status ? 'CONNECTED' : 'SESSION_INACTIVE'}</span>
<span className="opacity-40 select-none">|</span>
<span className="opacity-80">{auth.detail}</span>
</div>
</div>
);
};
const StatusHub = () => {
const activeSearches = Object.entries(searchStates).filter(([_, busy]) => busy);
return (
<div className="space-y-6 anim-fade-up">
{activeSearches.length > 0 && (
<div className="panel p-4 border-cyan-500/30 bg-cyan-500/5">
<h3 className="text-xs font-bold font-mono mb-3 flex items-center gap-2" style={{ color: 'var(--neon-cyan)' }}>
<div className="w-2 h-2 rounded-full bg-cyan-500 animate-pulse" />
LIVE_ACTIVITY_MONITOR [{activeSearches.length}]
</h3>
<div className="space-y-3">
{activeSearches.map(([platform, _]) => {
const progress = platform === 'telegram' ? tgProgress :
platform === 'instagram' ? igProgress :
platform === 'facebook' ? fbProgress :
platform === 'tiktok' ? ttProgress : xProgress;
const resultsCount = platform === 'telegram' ? tgResults.length :
platform === 'instagram' ? igResults.length :
platform === 'facebook' ? fbResults.length :
platform === 'tiktok' ? ttResults.length : xResults.length;
return (
<div key={platform} className="flex flex-col gap-1 p-2 rounded bg-black/40 border border-white/5">
<div className="flex justify-between items-center">
<span className="text-[10px] font-bold uppercase" style={{ color: platforms[platform].accent }}>{platform}</span>
<span className="text-[10px] font-mono opacity-60">{resultsCount} results found</span>
</div>
<div className="flex items-center gap-3">
<div className="flex-grow bg-white/5 h-1 rounded-full overflow-hidden">
<div className="h-full bg-cyan-500 animate-pulse" style={{ width: '100%' }} />
</div>
<span className="text-[9px] font-mono truncate max-w-[200px] opacity-80">{progress || 'Processing...'}</span>
</div>
</div>
);
})}
</div>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{Object.entries(platforms).filter(([k]) => k !== 'status').map(([key, p]) => {
const auth = platformsAuth[key] || { status: false, detail: 'UNKNOWN', updated: null };
const Icon = p.icon;
return (
<div key={key} className="status-card h-full flex flex-col">
<div className="status-card-header">
<div className="flex items-center gap-2">
<Icon size={16} style={{ color: p.accent }} />
<span className="font-bold text-xs tracking-wider uppercase">{p.label}</span>
</div>
<div className={`status-pill ${auth.status ? 'online' : 'offline'}`}>
{auth.status ? 'ONLINE' : 'OFFLINE'}
</div>
</div>
<div className="status-card-body flex-grow">
<div className="space-y-2 mb-4">
<div className="flex justify-between items-center bg-black/20 p-2 rounded border border-white/5">
<span className="text-[10px] uppercase text-ghost">Local Storage</span>
<span className="text-[10px] font-mono text-bright">{auth.detail}</span>
</div>
<div className="flex justify-between items-center bg-black/20 p-2 rounded border border-white/5">
<span className="text-[10px] uppercase text-ghost">Sync Status</span>
<span className="text-[10px] font-mono text-bright">{auth.updated || 'NEVER'}</span>
</div>
</div>
<button onClick={() => setActiveTab(key)}
className="btn-dim w-full text-[10px] font-mono py-2 flex items-center justify-center gap-2 group">
<ExternalLink size={12} className="group-hover:translate-x-0.5 group-hover:-translate-y-0.5 transition-transform" />
GOTO_{key.toUpperCase()}
</button>
</div>
</div>
);
})}
</div>
{/* System Management */}
<div className="flex flex-col items-center pt-8 border-t border-white/5">
<p className="text-[10px] font-mono text-ghost mb-4 uppercase tracking-[0.2em]">// security & maintenance</p>
<button
onClick={clearAuthSessions}
className="btn-abort flex items-center gap-2 px-8 py-3 group"
>
<Database size={16} className="group-hover:rotate-12 transition-transform" />
CLEAR_ALL_ACTIVE_SESSIONS
</button>
<p className="text-[9px] font-mono text-ghost/40 mt-3 text-center max-w-xs leading-relaxed">
CAUTION: This will permanently delete Instagram, Facebook, and X session files from the server.
</p>
</div>
</div>
);
};
// Platform config
const platforms = {
status: { icon: Database, label: 'STATUS', accent: 'var(--neon-cyan)' },
telegram: { icon: Send, label: 'Telegram', accent: 'var(--p-telegram)' },
facebook: { icon: Facebook, label: 'Facebook', accent: 'var(--p-facebook)' },
x: { icon: Twitter, label: 'X', accent: 'var(--p-x)' },
tiktok: { icon: Music2, label: 'TikTok', accent: 'var(--p-tiktok)' },
instagram: { icon: Instagram, label: 'Instagram', accent: 'var(--p-instagram)' },
};
const cur = platforms[activeTab] || platforms.telegram;
const CurIcon = cur.icon;
const searchStates = {
telegram: isTgSearching,
instagram: isIgSearching,
facebook: isFbSearching,
tiktok: isTtSearching,
x: isXSearching
};
const busy = activeTab === 'status' ? false : searchStates[activeTab] || false;
const curTerm = activeTab === 'status' ? '' :
activeTab === 'telegram' ? tgSearchTerm :
activeTab === 'instagram' ? igSearchTerm :
activeTab === 'facebook' ? fbSearchTerm :
activeTab === 'tiktok' ? ttSearchTerm : xSearchTerm;
return (
<div className="min-h-screen flex flex-col" style={{ color: 'var(--text-normal)' }}>
{/* Scanline overlay */}
<div className="scanline-overlay" />
{/* ═══ TOP NAV ═══ */}
<nav className="topnav">
{/* Brand */}
<div className="flex items-center gap-2 mr-6 select-none">
<Shield size={18} style={{ color: 'var(--neon-cyan)' }} />
<span className="text-sm font-bold tracking-tight text-neon font-mono">SM:TOOLS</span>
<span className="hidden sm:inline text-[9px] font-mono py-0.5 px-1.5 rounded ml-1"
style={{ background: 'var(--neon-cyan-glow)', color: 'var(--neon-cyan-dim)', border: '1px solid rgba(0,240,255,0.15)' }}>
OSINT
</span>
</div>
{/* Tabs */}
<div className="flex items-center gap-1">
{Object.entries(platforms).map(([key, p]) => {
const Icon = p.icon;
const isActive = activeTab === key;
const authInfo = platformsAuth[key] || { status: false };
const isAuth = authInfo.status;
return (
<button key={key} onClick={() => { setActiveTab(key); setSidebarOpen(false); }}
className={`nav-tab ${isActive ? 'active' : ''} relative`}>
<Icon size={15} style={isActive ? { color: 'var(--neon-cyan)' } : undefined} />
<span className="hidden md:inline">{p.label}</span>
{key !== 'status' && (
<div className="absolute -top-1 -right-1 flex gap-0.5">
{searchStates[key] && (
<div className="w-2 h-2 rounded-full bg-cyan-400 animate-ping opacity-75" />
)}
<div className={`status-dot-mini ${isAuth ? 'bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.4)]' : 'bg-red-500 shadow-[0_0_8px_rgba(239,68,68,0.4)]'}`}
title={isAuth ? 'Connected' : 'Login Required'} />
</div>
)}
</button>
);
})}
</div>
{/* Right side */}
<div className="ml-auto flex items-center gap-3">
{activeTab === 'telegram' && step === 'dashboard' && (
<button onClick={logout} className="btn-dim text-[10px]">SIGN OUT</button>
)}
<a href="http://github.com/InvertedShu" target="_blank" rel="noopener noreferrer"
className="flex items-center gap-1.5 px-2 py-1 rounded transition-all"
style={{ color: 'var(--text-dim)', border: '1px solid var(--line)' }}
onMouseEnter={e => { e.currentTarget.style.color = 'var(--neon-cyan)'; e.currentTarget.style.borderColor = 'rgba(0,240,255,0.25)'; e.currentTarget.style.boxShadow = '0 0 12px rgba(0,240,255,0.1)'; }}
onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-dim)'; e.currentTarget.style.borderColor = 'var(--line)'; e.currentTarget.style.boxShadow = 'none'; }}>
<svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"/></svg>
<span className="text-[10px] font-mono hidden sm:inline">by <span style={{ color: 'var(--neon-cyan-dim)' }}>InvertedShu</span></span>
</a>
<div className="status-dot" />
</div>
</nav>
{/* ═══ MAIN ═══ */}
<main className="flex-1 px-4 md:px-8 py-6 max-w-6xl mx-auto w-full">
{/* Page header */}
<div className="mb-6 anim-fade-up">
<div className="flex items-center gap-3 mb-1">
<CurIcon size={18} style={{ color: cur.accent }} />
<h1 className="text-xl font-bold" style={{ color: 'var(--text-bright)' }}>{cur.label} <span className="font-mono text-sm" style={{ color: 'var(--text-dim)' }}>// search</span></h1>
<StatusBadge platform={activeTab} />
</div>
<p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>
{activeTab === 'status' ? '> system command center // global health' :
activeTab === 'telegram' ? '> users, channels, groups' :
activeTab === 'facebook' ? '> pages, people, groups' :
activeTab === 'tiktok' ? '> profiles, creators' :
activeTab === 'instagram' ? '> profiles, accounts' :
'> users, profiles'}
</p>
</div>
{/* Errors */}
{error && <div className="err-box mb-5 anim-fade-up"><span className="font-mono text-xs">ERR</span><span>{error}</span></div>}
{activeTab === 'telegram' && tgError && <div className="err-box mb-5 anim-fade-up"><span className="font-mono text-xs">ERR</span><span>{tgError}</span></div>}
{activeTab === 'x' && xError && <div className="err-box mb-5 anim-fade-up"><span className="font-mono text-xs">ERR</span><span>{xError}</span></div>}
{loading && (
<div className="mb-5 text-center anim-fade-in">
<div className="prog-bar w-40 mx-auto mb-2" />
<span className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>INITIALIZING<span className="anim-blink">_</span></span>
</div>
)}
{/* ═══ TELEGRAM AUTH ═══ */}
{activeTab === 'telegram' && (step === 'phone' || step === 'code') && (
<div className="mx-auto mt-8 md:mt-16 max-w-md w-full auth-panel anim-fade-up">
<h2 className="text-lg font-bold mb-0.5 font-mono" style={{ color: 'var(--text-bright)' }}>
<span style={{ color: 'var(--neon-cyan)' }}>></span> Telegram.auth()
</h2>
<p className="text-xs mb-5 font-mono" style={{ color: 'var(--text-ghost)' }}>
{step === 'phone' ? '// enter phone in intl format' : '// enter verification code'}
</p>
{step === 'phone' ? (
<div className="space-y-3">
<input type="text" placeholder="+1234567890" value={phone} onChange={e => setPhone(e.target.value)} className="cyber-input" />
<button onClick={sendCode} disabled={loading || !phone} className="btn-neon w-full">SEND_CODE</button>
</div>
) : (
<div className="space-y-3">
<input type="text" placeholder="______" value={code} onChange={e => setCode(e.target.value)} className="cyber-input text-center tracking-[0.4em]" />
<button onClick={verifyCode} disabled={loading || !code} className="btn-neon w-full">VERIFY</button>
</div>
)}
</div>
)}
{/* ═══ DASHBOARD ═══ */}
{activeTab === 'status' ? (
<StatusHub />
) : (activeTab !== 'telegram' || step === 'dashboard') && (
<div className="space-y-5 anim-fade-up">
{!isFirstAuthCheckDone ? (
<div className="flex flex-col items-center justify-center py-20 anim-fade-in opacity-50">
<div className="prog-bar w-32 mb-4" />
<p className="text-[10px] font-mono uppercase tracking-widest">Verifying_Session_State...</p>
</div>
) : (
<>
{/* Config toggle */}
{(activeTab === 'instagram' || activeTab === 'facebook' || activeTab === 'x') && (
<div className="flex justify-end">
<button onClick={() => {
if (activeTab === 'instagram') setShowIgAuth(!showIgAuth);
else if (activeTab === 'facebook') setShowFbAuth(!showFbAuth);
else if (activeTab === 'x') setShowXAuth(!showXAuth);
}} className="btn-dim font-mono text-[10px]">
<Upload size={12} />
{(activeTab === 'instagram' ? showIgAuth : activeTab === 'facebook' ? showFbAuth : showXAuth) ? 'HIDE_CFG' : 'CONFIG'}
</button>
</div>
)}
{/* Facebook Auth */}
{activeTab === 'facebook' && (showFbAuth || !platformsAuth['facebook']?.status) && (
<div className="auth-panel anim-slide-down">
<h3 className="text-sm font-bold mb-0.5 font-mono" style={{ color: 'var(--text-bright)' }}><span style={{ color: 'var(--p-facebook)' }}>></span> fb.authenticate()</h3>
<p className="text-xs mb-4 font-mono" style={{ color: 'var(--text-ghost)' }}>// cookies required for search</p>
{fbAuthError && <div className="err-box mb-3 text-xs"><span>ERR</span><span>{fbAuthError}</span></div>}
{isRemote && !fbAuthSuccess && (
<div className="mb-4 p-3 rounded text-[10px] font-mono leading-relaxed bg-yellow-500/5 border border-yellow-500/20 text-yellow-500/80">
<p className="font-bold mb-1">REMOTE SERVER DETECTED</p>
<p>Browser login is disabled on Render to prevent crashes. Please perform login on your local machine and paste the cookies below.</p>
</div>
)}
{fbAuthSuccess ? (
<div className="ok-box"><span className="text-2xl">✓</span><span className="font-mono text-sm">cookies.saved()</span></div>
) : (
<div className="space-y-3">
<div>
<p className="sec-label mb-1.5">paste cookies</p>
<textarea placeholder='[{ "name": "c_user", ... }]' value={fbAuthInput} onChange={e => setFbAuthInput(e.target.value)}
className="cyber-input text-xs" style={{ height: '5rem', resize: 'vertical' }} />
</div>
<button onClick={saveFacebookCookies} disabled={isFbAuthenticating || !fbAuthInput} className="btn-dim w-full font-mono text-[10px]">{isFbAuthenticating ? 'SAVING...' : 'SAVE_COOKIES'}</button>
</div>
)}
</div>
)}
{/* X Auth */}
{activeTab === 'x' && (showXAuth || !platformsAuth['x']?.status) && (
<div className="auth-panel anim-slide-down">
<h3 className="text-sm font-bold mb-0.5 font-mono" style={{ color: 'var(--text-bright)' }}><span style={{ color: 'var(--p-x)' }}>></span> x.authenticate()</h3>
<p className="text-xs mb-4 font-mono" style={{ color: 'var(--text-ghost)' }}>// cookies required for search</p>
{xAuthError && <div className="err-box mb-3 text-xs"><span>ERR</span><span>{xAuthError}</span></div>}
{isRemote && !xAuthSuccess && (
<div className="mb-4 p-3 rounded text-[10px] font-mono leading-relaxed bg-yellow-500/5 border border-yellow-500/20 text-yellow-500/80">
<p className="font-bold mb-1">REMOTE SERVER DETECTED</p>
<p>Browser login is disabled on Render to prevent crashes. Please perform login on your local machine and paste the cookies below.</p>
</div>
)}
{xAuthSuccess ? (
<div className="ok-box"><span className="text-2xl">✓</span><span className="font-mono text-sm">cookies.saved()</span></div>
) : (
<div className="space-y-3">
<div>
<p className="sec-label mb-1.5">paste cookies</p>
<textarea placeholder='[{ "name": "auth_token", ... }]' value={xAuthInput} onChange={e => setXAuthInput(e.target.value)}
className="cyber-input text-xs" style={{ height: '5rem', resize: 'vertical' }} />
</div>
<button onClick={saveXCookies} disabled={isXAuthenticating || !xAuthInput} className="btn-dim w-full font-mono text-[10px]">{isXAuthenticating ? 'SAVING...' : 'SAVE_COOKIES'}</button>
</div>
)}
</div>
)}
{/* Instagram Auth */}
{activeTab === 'instagram' && (showIgAuth || !platformsAuth['instagram']?.status) && (
<div className="auth-panel anim-slide-down">
<h3 className="text-sm font-bold mb-0.5 font-mono" style={{ color: 'var(--text-bright)' }}><span style={{ color: 'var(--p-instagram)' }}>></span> ig.authenticate()</h3>
<p className="text-xs mb-4 font-mono" style={{ color: 'var(--text-ghost)' }}>// active session required</p>
{igAuthError && <div className="err-box mb-3 text-xs"><span>ERR</span><span>{igAuthError}</span></div>}
{igAuthSuccess ? (
<div className="ok-box"><span className="text-2xl">✓</span><span className="font-mono text-sm">credentials.saved()</span></div>
) : (
<div className="space-y-3">
{isRemote && (
<div className="mb-4 p-3 rounded text-[10px] font-mono leading-relaxed bg-yellow-500/5 border border-yellow-500/20 text-yellow-500/80">
<p className="font-bold mb-1">REMOTE SERVER DETECTED</p>
<p>Browser login is disabled on Render. Please perform login locally and provide tokens below.</p>
</div>
)}
<div className="space-y-2">
<p className="sec-label uppercase text-[10px] tracking-widest opacity-50">Manual Capture</p>
<div className="flex flex-col gap-1.5">
<label className="text-[9px] font-mono uppercase opacity-40">Paste Cookies JSON Array</label>
<textarea
placeholder='[{"name":"sessionid", "value":"..."}, ...]'
value={igAuthInput}
onChange={e => setIgAuthInput(e.target.value)}
className="cyber-input text-[10px] min-h-[100px] font-mono py-2"
/>
</div>
<button onClick={saveInstagramCookies} disabled={isIgAuthenticating} className="btn-dim w-full font-mono text-[10px] tracking-wider uppercase mt-1">
{isIgAuthenticating ? 'SAVING...' : 'Save_Manual_Tokens'}
</button>
</div>
</div>
)}
</div>
)}
{/* Facebook filters */}
{activeTab === 'facebook' && (
<div>
<p className="sec-label mb-2">target_type</p>
<div className="flex flex-wrap gap-1.5">
{['pages', 'people', 'groups'].map(t => (
<button key={t} onClick={() => setFbSearchTypes(prev => prev.includes(t) ? prev.length > 1 ? prev.filter(x => x !== t) : prev : [...prev, t])}
className={`sel-chip ${fbSearchTypes.includes(t) ? 'on' : ''}`}>{t}</button>
))}
<button onClick={() => fbSearchTypes.length === 3 ? setFbSearchTypes(['pages']) : setFbSearchTypes(['pages','people','groups'])}
className={`sel-chip ${fbSearchTypes.length === 3 ? 'on' : ''}`} style={{ flex: '0 0 auto' }}>{fbSearchTypes.length === 3 ? 'NONE' : 'ALL'}</button>
</div>
</div>
)}
{/* Search expansion */}
{(activeTab === 'telegram' || activeTab === 'instagram') && (
<div>
<p className="sec-label mb-2">expansion_mode</p>
<div className="flex flex-wrap gap-1.5">
{['none', 'a-z', '0-9', 'a-z0-9'].map(m => {
const cur = activeTab === 'telegram' ? tgSearchMode : igSearchMode;
const set = activeTab === 'telegram' ? setTgSearchMode : setIgSearchMode;
return <button key={m} onClick={() => set(m)} className={`sel-chip ${cur === m ? 'on' : ''}`}>{m === 'none' ? 'EXACT' : m}</button>;
})}
</div>
</div>
)}
{/* ═══ Search Area (Blocked until Auth) ═══ */}
{(activeTab === 'tiktok' || platformsAuth[activeTab]?.status) && (
<>
{/* Search Bar ═══ */}
<div className="panel anim-fade-up">
<div className="panel-header">
<span style={{ color: 'var(--neon-cyan-dim)' }}>⟩ QUERY_INPUT</span>
{busy && <div className="status-dot" />}
</div>
<div className="p-4 flex flex-col md:flex-row gap-3">
<div className="flex-grow">
<input type="text"
placeholder={activeTab === 'telegram' ? "target[a-z0-9]" : activeTab === 'x' ? "@handle OR #tag" : "keyword..."}
value={localSearchTerm}
onChange={e => {
const v = e.target.value;
setLocalSearchTerm(v);
if (activeTab === 'telegram') setTgSearchTerm(v);
else if (activeTab === 'instagram') setIgSearchTerm(v);
else if (activeTab === 'facebook') setFbSearchTerm(v);
else if (activeTab === 'tiktok') setTtSearchTerm(v);
else setXSearchTerm(v);
}}
disabled={busy}
onKeyDown={e => {
if (e.key === 'Enter' && !busy && localSearchTerm) {
if (activeTab === 'telegram') startSearch();
else if (activeTab === 'instagram') performInstagramSearch();
else if (activeTab === 'facebook') performFacebookSearch();
else if (activeTab === 'tiktok') performTikTokSearch();
else performXSearch();
}
}}
className="cyber-input"
/>
</div>
<div className="flex flex-col justify-end md:w-32">
{(activeTab === 'facebook' && isFbSearching) || (activeTab === 'x' && isXSearching) || (activeTab === 'tiktok' && isTtSearching) ? (
<button onClick={activeTab === 'facebook' ? stopFacebookSearch : activeTab === 'x' ? stopXSearch : stopTikTokSearch} className="btn-abort w-full">
<Square size={14} fill="currentColor" /> ABORT
</button>
) : (
<button onClick={() => {
if (activeTab === 'telegram') startSearch();
else if (activeTab === 'instagram') performInstagramSearch();
else if (activeTab === 'facebook') performFacebookSearch();
else if (activeTab === 'tiktok') performTikTokSearch();
else performXSearch();
}}
disabled={busy || !curTerm} className="btn-neon w-full">
{busy ? <span className="inline-block w-4 h-4 border-2 border-current/30 border-t-current rounded-full" style={{ animation: 'spin 0.6s linear infinite' }} /> : <><Search size={14} /> EXEC</>}
</button>
)}
</div>
</div>
</div>
{/* Progress */}
{activeTab === 'telegram' && (isTgSearching || tgProgress) && (
<div className="panel px-4 py-2.5 flex items-center justify-between anim-fade-in">
<span className="text-xs font-mono" style={{ color: 'var(--neon-cyan)' }}>{tgProgress}</span>
{isTgSearching && <div className="prog-bar" style={{ width: '50px' }} />}
</div>
)}
{activeTab === 'instagram' && (isIgSearching || igProgress) && (
<div className="panel px-4 py-2.5 flex items-center justify-between anim-fade-in">
<span className="text-xs font-mono" style={{ color: 'var(--p-instagram)' }}>{igProgress}</span>
{isIgSearching && <div className="prog-bar" style={{ width: '50px' }} />}
</div>
)}
{/* ═══ Telegram Results Grid ═══ */}
{activeTab === 'telegram' ? (
<div className="space-y-4 anim-fade-up">
<div className="flex justify-between items-center">
<span className="sec-label">results [{tgResults.length}]</span>
<button onClick={exportExcel} disabled={tgResults.length === 0} className="btn-export"><FileText size={11} /> EXPORT</button>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-2">
{tgResults.length === 0 ? (
<div className="col-span-full empty-zone py-8">
<Send className="w-8 h-8 mb-2" style={{ color: 'var(--text-ghost)' }} />
<p className="text-xs font-mono" style={{ color: 'var(--text-ghost)' }}>
{isTgSearching ? 'scanning...' : '// no data — execute a search'}
</p>
</div>
) : tgResults.map((r, i) => {
const TypeIcon = r.type === 'user' ? User : r.type === 'channel' ? Bell : Users;
const typeColor = r.type === 'user' ? 'var(--neon-cyan-dim)' : r.type === 'channel' ? '#a78bfa' : 'var(--neon-green-dim)';
const typeBg = r.type === 'user' ? 'rgba(0,240,255,0.06)' : r.type === 'channel' ? 'rgba(139,92,246,0.08)' : 'rgba(0,255,136,0.06)';
return (
<div key={i} className="r-card group">
<div className="r-card-border-glow" />
<div className="flex items-center gap-3 relative z-10">
<div className="relative">
{r.image ? (
<img src={r.image} alt={r.username} className="w-10 h-10 rounded object-cover shadow-sm" style={{ border: '1px solid var(--line)' }} />
) : (
<div className="w-10 h-10 rounded flex items-center justify-center"
style={{ background: 'var(--bg-raised)', border: '1px solid var(--line)' }}>
<TypeIcon size={18} style={{ color: typeColor }} />
</div>
)}
<div className="absolute -bottom-1 -right-1 w-3.5 h-3.5 rounded flex items-center justify-center"
style={{ background: typeBg, border: '1px solid var(--line)', backdropFilter: 'blur(4px)' }}>
<TypeIcon size={8} style={{ color: typeColor }} />
</div>
</div>
<div className="min-w-0 flex-1">
<div className="text-sm font-medium truncate" style={{ color: 'var(--text-bright)' }}>{r.name}</div>
<div className="text-[10px] font-mono truncate" style={{ color: 'var(--text-ghost)' }}>@{r.username}</div>
</div>
<a href={r.url} target="_blank" rel="noopener noreferrer"
className="p-1.5 rounded transition-colors" style={{ color: 'var(--text-dim)' }}><ExternalLink size={12} /></a>
</div>
<div className="mt-2.5 relative z-10">
<span className="tag" style={{ background: typeBg, color: typeColor, borderColor: 'rgba(255,255,255,0.05)' }}>
{r.type.toUpperCase()}
</span>
</div>
</div>
);
})}
</div>
</div>
) : null}
{activeTab === 'instagram' && platformsAuth['instagram']?.status && <InstagramSearch results={igResults} loading={isIgSearching} error={igError} term={igSearchTerm} />}
{activeTab === 'facebook' && platformsAuth['facebook']?.status && <FacebookSearch results={fbResults} loading={isFbSearching} error={fbError} term={fbSearchTerm} onExport={exportExcel} />}
{activeTab === 'x' && platformsAuth['x']?.status && <XSearch results={xResults} loading={isXSearching} error={xError} term={xSearchTerm} onExport={exportExcel} />}
{activeTab === 'tiktok' && (
<>
{(isTtSearching || ttProgress) && (
<div className="panel px-4 py-2.5 flex items-center justify-between anim-fade-in mb-1">
<span className="text-xs font-mono" style={{ color: 'var(--p-tiktok)' }}>{ttProgress}</span>
{isTtSearching && <div className="prog-bar" style={{ width: '50px' }} />}
</div>
)}
<TikTokSearch results={ttResults} loading={isTtSearching} error={ttError} term={ttSearchTerm} onExport={exportExcel} />
</>
)}
</>
)}
</>
)}
</div>
)}
</main>
</div>
);
}
import React, { useState, useEffect, useRef } from 'react';
import { Api, TelegramClient } from 'telegram';
import { StringSession } from 'telegram/sessions';
import * as XLSX from 'xlsx';
import { Facebook, Twitter, Send, Instagram, Menu, X, Globe, Search, Database, FileText, Upload, Shield, Square, User, Users, Bell, ExternalLink } from 'lucide-react';
import InstagramSearch from './components/InstagramSearch';
import FacebookSearch from './components/FacebookSearch';
import XSearch from './components/XSearch';
import TikTokSearch from './components/TikTokSearch';
import { Music2 } from 'lucide-react';
import { getApiUrl } from './config';
// User must provide these in .env.local
const apiId = Number(import.meta.env.VITE_TELEGRAM_API_ID) || 0;
const apiHash = import.meta.env.VITE_TELEGRAM_API_HASH || "";
// Simple range expander in JS. Equivalent to Python's extend_search_patterns
function expandRange(pattern) {
const chars = [];
const regex = /([a-z0-9])-([a-z0-9])/gi;
let match;
while ((match = regex.exec(pattern)) !== null) {
const start = match[1].charCodeAt(0);
const end = match[2].charCodeAt(0);
for (let c = start; c <= end; c++) {
chars.push(String.fromCharCode(c));
}
}
return chars;
}
function expandSearchPatterns(terms) {
const expandedTerms = [];
for (const term of terms) {
const matches = [...term.matchAll(/\[([^\[\]]+)\]/g)];
if (matches.length === 0) {
expandedTerms.push(term);
continue;
}
const staticParts = [];
const dynamicCharSets = [];
let lastEnd = 0;
for (const match of matches) {
staticParts.push(term.slice(lastEnd, match.index));
const pattern = match[1];
const ranges = pattern.match(/[a-z0-9]-[a-z0-9]/gi);
const singles = pattern.replace(/[a-z0-9]-[a-z0-9]/gi, '');
const charset = ranges ? expandRange(pattern) : [];
charset.push(...singles.split(''));
dynamicCharSets.push(charset);
lastEnd = match.index + match[0].length;
}
staticParts.push(term.slice(lastEnd));
// Cartesian product
const cartesianProduct = (arr) => arr.reduce((a, b) =>
a.flatMap(d => b.map(e => [d, e].flat()))
);
// We handle the edge case where dynamicCharSets only has 1 array differently
const combos = dynamicCharSets.length === 1 ? dynamicCharSets[0].map(x => [x]) : cartesianProduct(dynamicCharSets);
for (const combo of combos) {
let newTerm = '';
for (let i = 0; i < staticParts.length; i++) {
newTerm += staticParts[i] + (combo[i] !== undefined ? combo[i] : '');
}
expandedTerms.push(newTerm);
}
}
return expandedTerms;
}
export default function App() {
const [client, setClient] = useState(null);
const [sessionString, setSessionString] = useState('');
const [step, setStep] = useState('phone'); // phone, code, dashboard
const [activeTab, setActiveTab] = useState(() => localStorage.getItem('lastActiveTab') || 'telegram');
const isRemote = !!import.meta.env.VITE_API_URL;
const [platformsAuth, setPlatformsAuth] = useState({
telegram: { status: false, detail: 'OFFLINE', updated: null },
facebook: { status: false, detail: 'MISSING', updated: null },
x: { status: false, detail: 'MISSING', updated: null },
instagram: { status: false, detail: 'MISSING', updated: null },
tiktok: { status: true, detail: 'PUBLIC_ACCESS', updated: 'LIVE' }
});
const [expansion, setExpansion] = useState('none');
const [localSearchTerm, setLocalSearchTerm] = useState('');
// Auth state
const [phone, setPhone] = useState('');
const [phoneCodeHash, setPhoneCodeHash] = useState('');
const [code, setCode] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');