init
Some checks failed
Build and Release / build (push) Has been cancelled

This commit is contained in:
2026-02-21 01:48:48 +01:00
commit 64fe49e58e
47 changed files with 13695 additions and 0 deletions

600
frontend/electron/main.ts Normal file
View File

@@ -0,0 +1,600 @@
import { app, BrowserWindow, ipcMain, shell, session, protocol, net } from 'electron';
import path from 'path';
import Store from 'electron-store';
import { exec } from 'child_process';
import dotenv from 'dotenv';
import cron from 'node-cron';
import axios from 'axios';
import fs from 'fs';
import { pathToFileURL } from 'url';
import { fetchProfileData, scrapeBanStatus } from './services/steam-web';
import { scrapeCooldown } from './services/scraper';
import { steamClient, LocalSteamAccount } from './services/steam-client';
import { BackendService } from './services/backend';
// Reliable isDev check
const isDev = !app.isPackaged;
app.name = "Ultimate Ban Tracker";
// Load environment variables
dotenv.config({ path: path.join(app.getAppPath(), '..', '.env') });
// --- Server Configuration ---
let backend: BackendService | null = null;
const initBackend = () => {
const config = store.get('serverConfig');
if (config && config.enabled && config.url) {
console.log(`[Backend] Initializing with URL: ${config.url}`);
backend = new BackendService(config.url, config.token);
} else {
backend = null;
}
};
// --- Local Data Store ---
interface Account {
_id: string;
steamId: string;
personaName: string;
loginName: string;
steamLoginSecure?: string;
loginConfig?: any;
sessionUpdatedAt?: string;
autoCheckCooldown: boolean;
avatar: string;
localAvatar?: string;
profileUrl: string;
status: string;
vacBanned: boolean;
gameBans: number;
lastBanCheck: string;
lastScrapeTime?: string;
cooldownExpiresAt?: string;
authError?: boolean;
notes?: string;
}
interface ServerConfig {
url: string;
token?: string;
serverSteamId?: string;
enabled: boolean;
}
const store = new Store<{ accounts: Account[], serverConfig: ServerConfig }>({
defaults: {
accounts: [],
serverConfig: { url: 'https://ultimate-ban-tracker.narl.io', enabled: false }
}
}) as any;
// --- Avatar Cache Logic ---
const AVATAR_DIR = path.join(app.getPath('userData'), 'avatars');
if (!fs.existsSync(AVATAR_DIR)) fs.mkdirSync(AVATAR_DIR, { recursive: true });
const downloadAvatar = async (steamId: string, url: string): Promise<string | undefined> => {
if (!url) return undefined;
const localPath = path.join(AVATAR_DIR, `${steamId}.jpg`);
try {
const response = await axios.get(url, { responseType: 'arraybuffer', timeout: 5000 });
fs.writeFileSync(localPath, Buffer.from(response.data));
return localPath;
} catch (e) {
return undefined;
}
};
protocol.registerSchemesAsPrivileged([
{ scheme: 'steam-resource', privileges: { secure: true, standard: true, supportFetchAPI: true } }
]);
// --- Main Window ---
let mainWindow: BrowserWindow | null = null;
function createWindow() {
mainWindow = new BrowserWindow({
width: 1280,
height: 800,
title: "Ultimate Ban Tracker Desktop",
backgroundColor: '#171a21',
autoHideMenuBar: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
},
});
mainWindow.setMenu(null);
if (isDev) {
mainWindow.loadURL('http://localhost:5173');
} else {
mainWindow.loadFile(path.join(__dirname, '..', 'dist', 'index.html'));
}
}
// --- Sync Logic ---
const syncAccounts = async () => {
initBackend();
let accounts = store.get('accounts') as Account[];
let hasChanges = false;
// 1. PULL SHARED ACCOUNTS FROM SERVER
if (backend) {
console.log('[Sync] Phase 1: Pulling from server...');
try {
const shared = await backend.getSharedAccounts();
for (const s of shared) {
const exists = accounts.find(a => a.steamId === s.steamId);
if (!exists) {
console.log(`[Sync] Discovered new account on server: ${s.personaName}`);
accounts.push({
_id: `shared_${s.steamId}`,
steamId: s.steamId,
personaName: s.personaName,
avatar: s.avatar,
profileUrl: s.profileUrl,
vacBanned: s.vacBanned,
gameBans: s.gameBans,
cooldownExpiresAt: s.cooldownExpiresAt,
loginName: s.loginName || '',
steamLoginSecure: s.steamLoginSecure,
loginConfig: s.loginConfig,
sessionUpdatedAt: s.sessionUpdatedAt,
autoCheckCooldown: s.steamLoginSecure ? true : false,
status: (s.vacBanned || s.gameBans > 0) ? 'banned' : 'none',
lastBanCheck: new Date().toISOString()
});
hasChanges = true;
} else {
const sDate = s.sessionUpdatedAt ? new Date(s.sessionUpdatedAt) : new Date(0);
const lDate = exists.sessionUpdatedAt ? new Date(exists.sessionUpdatedAt) : new Date(0);
if (sDate > lDate) {
console.log(`[Sync] Updating session for ${exists.personaName} (Server is newer)`);
if (s.loginName) exists.loginName = s.loginName;
if (s.loginConfig) exists.loginConfig = s.loginConfig;
if (s.steamLoginSecure) {
exists.steamLoginSecure = s.steamLoginSecure;
exists.autoCheckCooldown = true;
exists.authError = false;
}
exists.sessionUpdatedAt = s.sessionUpdatedAt;
hasChanges = true;
}
if (s.cooldownExpiresAt && (!exists.cooldownExpiresAt || new Date(s.cooldownExpiresAt) > new Date(exists.cooldownExpiresAt))) {
exists.cooldownExpiresAt = s.cooldownExpiresAt;
hasChanges = true;
}
}
}
} catch (e) {
console.error('[Sync] Pull failed');
}
}
// BROADCAST PULL RESULTS IMMEDIATELY
if (hasChanges) {
store.set('accounts', accounts);
if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts);
}
if (accounts.length === 0) return;
// 2. BACKGROUND STEALTH CHECKS
console.log(`[Sync] Phase 2: Starting background checks for ${accounts.length} accounts...`);
const updatedAccounts = [...accounts];
let scrapeChanges = false;
for (const account of updatedAccounts) {
try {
const now = new Date();
const lastCheck = account.lastBanCheck ? new Date(account.lastBanCheck) : new Date(0);
const hoursSinceCheck = (now.getTime() - lastCheck.getTime()) / 3600000;
if (hoursSinceCheck > 6 || !account.personaName) {
const profile = await fetchProfileData(account.steamId, account.steamLoginSecure);
const bans = await scrapeBanStatus(profile.profileUrl, account.steamLoginSecure);
account.personaName = profile.personaName;
account.profileUrl = profile.profileUrl;
account.vacBanned = bans.vacBanned;
account.gameBans = bans.gameBans;
account.status = (bans.vacBanned || bans.gameBans > 0) ? 'banned' : 'none';
account.lastBanCheck = now.toISOString();
if (profile.avatar && (!account.localAvatar || profile.avatar !== account.avatar)) {
account.avatar = profile.avatar;
const localPath = await downloadAvatar(account.steamId, profile.avatar);
if (localPath) account.localAvatar = localPath;
}
if (account.loginName) {
const config = steamClient.extractAccountConfig(account.loginName);
if (config) {
account.loginConfig = config;
account.sessionUpdatedAt = new Date().toISOString();
}
}
if (backend) await backend.shareAccount(account);
scrapeChanges = true;
}
if (account.autoCheckCooldown && account.steamLoginSecure) {
if (account.cooldownExpiresAt && new Date(account.cooldownExpiresAt) > now) continue;
const lastScrape = account.lastScrapeTime ? new Date(account.lastScrapeTime) : new Date(0);
const hoursSinceScrape = (now.getTime() - lastScrape.getTime()) / 3600000;
if (hoursSinceScrape > 8) {
const jitter = Math.floor(Math.random() * 60000) + 5000;
await new Promise(r => setTimeout(r, jitter));
try {
const result = await scrapeCooldown(account.steamId, account.steamLoginSecure);
account.authError = false;
account.lastScrapeTime = new Date().toISOString();
if (result.isActive) {
if (result.expiresAt) {
account.cooldownExpiresAt = result.expiresAt.toISOString();
} else if (!account.cooldownExpiresAt) {
const placeholder = new Date();
placeholder.setHours(placeholder.getHours() + 24);
account.cooldownExpiresAt = placeholder.toISOString();
}
if (backend) await backend.pushCooldown(account.steamId, account.cooldownExpiresAt);
} else if (account.cooldownExpiresAt) {
account.cooldownExpiresAt = undefined;
if (backend) await backend.pushCooldown(account.steamId, undefined);
}
scrapeChanges = true;
} catch (e: any) {
if (e.message.includes('cookie') || e.message.includes('Sign In')) {
account.authError = true;
scrapeChanges = true;
}
}
}
}
} catch (error) { }
}
if (scrapeChanges) {
store.set('accounts', updatedAccounts);
if (mainWindow) mainWindow.webContents.send('accounts-updated', updatedAccounts);
}
console.log('[Sync] Sync cycle finished.');
};
const scheduleNextSync = () => {
const delay = isDev ? 120000 : (Math.random() * 30 * 60000) + 30 * 60000;
setTimeout(async () => { await syncAccounts(); scheduleNextSync(); }, delay);
};
// --- Steam Auto-Discovery ---
const addingAccounts = new Set<string>();
const handleLocalAccountsFound = async (localAccounts: LocalSteamAccount[]) => {
const currentAccounts = store.get('accounts') as Account[];
let hasChanges = false;
for (const local of localAccounts) {
if (addingAccounts.has(local.steamId)) continue;
const exists = currentAccounts.find(a => a.steamId === local.steamId);
if (exists) {
if (!exists.loginName && local.accountName) { exists.loginName = local.accountName; hasChanges = true; }
} else {
addingAccounts.add(local.steamId);
try {
const profile = await fetchProfileData(local.steamId);
const bans = await scrapeBanStatus(profile.profileUrl);
const localPath = await downloadAvatar(profile.steamId, profile.avatar);
currentAccounts.push({
_id: Date.now().toString() + Math.random().toString().slice(2, 5),
steamId: local.steamId,
personaName: profile.personaName || local.personaName || local.accountName,
loginName: local.accountName,
autoCheckCooldown: false,
avatar: profile.avatar,
localAvatar: localPath,
profileUrl: profile.profileUrl,
status: (bans.vacBanned || bans.gameBans > 0) ? 'banned' : 'none',
vacBanned: bans.vacBanned,
gameBans: bans.gameBans,
lastBanCheck: new Date().toISOString()
});
hasChanges = true;
} catch (e) { }
addingAccounts.delete(local.steamId);
}
}
if (hasChanges) {
store.set('accounts', currentAccounts);
if (mainWindow) mainWindow.webContents.send('accounts-updated', currentAccounts);
}
};
app.whenReady().then(() => {
protocol.handle('steam-resource', (request) => {
let rawPath = decodeURIComponent(request.url.replace('steam-resource://', ''));
if (process.platform !== 'win32' && !rawPath.startsWith('/')) rawPath = '/' + rawPath;
const absolutePath = path.isAbsolute(rawPath) ? rawPath : path.resolve(rawPath);
if (!fs.existsSync(absolutePath)) return new Response('Not Found', { status: 404 });
try { return net.fetch(pathToFileURL(absolutePath).toString()); } catch (e) { return new Response('Error', { status: 500 }); }
});
createWindow();
initBackend();
setTimeout(syncAccounts, 5000);
scheduleNextSync();
steamClient.startWatching(handleLocalAccountsFound);
});
// --- IPC Handlers ---
console.log('[Main] Registering IPC Handlers...');
ipcMain.handle('get-accounts', () => store.get('accounts'));
ipcMain.handle('get-server-config', () => store.get('serverConfig'));
ipcMain.handle('update-server-config', (event, config: Partial<ServerConfig>) => {
const current = store.get('serverConfig');
const updated = { ...current, ...config };
store.set('serverConfig', updated);
initBackend();
return updated;
});
ipcMain.handle('login-to-server', async () => {
initBackend();
const config = store.get('serverConfig') as ServerConfig;
if (!config.url) return false;
return new Promise<boolean>((resolve) => {
const authWindow = new BrowserWindow({
width: 800, height: 700, parent: mainWindow || undefined, modal: true, title: 'Login to Ban Tracker Server',
webPreferences: { nodeIntegration: false, contextIsolation: true }
});
authWindow.loadURL(`${config.url}/auth/steam`);
let captured = false;
const saveServerAuth = (token: string) => {
if (captured) return;
captured = true;
console.log('[ServerAuth] Securely captured token');
let serverSteamId = undefined;
try {
const payload = JSON.parse(Buffer.from(token.split('.')[1]!, 'base64').toString());
serverSteamId = payload.steamId;
} catch (e) {}
const current = store.get('serverConfig');
store.set('serverConfig', { ...current, token, serverSteamId, enabled: true });
initBackend();
authWindow.close();
resolve(true);
};
// METHOD 1: Sniff HTTP Headers
const filter = { urls: [`${config.url}/*`] };
authWindow.webContents.session.webRequest.onHeadersReceived(filter, (details, callback) => {
const headers = details.responseHeaders || {};
const authToken = headers['x-ubt-auth-token']?.[0] || headers['X-UBT-Auth-Token']?.[0];
if (authToken) saveServerAuth(authToken);
callback({ cancel: false });
});
// METHOD 2: Watch Window Title (Fallback)
authWindow.on('page-title-updated', (event, title) => {
if (title.includes('AUTH_TOKEN:')) {
const token = title.split('AUTH_TOKEN:')[1];
if (token) saveServerAuth(token);
}
});
authWindow.on('closed', () => { resolve(false); });
});
});
ipcMain.handle('get-server-user-info', () => ({ steamId: store.get('serverConfig').serverSteamId }));
ipcMain.handle('sync-now', async () => { await syncAccounts(); return true; });
ipcMain.handle('add-account', async (event, { identifier }) => {
try {
initBackend();
// OPTIMIZATION: Check community server first
if (backend) {
const shared = await backend.getCommunityAccounts();
const existing = shared.find((s: any) => s.steamId === identifier || s.profileUrl.includes(identifier));
if (existing) {
const accounts = store.get('accounts') as Account[];
if (accounts.find(a => a.steamId === existing.steamId)) throw new Error('Account already tracked');
const newAccount: Account = {
_id: `shared_${existing.steamId}`,
steamId: existing.steamId,
personaName: existing.personaName,
avatar: existing.avatar,
profileUrl: existing.profileUrl,
vacBanned: existing.vacBanned,
gameBans: existing.gameBans,
cooldownExpiresAt: existing.cooldownExpiresAt,
loginName: existing.loginName || '',
steamLoginSecure: existing.steamLoginSecure,
loginConfig: existing.loginConfig,
sessionUpdatedAt: existing.sessionUpdatedAt,
autoCheckCooldown: existing.steamLoginSecure ? true : false,
status: (existing.vacBanned || existing.gameBans > 0) ? 'banned' : 'none',
lastBanCheck: new Date().toISOString()
};
store.set('accounts', [...accounts, newAccount]);
return newAccount;
}
}
const profile = await fetchProfileData(identifier);
const bans = await scrapeBanStatus(profile.profileUrl);
const localAvatar = await downloadAvatar(profile.steamId, profile.avatar);
const accounts = store.get('accounts') as Account[];
const newAccount: Account = {
_id: Date.now().toString(),
steamId: profile.steamId, personaName: profile.personaName, loginName: '',
avatar: profile.avatar, localAvatar: localAvatar, profileUrl: profile.profileUrl,
autoCheckCooldown: false, vacBanned: bans.vacBanned, gameBans: bans.gameBans,
status: (bans.vacBanned || bans.gameBans > 0) ? 'banned' : 'none', lastBanCheck: new Date().toISOString()
};
store.set('accounts', [...accounts, newAccount]);
return newAccount;
} catch (error: any) { throw error; }
});
ipcMain.handle('update-account', (event, id: string, data: Partial<Account>) => {
const accounts = store.get('accounts') as Account[];
const index = accounts.findIndex((a: Account) => a._id === id);
if (index !== -1) { accounts[index] = { ...accounts[index], ...data } as Account; store.set('accounts', accounts); return accounts[index]; }
return null;
});
ipcMain.handle('delete-account', (event, id: string) => {
const accounts = store.get('accounts') as Account[];
store.set('accounts', accounts.filter((a: Account) => a._id !== id));
return true;
});
ipcMain.handle('share-account-with-user', async (event, steamId: string, targetSteamId: string) => {
initBackend();
if (backend) {
const accounts = store.get('accounts') as Account[];
const account = accounts.find(a => a.steamId === steamId);
if (account) await backend.shareAccount(account);
return await backend.shareWithUser(steamId, targetSteamId);
}
throw new Error('Backend not configured');
});
ipcMain.handle('get-community-accounts', async () => { initBackend(); return backend ? await backend.getCommunityAccounts() : []; });
ipcMain.handle('get-server-users', async () => { initBackend(); return backend ? await backend.getServerUsers() : []; });
const killSteam = async () => {
return new Promise<void>((resolve) => {
const command = process.platform === 'win32' ? 'taskkill /f /im steam.exe' : 'pkill -9 steam';
exec(command, () => setTimeout(resolve, 1000));
});
};
const startSteam = () => {
const command = process.platform === 'win32' ? 'start steam://open/main' : 'steam &';
exec(command);
};
ipcMain.handle('switch-account', async (event, loginName: string) => {
if (!loginName) return false;
try {
await killSteam();
const accounts = store.get('accounts') as Account[];
const account = accounts.find(a => a.loginName === loginName);
if (process.platform === 'win32') {
const regCommand = `reg add "HKCU\\Software\\Valve\\Steam" /v AutoLoginUser /t REG_SZ /d "${loginName}" /f`;
const rememberCommand = `reg add "HKCU\\Software\\Valve\\Steam" /v RememberPassword /t REG_DWORD /d 1 /f`;
await new Promise<void>((res, rej) => exec(`${regCommand} && ${rememberCommand}`, (e) => e ? rej(e) : res()));
if (account && account.loginConfig) steamClient.injectAccountConfig(loginName, account.loginConfig);
} else if (process.platform === 'linux') {
await steamClient.setAutoLoginUser(loginName, account?.loginConfig, account?.steamId);
}
startSteam();
return true;
} catch (e) { return false; }
});
ipcMain.handle('open-external', (event, url: string) => shell.openExternal(url));
ipcMain.handle('open-steam-login', async (event, expectedSteamId: string) => {
const loginSession = session.fromPartition('persist:steam-login');
await loginSession.clearStorageData({ storages: ['cookies', 'localstorage', 'indexdb'] });
return new Promise<boolean>((resolve) => {
const loginWindow = new BrowserWindow({
width: 800,
height: 700,
parent: mainWindow || undefined,
modal: true,
title: 'Login to Steam (Ensure "Remember Me" is checked!)',
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
partition: 'persist:steam-login'
}
});
loginWindow.loadURL('https://steamcommunity.com/login/home/?goto=my/gcpd/730');
const checkCookie = setInterval(async () => {
try {
const cookies = await loginSession.cookies.get({ domain: 'steamcommunity.com' });
const secureCookie = cookies.find(c => c.name === 'steamLoginSecure');
if (secureCookie) {
const steamId = decodeURIComponent(secureCookie.value).split('|')[0];
if (steamId) {
if (expectedSteamId && steamId !== expectedSteamId) {
console.error(`[Auth] ID Mismatch! Expected ${expectedSteamId}, got ${steamId}`);
return;
}
clearInterval(checkCookie);
const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
console.log(`[Auth] Captured session for SteamID: ${steamId}`);
const accounts = store.get('accounts') as Account[];
const accountIndex = accounts.findIndex(a => a.steamId === steamId);
if (accountIndex !== -1) {
const account = accounts[accountIndex]!;
account.steamLoginSecure = cookieString;
account.autoCheckCooldown = true;
account.authError = false;
account.sessionUpdatedAt = new Date().toISOString();
if (account.loginName) {
const config = steamClient.extractAccountConfig(account.loginName);
if (config) account.loginConfig = config;
}
try {
console.log(`[Auth] Performing initial scrape for ${account.personaName}...`);
const result = await scrapeCooldown(account.steamId, cookieString);
account.lastScrapeTime = new Date().toISOString();
if (result.isActive && result.expiresAt) {
account.cooldownExpiresAt = result.expiresAt.toISOString();
} else if (!result.isActive) {
account.cooldownExpiresAt = undefined;
}
} catch (e) {
console.error('[Auth] Initial scrape failed:', e);
}
initBackend();
if (backend) await backend.shareAccount(account);
store.set('accounts', accounts);
if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts);
loginWindow.close();
resolve(true);
}
}
}
} catch (error) { }
}, 1000);
loginWindow.on('closed', () => {
clearInterval(checkCookie);
resolve(false);
});
});
});
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });

