570 lines
30 KiB
TypeScript
570 lines
30 KiB
TypeScript
import { app, BrowserWindow, ipcMain, shell, session, protocol, net, Tray, Menu, nativeImage } from 'electron';
|
|
import path from 'path';
|
|
import Store from 'electron-store';
|
|
import { exec } from 'child_process';
|
|
import dotenv from 'dotenv';
|
|
import axios from 'axios';
|
|
import fs from 'fs';
|
|
import { pathToFileURL } from 'url';
|
|
import { fetchProfileData, scrapeBanStatus } from './services/steam-web';
|
|
import { scrapeCooldown, SteamAuthError } 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') });
|
|
|
|
// --- Types & Interfaces ---
|
|
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;
|
|
sharedWith?: any[];
|
|
}
|
|
|
|
interface ServerConfig {
|
|
url: string;
|
|
token?: string;
|
|
serverSteamId?: string;
|
|
enabled: boolean;
|
|
theme?: string;
|
|
isAdmin?: boolean;
|
|
}
|
|
|
|
// --- App State ---
|
|
let mainWindow: BrowserWindow | null = null;
|
|
let tray: Tray | null = null;
|
|
let backend: BackendService | null = null;
|
|
(app as any).isQuitting = false;
|
|
|
|
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; }
|
|
};
|
|
|
|
// --- Backend ---
|
|
const initBackend = () => {
|
|
const config = store.get('serverConfig');
|
|
if (config && config.enabled && config.url) {
|
|
backend = new BackendService(config.url, config.token);
|
|
} else { backend = null; }
|
|
};
|
|
|
|
// --- System Tray ---
|
|
const createTray = () => {
|
|
const possiblePaths = [
|
|
'/usr/share/pixmaps/ultimate-ban-tracker.png',
|
|
path.join(process.resourcesPath, 'assets-build', 'icon.png'),
|
|
path.join(app.getAppPath(), 'assets-build', 'icon.png'),
|
|
path.join(__dirname, '..', 'assets-build', 'icon.png')
|
|
];
|
|
|
|
let iconPath = '';
|
|
for (const p of possiblePaths) { if (p && fs.existsSync(p)) { iconPath = p; break; } }
|
|
|
|
if (!iconPath) { try { tray = new Tray(nativeImage.createEmpty()); } catch (e) {} return; }
|
|
|
|
try {
|
|
const icon = nativeImage.createFromPath(iconPath).resize({ width: 16, height: 16 });
|
|
tray = new Tray(icon);
|
|
tray.setToolTip('Ultimate Ban Tracker');
|
|
if (process.platform === 'linux') tray.setIgnoreMouseEvents(false);
|
|
tray.on('click', () => { if (mainWindow) { mainWindow.show(); mainWindow.focus(); } });
|
|
updateTrayMenu();
|
|
const config = store.get('serverConfig');
|
|
if (config?.theme) setAppIcon(config.theme);
|
|
} catch (e: any) { console.error(`[Tray] Error: ${e.message}`); }
|
|
};
|
|
|
|
const updateTrayMenu = () => {
|
|
if (!tray) return;
|
|
const accounts = store.get('accounts') as Account[];
|
|
const config = store.get('serverConfig');
|
|
const contextMenu = Menu.buildFromTemplate([
|
|
{ label: `Ultimate Ban Tracker v${app.getVersion()}`, enabled: false },
|
|
{ type: 'separator' },
|
|
{
|
|
label: 'Switch Account',
|
|
submenu: accounts.length > 0 ? accounts.map(acc => ({
|
|
label: `${acc.personaName} ${acc.loginName ? `(${acc.loginName})` : ''}`,
|
|
enabled: !!acc.loginName,
|
|
click: () => handleSwitchAccount(acc.loginName)
|
|
})) : [{ label: 'No accounts found', enabled: false }]
|
|
},
|
|
{ label: 'Sync Now', enabled: !!config?.enabled, click: () => syncAccounts(true) },
|
|
{ type: 'separator' },
|
|
{ label: 'Show Dashboard', click: () => { if (mainWindow) { mainWindow.show(); mainWindow.focus(); } } },
|
|
{ label: 'Quit', click: () => {
|
|
(app as any).isQuitting = true;
|
|
if (tray) tray.destroy();
|
|
app.quit();
|
|
} }
|
|
]);
|
|
tray.setContextMenu(contextMenu);
|
|
};
|
|
|
|
const setAppIcon = (themeName: string = 'steam') => {
|
|
const possiblePaths = [
|
|
path.join(__dirname, '..', 'assets-build', 'icons', `${themeName}.svg`),
|
|
path.join(app.getAppPath(), 'assets-build', 'icons', `${themeName}.svg`),
|
|
'/usr/share/pixmaps/ultimate-ban-tracker.png'
|
|
];
|
|
let iconPath = '';
|
|
for (const p of possiblePaths) { if (fs.existsSync(p)) { iconPath = p; break; } }
|
|
if (!iconPath) return;
|
|
const icon = nativeImage.createFromPath(iconPath);
|
|
if (tray) tray.setImage(icon.resize({ width: 16, height: 16 }));
|
|
if (mainWindow) mainWindow.setIcon(icon);
|
|
updateTrayMenu();
|
|
};
|
|
|
|
// --- Steam Logic ---
|
|
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);
|
|
};
|
|
|
|
const handleSwitchAccount = async (loginName: string) => {
|
|
if (!loginName) return false;
|
|
try {
|
|
const accounts = store.get('accounts') as Account[];
|
|
const account = accounts.find(a => a.loginName === loginName);
|
|
if (account && !account._id.startsWith('shared_')) {
|
|
const freshConfig = steamClient.extractAccountConfig(loginName);
|
|
if (freshConfig) {
|
|
account.loginConfig = freshConfig;
|
|
account.sessionUpdatedAt = new Date().toISOString();
|
|
if (backend) await backend.shareAccount(account);
|
|
store.set('accounts', accounts);
|
|
}
|
|
}
|
|
await killSteam();
|
|
if (process.platform === 'win32') {
|
|
const regBase = 'reg add "HKCU\\Software\\Valve\\Steam"';
|
|
const commands = [`${regBase} /v AutoLoginUser /t REG_SZ /d "${loginName}" /f`,`${regBase} /v RememberPassword /t REG_DWORD /d 1 /f`,`${regBase} /v AlreadyLoggedIn /t REG_DWORD /d 1 /f`,`${regBase} /v WantsOfflineMode /t REG_DWORD /d 0 /f`];
|
|
await new Promise<void>((res, rej) => exec(commands.join(' && '), (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; }
|
|
};
|
|
|
|
// --- Scraper Helper ---
|
|
const scrapeAccountData = async (account: Account) => {
|
|
const now = new Date();
|
|
try {
|
|
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.steamLoginSecure) {
|
|
try {
|
|
const result = await scrapeCooldown(account.steamId, account.steamLoginSecure);
|
|
account.authError = false; account.lastScrapeTime = now.toISOString();
|
|
if (result.isActive) {
|
|
account.cooldownExpiresAt = result.expiresAt ? result.expiresAt.toISOString() : new Date(Date.now() + 86400000).toISOString();
|
|
if (backend) await backend.pushCooldown(account.steamId, account.cooldownExpiresAt, now.toISOString());
|
|
} else {
|
|
account.cooldownExpiresAt = undefined;
|
|
if (backend) await backend.pushCooldown(account.steamId, undefined, now.toISOString());
|
|
}
|
|
} catch (e: any) { if (e instanceof SteamAuthError) account.authError = true; }
|
|
}
|
|
if (backend && !account._id.startsWith('shared_')) await backend.shareAccount(account);
|
|
return true;
|
|
} catch (e) { return false; }
|
|
};
|
|
|
|
// --- Sync Worker ---
|
|
const syncAccounts = async (isManual = false) => {
|
|
initBackend();
|
|
let accounts = store.get('accounts') as Account[];
|
|
let hasChanges = false;
|
|
if (backend) {
|
|
try {
|
|
const shared = await backend.getSharedAccounts();
|
|
for (const s of shared) {
|
|
const exists = accounts.find(a => a.steamId === s.steamId);
|
|
if (!exists) {
|
|
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, status: (s.vacBanned || s.gameBans > 0) ? 'banned' : 'none',
|
|
lastBanCheck: new Date().toISOString(), sharedWith: s.sharedWith
|
|
});
|
|
hasChanges = true;
|
|
} else {
|
|
const sSessionDate = s.sessionUpdatedAt ? new Date(s.sessionUpdatedAt) : new Date(0);
|
|
const lSessionDate = exists.sessionUpdatedAt ? new Date(exists.sessionUpdatedAt) : new Date(0);
|
|
const isLocalAccount = !exists._id.startsWith('shared_');
|
|
const isLocalSessionHealthy = exists.steamLoginSecure && !exists.authError;
|
|
const shouldOverwriteCredentials = !isLocalAccount ? (sSessionDate > lSessionDate) : (!isLocalSessionHealthy && sSessionDate > lSessionDate);
|
|
if (shouldOverwriteCredentials) {
|
|
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;
|
|
}
|
|
const sMetaDate = s.lastMetadataCheck ? new Date(s.lastMetadataCheck) : new Date(0);
|
|
const lMetaDate = exists.lastBanCheck ? new Date(exists.lastBanCheck) : new Date(0);
|
|
if (sMetaDate > lMetaDate) {
|
|
exists.personaName = s.personaName; exists.avatar = s.avatar;
|
|
exists.vacBanned = s.vacBanned; exists.gameBans = s.gameBans;
|
|
exists.status = (s.vacBanned || s.gameBans > 0) ? 'banned' : 'none';
|
|
exists.lastBanCheck = s.lastMetadataCheck;
|
|
hasChanges = true;
|
|
}
|
|
const sScrapeDate = s.lastScrapeTime ? new Date(s.lastScrapeTime) : new Date(0);
|
|
const lScrapeDate = exists.lastScrapeTime ? new Date(exists.lastScrapeTime) : new Date(0);
|
|
if (sScrapeDate > lScrapeDate) {
|
|
exists.cooldownExpiresAt = s.cooldownExpiresAt;
|
|
exists.lastScrapeTime = s.lastScrapeTime;
|
|
hasChanges = true;
|
|
}
|
|
if (JSON.stringify(exists.sharedWith) !== JSON.stringify(s.sharedWith)) { exists.sharedWith = s.sharedWith; hasChanges = true; }
|
|
}
|
|
}
|
|
} catch (e) { }
|
|
}
|
|
if (hasChanges) { store.set('accounts', accounts); if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts); updateTrayMenu(); }
|
|
|
|
const runScrapes = async () => {
|
|
const currentAccounts = [...store.get('accounts') as Account[]];
|
|
let scrapeChanges = false;
|
|
for (const account of currentAccounts) {
|
|
try {
|
|
const now = new Date();
|
|
if (backend && !account._id.startsWith('shared_')) await backend.shareAccount(account);
|
|
const lastCheck = account.lastBanCheck ? new Date(account.lastBanCheck) : new Date(0);
|
|
const lastScrape = account.lastScrapeTime ? new Date(account.lastScrapeTime) : new Date(0);
|
|
const needsMetadata = (now.getTime() - lastCheck.getTime()) / 3600000 > 6 || !account.personaName;
|
|
const needsCooldown = account.autoCheckCooldown && account.steamLoginSecure && (now.getTime() - lastScrape.getTime()) / 3600000 > 8;
|
|
if (needsMetadata || needsCooldown || isManual) {
|
|
if (!isManual && needsCooldown) await new Promise(r => setTimeout(r, Math.floor(Math.random() * 30000) + 5000));
|
|
if (await scrapeAccountData(account)) scrapeChanges = true;
|
|
}
|
|
} catch (error) { }
|
|
}
|
|
if (scrapeChanges) { store.set('accounts', currentAccounts); if (mainWindow) mainWindow.webContents.send('accounts-updated', currentAccounts); updateTrayMenu(); }
|
|
};
|
|
if (isManual) await runScrapes(); else runScrapes();
|
|
};
|
|
|
|
const scheduleNextSync = () => { setTimeout(async () => { await syncAccounts(false); scheduleNextSync(); }, isDev ? 300000 : 1800000); };
|
|
|
|
// --- 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);
|
|
let loginConfig = undefined;
|
|
for (let i = 0; i < 3; i++) { await new Promise(r => setTimeout(r, 2000)); loginConfig = steamClient.extractAccountConfig(local.accountName); if (loginConfig) break; }
|
|
currentAccounts.push({
|
|
_id: Date.now().toString() + Math.random().toString().slice(2, 5),
|
|
steamId: local.steamId, personaName: profile.personaName || local.accountName,
|
|
loginName: local.accountName, autoCheckCooldown: false, avatar: profile.avatar,
|
|
localAvatar: localPath, profileUrl: profile.profileUrl,
|
|
loginConfig, sessionUpdatedAt: loginConfig ? new Date().toISOString() : undefined,
|
|
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); updateTrayMenu(); }
|
|
};
|
|
|
|
// --- Single Instance & Window ---
|
|
const gotTheLock = app.requestSingleInstanceLock();
|
|
if (!gotTheLock) {
|
|
app.quit();
|
|
} else {
|
|
app.on('second-instance', () => { if (mainWindow) { if (mainWindow.isMinimized()) mainWindow.restore(); mainWindow.show(); mainWindow.focus(); } });
|
|
|
|
function createWindow() {
|
|
mainWindow = new BrowserWindow({
|
|
width: 1280, height: 800, title: "Ultimate Ban Tracker", backgroundColor: '#171a21', autoHideMenuBar: true,
|
|
webPreferences: { preload: path.join(__dirname, 'preload.js'), nodeIntegration: false, contextIsolation: true }
|
|
});
|
|
mainWindow.setMenu(null);
|
|
mainWindow.on('close', (event) => { if (!(app as any).isQuitting) { event.preventDefault(); mainWindow?.hide(); } return false; });
|
|
if (isDev) mainWindow.loadURL('http://localhost:5173');
|
|
else mainWindow.loadFile(path.join(__dirname, '..', 'dist', 'index.html'));
|
|
}
|
|
|
|
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(); createTray(); initBackend();
|
|
setTimeout(() => syncAccounts(false), 5000); scheduleNextSync();
|
|
steamClient.startWatching(handleLocalAccountsFound);
|
|
});
|
|
}
|
|
|
|
app.on('before-quit', () => { (app as any).isQuitting = true; if (tray) tray.destroy(); });
|
|
app.on('window-all-closed', () => { if (process.platform !== 'darwin' && (app as any).isQuitting) app.quit(); });
|
|
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0 && gotTheLock) createWindow(); else mainWindow?.show(); });
|
|
|
|
const handleSignal = (signal: string) => {
|
|
if (!(app as any).isQuitting && mainWindow) { mainWindow.hide(); }
|
|
else if ((app as any).isQuitting) { app.quit(); }
|
|
};
|
|
process.on('SIGINT', () => handleSignal('SIGINT'));
|
|
process.on('SIGTERM', () => handleSignal('SIGTERM'));
|
|
|
|
// --- 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 Server', webPreferences: { nodeIntegration: false, contextIsolation: true } });
|
|
authWindow.loadURL(`${config.url}/auth/steam`);
|
|
let captured = false;
|
|
const saveServerAuth = (token: string) => {
|
|
if (captured) return; captured = true;
|
|
let serverSteamId = undefined; let isAdmin = false;
|
|
try { const payload = JSON.parse(Buffer.from(token.split('.')[1]!, 'base64').toString()); serverSteamId = payload.steamId; isAdmin = !!payload.isAdmin; } catch (e) {}
|
|
const current = store.get('serverConfig');
|
|
store.set('serverConfig', { ...current, token, serverSteamId, isAdmin, enabled: true });
|
|
initBackend(); authWindow.close(); resolve(true);
|
|
};
|
|
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 });
|
|
});
|
|
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(true); return true; });
|
|
ipcMain.handle('scrape-account', async (event, steamId: string) => {
|
|
const accounts = store.get('accounts') as Account[];
|
|
const account = accounts.find(a => a.steamId === steamId);
|
|
if (!account) return false;
|
|
const success = await scrapeAccountData(account);
|
|
if (success) { store.set('accounts', accounts); if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts); updateTrayMenu(); }
|
|
return success;
|
|
});
|
|
ipcMain.handle('add-account', async (event, { identifier }) => {
|
|
try {
|
|
initBackend();
|
|
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, status: (existing.vacBanned || existing.gameBans > 0) ? 'banned' : 'none',
|
|
lastBanCheck: new Date().toISOString(), sharedWith: existing.sharedWith
|
|
};
|
|
store.set('accounts', [...accounts, newAccount]); updateTrayMenu(); 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]); updateTrayMenu(); 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); updateTrayMenu(); 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)); updateTrayMenu(); 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('revoke-account-access', async (event, steamId: string, targetSteamId: string) => { initBackend(); if (backend) return await backend.revokeAccess(steamId, targetSteamId); throw new Error('Backend not configured'); });
|
|
ipcMain.handle('revoke-all-account-access', async (event, steamId: string) => { initBackend(); if (backend) return await backend.revokeAllAccess(steamId); 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() : []; });
|
|
ipcMain.handle('admin-get-stats', async () => { initBackend(); return backend ? await backend.getAdminStats() : null; });
|
|
ipcMain.handle('admin-get-users', async () => { initBackend(); return backend ? await backend.getAdminUsers() : []; });
|
|
ipcMain.handle('admin-delete-user', async (event, userId: string) => { initBackend(); if (backend) await backend.deleteUser(userId); return true; });
|
|
ipcMain.handle('admin-get-accounts', async () => { initBackend(); return backend ? await backend.getAdminAccounts() : []; });
|
|
ipcMain.handle('admin-remove-account', async (event, steamId: string) => { initBackend(); if (backend) await backend.forceRemoveAccount(steamId); return true; });
|
|
ipcMain.handle('force-sync', async () => { await syncAccounts(true); return true; });
|
|
ipcMain.handle('update-app-icon', (event, themeName: string) => { setAppIcon(themeName); return true; });
|
|
ipcMain.handle('switch-account', async (event, loginName: string) => {
|
|
if (!loginName) return false;
|
|
try {
|
|
const accounts = store.get('accounts') as Account[];
|
|
const account = accounts.find(a => a.loginName === loginName);
|
|
if (account && !account._id.startsWith('shared_')) {
|
|
const freshConfig = steamClient.extractAccountConfig(loginName);
|
|
if (freshConfig) { account.loginConfig = freshConfig; account.sessionUpdatedAt = new Date().toISOString(); if (backend) await backend.shareAccount(account); store.set('accounts', accounts); }
|
|
}
|
|
await killSteam();
|
|
if (process.platform === 'win32') {
|
|
const regBase = 'reg add "HKCU\\Software\\Valve\\Steam"';
|
|
const commands = [`${regBase} /v AutoLoginUser /t REG_SZ /d "${loginName}" /f`,`${regBase} /v RememberPassword /t REG_DWORD /d 1 /f`,`${regBase} /v AlreadyLoggedIn /t REG_DWORD /d 1 /f`,`${regBase} /v WantsOfflineMode /t REG_DWORD /d 0 /f`];
|
|
await new Promise<void>((res, rej) => exec(commands.join(' && '), (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-app-login', async () => {
|
|
await killSteam();
|
|
if (process.platform === 'win32') {
|
|
const clearReg = 'reg add "HKCU\\Software\\Valve\\Steam" /v AutoLoginUser /t REG_SZ /d "" /f';
|
|
await new Promise<void>((res) => exec(clearReg, () => res()));
|
|
} else if (process.platform === 'linux') { await steamClient.setAutoLoginUser("", undefined, ""); }
|
|
const command = process.platform === 'win32' ? 'start steam://open/login' : 'xdg-open steam://open/login';
|
|
exec(command); return true;
|
|
});
|
|
ipcMain.handle('open-steam-login', async (event, expectedSteamId: string) => {
|
|
const partitionId = expectedSteamId ? `persist:steam-login-${expectedSteamId}` : 'persist:steam-login-new';
|
|
const loginSession = session.fromPartition(partitionId);
|
|
if (!expectedSteamId) await loginSession.clearStorageData({ storages: ['cookies', 'localstorage', 'indexdb'] });
|
|
if (expectedSteamId) {
|
|
const accounts = store.get('accounts') as Account[];
|
|
const account = accounts.find(a => a.steamId === expectedSteamId);
|
|
if (account?.steamLoginSecure) {
|
|
const cookiePairs = account.steamLoginSecure.split(';').map(c => c.trim());
|
|
for (const pair of cookiePairs) {
|
|
const [name, value] = pair.split('=');
|
|
if (name && value) {
|
|
try { await loginSession.cookies.set({ url: 'https://steamcommunity.com', domain: 'steamcommunity.com', name, value, path: '/', secure: true, httpOnly: name.includes('Secure') }); } catch (e) {}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return new Promise<boolean>((resolve) => {
|
|
const loginWindow = new BrowserWindow({ width: 800, height: 700, parent: mainWindow || undefined, modal: true, title: 'Login to Steam', webPreferences: { nodeIntegration: false, contextIsolation: true, partition: partitionId } });
|
|
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) return;
|
|
clearInterval(checkCookie);
|
|
const cookieString = cookies.map(c => `${c.name}=${c.value}`).join('; ');
|
|
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 { const result = await scrapeCooldown(account.steamId, cookieString); account.lastScrapeTime = new Date().toISOString(); account.cooldownExpiresAt = result.isActive && result.expiresAt ? result.expiresAt.toISOString() : undefined; } catch (e) { }
|
|
initBackend(); if (backend) await backend.shareAccount(account);
|
|
store.set('accounts', accounts); if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts); updateTrayMenu(); loginWindow.close(); resolve(true);
|
|
}
|
|
}
|
|
}
|
|
} catch (error) { }
|
|
}, 1000);
|
|
loginWindow.on('closed', () => { clearInterval(checkCookie); resolve(false); });
|
|
});
|
|
});
|