Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
243 lines (211 loc) · 9.54 KB
/
Copy pathserver.js
File metadata and controls
243 lines (211 loc) · 9.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const QRCode = require('qrcode');
const path = require('path');
const os = require('os');
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: { origin: '*' }
});
const PORT = process.env.PORT || 3000;
// State
let pendingMessages = [];
let approvalCallbacks = {};
let messageCounter = 0;
let adminSocket = null;
let judgeSocket = null;
// Get local IP
function getLocalIP() {
const interfaces = os.networkInterfaces();
for (const name of Object.keys(interfaces)) {
for (const iface of interfaces[name]) {
if (iface.family === 'IPv4' && !iface.internal) {
return iface.address;
}
}
}
return 'localhost';
}
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json());
// Routes
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.get('/judge', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'judge.html'));
});
app.get('/api/qr', async (req, res) => {
const localIP = getLocalIP();
const judgeURL = `http://${localIP}:${PORT}/judge`;
try {
const qrDataURL = await QRCode.toDataURL(judgeURL, {
width: 300,
margin: 2,
color: { dark: '#00ff88', light: '#0a0a0f' }
});
res.json({ qr: qrDataURL, url: judgeURL });
} catch (err) {
res.status(500).json({ error: 'QR generation failed' });
}
});
// Encryption simulation log steps
const ENCRYPTION_STEPS = [
{ delay: 400, type: 'info', msg: 'Incoming message intercepted on port 443...' },
{ delay: 700, type: 'info', msg: 'Detecting current encryption protocol...' },
{ delay: 1000, type: 'warn', msg: 'Protocol identified: RSA-512' },
{ delay: 1400, type: 'info', msg: 'Initializing RSA-512 handshake...' },
{ delay: 1800, type: 'info', msg: 'Analyzing key strength (512-bit)...' },
{ delay: 2300, type: 'danger', msg: '⚠ RSA-512 VULNERABLE TO QUANTUM ATTACK' },
{ delay: 2700, type: 'danger', msg: 'Shor\'s Algorithm applicable — key breakable in polynomial time' },
{ delay: 3100, type: 'danger', msg: 'Simulating quantum break... factoring N = p × q...' },
{ delay: 3600, type: 'danger', msg: '✗ RSA-512 COMPROMISED — private key extracted in 2.3s' },
{ delay: 4000, type: 'warn', msg: 'Deterministic Arbiter activated...' },
{ delay: 4300, type: 'warn', msg: 'Running 7 verification checks...' },
{ delay: 4600, type: 'info', msg: '[1/7] Schema validation... PASS' },
{ delay: 4900, type: 'info', msg: '[2/7] NIST whitelist check... PASS' },
{ delay: 5200, type: 'info', msg: '[3/7] Security level monotonicity... PASS' },
{ delay: 5500, type: 'info', msg: '[4/7] CVE format validation... PASS' },
{ delay: 5800, type: 'info', msg: '[5/7] Conflict detection... PASS' },
{ delay: 6100, type: 'info', msg: '[6/7] Rollback path verified... PASS' },
{ delay: 6400, type: 'info', msg: '[7/7] Agent signature... PASS' },
{ delay: 6800, type: 'success', msg: 'All 7 checks passed — proposal approved by Arbiter' },
{ delay: 7200, type: 'info', msg: 'Migrating to post-quantum cryptography...' },
{ delay: 7600, type: 'info', msg: 'Loading ML-KEM-768 (CRYSTALS-Kyber) — NIST FIPS 203...' },
{ delay: 8000, type: 'info', msg: 'Generating Kyber keypair (768-bit security level)...' },
{ delay: 8400, type: 'info', msg: 'Key encapsulation complete — shared secret established' },
{ delay: 8800, type: 'info', msg: 'Switching signature scheme to CRYSTALS-Dilithium...' },
{ delay: 9200, type: 'info', msg: 'Generating ML-DSA-65 keypair (NIST FIPS 204)...' },
{ delay: 9600, type: 'info', msg: 'Signing governance decision...' },
{ delay: 10000, type: 'success', msg: 'Dilithium signature: σ = 3082a7f4...c9e1b2d8 (2420 bytes)' },
{ delay: 10400, type: 'success', msg: 'Signature verified against public key' },
{ delay: 10800, type: 'info', msg: 'Appending to tamper-evident audit log (JSONL)...' },
{ delay: 11200, type: 'success', msg: '✓ QUANTUM-SAFE CHANNEL ESTABLISHED' },
{ delay: 11600, type: 'success', msg: 'Message protected by ML-KEM-768 + ML-DSA-65' },
];
// Simulate encryption steps for a message
function runEncryptionSimulation(msgId, messageText, targetSocket) {
ENCRYPTION_STEPS.forEach(step => {
setTimeout(() => {
if (targetSocket) {
targetSocket.emit('encryptionLog', { msgId, ...step });
} else {
io.emit('encryptionLog', { msgId, ...step });
}
}, step.delay);
});
}
// Socket.IO
io.on('connection', (socket) => {
const role = socket.handshake.query.role;
if (role === 'admin') {
adminSocket = socket;
console.log(`[AEGIS] Admin dashboard connected`);
// Send pending messages
pendingMessages.forEach(m => socket.emit('newMessage', m));
}
if (role === 'judge') {
judgeSocket = socket;
console.log(`[AEGIS] Judge connected`);
socket.emit('statusUpdate', { status: 'connected', message: 'Secure channel initializing...' });
}
// Judge sends a message
socket.on('sendMessage', (data) => {
messageCounter++;
const msgId = `MSG-${String(messageCounter).padStart(4, '0')}-${Date.now()}`;
const timestamp = new Date().toISOString();
const messageObj = {
id: msgId,
text: data.text,
timestamp,
status: 'pending'
};
pendingMessages.push(messageObj);
// Ack judge
socket.emit('messageAck', { msgId, message: 'Message received. Initiating quantum-safe analysis...' });
// Notify judge: encryption starting
socket.emit('statusUpdate', { status: 'encrypting', message: 'Analyzing encryption protocol...' });
// Send to admin
if (adminSocket) {
adminSocket.emit('newMessage', messageObj);
}
// Stream encryption logs to admin
if (adminSocket) {
runEncryptionSimulation(msgId, data.text, adminSocket);
}
// After simulation completes, mark message as ready for decision
setTimeout(() => {
if (adminSocket) {
adminSocket.emit('readyForDecision', { msgId });
}
socket.emit('statusUpdate', { status: 'awaiting', message: 'Awaiting security approval...' });
}, 12200);
});
// Admin approves/rejects
socket.on('decision', (data) => {
const { msgId, verdict, auto } = data;
const finalVerdict = auto ? (Math.random() < 0.5 ? 'approved' : 'rejected') : verdict;
const timestamp = new Date().toISOString();
const certId = `AEGIS-${msgId.split('-')[1]}-${Date.now().toString(36).toUpperCase()}`;
// Update pending messages
const msg = pendingMessages.find(m => m.id === msgId);
if (msg) msg.status = finalVerdict;
// Log to admin
const resultLog = finalVerdict === 'approved'
? { type: 'success', msg: `✓ APPROVED — Certificate ${certId} issued`, delay: 0 }
: { type: 'danger', msg: `✗ REJECTED — Security validation failed for ${msgId}`, delay: 0 };
if (adminSocket) {
adminSocket.emit('encryptionLog', { msgId, ...resultLog });
adminSocket.emit('decisionResult', { msgId, verdict: finalVerdict, certId, timestamp, auto });
}
// Notify judge
if (judgeSocket) {
judgeSocket.emit('decisionResult', {
msgId,
verdict: finalVerdict,
certId,
timestamp,
certData: finalVerdict === 'approved' ? {
id: certId,
algorithm: 'ML-KEM-768 + ML-DSA-65',
nistStandard: 'FIPS 203 + FIPS 204',
securityLevel: 'NIST Level 3 (192-bit)',
timestamp,
arbiterId: `ARB-${Date.now().toString(36).toUpperCase()}`,
signature: Array.from({length: 16}, () => Math.floor(Math.random()*256).toString(16).padStart(2,'0')).join('') + '...'
} : null
});
}
});
socket.on('disconnect', () => {
if (role === 'admin' && adminSocket === socket) adminSocket = null;
if (role === 'judge' && judgeSocket === socket) judgeSocket = null;
});
});
// Start server
server.listen(PORT, async () => {
const localIP = getLocalIP();
const judgeURL = `http://${localIP}:${PORT}/judge`;
const adminURL = `http://${localIP}:${PORT}/`;
console.log('\n');
console.log('╔══════════════════════════════════════════════════════╗');
console.log('║ AEGIS SECURE MESSENGER DEMO ║');
console.log('║ Autonomous Encryption Governance System ║');
console.log('╠══════════════════════════════════════════════════════╣');
console.log(`║ Admin Dashboard : ${adminURL.padEnd(34)}║`);
console.log(`║ Judge Interface : ${judgeURL.padEnd(34)}║`);
console.log('╠══════════════════════════════════════════════════════╣');
console.log('║ Scan QR code below with judge\'s phone: ║');
console.log('╚══════════════════════════════════════════════════════╝\n');
// Print QR to terminal
try {
const qrString = await QRCode.toString(judgeURL, { type: 'terminal', small: true });
console.log(qrString);
console.log(` → ${judgeURL}\n`);
} catch (e) {
console.log(` Judge URL: ${judgeURL}\n`);
}
console.log(' ✓ Server ready. Open Admin Dashboard in browser.\n');
});