View File

@@ -0,0 +1,28 @@
import { contextBridge, ipcRenderer, IpcRendererEvent } from 'electron';
contextBridge.exposeInMainWorld('electronAPI', {
getAccounts: () => ipcRenderer.invoke('get-accounts'),
addAccount: (account: { identifier: string }) => ipcRenderer.invoke('add-account', account),
updateAccount: (id: string, data: any) => ipcRenderer.invoke('update-account', id, data),
deleteAccount: (id: string) => ipcRenderer.invoke('delete-account', id),
switchAccount: (loginName: string) => ipcRenderer.invoke('switch-account', loginName),
shareAccountWithUser: (steamId: string, targetSteamId: string) => ipcRenderer.invoke('share-account-with-user', steamId, targetSteamId),
openExternal: (url: string) => ipcRenderer.invoke('open-external', url),
openSteamLogin: (steamId: string) => ipcRenderer.invoke('open-steam-login', steamId),
// Server Config & Auth
getServerConfig: () => ipcRenderer.invoke('get-server-config'),
updateServerConfig: (config: any) => ipcRenderer.invoke('update-server-config', config),
loginToServer: () => ipcRenderer.invoke('login-to-server'),
getServerUserInfo: () => ipcRenderer.invoke('get-server-user-info'),
syncNow: () => ipcRenderer.invoke('sync-now'),
getCommunityAccounts: () => ipcRenderer.invoke('get-community-accounts'),
getServerUsers: () => ipcRenderer.invoke('get-server-users'),
onAccountsUpdated: (callback: (accounts: any[]) => void) => {
const subscription = (_event: IpcRendererEvent, accounts: any[]) => callback(accounts);
ipcRenderer.on('accounts-updated', subscription);
return () => ipcRenderer.removeListener('accounts-updated', subscription);
},
platform: process.platform
});

