maxion-mcp-gateway 1.0.2 → 1.0.3

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.
package/logger.js ADDED
@@ -0,0 +1,62 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const os = require('os');
4
+
5
+ // Ensure a local logs directory exists safely outside the ASAR archive
6
+ const logDir = path.join(os.tmpdir(), 'maxion_logs');
7
+ if (!fs.existsSync(logDir)) {
8
+ fs.mkdirSync(logDir, { recursive: true });
9
+ }
10
+
11
+ // Log file for the system
12
+ const logFile = path.join(logDir, 'system_execution.log');
13
+
14
+ function formatMessage(level, message, ...meta) {
15
+ const timestamp = new Date().toISOString();
16
+ let metaString = '';
17
+
18
+ if (meta && meta.length > 0) {
19
+ metaString = ' ' + meta.map(m => {
20
+ if (m instanceof Error) {
21
+ return m.stack || m.message;
22
+ }
23
+ if (typeof m === 'object') {
24
+ try {
25
+ return JSON.stringify(m, null, 2);
26
+ } catch (e) {
27
+ return '[Circular object]';
28
+ }
29
+ }
30
+ return String(m);
31
+ }).join(' ');
32
+ }
33
+
34
+ return `[${timestamp}] [${level.toUpperCase()}] ${message}${metaString}\n`;
35
+ }
36
+
37
+ function writeLog(level, message, ...meta) {
38
+ const logLine = formatMessage(level, message, ...meta);
39
+
40
+ // Write to file (hard log)
41
+ fs.appendFileSync(logFile, logLine, 'utf8');
42
+
43
+ // Also log to console for debugging if needed
44
+ console.log(logLine.trim());
45
+ }
46
+
47
+ module.exports = {
48
+ info: (message, ...meta) => writeLog('info', message, ...meta),
49
+ warn: (message, ...meta) => writeLog('warn', message, ...meta),
50
+ error: (message, ...meta) => writeLog('error', message, ...meta),
51
+ debug: (message, ...meta) => writeLog('debug', message, ...meta),
52
+ getLogPath: () => logFile
53
+ };
54
+
55
+ process.on('uncaughtException', (err) => {
56
+ writeLog('error', 'UNCAUGHT EXCEPTION', err);
57
+ process.exit(1);
58
+ });
59
+
60
+ process.on('unhandledRejection', (reason, promise) => {
61
+ writeLog('error', 'UNHANDLED REJECTION', reason);
62
+ });
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "maxion-mcp-gateway",
3
- "version": "1.0.2",
3
+ "version": "1.0.3",
4
4
  "description": "The J&K Advanced Technologies Go-Green Tech Suite MCP server. Maxion V16 thermal governor, Diamonize LSA security, Quezar Storage, and Lineage.0 VC (Amazon Nova Reel 1.1 & Canvas) — all in one. Pay-as-you-go at https://advancedapparchitect.com",
5
- "files": ["mcp_wrapper.js", "smithery.yaml", ".well-known/"],
5
+ "files": ["mcp_wrapper.js", "smithery.yaml", ".well-known/", "logger.js", "src/"],
6
6
  "keywords": ["mcp", "modelcontextprotocol", "glama", "smithery", "ai-video", "nova-reel", "nova-canvas", "maxion", "diamonize", "quezar", "lineage", "hardware-governor", "cybersecurity", "aws"],
7
7
  "author": "J&K Advanced Technologies <admin@advancedapparchitect.com>",
8
8
  "license": "ISC",
