Compare commits
20 Commits
64fe49e58e
...
feat/revok
| Author | SHA1 | Date | |
|---|---|---|---|
| f3bc59e6d0 | |||
| 9d5f77dc09 | |||
| 75accbe5b6 | |||
| 2719bd527a | |||
| d68f0a2740 | |||
| e16a537621 | |||
| 6f66f33a9b | |||
| f0740997d0 | |||
| 1f5d2e08e5 | |||
| 7d1e19d881 | |||
| 6c6da941d5 | |||
| 6c46a31fe9 | |||
| 0b1bd727e6 | |||
| 59244e2b54 | |||
| ebed6c078c | |||
| 7d49209c0b | |||
| e47e722e27 | |||
| 1293331c50 | |||
| b7e22b33af | |||
| 20b41d90ab |
@@ -41,6 +41,12 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
ELECTRON_BUILDER_ALLOW_EMPTY_REPOSITORY: true
|
||||
|
||||
- name: Extract Version
|
||||
id: get_version
|
||||
run: |
|
||||
VERSION=$(node -p "require('./frontend/package.json').version")
|
||||
echo "VERSION=$VERSION" >> $GITHUB_OUTPUT
|
||||
|
||||
- name: Upload Release Artifacts
|
||||
uses: softprops/action-gh-release@v2
|
||||
if: startsWith(github.ref, 'refs/tags/') || github.ref == 'refs/heads/main'
|
||||
@@ -49,8 +55,8 @@ jobs:
|
||||
frontend/release/*.AppImage
|
||||
frontend/release/*.deb
|
||||
frontend/release/*.exe
|
||||
tag_name: v${{ github.run_number }}
|
||||
name: Release v${{ github.run_number }}
|
||||
tag_name: v${{ steps.get_version.outputs.VERSION }}
|
||||
name: Release v${{ steps.get_version.outputs.VERSION }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
env:
|
||||
|
||||
@@ -20,18 +20,11 @@ const isDev = !electron_1.app.isPackaged;
|
||||
electron_1.app.name = "Ultimate Ban Tracker";
|
||||
// Load environment variables
|
||||
dotenv_1.default.config({ path: path_1.default.join(electron_1.app.getAppPath(), '..', '.env') });
|
||||
// --- Server Configuration ---
|
||||
// --- App State ---
|
||||
let mainWindow = null;
|
||||
let tray = null;
|
||||
let backend = null;
|
||||
const initBackend = () => {
|
||||
const config = store.get('serverConfig');
|
||||
if (config && config.enabled && config.url) {
|
||||
console.log(`[Backend] Initializing with URL: ${config.url}`);
|
||||
backend = new backend_1.BackendService(config.url, config.token);
|
||||
}
|
||||
else {
|
||||
backend = null;
|
||||
}
|
||||
};
|
||||
electron_1.app.isQuitting = false;
|
||||
const store = new electron_store_1.default({
|
||||
defaults: {
|
||||
accounts: [],
|
||||
@@ -55,62 +48,131 @@ const downloadAvatar = async (steamId, url) => {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
electron_1.protocol.registerSchemesAsPrivileged([
|
||||
{ scheme: 'steam-resource', privileges: { secure: true, standard: true, supportFetchAPI: true } }
|
||||
]);
|
||||
// --- Main Window ---
|
||||
let mainWindow = null;
|
||||
function createWindow() {
|
||||
mainWindow = new electron_1.BrowserWindow({
|
||||
width: 1280,
|
||||
height: 800,
|
||||
title: "Ultimate Ban Tracker Desktop",
|
||||
backgroundColor: '#171a21',
|
||||
autoHideMenuBar: true,
|
||||
webPreferences: {
|
||||
preload: path_1.default.join(__dirname, 'preload.js'),
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
},
|
||||
});
|
||||
mainWindow.setMenu(null);
|
||||
if (isDev) {
|
||||
mainWindow.loadURL('http://localhost:5173');
|
||||
// --- Backend ---
|
||||
const initBackend = () => {
|
||||
const config = store.get('serverConfig');
|
||||
if (config && config.enabled && config.url) {
|
||||
backend = new backend_1.BackendService(config.url, config.token);
|
||||
}
|
||||
else {
|
||||
mainWindow.loadFile(path_1.default.join(__dirname, '..', 'dist', 'index.html'));
|
||||
backend = null;
|
||||
}
|
||||
}
|
||||
// --- Sync Logic ---
|
||||
};
|
||||
// --- System Tray ---
|
||||
const createTray = () => {
|
||||
const assetsDir = path_1.default.join(__dirname, '..', 'assets-build');
|
||||
const possibleIcons = ['icon.svg', 'icon.png'];
|
||||
let iconPath = '';
|
||||
for (const name of possibleIcons) {
|
||||
const fullPath = path_1.default.join(assetsDir, name);
|
||||
if (fs_1.default.existsSync(fullPath)) {
|
||||
iconPath = fullPath;
|
||||
break;
|
||||
}
|
||||
}
|
||||
console.log(`[Tray] Attempting to initialize with icon: ${iconPath || 'NONE FOUND'}`);
|
||||
if (!iconPath) {
|
||||
console.warn(`[Tray] FAILED: No valid icon found in ${assetsDir}`);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const icon = electron_1.nativeImage.createFromPath(iconPath).resize({ width: 16, height: 16 });
|
||||
tray = new electron_1.Tray(icon);
|
||||
tray.setToolTip('Ultimate Ban Tracker');
|
||||
tray.on('click', () => {
|
||||
if (mainWindow) {
|
||||
mainWindow.show();
|
||||
mainWindow.focus();
|
||||
}
|
||||
});
|
||||
updateTrayMenu();
|
||||
console.log(`[Tray] Successfully initialized`);
|
||||
}
|
||||
catch (e) {
|
||||
console.error(`[Tray] Critical error during initialization: ${e.message}`);
|
||||
}
|
||||
};
|
||||
const updateTrayMenu = () => {
|
||||
if (!tray)
|
||||
return;
|
||||
const accounts = store.get('accounts');
|
||||
const config = store.get('serverConfig');
|
||||
const contextMenu = electron_1.Menu.buildFromTemplate([
|
||||
{ label: `Ultimate Ban Tracker v${electron_1.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()
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{ label: 'Show Dashboard', click: () => { if (mainWindow)
|
||||
mainWindow.show(); } },
|
||||
{ label: 'Quit', click: () => { electron_1.app.isQuitting = true; electron_1.app.quit(); } }
|
||||
]);
|
||||
tray.setContextMenu(contextMenu);
|
||||
};
|
||||
// --- Steam Logic ---
|
||||
const killSteam = async () => {
|
||||
return new Promise((resolve) => {
|
||||
const command = process.platform === 'win32' ? 'taskkill /f /im steam.exe' : 'pkill -9 steam';
|
||||
(0, child_process_1.exec)(command, () => setTimeout(resolve, 1000));
|
||||
});
|
||||
};
|
||||
const startSteam = () => {
|
||||
const command = process.platform === 'win32' ? 'start steam://open/main' : 'steam &';
|
||||
(0, child_process_1.exec)(command);
|
||||
};
|
||||
const handleSwitchAccount = async (loginName) => {
|
||||
if (!loginName)
|
||||
return false;
|
||||
try {
|
||||
await killSteam();
|
||||
const accounts = store.get('accounts');
|
||||
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((res, rej) => (0, child_process_1.exec)(`${regCommand} && ${rememberCommand}`, (e) => e ? rej(e) : res()));
|
||||
if (account && account.loginConfig)
|
||||
steam_client_1.steamClient.injectAccountConfig(loginName, account.loginConfig);
|
||||
}
|
||||
else if (process.platform === 'linux') {
|
||||
await steam_client_1.steamClient.setAutoLoginUser(loginName, account?.loginConfig, account?.steamId);
|
||||
}
|
||||
startSteam();
|
||||
return true;
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
// --- Sync Worker ---
|
||||
const syncAccounts = async () => {
|
||||
initBackend();
|
||||
let accounts = store.get('accounts');
|
||||
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()
|
||||
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()
|
||||
});
|
||||
hasChanges = true;
|
||||
}
|
||||
@@ -118,7 +180,6 @@ const syncAccounts = async () => {
|
||||
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)
|
||||
@@ -138,28 +199,23 @@ const syncAccounts = async () => {
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (e) {
|
||||
console.error('[Sync] Pull failed');
|
||||
}
|
||||
catch (e) { }
|
||||
}
|
||||
// BROADCAST PULL RESULTS IMMEDIATELY
|
||||
if (hasChanges) {
|
||||
store.set('accounts', accounts);
|
||||
if (mainWindow)
|
||||
mainWindow.webContents.send('accounts-updated', accounts);
|
||||
updateTrayMenu();
|
||||
}
|
||||
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) {
|
||||
if ((now.getTime() - lastCheck.getTime()) / 3600000 > 6 || !account.personaName) {
|
||||
const profile = await (0, steam_web_1.fetchProfileData)(account.steamId, account.steamLoginSecure);
|
||||
const bans = await (0, steam_web_1.scrapeBanStatus)(profile.profileUrl, account.steamLoginSecure);
|
||||
account.personaName = profile.personaName;
|
||||
@@ -189,23 +245,14 @@ const syncAccounts = async () => {
|
||||
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));
|
||||
if ((now.getTime() - lastScrape.getTime()) / 3600000 > 8) {
|
||||
await new Promise(r => setTimeout(r, Math.floor(Math.random() * 60000) + 5000));
|
||||
try {
|
||||
const result = await (0, scraper_1.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();
|
||||
}
|
||||
account.cooldownExpiresAt = result.expiresAt ? result.expiresAt.toISOString() : new Date(Date.now() + 86400000).toISOString();
|
||||
if (backend)
|
||||
await backend.pushCooldown(account.steamId, account.cooldownExpiresAt);
|
||||
}
|
||||
@@ -231,14 +278,13 @@ const syncAccounts = async () => {
|
||||
store.set('accounts', updatedAccounts);
|
||||
if (mainWindow)
|
||||
mainWindow.webContents.send('accounts-updated', updatedAccounts);
|
||||
updateTrayMenu();
|
||||
}
|
||||
console.log('[Sync] Sync cycle finished.');
|
||||
};
|
||||
const scheduleNextSync = () => {
|
||||
const delay = isDev ? 120000 : (Math.random() * 30 * 60000) + 30 * 60000;
|
||||
setTimeout(async () => { await syncAccounts(); scheduleNextSync(); }, delay);
|
||||
setTimeout(async () => { await syncAccounts(); scheduleNextSync(); }, isDev ? 120000 : 1800000);
|
||||
};
|
||||
// --- Steam Auto-Discovery ---
|
||||
// --- Discovery ---
|
||||
const addingAccounts = new Set();
|
||||
const handleLocalAccountsFound = async (localAccounts) => {
|
||||
const currentAccounts = store.get('accounts');
|
||||
@@ -261,17 +307,11 @@ const handleLocalAccountsFound = async (localAccounts) => {
|
||||
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,
|
||||
steamId: local.steamId, personaName: profile.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()
|
||||
vacBanned: bans.vacBanned, gameBans: bans.gameBans, lastBanCheck: new Date().toISOString()
|
||||
});
|
||||
hasChanges = true;
|
||||
}
|
||||
@@ -283,8 +323,29 @@ const handleLocalAccountsFound = async (localAccounts) => {
|
||||
store.set('accounts', currentAccounts);
|
||||
if (mainWindow)
|
||||
mainWindow.webContents.send('accounts-updated', currentAccounts);
|
||||
updateTrayMenu();
|
||||
}
|
||||
};
|
||||
// --- Main Window Creation ---
|
||||
function createWindow() {
|
||||
mainWindow = new electron_1.BrowserWindow({
|
||||
width: 1280, height: 800, title: "Ultimate Ban Tracker", backgroundColor: '#171a21', autoHideMenuBar: true,
|
||||
webPreferences: { preload: path_1.default.join(__dirname, 'preload.js'), nodeIntegration: false, contextIsolation: true }
|
||||
});
|
||||
mainWindow.setMenu(null);
|
||||
mainWindow.on('close', (event) => {
|
||||
if (!electron_1.app.isQuitting) {
|
||||
event.preventDefault();
|
||||
mainWindow?.hide();
|
||||
}
|
||||
return false;
|
||||
});
|
||||
if (isDev)
|
||||
mainWindow.loadURL('http://localhost:5173');
|
||||
else
|
||||
mainWindow.loadFile(path_1.default.join(__dirname, '..', 'dist', 'index.html'));
|
||||
}
|
||||
// --- App Lifecycle ---
|
||||
electron_1.app.whenReady().then(() => {
|
||||
electron_1.protocol.handle('steam-resource', (request) => {
|
||||
let rawPath = decodeURIComponent(request.url.replace('steam-resource://', ''));
|
||||
@@ -301,13 +362,19 @@ electron_1.app.whenReady().then(() => {
|
||||
}
|
||||
});
|
||||
createWindow();
|
||||
createTray();
|
||||
initBackend();
|
||||
setTimeout(syncAccounts, 5000);
|
||||
scheduleNextSync();
|
||||
steam_client_1.steamClient.startWatching(handleLocalAccountsFound);
|
||||
});
|
||||
electron_1.app.on('window-all-closed', () => { if (process.platform !== 'darwin' && electron_1.app.isQuitting)
|
||||
electron_1.app.quit(); });
|
||||
electron_1.app.on('activate', () => { if (electron_1.BrowserWindow.getAllWindows().length === 0)
|
||||
createWindow();
|
||||
else
|
||||
mainWindow?.show(); });
|
||||
// --- IPC Handlers ---
|
||||
console.log('[Main] Registering IPC Handlers...');
|
||||
electron_1.ipcMain.handle('get-accounts', () => store.get('accounts'));
|
||||
electron_1.ipcMain.handle('get-server-config', () => store.get('serverConfig'));
|
||||
electron_1.ipcMain.handle('update-server-config', (event, config) => {
|
||||
@@ -333,7 +400,6 @@ electron_1.ipcMain.handle('login-to-server', async () => {
|
||||
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());
|
||||
@@ -346,7 +412,6 @@ electron_1.ipcMain.handle('login-to-server', async () => {
|
||||
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 || {};
|
||||
@@ -355,7 +420,6 @@ electron_1.ipcMain.handle('login-to-server', async () => {
|
||||
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];
|
||||
@@ -363,7 +427,7 @@ electron_1.ipcMain.handle('login-to-server', async () => {
|
||||
saveServerAuth(token);
|
||||
}
|
||||
});
|
||||
authWindow.on('closed', () => { resolve(false); });
|
||||
authWindow.on('closed', () => resolve(false));
|
||||
});
|
||||
});
|
||||
electron_1.ipcMain.handle('get-server-user-info', () => ({ steamId: store.get('serverConfig').serverSteamId }));
|
||||
@@ -371,7 +435,6 @@ electron_1.ipcMain.handle('sync-now', async () => { await syncAccounts(); return
|
||||
electron_1.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) => s.steamId === identifier || s.profileUrl.includes(identifier));
|
||||
@@ -380,23 +443,16 @@ electron_1.ipcMain.handle('add-account', async (event, { identifier }) => {
|
||||
if (accounts.find(a => a.steamId === existing.steamId))
|
||||
throw new Error('Account already tracked');
|
||||
const newAccount = {
|
||||
_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',
|
||||
_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()
|
||||
};
|
||||
store.set('accounts', [...accounts, newAccount]);
|
||||
updateTrayMenu();
|
||||
return newAccount;
|
||||
}
|
||||
}
|
||||
@@ -405,13 +461,13 @@ electron_1.ipcMain.handle('add-account', async (event, { identifier }) => {
|
||||
const localAvatar = await downloadAvatar(profile.steamId, profile.avatar);
|
||||
const accounts = store.get('accounts');
|
||||
const newAccount = {
|
||||
_id: Date.now().toString(),
|
||||
steamId: profile.steamId, personaName: profile.personaName, loginName: '',
|
||||
avatar: profile.avatar, localAvatar: localAvatar, profileUrl: profile.profileUrl,
|
||||
_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) {
|
||||
@@ -424,6 +480,7 @@ electron_1.ipcMain.handle('update-account', (event, id, data) => {
|
||||
if (index !== -1) {
|
||||
accounts[index] = { ...accounts[index], ...data };
|
||||
store.set('accounts', accounts);
|
||||
updateTrayMenu();
|
||||
return accounts[index];
|
||||
}
|
||||
return null;
|
||||
@@ -431,6 +488,7 @@ electron_1.ipcMain.handle('update-account', (event, id, data) => {
|
||||
electron_1.ipcMain.handle('delete-account', (event, id) => {
|
||||
const accounts = store.get('accounts');
|
||||
store.set('accounts', accounts.filter((a) => a._id !== id));
|
||||
updateTrayMenu();
|
||||
return true;
|
||||
});
|
||||
electron_1.ipcMain.handle('share-account-with-user', async (event, steamId, targetSteamId) => {
|
||||
@@ -444,58 +502,77 @@ electron_1.ipcMain.handle('share-account-with-user', async (event, steamId, targ
|
||||
}
|
||||
throw new Error('Backend not configured');
|
||||
});
|
||||
electron_1.ipcMain.handle('revoke-account-access', async (event, steamId, targetSteamId) => {
|
||||
initBackend();
|
||||
if (backend)
|
||||
return await backend.revokeAccess(steamId, targetSteamId);
|
||||
throw new Error('Backend not configured');
|
||||
});
|
||||
electron_1.ipcMain.handle('revoke-all-account-access', async (event, steamId) => {
|
||||
initBackend();
|
||||
if (backend)
|
||||
return await backend.revokeAllAccess(steamId);
|
||||
throw new Error('Backend not configured');
|
||||
});
|
||||
electron_1.ipcMain.handle('get-community-accounts', async () => { initBackend(); return backend ? await backend.getCommunityAccounts() : []; });
|
||||
electron_1.ipcMain.handle('get-server-users', async () => { initBackend(); return backend ? await backend.getServerUsers() : []; });
|
||||
const killSteam = async () => {
|
||||
return new Promise((resolve) => {
|
||||
const command = process.platform === 'win32' ? 'taskkill /f /im steam.exe' : 'pkill -9 steam';
|
||||
(0, child_process_1.exec)(command, () => setTimeout(resolve, 1000));
|
||||
});
|
||||
};
|
||||
const startSteam = () => {
|
||||
const command = process.platform === 'win32' ? 'start steam://open/main' : 'steam &';
|
||||
(0, child_process_1.exec)(command);
|
||||
};
|
||||
electron_1.ipcMain.handle('switch-account', async (event, loginName) => {
|
||||
if (!loginName)
|
||||
return false;
|
||||
try {
|
||||
await killSteam();
|
||||
const accounts = store.get('accounts');
|
||||
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((res, rej) => (0, child_process_1.exec)(`${regCommand} && ${rememberCommand}`, (e) => e ? rej(e) : res()));
|
||||
if (account && account.loginConfig)
|
||||
steam_client_1.steamClient.injectAccountConfig(loginName, account.loginConfig);
|
||||
}
|
||||
else if (process.platform === 'linux') {
|
||||
await steam_client_1.steamClient.setAutoLoginUser(loginName, account?.loginConfig, account?.steamId);
|
||||
}
|
||||
startSteam();
|
||||
return true;
|
||||
}
|
||||
catch (e) {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
electron_1.ipcMain.handle('switch-account', async (event, loginName) => await handleSwitchAccount(loginName));
|
||||
electron_1.ipcMain.handle('open-external', (event, url) => electron_1.shell.openExternal(url));
|
||||
electron_1.ipcMain.handle('open-steam-app-login', async () => {
|
||||
console.log('[SteamClient] Preparing for fresh login...');
|
||||
await killSteam();
|
||||
if (process.platform === 'win32') {
|
||||
// Clear auto-login registry
|
||||
const clearReg = 'reg add "HKCU\\Software\\Valve\\Steam" /v AutoLoginUser /t REG_SZ /d "" /f';
|
||||
await new Promise((res) => (0, child_process_1.exec)(clearReg, () => res()));
|
||||
}
|
||||
else if (process.platform === 'linux') {
|
||||
// On Linux we can use the steamClient helper to set an empty user
|
||||
await steam_client_1.steamClient.setAutoLoginUser("", undefined, "");
|
||||
}
|
||||
const command = process.platform === 'win32' ? 'start steam://open/login' : 'xdg-open steam://open/login';
|
||||
(0, child_process_1.exec)(command);
|
||||
return true;
|
||||
});
|
||||
electron_1.ipcMain.handle('open-steam-login', async (event, expectedSteamId) => {
|
||||
const loginSession = electron_1.session.fromPartition('persist:steam-login');
|
||||
await loginSession.clearStorageData({ storages: ['cookies', 'localstorage', 'indexdb'] });
|
||||
// Use a unique partition per account to prevent session bleeding
|
||||
const partitionId = expectedSteamId ? `persist:steam-login-${expectedSteamId}` : 'persist:steam-login-new';
|
||||
const loginSession = electron_1.session.fromPartition(partitionId);
|
||||
// If adding a brand new account, explicitly clear previous trash
|
||||
if (!expectedSteamId) {
|
||||
console.log('[Auth] Clearing session for new account login...');
|
||||
await loginSession.clearStorageData({ storages: ['cookies', 'localstorage', 'indexdb'] });
|
||||
}
|
||||
// If we have an existing cookie string for this account, pre-inject it
|
||||
if (expectedSteamId) {
|
||||
const accounts = store.get('accounts');
|
||||
const account = accounts.find(a => a.steamId === expectedSteamId);
|
||||
if (account?.steamLoginSecure) {
|
||||
console.log(`[Auth] Pre-injecting existing cookies for ${account.personaName}...`);
|
||||
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: name,
|
||||
value: value,
|
||||
path: '/',
|
||||
secure: true,
|
||||
httpOnly: name.includes('Secure')
|
||||
});
|
||||
}
|
||||
catch (e) { }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
const loginWindow = new electron_1.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'
|
||||
}
|
||||
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 () => {
|
||||
@@ -505,13 +582,10 @@ electron_1.ipcMain.handle('open-steam-login', async (event, expectedSteamId) =>
|
||||
if (secureCookie) {
|
||||
const steamId = decodeURIComponent(secureCookie.value).split('|')[0];
|
||||
if (steamId) {
|
||||
if (expectedSteamId && steamId !== expectedSteamId) {
|
||||
console.error(`[Auth] ID Mismatch! Expected ${expectedSteamId}, got ${steamId}`);
|
||||
if (expectedSteamId && steamId !== expectedSteamId)
|
||||
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');
|
||||
const accountIndex = accounts.findIndex(a => a.steamId === steamId);
|
||||
if (accountIndex !== -1) {
|
||||
@@ -526,25 +600,18 @@ electron_1.ipcMain.handle('open-steam-login', async (event, expectedSteamId) =>
|
||||
account.loginConfig = config;
|
||||
}
|
||||
try {
|
||||
console.log(`[Auth] Performing initial scrape for ${account.personaName}...`);
|
||||
const result = await (0, scraper_1.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);
|
||||
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);
|
||||
}
|
||||
@@ -553,11 +620,6 @@ electron_1.ipcMain.handle('open-steam-login', async (event, expectedSteamId) =>
|
||||
}
|
||||
catch (error) { }
|
||||
}, 1000);
|
||||
loginWindow.on('closed', () => {
|
||||
clearInterval(checkCookie);
|
||||
resolve(false);
|
||||
});
|
||||
loginWindow.on('closed', () => { clearInterval(checkCookie); resolve(false); });
|
||||
});
|
||||
});
|
||||
electron_1.app.on('window-all-closed', () => { if (process.platform !== 'darwin')
|
||||
electron_1.app.quit(); });
|
||||
|
||||
@@ -8,7 +8,10 @@ electron_1.contextBridge.exposeInMainWorld('electronAPI', {
|
||||
deleteAccount: (id) => electron_1.ipcRenderer.invoke('delete-account', id),
|
||||
switchAccount: (loginName) => electron_1.ipcRenderer.invoke('switch-account', loginName),
|
||||
shareAccountWithUser: (steamId, targetSteamId) => electron_1.ipcRenderer.invoke('share-account-with-user', steamId, targetSteamId),
|
||||
revokeAccountAccess: (steamId, targetSteamId) => electron_1.ipcRenderer.invoke('revoke-account-access', steamId, targetSteamId),
|
||||
revokeAllAccountAccess: (steamId) => electron_1.ipcRenderer.invoke('revoke-all-account-access', steamId),
|
||||
openExternal: (url) => electron_1.ipcRenderer.invoke('open-external', url),
|
||||
openSteamAppLogin: () => electron_1.ipcRenderer.invoke('open-steam-app-login'),
|
||||
openSteamLogin: (steamId) => electron_1.ipcRenderer.invoke('open-steam-login', steamId),
|
||||
// Server Config & Auth
|
||||
getServerConfig: () => electron_1.ipcRenderer.invoke('get-server-config'),
|
||||
|
||||
@@ -67,7 +67,8 @@ class BackendService {
|
||||
gameBans: account.gameBans,
|
||||
loginName: account.loginName,
|
||||
steamLoginSecure: account.steamLoginSecure,
|
||||
loginConfig: account.loginConfig
|
||||
loginConfig: account.loginConfig,
|
||||
sessionUpdatedAt: account.sessionUpdatedAt
|
||||
}, { headers: this.headers });
|
||||
}
|
||||
catch (e) {
|
||||
@@ -100,5 +101,34 @@ class BackendService {
|
||||
throw new Error(e.response?.data?.message || 'Failed to share account');
|
||||
}
|
||||
}
|
||||
async revokeAccess(steamId, targetSteamId) {
|
||||
if (!this.token)
|
||||
return;
|
||||
try {
|
||||
const response = await axios_1.default.delete(`${this.url}/api/sync/${steamId}/share`, {
|
||||
headers: this.headers,
|
||||
data: { targetSteamId }
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
catch (e) {
|
||||
console.error(`[Backend] Failed to revoke access for ${steamId} from ${targetSteamId}`);
|
||||
throw new Error(e.response?.data?.message || 'Failed to revoke access');
|
||||
}
|
||||
}
|
||||
async revokeAllAccess(steamId) {
|
||||
if (!this.token)
|
||||
return;
|
||||
try {
|
||||
const response = await axios_1.default.delete(`${this.url}/api/sync/${steamId}/share/all`, {
|
||||
headers: this.headers
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
catch (e) {
|
||||
console.error(`[Backend] Failed to revoke all access for ${steamId}`);
|
||||
throw new Error(e.response?.data?.message || 'Failed to revoke all access');
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.BackendService = BackendService;
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { app, BrowserWindow, ipcMain, shell, session, protocol, net } from 'electron';
|
||||
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 cron from 'node-cron';
|
||||
import axios from 'axios';
|
||||
import fs from 'fs';
|
||||
import { pathToFileURL } from 'url';
|
||||
@@ -20,20 +19,7 @@ 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 ---
|
||||
// --- Types & Interfaces ---
|
||||
interface Account {
|
||||
_id: string;
|
||||
steamId: string;
|
||||
@@ -61,8 +47,15 @@ interface ServerConfig {
|
||||
token?: string;
|
||||
serverSteamId?: string;
|
||||
enabled: boolean;
|
||||
theme?: string;
|
||||
}
|
||||
|
||||
// --- 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: [],
|
||||
@@ -86,403 +79,84 @@ const downloadAvatar = async (steamId: string, url: string): Promise<string | un
|
||||
}
|
||||
};
|
||||
|
||||
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');
|
||||
// --- Backend ---
|
||||
const initBackend = () => {
|
||||
const config = store.get('serverConfig');
|
||||
if (config && config.enabled && config.url) {
|
||||
backend = new BackendService(config.url, config.token);
|
||||
} else {
|
||||
mainWindow.loadFile(path.join(__dirname, '..', 'dist', 'index.html'));
|
||||
backend = null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// --- Sync Logic ---
|
||||
// --- System Tray ---
|
||||
const createTray = () => {
|
||||
const assetsDir = path.join(__dirname, '..', 'assets-build');
|
||||
const possibleIcons = ['icon.svg', 'icon.png'];
|
||||
let iconPath = '';
|
||||
|
||||
const syncAccounts = async () => {
|
||||
initBackend();
|
||||
let accounts = store.get('accounts') as Account[];
|
||||
let hasChanges = false;
|
||||
for (const name of possibleIcons) {
|
||||
const fullPath = path.join(assetsDir, name);
|
||||
if (fs.existsSync(fullPath)) {
|
||||
iconPath = fullPath;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 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');
|
||||
}
|
||||
console.log(`[Tray] Attempting to initialize with icon: ${iconPath || 'NONE FOUND'}`);
|
||||
|
||||
if (!iconPath) {
|
||||
console.warn(`[Tray] FAILED: No valid icon found in ${assetsDir}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// 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 icon = nativeImage.createFromPath(iconPath).resize({ width: 16, height: 16 });
|
||||
tray = new Tray(icon);
|
||||
tray.setToolTip('Ultimate Ban Tracker');
|
||||
tray.on('click', () => {
|
||||
if (mainWindow) {
|
||||
mainWindow.show();
|
||||
mainWindow.focus();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
updateTrayMenu();
|
||||
console.log(`[Tray] Successfully initialized`);
|
||||
} catch (e: any) {
|
||||
console.error(`[Tray] Critical error during initialization: ${e.message}`);
|
||||
}
|
||||
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 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()
|
||||
},
|
||||
{ type: 'separator' },
|
||||
{ label: 'Show Dashboard', click: () => { if (mainWindow) mainWindow.show(); } },
|
||||
{ label: 'Quit', click: () => { (app as any).isQuitting = true; app.quit(); } }
|
||||
]);
|
||||
|
||||
tray.setContextMenu(contextMenu);
|
||||
};
|
||||
|
||||
// --- Steam Logic ---
|
||||
const killSteam = async () => {
|
||||
return new Promise<void>((resolve) => {
|
||||
const command = process.platform === 'win32' ? 'taskkill /f /im steam.exe' : 'pkill -9 steam';
|
||||
@@ -495,7 +169,7 @@ const startSteam = () => {
|
||||
exec(command);
|
||||
};
|
||||
|
||||
ipcMain.handle('switch-account', async (event, loginName: string) => {
|
||||
const handleSwitchAccount = async (loginName: string) => {
|
||||
if (!loginName) return false;
|
||||
try {
|
||||
await killSteam();
|
||||
@@ -512,30 +186,386 @@ ipcMain.handle('switch-account', async (event, loginName: string) => {
|
||||
startSteam();
|
||||
return true;
|
||||
} catch (e) { return false; }
|
||||
};
|
||||
|
||||
// --- Sync Worker ---
|
||||
const syncAccounts = async () => {
|
||||
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()
|
||||
});
|
||||
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) {
|
||||
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) { }
|
||||
}
|
||||
|
||||
if (hasChanges) {
|
||||
store.set('accounts', accounts);
|
||||
if (mainWindow) mainWindow.webContents.send('accounts-updated', accounts);
|
||||
updateTrayMenu();
|
||||
}
|
||||
|
||||
if (accounts.length === 0) return;
|
||||
|
||||
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);
|
||||
if ((now.getTime() - lastCheck.getTime()) / 3600000 > 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);
|
||||
if ((now.getTime() - lastScrape.getTime()) / 3600000 > 8) {
|
||||
await new Promise(r => setTimeout(r, Math.floor(Math.random() * 60000) + 5000));
|
||||
try {
|
||||
const result = await scrapeCooldown(account.steamId, account.steamLoginSecure);
|
||||
account.authError = false; account.lastScrapeTime = new Date().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);
|
||||
} 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);
|
||||
updateTrayMenu();
|
||||
}
|
||||
};
|
||||
|
||||
const scheduleNextSync = () => {
|
||||
setTimeout(async () => { await syncAccounts(); scheduleNextSync(); }, isDev ? 120000 : 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);
|
||||
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,
|
||||
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();
|
||||
}
|
||||
};
|
||||
|
||||
// --- Main Window Creation ---
|
||||
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 Lifecycle ---
|
||||
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, 5000);
|
||||
scheduleNextSync();
|
||||
steamClient.startWatching(handleLocalAccountsFound);
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => { if (process.platform !== 'darwin' && (app as any).isQuitting) app.quit(); });
|
||||
app.on('activate', () => { if (BrowserWindow.getAllWindows().length === 0) createWindow(); else mainWindow?.show(); });
|
||||
|
||||
// --- 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;
|
||||
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);
|
||||
};
|
||||
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(); return true; });
|
||||
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()
|
||||
};
|
||||
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('switch-account', async (event, loginName: string) => await handleSwitchAccount(loginName));
|
||||
ipcMain.handle('open-external', (event, url: string) => shell.openExternal(url));
|
||||
|
||||
ipcMain.handle('open-steam-app-login', async () => {
|
||||
console.log('[SteamClient] Preparing for fresh login...');
|
||||
await killSteam();
|
||||
|
||||
if (process.platform === 'win32') {
|
||||
// Clear auto-login registry
|
||||
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') {
|
||||
// On Linux we can use the steamClient helper to set an empty user
|
||||
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 loginSession = session.fromPartition('persist:steam-login');
|
||||
await loginSession.clearStorageData({ storages: ['cookies', 'localstorage', 'indexdb'] });
|
||||
// Use a unique partition per account to prevent session bleeding
|
||||
const partitionId = expectedSteamId ? `persist:steam-login-${expectedSteamId}` : 'persist:steam-login-new';
|
||||
const loginSession = session.fromPartition(partitionId);
|
||||
|
||||
// If adding a brand new account, explicitly clear previous trash
|
||||
if (!expectedSteamId) {
|
||||
console.log('[Auth] Clearing session for new account login...');
|
||||
await loginSession.clearStorageData({ storages: ['cookies', 'localstorage', 'indexdb'] });
|
||||
}
|
||||
|
||||
// If we have an existing cookie string for this account, pre-inject it
|
||||
if (expectedSteamId) {
|
||||
const accounts = store.get('accounts') as Account[];
|
||||
const account = accounts.find(a => a.steamId === expectedSteamId);
|
||||
if (account?.steamLoginSecure) {
|
||||
console.log(`[Auth] Pre-injecting existing cookies for ${account.personaName}...`);
|
||||
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: name,
|
||||
value: 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 (Ensure "Remember Me" is checked!)',
|
||||
webPreferences: {
|
||||
nodeIntegration: false,
|
||||
contextIsolation: true,
|
||||
partition: 'persist:steam-login'
|
||||
}
|
||||
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' });
|
||||
@@ -543,45 +573,29 @@ ipcMain.handle('open-steam-login', async (event, expectedSteamId: string) => {
|
||||
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;
|
||||
}
|
||||
if (expectedSteamId && steamId !== expectedSteamId) 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.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);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
@@ -589,12 +603,6 @@ ipcMain.handle('open-steam-login', async (event, expectedSteamId: string) => {
|
||||
}
|
||||
} catch (error) { }
|
||||
}, 1000);
|
||||
|
||||
loginWindow.on('closed', () => {
|
||||
clearInterval(checkCookie);
|
||||
resolve(false);
|
||||
});
|
||||
loginWindow.on('closed', () => { clearInterval(checkCookie); resolve(false); });
|
||||
});
|
||||
});
|
||||
|
||||
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
|
||||
|
||||
@@ -7,7 +7,10 @@ contextBridge.exposeInMainWorld('electronAPI', {
|
||||
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),
|
||||
revokeAccountAccess: (steamId: string, targetSteamId: string) => ipcRenderer.invoke('revoke-account-access', steamId, targetSteamId),
|
||||
revokeAllAccountAccess: (steamId: string) => ipcRenderer.invoke('revoke-all-account-access', steamId),
|
||||
openExternal: (url: string) => ipcRenderer.invoke('open-external', url),
|
||||
openSteamAppLogin: () => ipcRenderer.invoke('open-steam-app-login'),
|
||||
openSteamLogin: (steamId: string) => ipcRenderer.invoke('open-steam-login', steamId),
|
||||
|
||||
// Server Config & Auth
|
||||
|
||||
@@ -61,7 +61,8 @@ export class BackendService {
|
||||
gameBans: account.gameBans,
|
||||
loginName: account.loginName,
|
||||
steamLoginSecure: account.steamLoginSecure,
|
||||
loginConfig: account.loginConfig
|
||||
loginConfig: account.loginConfig,
|
||||
sessionUpdatedAt: account.sessionUpdatedAt
|
||||
}, { headers: this.headers });
|
||||
} catch (e) {
|
||||
console.error('[Backend] Failed to share account');
|
||||
@@ -91,4 +92,31 @@ export class BackendService {
|
||||
throw new Error(e.response?.data?.message || 'Failed to share account');
|
||||
}
|
||||
}
|
||||
|
||||
public async revokeAccess(steamId: string, targetSteamId: string) {
|
||||
if (!this.token) return;
|
||||
try {
|
||||
const response = await axios.delete(`${this.url}/api/sync/${steamId}/share`, {
|
||||
headers: this.headers,
|
||||
data: { targetSteamId }
|
||||
});
|
||||
return response.data;
|
||||
} catch (e: any) {
|
||||
console.error(`[Backend] Failed to revoke access for ${steamId} from ${targetSteamId}`);
|
||||
throw new Error(e.response?.data?.message || 'Failed to revoke access');
|
||||
}
|
||||
}
|
||||
|
||||
public async revokeAllAccess(steamId: string) {
|
||||
if (!this.token) return;
|
||||
try {
|
||||
const response = await axios.delete(`${this.url}/api/sync/${steamId}/share/all`, {
|
||||
headers: this.headers
|
||||
});
|
||||
return response.data;
|
||||
} catch (e: any) {
|
||||
console.error(`[Backend] Failed to revoke all access for ${steamId}`);
|
||||
throw new Error(e.response?.data?.message || 'Failed to revoke all access');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
4
frontend/package-lock.json
generated
4
frontend/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "ultimate-ban-tracker-desktop",
|
||||
"version": "1.0.0",
|
||||
"version": "1.2.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "ultimate-ban-tracker-desktop",
|
||||
"version": "1.0.0",
|
||||
"version": "1.2.0",
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
"dependencies": {
|
||||
"@emotion/react": "^11.14.0",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "ultimate-ban-tracker-desktop",
|
||||
"description": "Professional Steam Account Manager & Ban Tracker",
|
||||
"version": "1.0.0",
|
||||
"version": "1.2.0",
|
||||
"author": "Nils Pukropp <nils@narl.io>",
|
||||
"homepage": "https://narl.io",
|
||||
"license": "SEE LICENSE IN LICENSE",
|
||||
|
||||
@@ -38,8 +38,11 @@ interface AccountsContextType {
|
||||
updateAccount: (id: string, data: Partial<Account>) => Promise<void>;
|
||||
deleteAccount: (id: string) => Promise<void>;
|
||||
switchAccount: (loginName: string) => Promise<void>;
|
||||
openSteamAppLogin: () => Promise<void>;
|
||||
openSteamLogin: (steamId: string) => Promise<void>;
|
||||
shareAccountWithUser: (steamId: string, targetSteamId: string) => Promise<any>;
|
||||
revokeAccountAccess: (steamId: string, targetSteamId: string) => Promise<any>;
|
||||
revokeAllAccountAccess: (steamId: string) => Promise<any>;
|
||||
|
||||
// Server Methods
|
||||
updateServerConfig: (config: Partial<ServerConfig>) => Promise<void>;
|
||||
@@ -125,6 +128,10 @@ export const AccountsProvider: React.FC<{ children: React.ReactNode }> = ({ chil
|
||||
await (window as any).electronAPI.switchAccount(loginName);
|
||||
};
|
||||
|
||||
const openSteamAppLogin = async () => {
|
||||
await (window as any).electronAPI.openSteamAppLogin();
|
||||
};
|
||||
|
||||
const openSteamLogin = async (steamId: string) => {
|
||||
await (window as any).electronAPI.openSteamLogin(steamId);
|
||||
await syncNow();
|
||||
@@ -136,6 +143,18 @@ export const AccountsProvider: React.FC<{ children: React.ReactNode }> = ({ chil
|
||||
return res;
|
||||
};
|
||||
|
||||
const revokeAccountAccess = async (steamId: string, targetSteamId: string) => {
|
||||
const res = await (window as any).electronAPI.revokeAccountAccess(steamId, targetSteamId);
|
||||
await syncNow();
|
||||
return res;
|
||||
};
|
||||
|
||||
const revokeAllAccountAccess = async (steamId: string) => {
|
||||
const res = await (window as any).electronAPI.revokeAllAccountAccess(steamId);
|
||||
await syncNow();
|
||||
return res;
|
||||
};
|
||||
|
||||
const updateServerConfig = async (config: Partial<ServerConfig>) => {
|
||||
const updated = await (window as any).electronAPI.updateServerConfig(config);
|
||||
setServerConfig(updated);
|
||||
@@ -158,8 +177,8 @@ export const AccountsProvider: React.FC<{ children: React.ReactNode }> = ({ chil
|
||||
return (
|
||||
<AccountsContext.Provider value={{
|
||||
accounts, serverConfig, isLoading, isSyncing, addAccount, updateAccount, deleteAccount,
|
||||
switchAccount, openSteamLogin, updateServerConfig, loginToServer,
|
||||
getCommunityAccounts, getServerUsers, shareAccountWithUser, syncNow, refreshAccounts
|
||||
switchAccount, openSteamAppLogin, openSteamLogin, updateServerConfig, loginToServer,
|
||||
getCommunityAccounts, getServerUsers, shareAccountWithUser, revokeAccountAccess, revokeAllAccountAccess, syncNow, refreshAccounts
|
||||
}}>
|
||||
{children}
|
||||
</AccountsContext.Provider>
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
DialogActions, CircularProgress, Paper, Chip,
|
||||
Table, TableBody, TableCell, TableContainer, TableHead, TableRow,
|
||||
Switch, FormControlLabel, Divider, List, ListItem, ListItemText, ListItemSecondaryAction,
|
||||
Tabs, Tab, Select, MenuItem, FormControl, InputLabel
|
||||
Select, MenuItem, FormControl, InputLabel
|
||||
} from '@mui/material';
|
||||
import SearchIcon from '@mui/icons-material/Search';
|
||||
import AddIcon from '@mui/icons-material/Add';
|
||||
@@ -20,10 +20,11 @@ import LockResetIcon from '@mui/icons-material/LockReset';
|
||||
import SettingsIcon from '@mui/icons-material/Settings';
|
||||
import ShareIcon from '@mui/icons-material/Share';
|
||||
import GroupAddIcon from '@mui/icons-material/GroupAdd';
|
||||
import PublicIcon from '@mui/icons-material/Public';
|
||||
import ShieldIcon from '@mui/icons-material/Shield';
|
||||
import GppBadIcon from '@mui/icons-material/GppBad';
|
||||
import PeopleIcon from '@mui/icons-material/People';
|
||||
import VerifiedUserIcon from '@mui/icons-material/VerifiedUser';
|
||||
import WorkspacePremiumIcon from '@mui/icons-material/WorkspacePremium';
|
||||
import { useAccounts, type Account } from '../hooks/useAccounts';
|
||||
import { useAppTheme } from '../theme/ThemeContext';
|
||||
import type { ThemeType } from '../theme/SteamTheme';
|
||||
@@ -32,62 +33,18 @@ import NebulaBanner from '../components/NebulaBanner';
|
||||
const Dashboard: React.FC = () => {
|
||||
const { currentTheme, setTheme } = useAppTheme();
|
||||
const {
|
||||
accounts, isLoading, isSyncing, serverConfig, addAccount, deleteAccount,
|
||||
switchAccount, openSteamLogin, updateServerConfig, loginToServer,
|
||||
getCommunityAccounts, syncNow
|
||||
accounts, isLoading, isSyncing, serverConfig, deleteAccount,
|
||||
switchAccount, openSteamAppLogin, openSteamLogin, updateServerConfig, loginToServer, syncNow
|
||||
} = useAccounts();
|
||||
|
||||
const [searchTerm, setSearchTerm] = useState('');
|
||||
const [isAddDialogOpen, setIsAddDialogOpen] = useState(false);
|
||||
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
|
||||
const [identifier, setIdentifier] = useState('');
|
||||
|
||||
const [addTab, setAddTab] = useState(0);
|
||||
const [communityAccounts, setCommunityAccounts] = useState<any[]>([]);
|
||||
const [isCommunityLoading, setIsCommunityLoading] = useState(false);
|
||||
const [serverUrl, setServerUrl] = useState('');
|
||||
|
||||
useEffect(() => {
|
||||
if (serverConfig?.url) {
|
||||
setServerUrl(serverConfig.url);
|
||||
}
|
||||
if (serverConfig?.url) setServerUrl(serverConfig.url);
|
||||
}, [serverConfig?.url]);
|
||||
|
||||
const loadCommunity = async () => {
|
||||
setIsCommunityLoading(true);
|
||||
try {
|
||||
const data = await getCommunityAccounts();
|
||||
setCommunityAccounts(Array.isArray(data) ? data : []);
|
||||
} catch (e) {
|
||||
} finally {
|
||||
setIsCommunityLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (isAddDialogOpen && addTab === 1) {
|
||||
loadCommunity();
|
||||
}
|
||||
}, [isAddDialogOpen, addTab]);
|
||||
|
||||
const handleAddAccount = async () => {
|
||||
if (!identifier) return;
|
||||
try {
|
||||
await addAccount({ identifier });
|
||||
setIsAddDialogOpen(false);
|
||||
setIdentifier('');
|
||||
} catch (e) {
|
||||
console.error("[Dashboard] Add failed:", e);
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddFromCommunity = async (commAcc: any) => {
|
||||
try {
|
||||
await addAccount({ identifier: commAcc.steamId });
|
||||
setIsAddDialogOpen(false);
|
||||
} catch (e) { }
|
||||
};
|
||||
|
||||
const saveSettings = async () => {
|
||||
await updateServerConfig({ url: serverUrl });
|
||||
alert("Server URL updated!");
|
||||
@@ -147,7 +104,7 @@ const Dashboard: React.FC = () => {
|
||||
variant="contained"
|
||||
color="primary"
|
||||
startIcon={<AddIcon />}
|
||||
onClick={() => setIsAddDialogOpen(true)}
|
||||
onClick={() => openSteamAppLogin()}
|
||||
sx={{ height: 32 }}
|
||||
>
|
||||
Add
|
||||
@@ -193,7 +150,7 @@ const Dashboard: React.FC = () => {
|
||||
{!isLoading && filteredAccounts.length === 0 && (
|
||||
<Box sx={{ width: '100%', mt: 10, textAlign: 'center' }}>
|
||||
<Typography variant="h6" color="textSecondary">
|
||||
No accounts tracked. Click "Add Account" to get started!
|
||||
No accounts tracked. Click "Add" to get started!
|
||||
</Typography>
|
||||
</Box>
|
||||
)}
|
||||
@@ -234,14 +191,7 @@ const Dashboard: React.FC = () => {
|
||||
InputProps={{
|
||||
endAdornment: (
|
||||
<InputAdornment position="end">
|
||||
<Button
|
||||
variant="contained"
|
||||
size="small"
|
||||
onClick={saveSettings}
|
||||
sx={{ height: 30 }}
|
||||
>
|
||||
Apply
|
||||
</Button>
|
||||
<Button variant="contained" size="small" onClick={saveSettings} sx={{ height: 30 }}>Apply</Button>
|
||||
</InputAdornment>
|
||||
),
|
||||
}}
|
||||
@@ -296,62 +246,6 @@ const Dashboard: React.FC = () => {
|
||||
<Button onClick={() => setIsSettingsOpen(false)} color="inherit" variant="contained">Done</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
|
||||
{/* Add Account Dialog */}
|
||||
<Dialog open={isAddDialogOpen} onClose={() => setIsAddDialogOpen(false)} maxWidth="sm" fullWidth>
|
||||
<DialogTitle sx={{ backgroundColor: 'background.paper', color: 'text.primary', p: 0 }}>
|
||||
<Tabs value={addTab} onChange={(_, v) => setAddTab(v)} variant="fullWidth" textColor="inherit" indicatorColor="primary">
|
||||
<Tab label="Manual Add" icon={<AddIcon />} iconPosition="start" />
|
||||
<Tab label="From Community" icon={<PublicIcon />} iconPosition="start" disabled={!serverConfig?.token} />
|
||||
</Tabs>
|
||||
</DialogTitle>
|
||||
<DialogContent sx={{ backgroundColor: 'background.paper', pt: 2, minHeight: 300 }}>
|
||||
{addTab === 0 ? (
|
||||
<>
|
||||
<Typography variant="body2" color="textSecondary" sx={{ mb: 2 }}>
|
||||
Enter a SteamID64 or Profile URL. You will need to authenticate to enable full tracking and instant login features.
|
||||
</Typography>
|
||||
<TextField
|
||||
fullWidth
|
||||
autoFocus
|
||||
placeholder="SteamID64 or Profile URL"
|
||||
value={identifier}
|
||||
onChange={(e) => setIdentifier(e.target.value)}
|
||||
sx={{ '& .MuiOutlinedInput-root': { backgroundColor: 'rgba(0, 0, 0, 0.1)' } }}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<Box>
|
||||
{isCommunityLoading ? (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'center', p: 4 }}><CircularProgress size={32} /></Box>
|
||||
) : (
|
||||
<List>
|
||||
{communityAccounts
|
||||
.filter(ca => !safeAccounts.find(a => a.steamId === ca.steamId))
|
||||
.map((ca) => (
|
||||
<ListItem key={ca.steamId} divider sx={{ borderColor: 'divider' }}>
|
||||
<Avatar src={ca.avatar} variant="square" sx={{ width: 32, height: 32, mr: 2 }} />
|
||||
<ListItemText
|
||||
primary={ca.personaName}
|
||||
secondary={ca.steamId}
|
||||
primaryTypographyProps={{ sx: { color: 'text.primary', fontWeight: 'bold' } }}
|
||||
/>
|
||||
<ListItemSecondaryAction>
|
||||
<Button size="small" variant="contained" onClick={() => handleAddFromCommunity(ca)}>Add</Button>
|
||||
</ListItemSecondaryAction>
|
||||
</ListItem>
|
||||
))}
|
||||
{communityAccounts.length === 0 && <Typography align="center" color="textSecondary" sx={{ p: 4 }}>No shared accounts found on server.</Typography>}
|
||||
</List>
|
||||
)}
|
||||
</Box>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ backgroundColor: 'background.paper', p: 2 }}>
|
||||
<Button onClick={() => setIsAddDialogOpen(false)} color="inherit">Cancel</Button>
|
||||
{addTab === 0 && <Button onClick={handleAddAccount} variant="contained" color="success" disabled={!identifier}>Add</Button>}
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
@@ -364,7 +258,7 @@ const AccountRow: React.FC<{
|
||||
onSwitch: (login: string) => void,
|
||||
onAuth: () => void
|
||||
}> = ({ account, onDelete, onSwitch, onAuth }) => {
|
||||
const { shareAccountWithUser, getServerUsers, serverConfig } = useAccounts();
|
||||
const { shareAccountWithUser, revokeAccountAccess, revokeAllAccountAccess, getServerUsers, serverConfig } = useAccounts();
|
||||
const [timeLeft, setTimeLeft] = useState<string | null>(null);
|
||||
const [isShareOpen, setIsShareOpen] = useState(false);
|
||||
const [targetUserId, setTargetUserId] = useState('');
|
||||
@@ -375,10 +269,7 @@ const AccountRow: React.FC<{
|
||||
const isCooldownActive = cooldownDate && !isNaN(cooldownDate.getTime()) && cooldownDate.getTime() > Date.now();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isCooldownActive || !cooldownDate) {
|
||||
setTimeLeft(null);
|
||||
return;
|
||||
}
|
||||
if (!isCooldownActive || !cooldownDate) { setTimeLeft(null); return; }
|
||||
const targetTime = cooldownDate.getTime();
|
||||
const timer = setInterval(() => {
|
||||
const diff = targetTime - Date.now();
|
||||
@@ -391,14 +282,9 @@ const AccountRow: React.FC<{
|
||||
return () => clearInterval(timer);
|
||||
}, [account?.cooldownExpiresAt, isCooldownActive]);
|
||||
|
||||
const avatarSrc = account?.localAvatar
|
||||
? `steam-resource://${account.localAvatar}`
|
||||
: (account?.avatar || '');
|
||||
const avatarSrc = account?.localAvatar ? `steam-resource://${account.localAvatar}` : (account?.avatar || '');
|
||||
const [imgSrc, setImgSrc] = useState(avatarSrc);
|
||||
|
||||
useEffect(() => {
|
||||
setImgSrc(avatarSrc);
|
||||
}, [avatarSrc]);
|
||||
useEffect(() => { setImgSrc(avatarSrc); }, [avatarSrc]);
|
||||
|
||||
const handleOpenShare = async () => {
|
||||
setIsShareOpen(true);
|
||||
@@ -420,130 +306,159 @@ const AccountRow: React.FC<{
|
||||
setIsSharing(true);
|
||||
try {
|
||||
await shareAccountWithUser(account.steamId, targetUserId);
|
||||
alert(`Account shared successfully!`);
|
||||
setIsShareOpen(false);
|
||||
setTargetUserId('');
|
||||
} catch (e: any) {
|
||||
alert(e.message || "Failed to share account");
|
||||
} finally {
|
||||
setIsSharing(false);
|
||||
}
|
||||
} catch (e: any) { alert(e.message || "Failed to share account");
|
||||
} finally { setIsSharing(false); }
|
||||
};
|
||||
|
||||
const handleRevoke = async (targetSteamId: string) => {
|
||||
if (!window.confirm("Revoke access for this user?")) return;
|
||||
try { await revokeAccountAccess(account.steamId, targetSteamId);
|
||||
} catch (e: any) { alert(e.message); }
|
||||
};
|
||||
|
||||
const handleRevokeAll = async () => {
|
||||
if (!window.confirm("Completely stop sharing this account?")) return;
|
||||
try { await revokeAllAccountAccess(account.steamId); setIsShareOpen(false);
|
||||
} catch (e: any) { alert(e.message); }
|
||||
};
|
||||
|
||||
const isBanned = account?.vacBanned || (account?.gameBans && account.gameBans > 0);
|
||||
const isShared = account?._id.startsWith('shared_');
|
||||
|
||||
// Primary account check
|
||||
const isPrimaryAccount = serverConfig?.serverSteamId === account.steamId;
|
||||
|
||||
// Refined Shared Logic
|
||||
const isSharedWithYou = account?._id.startsWith('shared_');
|
||||
const hasSharedMembers = (account as any).sharedWith && (account as any).sharedWith.length > 0;
|
||||
const showCommunityIcon = isSharedWithYou || hasSharedMembers;
|
||||
|
||||
return (
|
||||
<TableRow sx={{ '&:hover': { background: 'action.hover' }, borderBottom: '1px solid', borderColor: 'divider' }}>
|
||||
<TableCell>
|
||||
<Box sx={{ position: 'relative' }}>
|
||||
<Avatar src={imgSrc} variant="square" sx={{ width: 32, height: 32, border: '1px solid', borderColor: 'divider' }} />
|
||||
{isShared && (
|
||||
<Tooltip title="Community Shared Account">
|
||||
{isPrimaryAccount && (
|
||||
<Tooltip title="Primary Community Account">
|
||||
<WorkspacePremiumIcon sx={{ position: 'absolute', top: -8, left: -8, fontSize: 18, color: '#FFD700', filter: 'drop-shadow(0 0 2px rgba(0,0,0,0.5))' }} />
|
||||
</Tooltip>
|
||||
)}
|
||||
{showCommunityIcon && (
|
||||
<Tooltip title={isSharedWithYou ? "Remote Shared Account" : "Actively Shared with Community"}>
|
||||
<PeopleIcon sx={{ position: 'absolute', bottom: -4, right: -4, fontSize: 14, color: 'primary.main', bgcolor: 'background.default', borderRadius: '50%', border: '1px solid', borderColor: 'divider', p: 0.2 }} />
|
||||
</Tooltip>
|
||||
)}
|
||||
</Box>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="body2" sx={{ fontWeight: 'bold', color: isBanned ? 'error.main' : 'text.primary' }}>
|
||||
{account?.personaName || 'Unknown'}
|
||||
</Typography>
|
||||
<Typography variant="body2" sx={{ fontWeight: 'bold', color: isBanned ? 'error.main' : 'text.primary' }}>{account?.personaName || 'Unknown'}</Typography>
|
||||
<Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>{account?.steamId}</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{isBanned ? (
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, color: 'error.main' }}>
|
||||
<GppBadIcon sx={{ fontSize: 16 }} />
|
||||
<Typography variant="caption" sx={{ fontWeight: 'bold', letterSpacing: '0.5px' }}>ACCOUNT BANNED</Typography>
|
||||
<GppBadIcon sx={{ fontSize: 16 }} /><Typography variant="caption" sx={{ fontWeight: 'bold' }}>BANNED</Typography>
|
||||
</Box>
|
||||
<Box sx={{ display: 'flex', gap: 0.5 }}>
|
||||
{account?.vacBanned && (
|
||||
<Chip label="VAC" size="small" sx={{ height: 16, fontSize: '0.6rem', bgcolor: 'error.main', color: 'white', fontWeight: 'bold', borderRadius: 0.5 }} />
|
||||
)}
|
||||
{account?.gameBans ? account.gameBans > 0 && (
|
||||
<Chip label={`${account.gameBans} GAME`} size="small" sx={{ height: 16, fontSize: '0.6rem', bgcolor: 'error.main', color: 'white', fontWeight: 'bold', borderRadius: 0.5 }} />
|
||||
) : null}
|
||||
{account?.vacBanned && <Chip label="VAC" size="small" sx={{ height: 16, fontSize: '0.6rem', bgcolor: 'error.main', color: 'white', fontWeight: 'bold' }} />}
|
||||
{account?.gameBans ? account.gameBans > 0 && <Chip label={`${account.gameBans} GAME`} size="small" sx={{ height: 16, fontSize: '0.6rem', bgcolor: 'error.main', color: 'white', fontWeight: 'bold' }} /> : null}
|
||||
</Box>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, color: 'success.main' }}>
|
||||
<ShieldIcon sx={{ fontSize: 16 }} />
|
||||
<Typography variant="caption" sx={{ fontWeight: 'bold', letterSpacing: '0.5px' }}>SECURE</Typography>
|
||||
<ShieldIcon sx={{ fontSize: 16 }} /><Typography variant="caption" sx={{ fontWeight: 'bold' }}>SECURE</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{account?.authError ? (
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', color: 'warning.main', gap: 0.5 }}>
|
||||
<LockResetIcon sx={{ fontSize: 16 }} />
|
||||
<Typography variant="body2" sx={{ fontWeight: 'bold' }}>Needs Re-auth</Typography>
|
||||
<LockResetIcon sx={{ fontSize: 16 }} /><Typography variant="body2" sx={{ fontWeight: 'bold' }}>Needs Re-auth</Typography>
|
||||
</Box>
|
||||
) : isCooldownActive ? (
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', color: 'primary.main', gap: 0.5 }}>
|
||||
<TimerIcon sx={{ fontSize: 16 }} />
|
||||
<Typography variant="body2" sx={{ fontWeight: 'bold' }}>{timeLeft}</Typography>
|
||||
<TimerIcon sx={{ fontSize: 16 }} /><Typography variant="body2" sx={{ fontWeight: 'bold' }}>{timeLeft}</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<Typography variant="caption" sx={{ color: 'text.secondary' }}>Available</Typography>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 0.5 }}>
|
||||
{account?.steamLoginSecure ? (
|
||||
<Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 0.5, alignItems: 'center' }}>
|
||||
{account.loginName && (
|
||||
<Button
|
||||
variant="contained" size="small" onClick={() => onSwitch(account.loginName || '')}
|
||||
sx={{ height: 28, fontSize: '0.7rem', bgcolor: 'secondary.main', '&:hover': { opacity: 0.9 } }}
|
||||
>
|
||||
LOGIN
|
||||
</Button>
|
||||
) : (
|
||||
<Button variant="outlined" size="small" onClick={onAuth} sx={{ height: 28, fontSize: '0.7rem' }}>AUTH</Button>
|
||||
sx={{ height: 28, fontSize: '0.7rem', bgcolor: 'secondary.main', '&:hover': { opacity: 0.9 }, minWidth: 60 }}
|
||||
>LOGIN</Button>
|
||||
)}
|
||||
<Tooltip title={account.steamLoginSecure && !account.authError ? "Tracking active" : "Authenticate for cooldowns"}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
|
||||
<IconButton
|
||||
size="small" onClick={onAuth} disabled={!!(account.steamLoginSecure && !account.authError)}
|
||||
sx={{
|
||||
color: account.steamLoginSecure && !account.authError ? 'success.main' : (account.authError ? 'error.main' : 'warning.main'),
|
||||
border: '1px solid', borderColor: account.steamLoginSecure && !account.authError ? 'success.main' : 'divider',
|
||||
borderRadius: 1, background: account.steamLoginSecure && !account.authError ? 'rgba(163, 207, 6, 0.1)' : 'transparent'
|
||||
}}
|
||||
>
|
||||
{account.steamLoginSecure && !account.authError ? <VerifiedUserIcon fontSize="inherit" /> : (account.authError ? <LockResetIcon fontSize="inherit" /> : <BoltIcon fontSize="inherit" />)}
|
||||
</IconButton>
|
||||
{account.steamLoginSecure && !account.authError && (
|
||||
<Typography variant="caption" sx={{ color: 'success.main', fontWeight: 'bold', fontSize: '0.6rem' }}>TRACKING</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Tooltip>
|
||||
<Divider orientation="vertical" flexItem sx={{ mx: 0.5, my: 0.5 }} />
|
||||
<IconButton size="small" onClick={handleOpenShare} disabled={!serverConfig?.token}><ShareIcon fontSize="inherit" sx={{ color: 'primary.main' }}/></IconButton>
|
||||
<IconButton size="small" sx={{ color: 'text.secondary' }} onClick={() => (window as any).electronAPI.openExternal(account?.profileUrl || '')}><OpenInNewIcon fontSize="inherit"/></IconButton>
|
||||
<IconButton size="small" sx={{ color: 'error.main' }} onClick={() => onDelete(account?._id || '')}><DeleteIcon fontSize="inherit"/></IconButton>
|
||||
</Box>
|
||||
|
||||
{/* Share Dialog */}
|
||||
<Dialog open={isShareOpen} onClose={() => setIsShareOpen(false)} maxWidth="xs" fullWidth>
|
||||
<DialogTitle sx={{ backgroundColor: 'background.paper', color: 'text.primary' }}>Share Account</DialogTitle>
|
||||
<DialogTitle sx={{ backgroundColor: 'background.paper', color: 'text.primary' }}>Permissions</DialogTitle>
|
||||
<DialogContent sx={{ backgroundColor: 'background.paper', pt: 2 }}>
|
||||
<Typography variant="body2" sx={{ mb: 2 }}>
|
||||
Select a community member to share this account with.
|
||||
</Typography>
|
||||
<FormControl fullWidth size="small" sx={{ mt: 1 }}>
|
||||
<InputLabel sx={{ color: 'text.secondary' }}>Select User</InputLabel>
|
||||
<Select
|
||||
value={targetUserId}
|
||||
label="Select User"
|
||||
onChange={(e) => setTargetUserId(e.target.value as string)}
|
||||
sx={{ bgcolor: 'rgba(0,0,0,0.1)', color: 'text.primary' }}
|
||||
>
|
||||
{serverUsers.map(user => (
|
||||
<MenuItem key={user.steamId} value={user.steamId}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
|
||||
<Avatar src={user.avatar} sx={{ width: 24, height: 24 }} />
|
||||
{user.personaName}
|
||||
</Box>
|
||||
</MenuItem>
|
||||
))}
|
||||
{serverUsers.length === 0 && <MenuItem disabled>No users found on server</MenuItem>}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<Typography variant="subtitle2" sx={{ mb: 1, color: 'primary.main' }}>GRANT ACCESS</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 1, mb: 3 }}>
|
||||
<FormControl fullWidth size="small">
|
||||
<InputLabel sx={{ color: 'text.secondary' }}>Select User</InputLabel>
|
||||
<Select
|
||||
value={targetUserId} label="Select User" onChange={(e) => setTargetUserId(e.target.value as string)}
|
||||
sx={{ bgcolor: 'rgba(0,0,0,0.1)', color: 'text.primary' }}
|
||||
>
|
||||
{serverUsers
|
||||
.filter(u => !(account as any).sharedWith?.find((sw: any) => sw.steamId === u.steamId))
|
||||
.map(user => (
|
||||
<MenuItem key={user.steamId} value={user.steamId}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}><Avatar src={user.avatar} sx={{ width: 24, height: 24 }} />{user.personaName}</Box>
|
||||
</MenuItem>
|
||||
))}
|
||||
{serverUsers.length === 0 && <MenuItem disabled>No eligible users found</MenuItem>}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<Button onClick={handleShare} variant="contained" disabled={!targetUserId || isSharing} sx={{ minWidth: 80 }}>{isSharing ? <CircularProgress size={16} color="inherit" /> : "Add"}</Button>
|
||||
</Box>
|
||||
<Divider sx={{ my: 2, borderColor: 'divider' }} />
|
||||
<Typography variant="subtitle2" sx={{ mb: 1, color: 'primary.main' }}>CURRENT ACCESS</Typography>
|
||||
<List size="small" sx={{ bgcolor: 'rgba(0,0,0,0.05)', borderRadius: 1, mb: 2 }}>
|
||||
{(account as any).sharedWith?.map((sw: any) => (
|
||||
<ListItem key={sw.steamId} dense divider sx={{ borderColor: 'divider' }}>
|
||||
<Avatar src={sw.avatar} sx={{ width: 24, height: 24, mr: 1 }} />
|
||||
<ListItemText primary={sw.personaName} primaryTypographyProps={{ variant: 'body2', sx: { fontWeight: 'bold' } }} />
|
||||
<ListItemSecondaryAction>
|
||||
<IconButton size="small" color="error" onClick={() => handleRevoke(sw.steamId)}><DeleteIcon fontSize="inherit" /></IconButton>
|
||||
</ListItemSecondaryAction>
|
||||
</ListItem>
|
||||
))}
|
||||
{(!(account as any).sharedWith || (account as any).sharedWith.length === 0) && (
|
||||
<Typography variant="caption" align="center" sx={{ display: 'block', p: 2, opacity: 0.6 }}>Not shared with anyone yet.</Typography>
|
||||
)}
|
||||
</List>
|
||||
{(account as any).sharedWith?.length > 0 && (
|
||||
<Button fullWidth variant="outlined" color="error" size="small" onClick={handleRevokeAll} startIcon={<GppBadIcon />}>Revoke All Shared Access</Button>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ backgroundColor: 'background.paper', p: 2 }}>
|
||||
<Button onClick={() => setIsShareOpen(false)} color="inherit" disabled={isSharing}>Cancel</Button>
|
||||
<Button
|
||||
onClick={handleShare}
|
||||
variant="contained"
|
||||
startIcon={isSharing ? <CircularProgress size={16} color="inherit" /> : <GroupAddIcon />}
|
||||
disabled={!targetUserId || isSharing}
|
||||
>
|
||||
{isSharing ? "Sharing..." : "Grant Access"}
|
||||
</Button>
|
||||
</DialogActions>
|
||||
<DialogActions sx={{ backgroundColor: 'background.paper', p: 2 }}><Button onClick={() => setIsShareOpen(false)} color="inherit" variant="contained">Done</Button></DialogActions>
|
||||
</Dialog>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
|
||||
234
frontend/src/pages/DashboardRow.tsx
Normal file
234
frontend/src/pages/DashboardRow.tsx
Normal file
@@ -0,0 +1,234 @@
|
||||
const AccountRow: React.FC<{
|
||||
account: Account,
|
||||
onDelete: (id: string) => void,
|
||||
onSwitch: (login: string) => void,
|
||||
onAuth: () => void
|
||||
}> = ({ account, onDelete, onSwitch, onAuth }) => {
|
||||
const { shareAccountWithUser, revokeAccountAccess, revokeAllAccountAccess, getServerUsers, serverConfig } = useAccounts();
|
||||
const [timeLeft, setTimeLeft] = useState<string | null>(null);
|
||||
const [isShareOpen, setIsShareOpen] = useState(false);
|
||||
const [targetUserId, setTargetUserId] = useState('');
|
||||
const [isSharing, setIsSharing] = useState(false);
|
||||
const [serverUsers, setServerUsers] = useState<any[]>([]);
|
||||
|
||||
const cooldownDate = account?.cooldownExpiresAt ? new Date(account.cooldownExpiresAt) : null;
|
||||
const isCooldownActive = cooldownDate && !isNaN(cooldownDate.getTime()) && cooldownDate.getTime() > Date.now();
|
||||
|
||||
useEffect(() => {
|
||||
if (!isCooldownActive || !cooldownDate) {
|
||||
setTimeLeft(null);
|
||||
return;
|
||||
}
|
||||
const targetTime = cooldownDate.getTime();
|
||||
const timer = setInterval(() => {
|
||||
const diff = targetTime - Date.now();
|
||||
if (diff <= 0) { setTimeLeft(null); clearInterval(timer); return; }
|
||||
const hours = Math.floor(diff / 3600000);
|
||||
const mins = Math.floor((diff % 3600000) / 60000);
|
||||
const secs = Math.floor((diff % 60000) / 1000);
|
||||
setTimeLeft(`${hours}h ${mins}m ${secs}s`);
|
||||
}, 1000);
|
||||
return () => clearInterval(timer);
|
||||
}, [account?.cooldownExpiresAt, isCooldownActive]);
|
||||
|
||||
const avatarSrc = account?.localAvatar
|
||||
? `steam-resource://${account.localAvatar}`
|
||||
: (account?.avatar || '');
|
||||
const [imgSrc, setImgSrc] = useState(avatarSrc);
|
||||
|
||||
useEffect(() => {
|
||||
setImgSrc(avatarSrc);
|
||||
}, [avatarSrc]);
|
||||
|
||||
const handleOpenShare = async () => {
|
||||
setIsShareOpen(true);
|
||||
try {
|
||||
const [users, selfInfo] = await Promise.all([
|
||||
getServerUsers(),
|
||||
(window as any).electronAPI.getServerUserInfo()
|
||||
]);
|
||||
const filtered = (Array.isArray(users) ? users : []).filter(u =>
|
||||
u.steamId !== selfInfo.steamId &&
|
||||
u.steamId !== account.steamId
|
||||
);
|
||||
setServerUsers(filtered);
|
||||
} catch (e) {}
|
||||
};
|
||||
|
||||
const handleShare = async () => {
|
||||
if (!targetUserId) return;
|
||||
setIsSharing(true);
|
||||
try {
|
||||
await shareAccountWithUser(account.steamId, targetUserId);
|
||||
setTargetUserId('');
|
||||
} catch (e: any) {
|
||||
alert(e.message || "Failed to share account");
|
||||
} finally {
|
||||
setIsSharing(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRevoke = async (targetSteamId: string) => {
|
||||
if (!window.confirm("Revoke access for this user?")) return;
|
||||
try {
|
||||
await revokeAccountAccess(account.steamId, targetSteamId);
|
||||
} catch (e: any) { alert(e.message); }
|
||||
};
|
||||
|
||||
const handleRevokeAll = async () => {
|
||||
if (!window.confirm("Completely stop sharing this account with the community?")) return;
|
||||
try {
|
||||
await revokeAllAccountAccess(account.steamId);
|
||||
setIsShareOpen(false);
|
||||
} catch (e: any) { alert(e.message); }
|
||||
};
|
||||
|
||||
const isBanned = account?.vacBanned || (account?.gameBans && account.gameBans > 0);
|
||||
const isShared = account?._id.startsWith('shared_');
|
||||
|
||||
return (
|
||||
<TableRow sx={{ '&:hover': { background: 'action.hover' }, borderBottom: '1px solid', borderColor: 'divider' }}>
|
||||
<TableCell>
|
||||
<Box sx={{ position: 'relative' }}>
|
||||
<Avatar src={imgSrc} variant="square" sx={{ width: 32, height: 32, border: '1px solid', borderColor: 'divider' }} />
|
||||
{isShared && (
|
||||
<Tooltip title="Community Shared Account">
|
||||
<PeopleIcon sx={{ position: 'absolute', bottom: -4, right: -4, fontSize: 14, color: 'primary.main', bgcolor: 'background.default', borderRadius: '50%', border: '1px solid', borderColor: 'divider', p: 0.2 }} />
|
||||
</Tooltip>
|
||||
)}
|
||||
</Box>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Typography variant="body2" sx={{ fontWeight: 'bold', color: isBanned ? 'error.main' : 'text.primary' }}>
|
||||
{account?.personaName || 'Unknown'}
|
||||
</Typography>
|
||||
<Typography variant="caption" sx={{ color: 'text.secondary', display: 'block' }}>{account?.steamId}</Typography>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{isBanned ? (
|
||||
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 0.5 }}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, color: 'error.main' }}>
|
||||
<GppBadIcon sx={{ fontSize: 16 }} />
|
||||
<Typography variant="caption" sx={{ fontWeight: 'bold', letterSpacing: '0.5px' }}>ACCOUNT BANNED</Typography>
|
||||
</Box>
|
||||
<Box sx={{ display: 'flex', gap: 0.5 }}>
|
||||
{account?.vacBanned && (
|
||||
<Chip label="VAC" size="small" sx={{ height: 16, fontSize: '0.6rem', bgcolor: 'error.main', color: 'white', fontWeight: 'bold', borderRadius: 0.5 }} />
|
||||
)}
|
||||
{account?.gameBans ? account.gameBans > 0 && (
|
||||
<Chip label={`${account.gameBans} GAME`} size="small" sx={{ height: 16, fontSize: '0.6rem', bgcolor: 'error.main', color: 'white', fontWeight: 'bold', borderRadius: 0.5 }} />
|
||||
) : null}
|
||||
</Box>
|
||||
</Box>
|
||||
) : (
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5, color: 'success.main' }}>
|
||||
<ShieldIcon sx={{ fontSize: 16 }} />
|
||||
<Typography variant="caption" sx={{ fontWeight: 'bold', letterSpacing: '0.5px' }}>SECURE</Typography>
|
||||
</Box>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
{account?.authError ? (
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', color: 'warning.main', gap: 0.5 }}>
|
||||
<LockResetIcon sx={{ fontSize: 16 }} />
|
||||
<Typography variant="body2" sx={{ fontWeight: 'bold' }}>Needs Re-auth</Typography>
|
||||
</Box>
|
||||
) : isCooldownActive ? (
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', color: 'primary.main', gap: 0.5 }}>
|
||||
<TimerIcon sx={{ fontSize: 16 }} />
|
||||
<Typography variant="body2" sx={{ fontWeight: 'bold' }}>{timeLeft}</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<Typography variant="caption" sx={{ color: 'text.secondary' }}>Available</Typography>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell align="right">
|
||||
<Box sx={{ display: 'flex', justifyContent: 'flex-end', gap: 0.5, alignItems: 'center' }}>
|
||||
{account.loginName && (
|
||||
<Button
|
||||
variant="contained" size="small" onClick={() => onSwitch(account.loginName || '')}
|
||||
sx={{ height: 28, fontSize: '0.7rem', bgcolor: 'secondary.main', '&:hover': { opacity: 0.9 }, minWidth: 60 }}
|
||||
>
|
||||
LOGIN
|
||||
</Button>
|
||||
)}
|
||||
|
||||
<Tooltip title={account.steamLoginSecure && !account.authError ? "Session valid - Tracking active" : (account.steamLoginSecure ? "Refresh scraper session" : "Authenticate for cooldown tracking")}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 0.5 }}>
|
||||
<IconButton
|
||||
size="small" onClick={onAuth}
|
||||
disabled={!!(account.steamLoginSecure && !account.authError)}
|
||||
sx={{
|
||||
color: account.steamLoginSecure && !account.authError ? 'success.main' : (account.authError ? 'error.main' : 'warning.main'),
|
||||
border: '1px solid', borderColor: account.steamLoginSecure && !account.authError ? 'success.main' : 'divider',
|
||||
borderRadius: 1, background: account.steamLoginSecure && !account.authError ? 'rgba(163, 207, 6, 0.1)' : 'transparent'
|
||||
}}
|
||||
>
|
||||
{account.steamLoginSecure && !account.authError ? <VerifiedUserIcon fontSize="inherit" /> : (account.authError ? <LockResetIcon fontSize="inherit" /> : <BoltIcon fontSize="inherit" />)}
|
||||
</IconButton>
|
||||
{account.steamLoginSecure && !account.authError && (
|
||||
<Typography variant="caption" sx={{ color: 'success.main', fontWeight: 'bold', fontSize: '0.6rem', letterSpacing: '0.5px' }}>
|
||||
TRACKING
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
</Tooltip>
|
||||
|
||||
<Divider orientation="vertical" flexItem sx={{ mx: 0.5, my: 0.5 }} />
|
||||
|
||||
<IconButton size="small" onClick={handleOpenShare} disabled={!serverConfig?.token}><ShareIcon fontSize="inherit" sx={{ color: 'primary.main' }}/></IconButton>
|
||||
<IconButton size="small" sx={{ color: 'text.secondary' }} onClick={() => (window as any).electronAPI.openExternal(account?.profileUrl || '')}><OpenInNewIcon fontSize="inherit"/></IconButton>
|
||||
<IconButton size="small" sx={{ color: 'error.main' }} onClick={() => onDelete(account?._id || '')}><DeleteIcon fontSize="inherit"/></IconButton>
|
||||
</Box>
|
||||
|
||||
<Dialog open={isShareOpen} onClose={() => setIsShareOpen(false)} maxWidth="xs" fullWidth>
|
||||
<DialogTitle sx={{ backgroundColor: 'background.paper', color: 'text.primary' }}>Account Permissions</DialogTitle>
|
||||
<DialogContent sx={{ backgroundColor: 'background.paper', pt: 2 }}>
|
||||
<Typography variant="subtitle2" sx={{ mb: 1, color: 'primary.main' }}>GRANT ACCESS</Typography>
|
||||
<Box sx={{ display: 'flex', gap: 1, mb: 3 }}>
|
||||
<FormControl fullWidth size="small">
|
||||
<InputLabel sx={{ color: 'text.secondary' }}>Select User</InputLabel>
|
||||
<Select
|
||||
value={targetUserId} label="Select User" onChange={(e) => setTargetUserId(e.target.value as string)}
|
||||
sx={{ bgcolor: 'rgba(0,0,0,0.1)', color: 'text.primary' }}
|
||||
>
|
||||
{serverUsers
|
||||
.filter(u => !(account as any).sharedWith?.find((sw: any) => sw.steamId === u.steamId))
|
||||
.map(user => (
|
||||
<MenuItem key={user.steamId} value={user.steamId}>
|
||||
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}><Avatar src={user.avatar} sx={{ width: 24, height: 24 }} />{user.personaName}</Box>
|
||||
</MenuItem>
|
||||
))}
|
||||
{serverUsers.length === 0 && <MenuItem disabled>No eligible users found</MenuItem>}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<Button onClick={handleShare} variant="contained" disabled={!targetUserId || isSharing} sx={{ minWidth: 80 }}>
|
||||
{isSharing ? <CircularProgress size={16} color="inherit" /> : "Add"}
|
||||
</Button>
|
||||
</Box>
|
||||
<Divider sx={{ my: 2, borderColor: 'divider' }} />
|
||||
<Typography variant="subtitle2" sx={{ mb: 1, color: 'primary.main' }}>CURRENT ACCESS</Typography>
|
||||
<List size="small" sx={{ bgcolor: 'rgba(0,0,0,0.05)', borderRadius: 1, mb: 2 }}>
|
||||
{(account as any).sharedWith?.map((sw: any) => (
|
||||
<ListItem key={sw.steamId} dense divider sx={{ borderColor: 'divider' }}>
|
||||
<Avatar src={sw.avatar} sx={{ width: 24, height: 24, mr: 1 }} />
|
||||
<ListItemText primary={sw.personaName} primaryTypographyProps={{ variant: 'body2', sx: { fontWeight: 'bold' } }} />
|
||||
<ListItemSecondaryAction>
|
||||
<IconButton size="small" color="error" onClick={() => handleRevoke(sw.steamId)}><DeleteIcon fontSize="inherit" /></IconButton>
|
||||
</ListItemSecondaryAction>
|
||||
</ListItem>
|
||||
))}
|
||||
{(!(account as any).sharedWith || (account as any).sharedWith.length === 0) && (
|
||||
<Typography variant="caption" align="center" sx={{ display: 'block', p: 2, opacity: 0.6 }}>Not shared with anyone yet.</Typography>
|
||||
)}
|
||||
</List>
|
||||
{(account as any).sharedWith?.length > 0 && (
|
||||
<Button fullWidth variant="outlined" color="error" size="small" onClick={handleRevokeAll} startIcon={<GppBadIcon />}>Revoke All Shared Access</Button>
|
||||
)}
|
||||
</DialogContent>
|
||||
<DialogActions sx={{ backgroundColor: 'background.paper', p: 2 }}><Button onClick={() => setIsShareOpen(false)} color="inherit" variant="contained">Done</Button></DialogActions>
|
||||
</Dialog>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user