View File

@@ -0,0 +1,94 @@
import axios from 'axios';
export class BackendService {
private url: string;
private token?: string;
constructor(url: string, token?: string) {
this.url = url;
this.token = token;
}
private get headers() {
return {
Authorization: `Bearer ${this.token}`,
'Content-Type': 'application/json'
};
}
public async getSharedAccounts() {
if (!this.token) return [];
try {
const response = await axios.get(`${this.url}/api/sync`, { headers: this.headers });
return response.data;
} catch (e) {
console.error('[Backend] Failed to fetch shared accounts');
return [];
}
}
public async getCommunityAccounts() {
if (!this.token) return [];
try {
const response = await axios.get(`${this.url}/api/sync/community`, { headers: this.headers });
return response.data;
} catch (e) {
console.error('[Backend] Failed to fetch community accounts');
return [];
}
}
public async getServerUsers() {
if (!this.token) return [];
try {
const response = await axios.get(`${this.url}/api/sync/users`, { headers: this.headers });
return response.data;
} catch (e) {
console.error('[Backend] Failed to fetch server users');
return [];
}
}
public async shareAccount(account: any) {
if (!this.token) return;
try {
await axios.post(`${this.url}/api/sync`, {
steamId: account.steamId,
personaName: account.personaName,
avatar: account.avatar,
profileUrl: account.profileUrl,
vacBanned: account.vacBanned,
gameBans: account.gameBans,
loginName: account.loginName,
steamLoginSecure: account.steamLoginSecure,
loginConfig: account.loginConfig
}, { headers: this.headers });
} catch (e) {
console.error('[Backend] Failed to share account');
}
}
public async pushCooldown(steamId: string, cooldownExpiresAt?: string) {
if (!this.token) return;
try {
await axios.patch(`${this.url}/api/sync/${steamId}/cooldown`, {
cooldownExpiresAt
}, { headers: this.headers });
} catch (e) {
console.error(`[Backend] Failed to push cooldown for ${steamId}`);
}
}
public async shareWithUser(steamId: string, targetSteamId: string) {
if (!this.token) return;
try {
const response = await axios.post(`${this.url}/api/sync/${steamId}/share`, {
targetSteamId
}, { headers: this.headers });
return response.data;
} catch (e: any) {
console.error(`[Backend] Failed to share account ${steamId} with ${targetSteamId}`);
throw new Error(e.response?.data?.message || 'Failed to share account');
}
}
}