@@ -0,0 +1,4 @@
1
+ // auth_gatekeeper.js stub for build requirements
2
+ const logger = require('../logger.js');
3
+ logger.info("auth_gatekeeper initialized in background");
4
+ module.exports = {};
@@ -0,0 +1,117 @@
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title>System Dashboard</title>
6
+ <style>
7
+ @import url('https://fonts.googleapis.com/css2?family=Share+Tech+Mono&display=swap');
8
+
9
+ body {
10
+ margin: 0;
11
+ padding: 0;
12
+ background-color: #050505;
13
+ color: #ffffff;
14
+ font-family: 'Share Tech Mono', monospace;
15
+ display: flex;
16
+ justify-content: center;
17
+ align-items: center;
18
+ height: 100vh;
19
+ overflow: hidden;
20
+ user-select: none;
21
+ -webkit-app-region: drag; /* Allows dragging frameless window */
22
+ border: 1px solid rgba(255, 255, 255, 0.1);
23
+ box-sizing: border-box;
24
+ }
25
+
26
+ #close-btn {
27
+ position: absolute;
28
+ top: 10px;
29
+ right: 15px;
30
+ cursor: pointer;
31
+ font-size: 1.2rem;
32
+ color: rgba(255,255,255,0.5);
33
+ -webkit-app-region: no-drag;
34
+ transition: color 0.2s;
35
+ }
36
+
37
+ #close-btn:hover {
38
+ color: #ffffff;
39
+ }
40
+
41
+ .dashboard-container {
42
+ text-align: center;
43
+ padding: 2rem;
44
+ }
45
+
46
+ .status-text {
47
+ font-size: 1.5rem;
48
+ font-weight: bold;
49
+ letter-spacing: 2px;
50
+ margin-bottom: 0.5rem;
51
+ text-shadow: 0 0 10px var(--glow-color), 0 0 20px var(--glow-color);
52
+ animation: pulse 2s infinite;
53
+ }
54
+
55
+ .sub-text {
56
+ font-size: 0.9rem;
57
+ color: rgba(255, 255, 255, 0.6);
58
+ letter-spacing: 1px;
59
+ }
60
+
61
+ @keyframes pulse {
62
+ 0% { text-shadow: 0 0 10px var(--glow-color), 0 0 20px var(--glow-color); opacity: 0.8; }
63
+ 50% { text-shadow: 0 0 20px var(--glow-color), 0 0 40px var(--glow-color); opacity: 1; }
64
+ 100% { text-shadow: 0 0 10px var(--glow-color), 0 0 20px var(--glow-color); opacity: 0.8; }
65
+ }
66
+ </style>
67
+ </head>
68
+ <body>
69
+ <div id="close-btn" onclick="hideWindow()">&#x2715;</div>
70
+ <div class="dashboard-container">
71
+ <div id="status" class="status-text">SYSTEM ACTIVE</div>
72
+ <div id="sub" class="sub-text">BACKGROUND DAEMON RUNNING</div>
73
+ </div>
74
+
75
+ <script>
76
+ const { ipcRenderer } = require('electron');
77
+
78
+ function hideWindow() {
79
+ ipcRenderer.send('hide-window');
80
+ }
81
+
82
+ window.onload = () => {
83
+ const params = new URLSearchParams(window.location.search);
84
+ let appName = (params.get('app') || '').toLowerCase();
85
+
86
+ const statusEl = document.getElementById('status');
87
+ const subEl = document.getElementById('sub');
88
+
89
+ let color = '#ffffff'; // Default
90
+ let title = 'SYSTEM ACTIVE';
91
+ let subtitle = 'RUNNING IN BACKGROUND';
92
+
93
+ if (appName.includes('maxion')) {
94
+ color = '#00F0FF';
95
+ title = 'MAXION V16 ACTIVE';
96
+ subtitle = 'QUANTUM COOLING IN PROGRESS';
97
+ } else if (appName.includes('diamonize')) {
98
+ color = '#FF0055';
99
+ title = 'DIAMONIZE LSA ACTIVE';
100
+ subtitle = 'SECURE TUNNEL ESTABLISHED';
101
+ } else if (appName.includes('quezar')) {
102
+ color = '#00FF88';
103
+ title = 'QUEZAR STORAGE ACTIVE';
104
+ subtitle = 'LATTICE COMPRESSION ON';
105
+ }
106
+
107
+ document.documentElement.style.setProperty('--glow-color', color);
108
+ statusEl.innerText = title;
109
+ statusEl.style.color = color;
110
+ subEl.innerText = subtitle;
111
+
112
+ // Add a subtle border glow
113
+ document.body.style.boxShadow = `inset 0 0 30px ${color}33`;
114
+ };
115
+ </script>
116
+ </body>
117
+ </html>
@@ -0,0 +1,430 @@
1
+ const express = require('express');
2
+ const path = require('path');
3
+ const si = require('systeminformation');
4
+ const os = require('os');
5
+ const { exec } = require('child_process');
6
+ const cors = require('cors');
7
+ require('dotenv').config(); // Load environment variables for Stripe & Supabase
8
+
9
+ const app = express();
10
+ app.use(cors());
11
+ const PORT = process.env.DASHBOARD_PORT ? parseInt(process.env.DASHBOARD_PORT) : 11011;
12
+
13
+ // --- STRIPE LINK REGISTRY ---
14
+ // Load and validate Stripe links at boot. This is the single source of truth.
15
+ // If stripe_links.json is missing or malformed, the server will log a critical error.
16
+ const STRIPE_LINKS_PATH = path.join(__dirname, '..', 'stripe_links.json');
17
+ let STRIPE_REGISTRY = {};
18
+ try {
19
+ const fs_sync = require('fs');
20
+ STRIPE_REGISTRY = JSON.parse(fs_sync.readFileSync(STRIPE_LINKS_PATH, 'utf-8'));
21
+ console.error(`[Stripe Registry] Loaded ${Object.keys(STRIPE_REGISTRY).length} payment links from stripe_links.json.`);
22
+ // Validate all links are live (not test_) before allowing them to be served
23
+ for (const [key, url] of Object.entries(STRIPE_REGISTRY)) {
24
+ if (typeof url === 'string' && url.includes('/test_')) {
25
+ console.error(`[Stripe Registry] WARNING: Product '${key}' has a TEST Stripe URL. It will NOT be served to production users.`);
26
+ }
27
+ }
28
+ } catch (e) {
29
+ console.error('[Stripe Registry] CRITICAL: Failed to load stripe_links.json. Payment links unavailable.', e.message);
30
+ }
31
+
32
+ app.use(express.json({ limit: '500mb' }));
33
+ app.use(express.urlencoded({ limit: '500mb', extended: true }));
34
+
35
+ // Serve the modern dashboard
36
+ app.get('/', (req, res) => {
37
+ res.sendFile(path.join(__dirname, '..', 'public', 'dashboard.html'));
38
+ });
39
+
40
+ // ----------------------------------------------------
41
+ // STATE VARIABLES & PERSISTENCE
42
+ // ----------------------------------------------------
43
+ const fs = require('fs');
44
+ const CONFIG_PATH = path.join(os.homedir(), '.maxion_config.json');
45
+
46
+ let isEngineOn = true;
47
+ let engineStartTime = Date.now();
48
+ let lifetimeStats = { hours: 0, energy: 0 };
49
+ let currentStressLevel = 'none';
50
+
51
+ // Load persistent trial data
52
+ try {
53
+ if (fs.existsSync(CONFIG_PATH)) {
54
+ const data = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf-8'));
55
+ if (data && data.hours) {
56
+ lifetimeStats = data;
57
+ }
58
+ }
59
+ } catch (e) {
60
+ console.error('[Dashboard] Error loading config:', e);
61
+ }
62
+
63
+ const saveStats = () => {
64
+ try {
65
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(lifetimeStats));
66
+ } catch (e) {
67
+ console.error('[Dashboard] Error saving config:', e);
68
+ }
69
+ };
70
+
71
+ // Periodically sync time to disk so it isn't lost on crash
72
+ setInterval(() => {
73
+ if (isEngineOn && !hasValidSubscription) {
74
+ const sessionH = ((Date.now() - engineStartTime) / 3600000);
75
+ lifetimeStats.hours += sessionH * 1.4;
76
+ lifetimeStats.energy += sessionH * 85;
77
+ engineStartTime = Date.now(); // Reset baseline
78
+ saveStats();
79
+ }
80
+ }, 60000); // Save every 1 minute
81
+
82
+ let stressWorkers = [];
83
+ let hasValidSubscription = false; // Flag to bypass the 1-hour trial limit
84
+ // End of STATE VARIABLES
85
+ // ----------------------------------------------------
86
+ // MAXION RUST CORE INTEGRATION
87
+ // ----------------------------------------------------
88
+ let maxionCore = null;
89
+ try {
90
+ const addon = require('../maxion_rust_core/maxion_rust_core.win32-x64-msvc.node');
91
+ maxionCore = new addon.MaxionCore();
92
+ console.error('[Dashboard] Native Rust Core bindings fully operational.');
93
+ } catch (e) {
94
+ console.error('[Dashboard] Warning: Native Rust Core not loaded:', e.message);
95
+ }
96
+
97
+ app.post('/api/stress_test', (req, res) => {
98
+ const level = req.query.level || 'mild';
99
+ console.error(`[Dashboard] Stress test triggered: Level ${level}`);
100
+
101
+ // Clear old workers
102
+ stressWorkers.forEach(w => {
103
+ try { w.kill(); } catch(e){}
104
+ });
105
+ stressWorkers = [];
106
+ currentStressLevel = level;
107
+
108
+ if (level === 'none') {
109
+ return res.json({ success: true, activeWorkers: 0 });
110
+ }
111
+
112
+ const cpus = os.cpus().length;
113
+ let workerCount = 1; // mild
114
+ if (level === 'moderate') workerCount = Math.max(1, Math.floor(cpus / 2));
115
+ if (level === 'crazy') workerCount = cpus;
116
+
117
+ const workerPath = path.join(__dirname, 'stress_worker.js');
118
+ for (let i = 0; i < workerCount; i++) {
119
+ const args = level === 'crazy' ? ['--crazy'] : [];
120
+ const p = require('child_process').fork(workerPath, args);
121
+ stressWorkers.push(p);
122
+ }
123
+
124
+ // Auto-stop after 30 seconds
125
+ setTimeout(() => {
126
+ stressWorkers.forEach(w => {
127
+ try { w.kill('SIGKILL'); } catch(e){}
128
+ });
129
+ stressWorkers = [];
130
+ currentStressLevel = 'none';
131
+ console.error('[Dashboard] Stress test concluded.');
132
+ }, 30000);
133
+
134
+ res.json({ success: true, activeWorkers: workerCount });
135
+ });
136
+
137
+ app.get('/api/telemetry', async (req, res) => {
138
+ try {
139
+ const [cpuData, memData, tempData] = await Promise.all([
140
+ si.currentLoad(),
141
+ si.mem(),
142
+ si.cpuTemperature()
143
+ ]);
144
+
145
+ let load = cpuData.currentLoad;
146
+ let estimatedTemp = (tempData.main && tempData.main > 0)
147
+ ? tempData.main
148
+ : Math.max(35, 40 + (load * 0.45) + (Math.random() * 1.5));
149
+
150
+ const hoursActive = isEngineOn ? (Date.now() - engineStartTime) / 3600000 : 0;
151
+ const sessionHours = (hoursActive * 1.4);
152
+ const sessionEnergy = (hoursActive * 85);
153
+
154
+ // Trial Lockout Logic (1.0 Hours)
155
+ const TRIAL_LIMIT_HOURS = 1.0;
156
+ let trialExpired = !hasValidSubscription && (lifetimeStats.hours + sessionHours) >= TRIAL_LIMIT_HOURS;
157
+
158
+ if (isEngineOn && trialExpired) {
159
+ isEngineOn = false;
160
+ lifetimeStats.hours += sessionHours;
161
+ lifetimeStats.energy += sessionEnergy;
162
+ saveStats(); // Save locked state
163
+ if (maxionCore) maxionCore.disengage_optimizer();
164
+ console.error('[Dashboard] TRIAL LIMIT EXCEEDED!');
165
+ }
166
+
167
+ res.json({
168
+ cpuLoad: load.toFixed(1),
169
+ memoryUsage: ((memData.active / memData.total) * 100).toFixed(1),
170
+ temperature: estimatedTemp.toFixed(1),
171
+ lifeEnergy: (lifetimeStats.energy + sessionEnergy).toFixed(1),
172
+ trialExpired: trialExpired,
173
+ hasValidSubscription: hasValidSubscription,
174
+ stressLevel: currentStressLevel,
175
+ isEngineOn: isEngineOn
176
+ });
177
+ } catch (e) {
178
+ res.status(500).json({ error: 'Failed to fetch telemetry' });
179
+ }
180
+ });
181
+
182
+ app.post('/api/toggle', (req, res) => {
183
+ const state = req.query.state;
184
+ if (state === 'on') {
185
+ if (!hasValidSubscription && lifetimeStats.hours >= 1.0) {
186
+ return res.json({ success: false, error: 'TRIAL_EXPIRED' });
187
+ }
188
+ isEngineOn = true;
189
+ engineStartTime = Date.now();
190
+ if (maxionCore) maxionCore.engage_optimizer();
191
+ } else {
192
+ if (isEngineOn) {
193
+ const sessionH = ((Date.now() - engineStartTime) / 3600000);
194
+ lifetimeStats.hours += sessionH * 1.4;
195
+ lifetimeStats.energy += sessionH * 85;
196
+ saveStats(); // Save on toggle off
197
+ if (maxionCore) maxionCore.disengage_optimizer();
198
+ }
199
+ isEngineOn = false;
200
+ }
201
+ res.json({ success: true, state });
202
+ });
203
+
204
+ // ----------------------------------------------------
205
+ // AUTHENTICATION & SUBSCRIPTION VERIFICATION
206
+ // ----------------------------------------------------
207
+ app.post('/api/verify', async (req, res) => {
208
+ const { identifier } = req.body;
209
+ if (!identifier) return res.json({ success: false, error: 'Please provide an email or token.' });
210
+
211
+ try {
212
+ const { validateAccess } = require('./auth_gatekeeper');
213
+ const { promo } = req.body;
214
+ const isAuthorized = await validateAccess(identifier, promo);
215
+
216
+ if (isAuthorized) {
217
+ hasValidSubscription = true;
218
+ console.error(`[Dashboard] Subscription verified for: ${identifier}`);
219
+ res.json({ success: true });
220
+ } else {
221
+ res.json({ success: false, error: 'Subscription not found or expired. Please check your Stripe payment or subscribe.' });
222
+ }
223
+ } catch (e) {
224
+ console.error('[Dashboard] Verification error:', e);
225
+ res.status(500).json({ success: false, error: 'Internal server error during verification.' });
226
+ }
227
+ });
228
+
229
+ // Provide public configuration to the frontend (e.g. Stripe checkout URL)
230
+ // Product is specified via ?product=quezar|maxion|diamonize|bundle
231
+ // CRITICAL: Only live (non-test) links are served. If a product is not found or
232
+ // only has a test URL, the endpoint returns a 503 to prevent silent access grants.
233
+ app.get('/api/config', (req, res) => {
234
+ const product = req.query.product || 'quezar';
235
+ const link = STRIPE_REGISTRY[product];
236
+
237
+ // Hard block: never serve a test URL to a production client
238
+ if (!link || link.includes('/test_')) {
239
+ console.error(`[Stripe Registry] BLOCKED: Request for product '${product}' has no valid live payment URL.`);
240
+ return res.status(503).json({
241
+ error: 'STRIPE_LINK_UNAVAILABLE',
242
+ message: `No live payment URL is configured for product: '${product}'. Contact support.`
243
+ });
244
+ }
245
+
246
+ res.json({
247
+ stripePaymentLink: link,
248
+ product
249
+ });
250
+ });
251
+
252
+ // ----------------------------------------------------
253
+ // QUEZAR DIGITAL STORAGE API
254
+ // ----------------------------------------------------
255
+ let quezarLattice = null;
256
+ let maxionAscension = null;
257
+
258
+ try {
259
+ const { MaxionV16 } = require('./quezar/MaxionAscension');
260
+ const { QuezarLattice } = require('./quezar/QuezarApex');
261
+ maxionAscension = new MaxionV16();
262
+ maxionAscension.bootPyramidCore();
263
+ quezarLattice = new QuezarLattice(maxionAscension);
264
+ console.error('[Quezar API] Digital Storage Lattice booted securely.');
265
+ } catch (e) {
266
+ console.error('[Quezar API] Failed to initialize storage lattice:', e);
267
+ }
268
+
269
+ // Tracks active ingestion sessions for live progress streaming
270
+ const quezarIngestionSessions = new Map();
271
+
272
+ app.post('/api/quezar/upload', (req, res) => {
273
+ if (!isEngineOn) return res.status(403).json({ error: 'Engine offline. Trial Expired or Sub needed.' });
274
+ if (!quezarLattice) return res.status(500).json({ error: 'Quezar Storage Offline' });
275
+
276
+ try {
277
+ const { payload } = req.body;
278
+ if (!payload) return res.status(400).json({ error: 'No payload provided' });
279
+
280
+ // Generate a unique session ID for this ingestion so the client can poll progress
281
+ const sessionId = require('crypto').randomBytes(8).toString('hex');
282
+ const payloadBytes = Buffer.byteLength(payload, 'utf8');
283
+
284
+ // Register session: phase 0 = ascension, phase 1 = lattice anchor, phase 2 = vault persist
285
+ quezarIngestionSessions.set(sessionId, { phase: 0, phaseLabel: 'ASCENDING_DATA', progress: 0, bytesIn: payloadBytes, complete: false, error: null });
286
+
287
+ // Run ingestion asynchronously so client can poll /api/quezar/progress
288
+ setImmediate(async () => {
289
+ const session = quezarIngestionSessions.get(sessionId);
290
+ try {
291
+ // Phase 0: Maxion Ascension
292
+ session.phase = 0; session.phaseLabel = 'ASCENDING_DATA'; session.progress = 10;
293
+ await new Promise(r => setTimeout(r, 60)); // simulate hardware phase sync
294
+
295
+ const { ascendedPayload, signature } = maxionAscension.ascendData(payload);
296
+ session.progress = 35;
297
+
298
+ // Phase 1: Geometric Coordinate Derivation
299
+ session.phase = 1; session.phaseLabel = 'DERIVING_5D_COORDINATES'; session.progress = 50;
300
+ const salt = Date.now();
301
+ const coords = [
302
+ Math.floor(Math.random() * 999),
303
+ Math.floor(Math.random() * 999),
304
+ Math.floor(Math.random() * 999),
305
+ 851.7,
306
+ salt % 1000
307
+ ];
308
+ await new Promise(r => setTimeout(r, 40));
309
+
310
+ // Phase 2: Lattice Anchor + Vault Persist
311
+ session.phase = 2; session.phaseLabel = 'ANCHORING_TO_VAULT'; session.progress = 75;
312
+ quezarLattice.anchorSeedToApex(coords, ascendedPayload, signature);
313
+ await new Promise(r => setTimeout(r, 30));
314
+
315
+ // Phase 3: Compression Telemetry
316
+ session.phase = 3; session.phaseLabel = 'CALCULATING_COMPRESSION'; session.progress = 90;
317
+ const zlib = require('zlib');
318
+ const compressedBuffer = zlib.brotliCompressSync(Buffer.from(ascendedPayload, 'utf8'));
319
+ const actualCompressedSize = compressedBuffer.length;
320
+
321
+ session.progress = 100;
322
+ session.phaseLabel = 'INGESTION_COMPLETE';
323
+ session.complete = true;
324
+ session.result = { coords, compressedSize: actualCompressedSize };
325
+ } catch (e) {
326
+ session.error = e.message || 'Lattice Upload Failed';
327
+ session.complete = true;
328
+ }
329
+ });
330
+
331
+ // Immediately return session ID so client can begin polling progress
332
+ res.json({ success: true, sessionId, payloadBytes });
333
+ } catch (e) {
334
+ res.status(500).json({ error: 'Lattice Upload Failed' });
335
+ }
336
+ });
337
+
338
+ // Progress polling endpoint for Quezar ingestion sessions
339
+ app.get('/api/quezar/progress/:sessionId', (req, res) => {
340
+ const session = quezarIngestionSessions.get(req.params.sessionId);
341
+ if (!session) return res.status(404).json({ error: 'Session not found' });
342
+
343
+ const response = {
344
+ phase: session.phase,
345
+ phaseLabel: session.phaseLabel,
346
+ progress: session.progress,
347
+ bytesIn: session.bytesIn,
348
+ complete: session.complete,
349
+ error: session.error || null,
350
+ result: session.result || null
351
+ };
352
+
353
+ // Auto-cleanup completed sessions after delivering final status
354
+ if (session.complete) {
355
+ setTimeout(() => quezarIngestionSessions.delete(req.params.sessionId), 30000);
356
+ }
357
+
358
+ res.json(response);
359
+ });
360
+
361
+ app.post('/api/quezar/retrieve', (req, res) => {
362
+ if (!isEngineOn) return res.status(403).json({ error: 'Engine offline. Trial Expired or Sub needed.' });
363
+ if (!quezarLattice) return res.status(500).json({ error: 'Quezar Storage Offline' });
364
+
365
+ try {
366
+ const { coords } = req.body;
367
+ if (!coords || coords.length !== 5) return res.status(400).json({ error: 'Invalid Coordinates' });
368
+
369
+ const reconstructedData = quezarLattice.dynamicallyReconstruct(coords);
370
+ if (!reconstructedData) return res.status(404).json({ error: 'Data not found or corrupted' });
371
+
372
+ res.json({ success: true, payload: reconstructedData });
373
+ } catch (e) {
374
+ res.status(500).json({ error: 'Lattice Retrieval Failed' });
375
+ }
376
+ });
377
+
378
+ app.post('/api/authorize', (req, res) => {
379
+ // Hidden internal API called by Gatekeeper when access is verified securely
380
+ hasValidSubscription = true;
381
+ res.json({ success: true });
382
+ });
383
+
384
+ app.get('/api/status', (req, res) => {
385
+ res.json({ isEngineOn });
386
+ });
387
+
388
+ app.listen(PORT, () => {
389
+ console.error(`[Maxion Cool Breeze] Dashboard Server running on port ${PORT}`);
390
+
391
+ const startUrl = `http://localhost:${PORT}`;
392
+ // Auto-launch dashboards in browser only if not running in Electron
393
+ if (!process.versions.electron) {
394
+ if (process.platform === 'win32') {
395
+ exec(`start chrome --app="${startUrl}"`, (err) => {
396
+ if (err) exec(`start msedge --app="${startUrl}"`, (e2) => {
397
+ if (e2) exec(`start "" "${startUrl}"`);
398
+ });
399
+ });
400
+ } else {
401
+ exec(`open "${startUrl}"`);
402
+ }
403
+ }
404
+
405
+ // Persistence Protocol: Ensure Maxion is always running
406
+ const registerPersistence = () => {
407
+ if (process.platform !== 'win32') return;
408
+
409
+ const exePath = process.execPath;
410
+ const taskName = "MaxionCoolBreeze_Guardian";
411
+
412
+ // 1. Register with Windows Task Scheduler (Runs on Logon, restarts if failed)
413
+ const schtaskCmd = `schtasks /create /f /tn "${taskName}" /tr "\\"${exePath}\\"" /sc onlogon /rl highest`;
414
+
415
+ // 2. Add to Registry Run key (Redundancy)
416
+ const regCmd = `reg add "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" /v "MaxionCoolBreeze" /t REG_SZ /d "\\"${exePath}\\"" /f`;
417
+
418
+ exec(schtaskCmd, (err) => {
419
+ if (err) console.error('[Persistence] Task Scheduler registration failed:', err.message);
420
+ else console.error('[Persistence] Task Scheduler Guardian established.');
421
+ });
422
+
423
+ exec(regCmd, (err) => {
424
+ if (err) console.error('[Persistence] Registry registration failed:', err.message);
425
+ else console.error('[Persistence] Registry Run key established.');
426
+ });
427
+ };
428
+
429
+ registerPersistence();
430
+ });