exiouss 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of exiouss might be problematic. Click here for more details.

package/main.js ADDED
@@ -0,0 +1,833 @@
1
+ // ═══════════════════════════════════════════
2
+ // GLOBAL STEALTH BOOT (MUST BE FIRST)
3
+ // ═══════════════════════════════════════════
4
+ const { app, BrowserWindow, screen, ipcMain, globalShortcut, clipboard, nativeImage, desktopCapturer, session } = require('electron');
5
+ app.commandLine.appendSwitch('disable-blink-features', 'AutomationControlled');
6
+ app.commandLine.appendSwitch('disable-features', 'UserAgentClientHint');
7
+ app.commandLine.appendSwitch('no-sandbox');
8
+ app.commandLine.appendSwitch('disable-site-isolation-trials');
9
+
10
+ // CRITICAL: Prevent Chromium from pausing DOM updates when window is "hidden"
11
+ app.commandLine.appendSwitch('disable-renderer-backgrounding');
12
+ app.commandLine.appendSwitch('disable-background-timer-throttling');
13
+ app.commandLine.appendSwitch('disable-backgrounding-occluded-windows');
14
+ app.commandLine.appendSwitch('disable-features', 'CalculateNativeWinOcclusion');
15
+
16
+ const path = require('path');
17
+ const fs = require('fs');
18
+ const { exec } = require('child_process');
19
+ const { powerSaveBlocker } = require('electron');
20
+
21
+ // 🛡️ POWER SHIELD: Prevent system/renderer suspension
22
+ powerSaveBlocker.start('prevent-app-suspension');
23
+
24
+ // ═══════════════════════════════════════════
25
+ // PROJECT GHOST-MODE 🛸 (Native Stealth)
26
+ // ═══════════════════════════════════════════
27
+ const { uIOhook } = require('uiohook-napi');
28
+ const koffi = require('koffi');
29
+
30
+ // ═══════════════════════════════════════════
31
+ // PROJECT PHANTOM-BATCH v12.0 🛸 (Lex200 Sealed)
32
+ // ═══════════════════════════════════════════
33
+
34
+ let overlayWindow = null;
35
+ let chatgptWin = null;
36
+
37
+ let batchQueue = []; // Array of { img: String, timestamp }
38
+ let isForcedHidden = false; // Start VISIBLE
39
+ let isUiHidden = false; // Alt+E toggle
40
+ let isAdminVisible = false;
41
+ let isPinned = false;
42
+ let isAlwaysOnTop = true;
43
+ let isCombatMode = false; // "Click-Through" Mode (Lex200 Defense)
44
+ let activeSection = "GEN"; // GEN, DEB, APT, PRG
45
+ let promptSent = false;
46
+
47
+ // AMCAT Specialized Prompts — Ignore all page noise, solve ONLY the question
48
+ const SECTION_PROMPTS = {
49
+ "GEN": "IGNORE all navigation, sidebar, comments, similar questions, and UI noise in the text. Focus ONLY on the actual problem/question. Solve with 100% accuracy. Think step-by-step internally. RESPOND WITH ONLY THE FINAL ANSWER on the first line. If MCQ, give only the option letter. If coding, give only the code. Brief explanation below if needed.",
50
+ "DEB": "IGNORE page noise. Focus ONLY on the code with the bug. Find the bug. RESPOND WITH ONLY THE CORRECTED CODE on the first line.",
51
+ "APT": "IGNORE page noise. Focus ONLY on the math/aptitude problem. Solve step-by-step internally. RESPOND WITH ONLY THE FINAL NUMBER on the first line.",
52
+ "PRG": "IGNORE page noise. Focus ONLY on the programming problem statement, examples, and constraints. Write a complete, optimized, correct solution in C++ as a LeetCode Solution class with the correct function signature. The code must be ready to paste directly into LeetCode. RESPOND WITH ONLY THE CODE. No explanation unless critical."
53
+ };
54
+
55
+ // Configuration State
56
+ let SYSTEM_PROMPT = "IGNORE all navigation, sidebar, comments, and UI noise. Focus ONLY on the actual question. Solve with 100% accuracy. Think step-by-step internally. RESPOND WITH ONLY THE ANSWER. Keep it extremely concise.";
57
+ let PROXY_RULE = "";
58
+
59
+ // ═══════════════════════════════════════════
60
+ // ENVIRONMENT SELF-HEALING
61
+ // ═══════════════════════════════════════════
62
+ function checkEnvironment() {
63
+ console.log('[SYSTEM] Verifying system dependencies...');
64
+
65
+ // Check for Admin rights (RECRUIT: Warn if non-admin)
66
+ exec('net session', (err) => {
67
+ if (err) {
68
+ console.warn('[SECURITY] App not running as Administrator.');
69
+ } else {
70
+ console.log('[SECURITY] Running with Administrator privileges.');
71
+ }
72
+ });
73
+ }
74
+
75
+ const configPath = path.join(process.cwd(), 'config.json');
76
+
77
+ // Load User Config if exists
78
+ if (fs.existsSync(configPath)) {
79
+ try {
80
+ const userConfig = JSON.parse(fs.readFileSync(configPath, 'utf8'));
81
+ if (userConfig.prompt) SYSTEM_PROMPT = userConfig.prompt;
82
+ if (userConfig.proxy) PROXY_RULE = userConfig.proxy;
83
+ } catch (e) {
84
+ console.error('[CONFIG] Failed to parse config.json, using default prompt.');
85
+ }
86
+ } else {
87
+ // Create default config if missing
88
+ try {
89
+ fs.writeFileSync(configPath, JSON.stringify({
90
+ prompt: SYSTEM_PROMPT,
91
+ proxy: ""
92
+ }, null, 4));
93
+ console.log('[CONFIG] Default config.json created.');
94
+ } catch (e) {
95
+ console.error('[CONFIG] Failed to create default config.json');
96
+ }
97
+ }
98
+
99
+ // Override with CLI Arg if provided (--prompt="..." or --proxy="...")
100
+ const promptArg = process.argv.find(arg => arg.startsWith('--prompt='));
101
+ if (promptArg) SYSTEM_PROMPT = promptArg.split('=')[1];
102
+
103
+ const proxyArg = process.argv.find(arg => arg.startsWith('--proxy='));
104
+ if (proxyArg) PROXY_RULE = proxyArg.split('=')[1];
105
+
106
+ // Mouse Analytics
107
+ let lastMousePos = { x: 0, y: 0 };
108
+ let edgeCooldown = 0;
109
+ let edgeActive = { left: false, right: false }; // Track if mouse is currently on edge
110
+ let wasVisible = true; // Sync state
111
+ // UI State
112
+ let lastOpacity = -1;
113
+
114
+ // ═══════════════════════════════════════════
115
+ // WINDOW CREATION
116
+ // ═══════════════════════════════════════════
117
+
118
+ function createOverlayWindow() {
119
+ overlayWindow = new BrowserWindow({
120
+ width: 400, height: 300, transparent: true, frame: false, alwaysOnTop: true,
121
+ skipTaskbar: true, resizable: false, focusable: false,
122
+ webPreferences: { nodeIntegration: true, contextIsolation: false }
123
+ });
124
+ overlayWindow.loadFile('index.html');
125
+
126
+ // Layer 1: System Level Stealth
127
+ overlayWindow.setAlwaysOnTop(true, 'screen-saver', 100);
128
+ overlayWindow.setVisibleOnAllWorkspaces(true, { visibleOnFullScreen: true });
129
+
130
+ // Layer 2: Ultimate Stealth (True Invisibility)
131
+ setUltimateStealth(overlayWindow);
132
+
133
+ overlayWindow.setOpacity(0.9);
134
+ overlayWindow.showInactive();
135
+ }
136
+
137
+ function setUltimateStealth(window) {
138
+ if (!window || process.platform !== 'win32') return;
139
+ try {
140
+ const user32 = koffi.load('user32.dll');
141
+ const SetWindowDisplayAffinity = user32.func('bool __stdcall SetWindowDisplayAffinity(intptr hWnd, uint32_t dwAffinity)');
142
+ const SetWindowPos = user32.func('bool __stdcall SetWindowPos(intptr hWnd, intptr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags)');
143
+ const GetForegroundWindow = user32.func('intptr __stdcall GetForegroundWindow()');
144
+
145
+ // Define mouse_event globally or within this scope if needed
146
+ global.mouse_event = user32.func('void __stdcall mouse_event(uint32_t dwFlags, uint32_t dx, uint32_t dy, uint32_t dwData, uintptr dwExtraInfo)');
147
+ global.MOUSEEVENTF_WHEEL = 0x0800;
148
+
149
+ const handle = window.getNativeWindowHandle();
150
+ const hwnd = handle.readUInt32LE();
151
+
152
+
153
+ // 🛡️ LAYER 1: Capture Protection
154
+ const result = SetWindowDisplayAffinity(hwnd, 0x00000011);
155
+ if (result) {
156
+ console.log('🛡️ STEALTH: WDA_EXCLUDEFROMCAPTURE Activated.');
157
+ } else {
158
+ window.setContentProtection(true);
159
+ }
160
+
161
+ // 🛡️ LAYER 2: Z-ORDER DOMINANCE LOOP (Fights SEB for the Top)
162
+ // SEB constantly tries to be the topmost window. We fight back every 100ms.
163
+ setInterval(() => {
164
+ if (window.isDestroyed()) return;
165
+
166
+ // SWP_NOSIZE | SWP_NOMOVE | SWP_SHOWWINDOW | SWP_NOACTIVATE = 0x0001 | 0x0002 | 0x0040 | 0x0010 = 0x0053
167
+ // HWND_TOPMOST = -1
168
+ SetWindowPos(hwnd, -1, 0, 0, 0, 0, 0x0053);
169
+
170
+ // Re-assert alwaysOnTop status for Chromium's internal logic
171
+ if (isAlwaysOnTop) {
172
+ window.setAlwaysOnTop(true, 'screen-saver', 100);
173
+ }
174
+ }, 100);
175
+
176
+ } catch (e) {
177
+ console.warn('🛡️ koffi Stealth Failure:', e.message);
178
+ window.setContentProtection(true);
179
+ }
180
+ }
181
+
182
+ // ═══════════════════════════════════════════
183
+ // STEALTH HANDSHAKE (Active Stealth Bridge)
184
+ // ═══════════════════════════════════════════
185
+
186
+ function createBridge(name, url, partition) {
187
+ const win = new BrowserWindow({
188
+ width: 1100, height: 850, x: -10000, y: -10000, show: true, // Off-screen full render (prevents focus steal)
189
+ skipTaskbar: true, frame: false, transparent: true, opacity: 0.01,
190
+ webPreferences: {
191
+ partition: `persist:${partition}`,
192
+ contextIsolation: true,
193
+ nodeIntegration: false,
194
+ javascript: true,
195
+ webSecurity: true,
196
+ backgroundThrottling: false,
197
+ offscreen: false
198
+ }
199
+ });
200
+
201
+ // 🛡️ ULTIMATE STEALTH: Hide from all capture tools even while at (0,0)
202
+ setUltimateStealth(win);
203
+
204
+ // High-Trust Firefox User Agent
205
+ const highTrustUA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0";
206
+ const sess = session.fromPartition(`persist:${partition}`);
207
+ sess.setUserAgent(highTrustUA);
208
+
209
+ sess.setPermissionRequestHandler((webContents, permission, callback) => {
210
+ if (permission === 'notifications') return callback(false);
211
+ callback(true);
212
+ });
213
+
214
+ win.webContents.setUserAgent(highTrustUA);
215
+
216
+ // Deep Stealth Fingerprint (Enhanced for Resilience)
217
+ win.webContents.on('dom-ready', () => {
218
+ win.webContents.executeJavaScript(`
219
+ // Security/Bot Detection Bypass
220
+ Object.defineProperty(navigator, 'webdriver', { get: () => false });
221
+ Object.defineProperty(navigator, 'platform', { get: () => 'Win32' });
222
+ Object.defineProperty(navigator, 'deviceMemory', { get: () => 16 });
223
+
224
+ // Mask Visibility API (Force "Running" state)
225
+ Object.defineProperty(document, 'visibilityState', { get: () => 'visible', configurable: true });
226
+ Object.defineProperty(document, 'hidden', { get: () => false, configurable: true });
227
+ document.dispatchEvent(new Event('visibilitychange'));
228
+
229
+ // State Force Injection
230
+ window.isSleeping = false;
231
+ window.isRunning = true;
232
+
233
+ // Animation Heartbeat (Prevents renderer sleep)
234
+ setInterval(() => {
235
+ window.dispatchEvent(new Event('mousemove'));
236
+ if (window.requestAnimationFrame) {
237
+ window.requestAnimationFrame(() => {});
238
+ }
239
+ }, 1000);
240
+
241
+ // Mock Focus
242
+ try { document.hasFocus = () => true; } catch(e) {}
243
+
244
+ "Injection Success";
245
+ `).catch(err => console.error("[DOM-READY ERR]", err));
246
+ });
247
+
248
+ win.loadURL(url);
249
+
250
+ win.on('close', (e) => {
251
+ e.preventDefault();
252
+ win.setBounds({ x: -10000, y: -10000, width: 1100, height: 850 });
253
+ isAdminVisible = false;
254
+ });
255
+ return win;
256
+ }
257
+
258
+ // ═══════════════════════════════════════════
259
+ // CORE WORKFLOW: CAPTURE -> BATCH -> STRIKE
260
+ // ═══════════════════════════════════════════
261
+
262
+ async function captureImageQuestion() {
263
+ if (batchQueue.length >= 10) return;
264
+ console.log(`[CAPTURE] Using Stealth GDI Memory Capture (Zero-Screenshot)...`);
265
+
266
+ const psPath = path.join(__dirname, 'bin', 'stealth_capture.ps1');
267
+ const cmd = `powershell -ExecutionPolicy Bypass -File "${psPath}"`;
268
+
269
+ // Increase buffer size for Base64 image data and PREVENT CONSOLE FLASH
270
+ exec(cmd, { maxBuffer: 1024 * 1024 * 10, windowsHide: true }, (error, stdout, stderr) => {
271
+ if (error) {
272
+ console.error(`[CAPTURE] GDI Error: ${error.message}`);
273
+ return;
274
+ }
275
+ const dataUrl = stdout.trim();
276
+ if (dataUrl && dataUrl.startsWith("data:image")) {
277
+ batchQueue.push({ img: dataUrl, text: null, time: Date.now() });
278
+ console.log(`[QUEUE] Added stealth image ${batchQueue.length}/10`);
279
+ updateUI();
280
+ } else {
281
+ console.warn(`[CAPTURE] Failed to get pixel data: ${dataUrl}`);
282
+ }
283
+ });
284
+ }
285
+
286
+ // ═══════════════════════════════════════════
287
+ // TEXT CLEANING (Strip page noise before sending to AI)
288
+ // ═══════════════════════════════════════════
289
+ function cleanExtractedText(raw) {
290
+ if (!raw) return raw;
291
+
292
+ const lines = raw.split('\n');
293
+ let cleaned = [];
294
+ let hitCutoff = false;
295
+
296
+ // Patterns that signal "end of real question content" (less strict about line start)
297
+ const CUTOFF_PATTERNS = [
298
+ /discussion\s*\(/i,
299
+ /similar questions/i,
300
+ /comments?$/i,
301
+ /sort by/i,
302
+ /choose a type/i,
303
+ /copyright/i,
304
+ /daily question tag/i,
305
+ /\d+ days? badge/i,
306
+ ];
307
+
308
+ // Lines to always skip
309
+ const SKIP_PATTERNS = [
310
+ /^(back|forward|reload|extensions|bookmark|new tab|mute tab|restore)$/i,
311
+ /address and search bar|search tabs|tab content shared|memory usage/i,
312
+ /view site information|control your music|install \w+/i,
313
+ /prev question|next question|pick one|expand panel|upgrade to premium/i,
314
+ /ask leet|layouts|settings|stopwatch|invite|user menu|premium lock/i,
315
+ /leetcode logo|online|saved|ln \d+|col \d+/i,
316
+ /\d+ minutes?.*seconds?/i,
317
+ /accepted|acceptance rate|seen this question/i,
318
+ /hint \d|topics|companies/i,
319
+ /\w+\s+(easy|med\.|medium|hard)/i,
320
+ /\d+\.\s+\w+.*\s+(easy|med\.|medium|hard)/i,
321
+ ];
322
+
323
+ // SECOND PASS: Extract code editor template from FULL text (priority)
324
+ const codePatterns = [
325
+ /class\s+Solution[\s\S]*?\{[\s\S]*?\};?/, // LeetCode C++/Java Class
326
+ /def\s+\w+\(self[\s\S]*?\):/, // Python
327
+ /function\s+\w+\([\s\S]*?\)\s*\{/, // JS
328
+ /public\s+[\s\S]*?class\s+\w+[\s\S]*?\{/, // General Java
329
+ ];
330
+
331
+ let template = "";
332
+ for (const pat of codePatterns) {
333
+ const match = raw.match(pat);
334
+ if (match) { template = match[0].trim(); break; }
335
+ }
336
+
337
+ for (const line of lines) {
338
+ const trimmed = line.trim();
339
+ if (!trimmed) continue;
340
+
341
+ // Check cutoff
342
+ for (const pat of CUTOFF_PATTERNS) {
343
+ if (pat.test(trimmed)) { hitCutoff = true; break; }
344
+ }
345
+ if (hitCutoff) break;
346
+
347
+ // Check skip
348
+ let skip = false;
349
+ for (const pat of SKIP_PATTERNS) {
350
+ if (pat.test(trimmed)) { skip = true; break; }
351
+ }
352
+ if (skip) continue;
353
+
354
+ cleaned.push(trimmed);
355
+ }
356
+
357
+ // Cap description at 8000 chars for modern LLMs
358
+ let description = cleaned.join('\n');
359
+ if (description.length > 8000) {
360
+ description = description.substring(0, 8000) + '\n[...Description Truncated...]';
361
+ }
362
+
363
+ // Final assembly: Template FIRST so AI definitely sees what function to fix
364
+ let final = "";
365
+ if (template) final += "--- CODE TEMPLATE (DO NOT CHANGE SIGNATURE) ---\n" + template + "\n\n";
366
+ final += "--- PROBLEM DESCRIPTION ---\n" + description;
367
+
368
+ return final;
369
+ }
370
+
371
+ async function captureTextQuestion() {
372
+ if (batchQueue.length >= 10) return;
373
+ console.log(`[CAPTURE] Using Standalone UIA Engine (.exe)...`);
374
+
375
+ // Call the compiled executable (zero-dependency, skips Electron windows)
376
+ const exePath = path.join(__dirname, 'bin', 'uia_extract.exe');
377
+ const cmd = `"${exePath}"`;
378
+
379
+ // Ensure no terminal pops up and steals focus
380
+ exec(cmd, { encoding: 'utf8', windowsHide: true }, (error, stdout, stderr) => {
381
+ if (error) {
382
+ console.error(`[UIA] Engine Error: ${error.message}`);
383
+ return;
384
+ }
385
+ const rawText = stdout.trim();
386
+ const text = cleanExtractedText(rawText);
387
+ if (text && !text.startsWith("ERROR") && !text.startsWith("TARGET:")) {
388
+ batchQueue.push({ img: null, text: text, time: Date.now() });
389
+ console.log(`[QUEUE] Added text question ${batchQueue.length}/10 (${text.length} chars, cleaned from ${rawText.length})`);
390
+ updateUI();
391
+ } else {
392
+ console.warn(`[UIA] No text extracted or fallback only: ${text}`);
393
+ if (overlayWindow) overlayWindow.webContents.send('update-ans', '⚠️ NO TEXT DETECTED (USE IMAGE CAPTURE)');
394
+ }
395
+ });
396
+ }
397
+
398
+ async function performOracleStrike() {
399
+ if (batchQueue.length === 0) return;
400
+
401
+ console.log(`[STRIKE] Sending ${batchQueue.length} questions to ChatGPT...`);
402
+
403
+ const images = batchQueue.filter(q => q.img).map(item => item.img);
404
+ const textContext = batchQueue.filter(q => q.text).map(item => item.text).join('\n\n───\n\n');
405
+
406
+ // Build the correct prompt based on section
407
+ const finalPrompt = SECTION_PROMPTS[activeSection] || SYSTEM_PROMPT;
408
+
409
+ // Preparation Script
410
+ const injectionScript = `
411
+ (async function() {
412
+ try {
413
+ const imgs = ${JSON.stringify(images)};
414
+ const texts = ${JSON.stringify(textContext)};
415
+ const PROMPT = ${JSON.stringify(finalPrompt)};
416
+
417
+ const input = document.querySelector('div[contenteditable="true"]') ||
418
+ document.querySelector('textarea') ||
419
+ document.querySelector('.ProseMirror') ||
420
+ document.querySelector('[aria-label*="message"]');
421
+ if (!input) return "Input Not Found";
422
+
423
+ input.focus();
424
+
425
+ // 1. Paste Images if any
426
+ for (const dataUrl of imgs) {
427
+ const parts = dataUrl.split(',');
428
+ const bstr = atob(parts[1]);
429
+ let n = bstr.length;
430
+ const u8arr = new Uint8Array(n);
431
+ while(n--) u8arr[n] = bstr.charCodeAt(n);
432
+ const file = new File([u8arr], "question.png", { type: "image/png" });
433
+ const dt = new DataTransfer();
434
+ dt.items.add(file);
435
+ const pasteEvent = new ClipboardEvent('paste', { clipboardData: dt, bubbles: true, cancelable: true });
436
+ input.dispatchEvent(pasteEvent);
437
+ await new Promise(r => setTimeout(r, 800));
438
+ }
439
+
440
+ // 2. Insert Accumulated Text Context
441
+ if (texts) {
442
+ document.execCommand('insertText', false, "CONTEXT FROM UIA:\\n" + texts + "\\n\\n");
443
+ input.dispatchEvent(new Event('input', { bubbles: true }));
444
+ }
445
+
446
+ // 3. Dynamic User-Controlled Prompt
447
+ document.execCommand('insertText', false, PROMPT);
448
+ input.dispatchEvent(new Event('input', { bubbles: true }));
449
+
450
+ // ☢️ STATE FORCE: Make React/ProseMirror recognize our text
451
+ input.dispatchEvent(new Event('input', { bubbles: true }));
452
+ input.dispatchEvent(new Event('change', { bubbles: true }));
453
+
454
+ // 🎯 WAIT for Send button to become active, THEN press Enter
455
+ let attempts = 0;
456
+ while (attempts < 50) {
457
+ await new Promise(r => setTimeout(r, 200));
458
+
459
+ const sendBtn = document.querySelector('button[data-testid="send-button"]') ||
460
+ document.querySelector('button[aria-label*="Send"]');
461
+
462
+ if (sendBtn && !sendBtn.disabled) {
463
+ // Button is ready — fire Enter
464
+ const enterDown = new KeyboardEvent('keydown', {
465
+ key: 'Enter', code: 'Enter', keyCode: 13, which: 13,
466
+ bubbles: true, cancelable: true
467
+ });
468
+ const enterPress = new KeyboardEvent('keypress', {
469
+ key: 'Enter', code: 'Enter', keyCode: 13, which: 13,
470
+ bubbles: true, cancelable: true
471
+ });
472
+ const enterUp = new KeyboardEvent('keyup', {
473
+ key: 'Enter', code: 'Enter', keyCode: 13, which: 13,
474
+ bubbles: true, cancelable: true
475
+ });
476
+
477
+ input.focus();
478
+ input.dispatchEvent(enterDown);
479
+ input.dispatchEvent(enterPress);
480
+ input.dispatchEvent(enterUp);
481
+
482
+ return "Success (Enter after " + (attempts * 200) + "ms)";
483
+ }
484
+ attempts++;
485
+ }
486
+ return "Timeout - Send never activated";
487
+ } catch (err) { return "Error: " + err.message; }
488
+ })()
489
+ `;
490
+
491
+ if (chatgptWin) {
492
+ chatgptWin.webContents.executeJavaScript(injectionScript)
493
+ .then(result => console.log("[STRIKE] Script Result:", result))
494
+ .catch(err => console.error("[STRIKE ERROR] Failed to execute injection:", err));
495
+
496
+ pollForResult(chatgptWin, 'chatgpt');
497
+ promptSent = true;
498
+ }
499
+
500
+ questionCounter++;
501
+ overlayWindow.webContents.send('update-ans', JSON.stringify({ type: 'solving', qNum: questionCounter }));
502
+ batchQueue = [];
503
+ updateUI();
504
+ }
505
+
506
+ let sessionHistory = []; // [{qNum: 1, answer: "Option B"}, ...]
507
+ let questionCounter = 0;
508
+ let lastPollHash = "";
509
+
510
+ let pollInterval = null;
511
+ async function pollForResult(win) {
512
+ if (pollInterval) clearTimeout(pollInterval);
513
+
514
+ // Grab ALL assistant response texts
515
+ const pollScript = `
516
+ (function() {
517
+ try {
518
+ // Target the specific assistant message content blocks
519
+ const assistantMsgs = document.querySelectorAll('[data-message-author-role="assistant"]');
520
+ const results = [];
521
+
522
+ assistantMsgs.forEach(msg => {
523
+ // Try to find the inner prose/markdown content first (cleanest)
524
+ const content = msg.querySelector('.prose, .markdown') || msg;
525
+ const text = content.innerText.trim();
526
+ if (text && text.length > 3 && text !== "Thinking...") {
527
+ results.push(text);
528
+ }
529
+ });
530
+
531
+ // Final safety: Remove identical consecutive duplicates
532
+ return JSON.stringify(results.filter((item, pos, self) => {
533
+ return !pos || item !== self[pos - 1];
534
+ }));
535
+ } catch(e) { return null; }
536
+ })()
537
+ `;
538
+
539
+ async function runPoll() {
540
+ if (!win || win.isDestroyed()) return;
541
+ try {
542
+ const result = await win.webContents.executeJavaScript(pollScript);
543
+ if (result) {
544
+ const allAnswers = JSON.parse(result);
545
+ // Include total length in hash so streaming updates trigger UI refresh
546
+ const lastIdx = allAnswers.length - 1;
547
+ const lastText = lastIdx >= 0 ? allAnswers[lastIdx] : "";
548
+ const hash = allAnswers.length + ':' + lastText.length + ':' + lastText.substring(0, 20);
549
+
550
+ if (hash !== lastPollHash && allAnswers.length > 0) {
551
+ lastPollHash = hash;
552
+
553
+ // Map each answer to a question number
554
+ sessionHistory = allAnswers.map((ans, i) => ({
555
+ qNum: i + 1,
556
+ answer: ans.replace(/\n+$/, '').trim()
557
+ }));
558
+
559
+ // Keep questionCounter in sync
560
+ if (questionCounter < sessionHistory.length) {
561
+ questionCounter = sessionHistory.length;
562
+ }
563
+
564
+ if (overlayWindow && !overlayWindow.isDestroyed()) {
565
+ overlayWindow.webContents.send('update-ans', JSON.stringify({ type: 'history', items: sessionHistory }));
566
+ updateUI();
567
+ }
568
+ }
569
+ }
570
+ } catch (e) {
571
+ // Silent poll retry
572
+ }
573
+ pollInterval = setTimeout(runPoll, 500);
574
+ }
575
+
576
+ runPoll();
577
+ }
578
+
579
+ // ═══════════════════════════════════════════
580
+ // UI DISPATCH & HUD
581
+ // ═══════════════════════════════════════════
582
+
583
+ function updateUI() {
584
+ if (!overlayWindow) return;
585
+ overlayWindow.webContents.send('update-hud', {
586
+ count: batchQueue.length,
587
+ isForcedHidden,
588
+ isUiHidden,
589
+ isPinned,
590
+ isAlwaysOnTop,
591
+ isCombatMode,
592
+ activeSection
593
+ });
594
+ if (sessionHistory.length > 0) {
595
+ overlayWindow.webContents.send('update-ans', JSON.stringify({ type: 'history', items: sessionHistory }));
596
+ }
597
+ }
598
+
599
+ // ═══════════════════════════════════════════
600
+ // STEALTH POLLING (Hover Reveal)
601
+ // ═══════════════════════════════════════════
602
+ // ═══════════════════════════════════════════
603
+ // STEALTH ENGINE (Edges & Jitter)
604
+ // ═══════════════════════════════════════════
605
+ setInterval(() => {
606
+ if (!overlayWindow || overlayWindow.isDestroyed()) return;
607
+
608
+ const mouse = screen.getCursorScreenPoint();
609
+ const { width: screenWidth, height: screenHeight } = screen.getPrimaryDisplay().bounds;
610
+
611
+ // 1. Edge Triggers (Capture/Solve)
612
+ if (Date.now() > edgeCooldown) {
613
+ if (mouse.x >= screenWidth - 1) { // Right Edge Proximity
614
+ if (!edgeActive.right) {
615
+ captureTextQuestion();
616
+ edgeActive.right = true;
617
+ edgeCooldown = Date.now() + 2000; // 2s cooldown
618
+ }
619
+ } else {
620
+ edgeActive.right = false;
621
+ }
622
+
623
+ if (mouse.x <= 0) { // Left Edge Proximity
624
+ if (!edgeActive.left) {
625
+ performOracleStrike();
626
+ edgeActive.left = true;
627
+ edgeCooldown = Date.now() + 2000;
628
+ }
629
+ } else {
630
+ edgeActive.left = false;
631
+ }
632
+ }
633
+
634
+ lastMousePos = { x: mouse.x, y: mouse.y };
635
+
636
+ // 3. Position HUD Window
637
+ if (isPinned) return;
638
+
639
+ if (isForcedHidden) {
640
+ if (wasVisible) {
641
+ overlayWindow.hide();
642
+ wasVisible = false;
643
+ }
644
+ } else {
645
+ if (!wasVisible) {
646
+ overlayWindow.showInactive();
647
+ wasVisible = true;
648
+ }
649
+
650
+ const sf = screen.getPrimaryDisplay().scaleFactor || 1.0;
651
+ overlayWindow.setBounds({
652
+ x: Math.round(mouse.x + 10), y: Math.round(mouse.y + 10),
653
+ width: Math.round(300 * sf), height: Math.round(150 * sf)
654
+ });
655
+ }
656
+ }, 25);
657
+
658
+ // ═══════════════════════════════════════════
659
+ // HOTKEYS
660
+ // ═══════════════════════════════════════════
661
+
662
+ app.whenReady().then(async () => {
663
+ app.setName('Windows Diagnostic Utility');
664
+
665
+ // 🛡️ FIREWALL SHIELD: Apply Proxy if specified
666
+ if (PROXY_RULE) {
667
+ console.log(`[PROXY] Routing traffic through: ${PROXY_RULE}`);
668
+ const proxyConfig = { proxyRules: PROXY_RULE };
669
+ await session.defaultSession.setProxy(proxyConfig);
670
+ const gptSess = session.fromPartition('persist:chatgpt');
671
+ await gptSess.setProxy(proxyConfig);
672
+ }
673
+
674
+ createOverlayWindow();
675
+ chatgptWin = createBridge('chatgpt', 'https://chat.openai.com', 'chatgpt');
676
+
677
+ // Run environment check after windows are ready
678
+ setTimeout(checkEnvironment, 2000);
679
+
680
+ const register = (key, fn) => {
681
+ const success = globalShortcut.register(key, fn);
682
+ console.log(`[KEY] ${key} registration: ${success ? 'OK' : 'FAILED'}`);
683
+ return success;
684
+ };
685
+
686
+ // 🎯 HOTKEYS: Only keep Alt+X and Alt+C
687
+ register('Alt+C', () => {
688
+ isCombatMode = !isCombatMode;
689
+ updateUI();
690
+ console.log(`[APP] Combat Mode (Lex200 Defense): ${isCombatMode}`);
691
+ });
692
+
693
+ register('Alt+X', () => {
694
+ if (isCombatMode) return;
695
+ isAdminVisible = !isAdminVisible;
696
+ if (chatgptWin) {
697
+ if (isAdminVisible) {
698
+ const { width, height } = screen.getPrimaryDisplay().workAreaSize;
699
+ chatgptWin.setOpacity(1.0);
700
+ chatgptWin.setBounds({
701
+ x: Math.round(width/2 - 550),
702
+ y: Math.round(height/2 - 425),
703
+ width: 1100, height: 850
704
+ });
705
+ chatgptWin.focus();
706
+ } else {
707
+ chatgptWin.setOpacity(0.01);
708
+ chatgptWin.setBounds({ x: -10000, y: -10000, width: 1100, height: 850 });
709
+ }
710
+ }
711
+ });
712
+
713
+ // 🕊️ GHOST MODE: uIOhook Listener (Arrow Keys only)
714
+ let isUpPressed = false, isDownPressed = false, isLeftPressed = false, isRightPressed = false;
715
+ let isShiftPressed = false;
716
+ let isChordLocked = false;
717
+
718
+ uIOhook.on('keydown', (e) => {
719
+ // Wrap in setImmediate to prevent N-API thread crash
720
+ setImmediate(() => {
721
+ if (e.keycode === 57416 || e.keycode === 72) isUpPressed = true;
722
+ if (e.keycode === 57424 || e.keycode === 80) isDownPressed = true;
723
+ if (e.keycode === 57419 || e.keycode === 75) isLeftPressed = true;
724
+ if (e.keycode === 57421 || e.keycode === 77) isRightPressed = true;
725
+ if (e.keycode === 42 || e.keycode === 54) isShiftPressed = true;
726
+
727
+ // 1. Hide/Unhide HUD (Up + Down)
728
+ if (isUpPressed && isDownPressed) {
729
+ isForcedHidden = !isForcedHidden;
730
+ updateUI();
731
+ isUpPressed = false; isDownPressed = false;
732
+ }
733
+
734
+ // 3. TEXT CAPTURE (Left + Right) — 100% Safe
735
+ if (isLeftPressed && isRightPressed) {
736
+ if (isChordLocked) return;
737
+ console.log(`[CHORD] TEXT CAPTURE Triggered (Safe Mode)...`);
738
+ isChordLocked = true;
739
+ captureTextQuestion();
740
+ isLeftPressed = false; isRightPressed = false;
741
+ setTimeout(() => { isChordLocked = false; }, 2000);
742
+ }
743
+
744
+ // 3b. IMAGE CAPTURE (Down + Left) — Diagram Mode
745
+ if (isDownPressed && isLeftPressed) {
746
+ if (isChordLocked) return;
747
+ console.log(`[CHORD] DIAGRAM CAPTURE Triggered (GDI Mode)...`);
748
+ isChordLocked = true;
749
+ captureImageQuestion();
750
+ isDownPressed = false; isLeftPressed = false;
751
+ setTimeout(() => { isChordLocked = false; }, 2000);
752
+ }
753
+
754
+ // 4. Perform Strike (Up + Right)
755
+ if (isUpPressed && isRightPressed) {
756
+ performOracleStrike();
757
+ isUpPressed = false; isRightPressed = false;
758
+ }
759
+
760
+ // 5. Pin/Unpin (Up + Left)
761
+ if (isUpPressed && isLeftPressed) {
762
+ isPinned = !isPinned;
763
+ updateUI();
764
+ isUpPressed = false; isLeftPressed = false;
765
+ }
766
+ });
767
+ });
768
+
769
+ uIOhook.on('keyup', (e) => {
770
+ setImmediate(() => {
771
+ if (e.keycode === 57416 || e.keycode === 72) isUpPressed = false;
772
+ if (e.keycode === 57424 || e.keycode === 80) isDownPressed = false;
773
+ if (e.keycode === 57419 || e.keycode === 75) isLeftPressed = false;
774
+ if (e.keycode === 57421 || e.keycode === 77) isRightPressed = false;
775
+ if (e.keycode === 42 || e.keycode === 54) isShiftPressed = false;
776
+ });
777
+ });
778
+
779
+ // STEALTH CLICK HANDLER: Manually route clicks when window is focusable:false
780
+ uIOhook.on('mousedown', (e) => {
781
+ setImmediate(() => {
782
+ if (!overlayWindow || overlayWindow.isDestroyed() || !overlayWindow.isVisible()) return;
783
+ const bounds = overlayWindow.getBounds();
784
+ const primaryDisplay = screen.getPrimaryDisplay();
785
+ const sf = primaryDisplay.scaleFactor;
786
+
787
+ const mX = e.x / sf;
788
+ const mY = e.y / sf;
789
+
790
+ if (mX >= bounds.x && mX <= bounds.x + bounds.width &&
791
+ mY >= bounds.y && mY <= bounds.y + bounds.height) {
792
+ const clientX = Math.round(mX - bounds.x);
793
+ const clientY = Math.round(mY - bounds.y);
794
+ overlayWindow.webContents.send('stealth-click', { x: clientX, y: clientY });
795
+ }
796
+ });
797
+ });
798
+
799
+ // (Manual wheel listener removed to allow native touchpad support)
800
+
801
+ // Delay start to let Electron event loop stabilize
802
+ setTimeout(() => {
803
+ uIOhook.start();
804
+ console.log('[GHOST] uIOhook started successfully.');
805
+ }, 500);
806
+
807
+ // ☢️ DECONTAMINATION PROTOCOL (Alt + Shift + X)
808
+ register('Alt+Shift+X', async () => {
809
+ console.log("☢️ SELF-DESTRUCT INITIATED...");
810
+ const burnScript = `
811
+ (async function() {
812
+ try {
813
+ const gptDelete = document.querySelector('nav .bg-red-500') || document.querySelector('[aria-label*="Delete"]');
814
+ if (gptDelete) gptDelete.click();
815
+ await new Promise(r => setTimeout(r, 500));
816
+ } catch(e) {}
817
+ })()
818
+ `;
819
+ if (chatgptWin) {
820
+ chatgptWin.webContents.executeJavaScript(burnScript).catch(e => {});
821
+ await chatgptWin.webContents.session.clearStorageData();
822
+ }
823
+ promptSent = false;
824
+ await session.defaultSession.clearStorageData();
825
+ console.log("☢️ WIPE COMPLETE. EXITING.");
826
+ app.exit(0);
827
+ });
828
+
829
+ ipcMain.on('double-click', () => {
830
+ isPinned = !isPinned;
831
+ updateUI();
832
+ });
833
+ });