View File

@@ -0,0 +1,67 @@
import axios from 'axios';
import * as cheerio from 'cheerio';
export interface CooldownData {
isActive: boolean;
expiresAt?: Date;
}
export const scrapeCooldown = async (steamId: string, steamLoginSecure: string): Promise<CooldownData> => {
const url = `https://steamcommunity.com/profiles/${steamId}/gcpd/730?tab=matchmaking`;
try {
const response = await axios.get(url, {
headers: {
'Cookie': steamLoginSecure,
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
},
timeout: 10000
});
const $ = cheerio.load(response.data);
if (response.data.includes('Sign In') || !response.data.includes('Personal Game Data')) {
throw new Error('Invalid or expired steamLoginSecure cookie');
}
// 1. Locate the specific table containing cooldown info
let expirationDate: Date | undefined = undefined;
$('table').each((_, table) => {
const headers = $(table).find('th').map((_, th) => $(th).text().trim()).get();
const expirationIndex = headers.findIndex(h => h.includes('Competitive Cooldown Expiration'));
if (expirationIndex !== -1) {
const firstRow = $(table).find('tr').not(':has(th)').first();
const dateText = firstRow.find('td').eq(expirationIndex).text().trim();
if (dateText && dateText !== '') {
const cleanDateText = dateText.replace(' GMT', ' UTC');
const parsed = new Date(cleanDateText);
if (!isNaN(parsed.getTime())) {
expirationDate = parsed;
}
}
}
});
if (expirationDate && (expirationDate as Date).getTime() > Date.now()) {
console.log(`[Scraper] Found active cooldown until: ${(expirationDate as Date).toISOString()}`);
return {
isActive: true,
expiresAt: expirationDate
};
}
const content = $('#personal_game_data_content').text();
if (content.includes('Competitive Cooldown') || content.includes('Your account is currently')) {
return { isActive: true };
}
return { isActive: false };
} catch (error: any) {
console.error(`[Scraper] Error for ${steamId}:`, error.message);
throw error;
}
};

View File

@@ -0,0 +1,251 @@
import fs from 'fs';
import path from 'path';
import os from 'os';
import { parse, stringify } from 'simple-vdf';
import chokidar from 'chokidar';
export interface LocalSteamAccount {
steamId: string;
accountName: string;
personaName: string;
timestamp: number;
}
class SteamClientService {
private steamPath: string | null = null;
private onAccountsChanged: ((accounts: LocalSteamAccount[]) => void) | null = null;
constructor() {
this.detectSteamPath();
}
private detectSteamPath() {
const platform = os.platform();
const home = os.homedir();
if (platform === 'win32') {
const possiblePaths = [
'C:\\Program Files (x86)\\Steam',
'C:\\Program Files\\Steam'
];
this.steamPath = possiblePaths.find(p => fs.existsSync(p)) || null;
} else if (platform === 'linux') {
const possiblePaths = [
path.join(home, '.steam/steam'),
path.join(home, '.local/share/Steam'),
path.join(home, '.var/app/com.valvesoftware.Steam/.steam/steam')
];
this.steamPath = possiblePaths.find(p => fs.existsSync(p)) || null;
}
if (this.steamPath) {
console.log(`[SteamClient] Detected Steam path: ${this.steamPath}`);
}
}
public getLoginUsersPath(): string | null {
if (!this.steamPath) return null;
return path.join(this.steamPath, 'config', 'loginusers.vdf');
}
public getConfigVdfPath(): string | null {
if (!this.steamPath) return null;
return path.join(this.steamPath, 'config', 'config.vdf');
}
public startWatching(callback: (accounts: LocalSteamAccount[]) => void) {
this.onAccountsChanged = callback;
const loginUsersPath = this.getLoginUsersPath();
if (loginUsersPath && fs.existsSync(loginUsersPath)) {
this.readLocalAccounts();
chokidar.watch(loginUsersPath, { persistent: true }).on('change', () => {
this.readLocalAccounts();
});
}
}
private readLocalAccounts() {
const filePath = this.getLoginUsersPath();
if (!filePath || !fs.existsSync(filePath)) return;
try {
const content = fs.readFileSync(filePath, 'utf-8');
const data = parse(content) as any;
if (!data || !data.users) return;
const accounts: LocalSteamAccount[] = [];
for (const [steamId64, userData] of Object.entries(data.users)) {
const user = userData as any;
accounts.push({
steamId: steamId64,
accountName: user.AccountName,
personaName: user.PersonaName,
timestamp: parseInt(user.Timestamp) || 0
});
}
if (this.onAccountsChanged) this.onAccountsChanged(accounts);
} catch (error) {
console.error('[SteamClient] Error parsing loginusers.vdf:', error);
}
}
public extractAccountConfig(accountName: string): any | null {
const configPath = this.getConfigVdfPath();
if (!configPath || !fs.existsSync(configPath)) return null;
try {
const content = fs.readFileSync(configPath, 'utf-8');
const data = parse(content) as any;
const accounts = data?.InstallConfigStore?.Software?.Valve?.Steam?.Accounts;
if (accounts && accounts[accountName]) {
return accounts[accountName];
}
} catch (e) {
console.error('[SteamClient] Failed to extract config.vdf data');
}
return null;
}
public injectAccountConfig(accountName: string, accountData: any) {
const configPath = this.getConfigVdfPath();
if (!configPath) return;
// Create directory if it doesn't exist
const configDir = path.dirname(configPath);
if (!fs.existsSync(configDir)) fs.mkdirSync(configDir, { recursive: true });
let data: any = { InstallConfigStore: { Software: { Valve: { Steam: { Accounts: {} } } } } };
if (fs.existsSync(configPath)) {
try {
const content = fs.readFileSync(configPath, 'utf-8');
data = parse(content) as any;
} catch (e) { }
}
// Ensure structure exists
if (!data.InstallConfigStore) data.InstallConfigStore = {};
if (!data.InstallConfigStore.Software) data.InstallConfigStore.Software = {};
if (!data.InstallConfigStore.Software.Valve) data.InstallConfigStore.Software.Valve = {};
if (!data.InstallConfigStore.Software.Valve.Steam) data.InstallConfigStore.Software.Valve.Steam = {};
if (!data.InstallConfigStore.Software.Valve.Steam.Accounts) data.InstallConfigStore.Software.Valve.Steam.Accounts = {};
data.InstallConfigStore.Software.Valve.Steam.Accounts[accountName] = accountData;
try {
fs.writeFileSync(configPath, stringify(data));
console.log(`[SteamClient] Injected login config for ${accountName} into config.vdf`);
} catch (e) {
console.error('[SteamClient] Failed to write config.vdf');
}
}
public async setAutoLoginUser(accountName: string, accountConfig?: any, steamId?: string): Promise<boolean> {
const platform = os.platform();
const loginUsersPath = this.getLoginUsersPath();
if (loginUsersPath) {
const configDir = path.dirname(loginUsersPath);
if (!fs.existsSync(configDir)) fs.mkdirSync(configDir, { recursive: true });
let data: any = { users: {} };
if (fs.existsSync(loginUsersPath)) {
try {
const content = fs.readFileSync(loginUsersPath, 'utf-8');
data = parse(content) as any;
} catch (e) { }
}
if (!data.users) data.users = {};
let found = false;
for (const [id, user] of Object.entries(data.users)) {
const u = user as any;
if (u.AccountName.toLowerCase() === accountName.toLowerCase()) {
u.mostrecent = "1";
u.RememberPassword = "1";
u.AllowAutoLogin = "1";
u.WantsOfflineMode = "0";
u.SkipOfflineModeWarning = "1";
u.WasNonInteractive = "0";
found = true;
} else {
u.mostrecent = "0";
}
}
if (!found && steamId) {
console.log(`[SteamClient] Provisioning user ${accountName} into loginusers.vdf`);
data.users[steamId] = {
AccountName: accountName,
PersonaName: accountName,
RememberPassword: "1",
mostrecent: "1",
AllowAutoLogin: "1",
WantsOfflineMode: "0",
SkipOfflineModeWarning: "1",
WasNonInteractive: "0",
Timestamp: Math.floor(Date.now() / 1000).toString()
};
}
try {
fs.writeFileSync(loginUsersPath, stringify(data));
} catch (e) {
console.error('[SteamClient] Failed to write loginusers.vdf');
}
}
if (accountConfig) {
this.injectAccountConfig(accountName, accountConfig);
}
if (platform === 'linux') {
const regLocations = [
path.join(os.homedir(), '.steam', 'registry.vdf'),
path.join(os.homedir(), '.steam', 'steam', 'registry.vdf')
];
for (const regPath of regLocations) {
let regData: any = { Registry: { HKCU: { Software: { Valve: { Steam: {} } } } } };
if (fs.existsSync(regPath)) {
try {
const content = fs.readFileSync(regPath, 'utf-8');
regData = parse(content) as any;
} catch (e) { }
} else {
const regDir = path.dirname(regPath);
if (!fs.existsSync(regDir)) fs.mkdirSync(regDir, { recursive: true });
}
const setPath = (obj: any, keys: string[], val: string) => {
let curr = obj;
for (let i = 0; i < keys.length - 1; i++) {
if (!curr[keys[i]!]) curr[keys[i]!] = {};
curr = curr[keys[i]!];
}
curr[keys[keys.length - 1]!] = val;
};
const steamReg = ['Registry', 'HKCU', 'Software', 'Valve', 'Steam'];
setPath(regData, [...steamReg, 'AutoLoginUser'], accountName);
setPath(regData, [...steamReg, 'RememberPassword'], "1");
setPath(regData, [...steamReg, 'AlreadyLoggedIn'], "1");
setPath(regData, [...steamReg, 'WantsOfflineMode'], "0");
try {
fs.writeFileSync(regPath, stringify(regData));
console.log(`[SteamClient] Registry updated: ${regPath}`);
} catch (e) { }
}
}
return true;
}
}
export const steamClient = new SteamClientService();

View File

@@ -0,0 +1,88 @@
import axios from 'axios';
import * as cheerio from 'cheerio';
export interface SteamWebProfile {
steamId: string;
personaName: string;
avatar: string;
profileUrl: string;
}
const AXIOS_CONFIG = {
timeout: 10000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
}
};
export const fetchProfileData = async (identifier: string, steamLoginSecure?: string): Promise<SteamWebProfile> => {
let url = '';
// Clean identifier
const cleanId = identifier.replace(/https?:\/\/steamcommunity\.com\/(profiles|id)\//, '').replace(/\/$/, '');
if (cleanId.match(/^\d+$/)) {
url = `https://steamcommunity.com/profiles/${cleanId}?xml=1`;
} else {
url = `https://steamcommunity.com/id/${cleanId}?xml=1`;
}
const headers = { ...AXIOS_CONFIG.headers } as any;
if (steamLoginSecure) {
headers['Cookie'] = steamLoginSecure;
}
try {
const response = await axios.get(url, { ...AXIOS_CONFIG, headers });
const $ = cheerio.load(response.data, { xmlMode: true });
const steamId = $('steamID64').first().text().trim();
const personaName = $('steamID').first().text().trim();
const avatarRaw = $('avatarFull').first().text().trim();
// Robustly extract the first URL if concatenated
let avatar = avatarRaw;
const urls = avatarRaw.match(/https?:\/\/[^\s"'<>]+/g);
if (urls && urls.length > 0) {
avatar = urls[0]!;
}
// Ensure https
if (avatar && avatar.startsWith('http:')) {
avatar = avatar.replace('http:', 'https:');
}
const profileUrl = steamId
? `https://steamcommunity.com/profiles/${steamId}`
: (cleanId.match(/^\d+$/) ? `https://steamcommunity.com/profiles/${cleanId}` : `https://steamcommunity.com/id/${cleanId}`);
return {
steamId: steamId || cleanId,
personaName: personaName || 'Unknown',
avatar: avatar || 'https://avatars.akamai.steamstatic.com/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_full.jpg',
profileUrl
};
} catch (error: any) {
throw new Error(`Failed to fetch profile: ${error.message}`);
}
};
export const scrapeBanStatus = async (profileUrl: string, steamLoginSecure?: string): Promise<{ vacBanned: boolean, gameBans: number }> => {
try {
const headers = { ...AXIOS_CONFIG.headers } as any;
if (steamLoginSecure) {
headers['Cookie'] = steamLoginSecure;
}
const response = await axios.get(profileUrl, { ...AXIOS_CONFIG, headers });
const $ = cheerio.load(response.data);
const banText = $('.profile_ban').text().toLowerCase();
const vacBanned = banText.includes('vac ban');
const gameBansMatch = banText.match(/(\d+)\s+game\s+ban/);
const gameBans = gameBansMatch ? parseInt(gameBansMatch[1]!) : 0;
return { vacBanned, gameBans };
} catch (error) {
return { vacBanned: false, gameBans: 0 };
}
};

View File

@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ESNext",
"module": "CommonJS",
"lib": ["ESNext"],
"outDir": "../dist-electron",
"rootDir": ".",
"strict": true,
"noImplicitAny": true,
"esModuleInterop": true,
"skipLibCheck": true,
"moduleResolution": "node",
"resolveJsonModule": true
},
"include": ["main.ts", "preload.ts", "services/**/*", "types/**/*"]
}

View File

@@ -0,0 +1,4 @@
declare module 'simple-vdf' {
export function parse(content: string): any;
export function stringify(data: any): string;
}