-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauth.js
More file actions
1175 lines (1042 loc) · 42.4 KB
/
Copy pathauth.js
File metadata and controls
1175 lines (1042 loc) · 42.4 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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* ==========================================================================
ARGOS - USER AUTHENTICATION & SESSION CONTROLLER (auth.js)
========================================================================== */
// Simple Synth for Auth Audios
class AuthSynth {
constructor() {
this.ctx = null;
}
init() {
if (this.ctx) return;
try {
const AudioContextClass = window.AudioContext || window.webkitAudioContext;
this.ctx = new AudioContextClass();
} catch (e) {
console.warn('AudioContext not supported in this browser.');
}
}
beep(freq = 600, type = 'sine', duration = 0.08) {
this.init();
if (!this.ctx) return;
try {
if (this.ctx.state === 'suspended') {
this.ctx.resume();
}
const osc = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc.type = type;
osc.frequency.setValueAtTime(freq, this.ctx.currentTime);
gain.gain.setValueAtTime(0.05, this.ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.0001, this.ctx.currentTime + duration);
osc.connect(gain);
gain.connect(this.ctx.destination);
osc.start();
osc.stop(this.ctx.currentTime + duration);
} catch (err) {}
}
speak(text) {
if ('speechSynthesis' in window) {
try {
window.speechSynthesis.cancel();
const utterance = new SpeechSynthesisUtterance(text);
utterance.lang = 'es-ES';
utterance.rate = 1.05;
utterance.pitch = 1.1;
window.speechSynthesis.speak(utterance);
} catch (e) {}
}
}
}
const authSynth = new AuthSynth();
// Helper functions for UI interaction sounds
function playClickSound() {
authSynth.beep(750, 'sine', 0.04);
}
function playHoverSound() {
authSynth.beep(900, 'sine', 0.02);
}
// Global functions (needed for inline HTML onclick handlers)
window.togglePasswordVisibility = function(inputId, buttonEl) {
playClickSound();
const input = document.getElementById(inputId);
if (!input) return;
const icon = buttonEl.querySelector('i');
if (input.type === 'password') {
input.type = 'text';
icon.className = 'fa-solid fa-eye-slash';
} else {
input.type = 'password';
icon.className = 'fa-solid fa-eye';
}
};
document.addEventListener('DOMContentLoaded', () => {
// --- DATABASE & SESSION STATE MANAGEMENT ---
// Secure SHA-256 Implementation in pure JS
function sha256(ascii) {
function rightRotate(value, amount) {
return (value >>> amount) | (value << (32 - amount));
}
var mathPow = Math.pow;
var maxWord = mathPow(2, 32);
var lengthProperty = 'length';
var i, j;
var result = '';
var words = [];
var asciiLength = ascii[lengthProperty];
var hash = sha256.h = sha256.h || [];
var k = sha256.k = sha256.k || [];
var primeCounter = k[lengthProperty];
var isPrime = {};
for (var candidate = 2; primeCounter < 64; candidate++) {
if (!isPrime[candidate]) {
for (i = 0; i < 313; i += candidate) {
isPrime[i] = 1;
}
hash[primeCounter] = (mathPow(candidate, .5)*maxWord)|0;
k[primeCounter++] = (mathPow(candidate, 1/3)*maxWord)|0;
}
}
ascii += '\x80';
while (ascii[lengthProperty] % 64 - 56) ascii += '\x00';
for (i = 0; i < ascii[lengthProperty]; i++) {
var charCode = ascii.charCodeAt(i);
if (charCode >> 8) return '';
words[i >> 2] |= charCode << (24 - i % 4 * 8);
}
words[words[lengthProperty]] = ((asciiLength * 8) / maxWord) | 0;
words[words[lengthProperty]] = (asciiLength * 8);
var hashCopy = hash.slice(0);
for (i = 0; i < words[lengthProperty]; i += 16) {
var w = words.slice(i, i + 16);
var oldHash = hash.slice(0);
for (j = 0; j < 64; j++) {
var wj = w[j];
if (j >= 16) {
var s0 = rightRotate(w[j - 15], 7) ^ rightRotate(w[j - 15], 18) ^ (w[j - 15] >>> 3);
var s1 = rightRotate(w[j - 2], 17) ^ rightRotate(w[j - 2], 19) ^ (w[j - 2] >>> 10);
wj = w[j] = (w[j - 16] + s0 + w[j - 7] + s1) | 0;
}
var ch = (hash[4] & hash[5]) ^ (~hash[4] & hash[6]);
var maj = (hash[0] & hash[1]) ^ (hash[0] & hash[2]) ^ (hash[1] & hash[2]);
var temp1 = (hash[7] + (rightRotate(hash[4], 6) ^ rightRotate(hash[4], 11) ^ rightRotate(hash[4], 25)) + ch + k[j] + wj) | 0;
var temp2 = ((rightRotate(hash[0], 2) ^ rightRotate(hash[0], 13) ^ rightRotate(hash[0], 22)) + maj) | 0;
hash[7] = hash[6];
hash[6] = hash[5];
hash[5] = hash[4];
hash[4] = (hash[3] + temp1) | 0;
hash[3] = hash[2];
hash[2] = hash[1];
hash[1] = hash[0];
hash[0] = (temp1 + temp2) | 0;
}
for (j = 0; j < 8; j++) {
hash[j] = (hash[j] + oldHash[j]) | 0;
}
}
for (i = 0; i < 8; i++) {
for (j = 3; j >= 0; j--) {
var byte = (hash[i] >> (j * 8)) & 255;
result += (byte < 16 ? '0' : '') + byte.toString(16);
}
}
for (i = 0; i < 8; i++) {
hash[i] = hashCopy[i];
}
return result;
}
// Secure salted hash password function
function hashPassword(password) {
if (password.startsWith('argos_')) return password; // Already hashed
const salt = "ARGOS_SECURE_SALT_2026_MISAEL_DAYRON";
return 'argos_' + sha256(password + salt);
}
// JSON Web Token (JWT) Layer for Secure client-side session control
const JWT_SECRET = "ARGOS_JWT_SECRET_SIGNING_KEY_2026_MISAEL_PROT";
function stringToByteArray(str) {
var bytes = [];
for (var i = 0; i < str.length; i++) {
bytes.push(str.charCodeAt(i) & 0xff);
}
return bytes;
}
function byteArrayToString(bytes) {
var str = "";
for (var i = 0; i < bytes.length; i++) {
str += String.fromCharCode(bytes[i]);
}
return str;
}
function hexToByteArray(hex) {
var bytes = [];
for (var i = 0; i < hex.length; i += 2) {
bytes.push(parseInt(hex.substr(i, 2), 16));
}
return bytes;
}
function hmacSha256(key, message) {
var blocksize = 64;
var keyBytes = stringToByteArray(key);
var msgBytes = stringToByteArray(message);
if (keyBytes.length > blocksize) {
keyBytes = hexToByteArray(sha256(key));
}
if (keyBytes.length < blocksize) {
var newKey = new Array(blocksize);
for (var i = 0; i < keyBytes.length; i++) newKey[i] = keyBytes[i];
for (var i = keyBytes.length; i < blocksize; i++) newKey[i] = 0;
keyBytes = newKey;
}
var ipad = new Array(blocksize);
var opad = new Array(blocksize);
for (var i = 0; i < blocksize; i++) {
ipad[i] = keyBytes[i] ^ 0x36;
opad[i] = keyBytes[i] ^ 0x5c;
}
var innerMsg = ipad.concat(msgBytes);
var innerHashHex = sha256(byteArrayToString(innerMsg));
var innerHashBytes = hexToByteArray(innerHashHex);
var outerMsg = opad.concat(innerHashBytes);
return sha256(byteArrayToString(outerMsg));
}
function generateJWT(payload) {
const header = btoa(JSON.stringify({ alg: "HS256", typ: "JWT" })).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
const payloadStr = btoa(JSON.stringify(payload)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
const signature = hmacSha256(JWT_SECRET, header + "." + payloadStr);
return `${header}.${payloadStr}.${signature}`;
}
function verifyJWT(token) {
if (!token) return null;
const parts = token.split('.');
if (parts.length !== 3) return null;
const [header, payload, signature] = parts;
// Verify signature cryptographically to prevent role tampering
const expectedSignature = hmacSha256(JWT_SECRET, header + "." + payload);
if (signature !== expectedSignature) {
console.warn("[🛡️ AUTH] Firma de JWT no válida. Acceso denegado.");
return null;
}
try {
const decodedPayload = JSON.parse(atob(payload.replace(/-/g, '+').replace(/_/g, '/')));
if (decodedPayload.exp && Date.now() > decodedPayload.exp) {
console.warn("[🛡️ AUTH] El token JWT ha expirado.");
return null;
}
return decodedPayload;
} catch (e) {
return null;
}
}
// Symmetric Cryptographic Cipher for User Database payload protection
const DB_ENCRYPTION_KEY = "ARGOS_DATABASE_SYMMETRIC_CYPHER_MASTER_KEY_2026";
function encryptData(plaintext) {
var keyHash = sha256(DB_ENCRYPTION_KEY);
var out = "";
for (var i = 0; i < plaintext.length; i++) {
var charCode = plaintext.charCodeAt(i);
var keyChar = keyHash.charCodeAt(i % keyHash.length);
var encryptedVal = (charCode ^ keyChar) + (i % 256);
out += ("00" + encryptedVal.toString(16)).slice(-3);
}
return btoa(out);
}
function decryptData(ciphertext) {
try {
var decoded = atob(ciphertext);
var keyHash = sha256(DB_ENCRYPTION_KEY);
var out = "";
for (var i = 0; i < decoded.length; i += 3) {
var encValStr = decoded.substr(i, 3);
var encVal = parseInt(encValStr, 16);
var keyChar = keyHash.charCodeAt((i / 3) % keyHash.length);
var charCode = (encVal - ((i / 3) % 256)) ^ keyChar;
out += String.fromCharCode(charCode);
}
return out;
} catch (e) {
console.error("[🛡️ SHIELD] Failed to decrypt data store:", e);
return null;
}
}
// HTML Input Sanitizer (Prevents XSS/HTML Injection)
function sanitizeInput(str) {
return str.replace(/[&<>"']/g, function(m) {
switch (m) {
case '&': return '&';
case '<': return '<';
case '>': return '>';
case '"': return '"';
case "'": return ''';
default: return m;
}
});
}
// Brute Force Prevention state variables
let loginAttempts = 0;
let lockoutUntil = 0;
const DEFAULT_USERS = [
{ fullname: "Carlos Mendoza (Operador)", username: "operador", password: hashPassword("123"), role: "operador" },
{ fullname: "Sofía Ruiz (Estudiante)", username: "estudiante", password: hashPassword("123"), role: "estudiante" },
{ fullname: "Prof. Alejandro Silva", username: "docente", password: hashPassword("123"), role: "docente" }
];
// Obfuscated cloud credentials to hide URLs and keys from plain-text scrapers
const CLOUD_DB_URL = atob("aHR0cHM6Ly9leHRlbmRzY2xhc3MuY29tL2FwaS9qc29uLXN0b3JhZ2UvYmluL2RhZGFlZmI=");
const SECURITY_KEY = atob("QVJHT1NfU0VDVVJJVFlfVE9LRU5fMjAyNg==");
// Fetch and sync users from the cloud
async function syncUsersFromCloud() {
try {
const response = await fetch(CLOUD_DB_URL);
if (response.ok) {
const payloadText = await response.text();
let cloudUsers = null;
try {
// Attempt raw JSON parse first for backwards compatibility
cloudUsers = JSON.parse(payloadText);
} catch (e) {
// If not valid JSON, it's encrypted ciphertext
const decrypted = decryptData(payloadText);
if (decrypted) {
cloudUsers = JSON.parse(decrypted);
}
}
if (Array.isArray(cloudUsers) && cloudUsers.length > 0) {
const localUsers = getUsers();
let merged = [...localUsers];
cloudUsers.forEach(cu => {
const index = merged.findIndex(lu => lu.username.toLowerCase() === cu.username.toLowerCase());
if (index === -1) {
merged.push(cu);
} else {
merged[index] = cu;
}
});
localStorage.setItem('argos_users', JSON.stringify(merged));
console.log("[☁️ CLOUD SYNC] Sincronización de base de datos de usuarios completada con la nube.");
return merged;
}
}
} catch (e) {
console.warn("[☁️ CLOUD SYNC] Error al sincronizar desde la nube. Usando base de datos local offline.", e);
}
return getUsers();
}
// Save and upload users to the cloud with full database encryption
async function syncUsersToCloud(usersList) {
try {
const encryptedPayload = encryptData(JSON.stringify(usersList));
const response = await fetch(CLOUD_DB_URL, {
method: 'PUT',
headers: {
'Content-Type': 'text/plain',
'Security-key': SECURITY_KEY
},
body: encryptedPayload
});
if (response.ok) {
console.log("[☁️ CLOUD SYNC] Base de datos respaldada en la nube con éxito (Cifrado Extremo Activo).");
} else {
console.warn("[☁️ CLOUD SYNC] Error del servidor al guardar en la nube.");
}
} catch (e) {
console.warn("[☁️ CLOUD SYNC] Error de red al guardar en la nube.", e);
}
}
// Initialize simulated DB & Sync with error fallback
try {
const testParse = JSON.parse(localStorage.getItem('argos_users'));
if (!Array.isArray(testParse) || testParse.length === 0) {
localStorage.setItem('argos_users', JSON.stringify(DEFAULT_USERS));
} else {
migrateUserPasswords();
}
} catch (e) {
localStorage.setItem('argos_users', JSON.stringify(DEFAULT_USERS));
}
// Trigger cloud sync asynchronously at startup
syncUsersFromCloud();
function getUsers() {
try {
return JSON.parse(localStorage.getItem('argos_users')) || [];
} catch (e) {
return [];
}
}
function migrateUserPasswords() {
const users = getUsers();
let migrated = false;
users.forEach(u => {
if (!u.password.startsWith('argos_')) {
u.password = hashPassword(u.password);
migrated = true;
}
});
if (migrated) {
localStorage.setItem('argos_users', JSON.stringify(users));
}
}
function saveUser(user) {
const users = getUsers();
users.push(user);
localStorage.setItem('argos_users', JSON.stringify(users));
// Backup database to the cloud
syncUsersToCloud(users);
}
function getActiveSession() {
const token = localStorage.getItem('argos_session_token');
return verifyJWT(token);
}
function setActiveSession(user) {
const token = generateJWT({
fullname: user.fullname,
username: user.username,
role: user.role,
exp: Date.now() + 24 * 60 * 60 * 1000 // 24 hours session
});
localStorage.setItem('argos_session_token', token);
}
function removeActiveSession() {
localStorage.removeItem('argos_session_token');
}
// --- ELEMENT SELECTORS ---
const btnOpenLogin = document.getElementById('btn-open-login');
const btnOpenRegister = document.getElementById('btn-open-register');
const btnLogout = document.getElementById('btn-logout');
const loginModal = document.getElementById('login-modal-overlay');
const registerModal = document.getElementById('register-modal-overlay');
const licenseModal = document.getElementById('license-modal-overlay');
const privacyModal = document.getElementById('privacy-modal-overlay');
const btnOpenLicense = document.getElementById('btn-open-license');
const btnOpenPrivacy = document.getElementById('btn-open-privacy');
const btnCloseLogin = document.getElementById('btn-close-login');
const btnCloseRegister = document.getElementById('btn-close-register');
const btnCloseLicense = document.getElementById('btn-close-license');
const btnClosePrivacy = document.getElementById('btn-close-privacy');
const loginForm = document.getElementById('login-form');
const registerForm = document.getElementById('register-form');
const linkToRegister = document.getElementById('link-to-register');
const linkToLogin = document.getElementById('link-to-login');
const loginErrorMsg = document.getElementById('login-error-msg');
const registerErrorMsg = document.getElementById('register-error-msg');
// Profile Selector link
const nativeProfileSelect = document.getElementById('profile-select');
// --- MODAL CONTROLS ---
// Booting Log Console Terminal Simulator
function runTerminalBoot(terminalElId, logsArray) {
const el = document.getElementById(terminalElId);
if (!el) return;
el.innerHTML = '';
let lineIdx = 0;
// Add header
const header = document.createElement('div');
header.style.display = 'flex';
header.style.justifyContent = 'space-between';
header.style.borderBottom = '1px solid rgba(255,255,255,0.1)';
header.style.paddingBottom = '4px';
header.style.marginBottom = '6px';
header.innerHTML = `<span><i class="fa-solid fa-terminal"></i> CONEXIÓN SEGURA</span><span style="color:#00ff66; animation: pulseFlashing 0.8s infinite alternate;"><i class="fa-solid fa-circle"></i> PROTEGIDO</span>`;
el.appendChild(header);
function printLine() {
if (lineIdx >= logsArray.length) return;
const line = document.createElement('div');
line.style.color = '#888';
line.textContent = logsArray[lineIdx];
el.appendChild(line);
lineIdx++;
setTimeout(printLine, 120);
}
printLine();
}
function showModal(modalEl) {
modalEl.classList.remove('hidden');
authSynth.beep(500, 'sine', 0.1);
// Trigger terminal animation if applicable
if (modalEl.id === 'login-modal-overlay') {
runTerminalBoot('login-terminal-logs', [
"> INICIANDO PROTOCOLO SHIELD v5.20...",
"> ENLACE DE DATOS ENCRIPTADO... [OK]",
"> FIREWALL ACTIVO (DETECCION DDoS)... [OK]",
"> VERIFICANDO INTEGRIDAD LOCAL... [COMPLETO]"
]);
// Reset Captcha status
const check = document.getElementById('login-human-check');
if (check) check.checked = false;
const status = document.getElementById('login-captcha-status');
if (status) {
status.textContent = '[ESPERANDO...]';
status.style.color = '#ff8c00';
}
} else if (modalEl.id === 'register-modal-overlay') {
runTerminalBoot('register-terminal-logs', [
"> GENERANDO LLAVE PÚBLICA / PRIVADA...",
"> CANAL CREADOR DE CUENTAS: SEGURO",
"> AUDITANDO PARÁMETROS XSS... [INICIADO]",
"> SISTEMA LISTO PARA ASIGNACIÓN DE ROL"
]);
// Reset strength bar
const strengthBar = document.getElementById('strength-bar-fill');
if (strengthBar) strengthBar.style.width = '0%';
const strengthLabel = document.getElementById('strength-label');
if (strengthLabel) {
strengthLabel.textContent = 'Ninguna';
strengthLabel.style.color = '#888';
}
}
// Add visual glow reaction on form inputs
const firstInput = modalEl.querySelector('input');
if (firstInput) setTimeout(() => firstInput.focus(), 150);
}
function hideModal(modalEl) {
modalEl.classList.add('hidden');
authSynth.beep(300, 'sine', 0.05);
// Clear forms and errors
const form = modalEl.querySelector('form');
if (form) form.reset();
const errors = modalEl.querySelectorAll('.auth-error-msg');
errors.forEach(err => err.classList.add('hidden'));
// Reset password field types
const passwords = modalEl.querySelectorAll('input[type="text"]');
passwords.forEach(pwd => {
if (pwd.id.includes('password')) pwd.type = 'password';
});
const eyeIcons = modalEl.querySelectorAll('.btn-toggle-password i');
eyeIcons.forEach(icon => { icon.className = 'fa-solid fa-eye'; });
}
// Bind Openers
if (btnOpenLogin) btnOpenLogin.addEventListener('click', () => showModal(loginModal));
if (btnOpenRegister) btnOpenRegister.addEventListener('click', () => showModal(registerModal));
if (btnOpenLicense) {
btnOpenLicense.addEventListener('click', (e) => {
e.preventDefault();
showModal(licenseModal);
});
}
if (btnOpenPrivacy) {
btnOpenPrivacy.addEventListener('click', (e) => {
e.preventDefault();
showModal(privacyModal);
});
}
// Bind Closers
if (btnCloseLogin) btnCloseLogin.addEventListener('click', () => hideModal(loginModal));
if (btnCloseRegister) btnCloseRegister.addEventListener('click', () => hideModal(registerModal));
if (btnCloseLicense) btnCloseLicense.addEventListener('click', () => hideModal(licenseModal));
if (btnClosePrivacy) btnClosePrivacy.addEventListener('click', () => hideModal(privacyModal));
// Switch between modals
if (linkToRegister) {
linkToRegister.addEventListener('click', (e) => {
e.preventDefault();
hideModal(loginModal);
setTimeout(() => showModal(registerModal), 200);
});
}
if (linkToLogin) {
linkToLogin.addEventListener('click', (e) => {
e.preventDefault();
hideModal(registerModal);
setTimeout(() => showModal(loginModal), 200);
});
}
// Close modals when clicking overlay background
[loginModal, registerModal, licenseModal, privacyModal].forEach(modal => {
if (modal) {
modal.addEventListener('click', (e) => {
if (e.target === modal) {
hideModal(modal);
}
});
}
});
// Close on Escape key
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
if (loginModal && !loginModal.classList.contains('hidden')) hideModal(loginModal);
if (registerModal && !registerModal.classList.contains('hidden')) hideModal(registerModal);
if (licenseModal && !licenseModal.classList.contains('hidden')) hideModal(licenseModal);
if (privacyModal && !privacyModal.classList.contains('hidden')) hideModal(privacyModal);
}
});
// Add click/hover sounds to new buttons/inputs
function attachAuthSounds() {
const elList = document.querySelectorAll('.auth-modal-card button, .auth-modal-card input, .auth-modal-card select, .auth-modal-card a, .user-session-container button');
elList.forEach(el => {
el.addEventListener('mouseenter', playHoverSound);
el.addEventListener('click', playClickSound);
});
}
// Execute after small delays to ensure elements render
setTimeout(attachAuthSounds, 300);
// --- CHECK AND INJECT EXPERT ROLE ---
window.checkAndInjectExpertRole = function() {
const isExpertUnlocked = localStorage.getItem('argos_expert_unlocked') === 'true';
if (isExpertUnlocked) {
if (nativeProfileSelect && !nativeProfileSelect.querySelector('option[value="expert"]')) {
const opt = document.createElement('option');
opt.value = 'expert';
opt.textContent = 'Controlador Experto 🏆';
nativeProfileSelect.appendChild(opt);
}
const regSelect = document.getElementById('register-role');
if (regSelect && !regSelect.querySelector('option[value="expert"]')) {
const opt = document.createElement('option');
opt.value = 'expert';
opt.textContent = 'Controlador Experto (Acceso Total) 🏆';
regSelect.appendChild(opt);
}
}
};
// --- PANEL LOCK CONTROL ---
function updatePanelLocks(role) {
const flightCard = document.getElementById('flight-control-card');
const studentModule = document.getElementById('student-module');
const teacherModule = document.getElementById('teacher-module');
const currentRole = role || 'publico';
// Flight Control Lock
if (flightCard) {
const lockOverlayFlight = document.getElementById('lock-overlay-flight');
if (currentRole === 'operador' || currentRole === 'docente' || currentRole === 'expert') {
flightCard.classList.remove('panel-locked');
} else {
flightCard.classList.add('panel-locked');
if (lockOverlayFlight) {
const title = lockOverlayFlight.querySelector('h4');
const desc = lockOverlayFlight.querySelector('p');
if (currentRole === 'estudiante') {
if (title) title.innerHTML = '<i class="fa-solid fa-lock"></i> SEGURIDAD ACTIVA';
if (desc) desc.textContent = "Los estudiantes no pueden operar la maquinaria física. Por favor accede a los simuladores de vuelo.";
} else {
if (title) title.innerHTML = 'ACCESO OPERADOR REQUERIDO';
if (desc) desc.textContent = "Inicia sesión como Operador Autorizado para desbloquear y controlar la navegación terrestre y aérea del robot.";
}
}
}
}
// Student Module (STEAM Labs) Lock
if (studentModule) {
const lockOverlayLabs = document.getElementById('lock-overlay-labs');
if (currentRole !== 'publico') {
studentModule.classList.remove('panel-locked');
} else {
studentModule.classList.add('panel-locked');
if (lockOverlayLabs) {
const title = lockOverlayLabs.querySelector('h4');
const desc = lockOverlayLabs.querySelector('p');
if (title) title.innerHTML = 'REGISTRO REQUERIDO';
if (desc) desc.textContent = "Inicia sesión o regístrate en la plataforma para participar de la trivia y misiones STEAM.";
}
}
}
// Teacher Module Lock
if (teacherModule) {
const lockOverlayTeacher = document.getElementById('lock-overlay-teacher');
if (currentRole === 'docente' || currentRole === 'expert') {
teacherModule.classList.remove('panel-locked');
} else {
teacherModule.classList.add('panel-locked');
if (lockOverlayTeacher) {
const title = lockOverlayTeacher.querySelector('h4');
const desc = lockOverlayTeacher.querySelector('p');
if (title) title.innerHTML = 'ACCESO DOCENTE EXCLUSIVO';
if (desc) desc.textContent = "Este panel administrativo está reservado para docentes certificados. Permite calificar y auditar registros.";
}
}
}
}
// Intercept click on lock overlay triggers
document.addEventListener('click', (e) => {
if (e.target && e.target.classList.contains('btn-lock-action-trigger')) {
playClickSound();
showModal(loginModal);
}
if (e.target && e.target.classList.contains('btn-bypass-lock')) {
playClickSound();
const pin = prompt("Ingrese la clave de anulación de seguridad (Master Developer PIN):");
if (pin === "2026_MISAEL_DEV") {
const parentCard = e.target.closest('.panel-locked');
if (parentCard) {
parentCard.classList.remove('panel-locked');
// Flight Control specific bypass logic
if (parentCard.id === 'flight-control-card') {
const manualControls = document.getElementById('manual-controls-card');
if (manualControls) manualControls.classList.remove('locked');
const flightStatus = document.getElementById('flight-system-status');
if (flightStatus) {
flightStatus.className = 'system-level unlocked';
flightStatus.textContent = 'CONTROL MANUAL (DEMO)';
}
const droneFeed = document.getElementById('drone-feed-overlay');
if (droneFeed) {
droneFeed.classList.remove('offline');
// Hide camera offline overlay text
const offlineText = droneFeed.querySelector('.offline-overlay-text');
if (offlineText) offlineText.style.display = 'none';
}
}
alert("MODO DEMO DESBLOQUEADO CON ÉXITO");
}
} else {
alert("Clave de anulación incorrecta. Acceso denegado.");
authSynth.beep(180, 'sawtooth', 0.4);
}
}
});
// --- SESSION CORE LOGIC ---
function updateSessionUI(session) {
const loggedOutDiv = document.getElementById('session-logged-out');
const loggedInDiv = document.getElementById('session-logged-in');
if (session) {
// User is logged in
if (loggedOutDiv) loggedOutDiv.classList.add('hidden');
if (loggedInDiv) loggedInDiv.classList.remove('hidden');
const nameEl = document.getElementById('user-name-display');
const roleEl = document.getElementById('user-role-display');
const iconEl = document.getElementById('user-role-icon');
if (nameEl) nameEl.textContent = session.fullname;
let roleLabel = 'Público';
let iconClass = 'fa-solid fa-user';
let roleColorClass = 'role-publico';
switch (session.role) {
case 'operador':
roleLabel = 'Operador Autorizado';
iconClass = 'fa-solid fa-user-shield';
roleColorClass = 'role-operador';
break;
case 'estudiante':
roleLabel = 'Estudiante STEAM';
iconClass = 'fa-solid fa-user-graduate';
roleColorClass = 'role-estudiante';
break;
case 'docente':
roleLabel = 'Docente';
iconClass = 'fa-solid fa-chalkboard-user';
roleColorClass = 'role-docente';
break;
case 'expert':
roleLabel = 'Controlador Experto 🏆';
iconClass = 'fa-solid fa-crown';
roleColorClass = 'role-expert';
break;
}
if (roleEl) {
roleEl.textContent = roleLabel;
roleEl.className = `user-role-display ${roleColorClass}`;
}
if (iconEl) {
iconEl.className = `${iconClass} ${roleColorClass}`;
}
// Sync native select and trigger changes
if (nativeProfileSelect) {
nativeProfileSelect.value = session.role;
nativeProfileSelect.dispatchEvent(new Event('change'));
}
// Update Panel Locks
updatePanelLocks(session.role);
} else {
// User is logged out
if (loggedOutDiv) loggedOutDiv.classList.remove('hidden');
if (loggedInDiv) loggedInDiv.classList.add('hidden');
// Revert native select to public mode
if (nativeProfileSelect) {
nativeProfileSelect.value = 'publico';
nativeProfileSelect.dispatchEvent(new Event('change'));
}
// Update Panel Locks
updatePanelLocks('publico');
}
// Attach sound events to any new elements dynamically
setTimeout(attachAuthSounds, 200);
}
// Dynamic Register Modal Accent Colors based on role
const registerRoleSelect = document.getElementById('register-role');
const registerModalCard = registerModal ? registerModal.querySelector('.auth-modal-card') : null;
if (registerRoleSelect && registerModalCard) {
const resetRoleClasses = () => {
registerModalCard.classList.remove('card-role-publico', 'card-role-operador', 'card-role-estudiante', 'card-role-docente');
};
registerRoleSelect.addEventListener('change', (e) => {
resetRoleClasses();
registerModalCard.classList.add(`card-role-${e.target.value}`);
authSynth.beep(600, 'sine', 0.05);
});
// Set default initial state
resetRoleClasses();
registerModalCard.classList.add(`card-role-${registerRoleSelect.value}`);
}
// --- ACTIONS LOGIC (LOGIN / REGISTER / LOGOUT) ---
// Submit Login
if (loginForm) {
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
const usernameInput = sanitizeInput(document.getElementById('login-username').value.trim());
const passwordInput = document.getElementById('login-password').value;
// Captcha Human Check
const loginHumanCheck = document.getElementById('login-human-check');
if (loginHumanCheck && !loginHumanCheck.checked) {
if (loginErrorMsg) {
loginErrorMsg.textContent = "Por seguridad, confirma la autenticación humana (Anti-Bot).";
loginErrorMsg.classList.remove('hidden');
}
authSynth.beep(150, 'sawtooth', 0.2);
return;
}
// Brute force check
if (Date.now() < lockoutUntil) {
const remaining = Math.ceil((lockoutUntil - Date.now()) / 1000);
if (loginErrorMsg) {
loginErrorMsg.textContent = `Acceso bloqueado por seguridad. Reintente en ${remaining}s.`;
loginErrorMsg.classList.remove('hidden');
}
authSynth.beep(150, 'sawtooth', 0.2);
return;
}
const users = getUsers();
const hashedInput = hashPassword(passwordInput);
const matchedUser = users.find(u => u.username.toLowerCase() === usernameInput.toLowerCase() && u.password === hashedInput);
if (matchedUser) {
// Success
loginAttempts = 0;
if (loginErrorMsg) loginErrorMsg.classList.add('hidden');
setActiveSession(matchedUser);
updateSessionUI(matchedUser);
hideModal(loginModal);
authSynth.beep(880, 'sine', 0.15);
setTimeout(() => authSynth.beep(1100, 'sine', 0.25), 100);
authSynth.speak(`Acceso concedido. Bienvenido al nodo, ${matchedUser.fullname.split(' ')[0]}.`);
} else {
// Fail
loginAttempts++;
if (loginAttempts >= 5) {
lockoutUntil = Date.now() + 30000;
if (loginErrorMsg) {
loginErrorMsg.textContent = "Demasiados intentos fallidos. Cuenta bloqueada por 30s.";
loginErrorMsg.classList.remove('hidden');
}
authSynth.speak("Bloqueo de seguridad activado por sospecha de fuerza bruta.");
} else {
if (loginErrorMsg) {
loginErrorMsg.textContent = "Usuario o contraseña incorrectos.";
loginErrorMsg.classList.remove('hidden');
}
}
authSynth.beep(150, 'sawtooth', 0.35);
}
});
}
// Submit Register
if (registerForm) {
registerForm.addEventListener('submit', (e) => {
e.preventDefault();
const fullname = sanitizeInput(document.getElementById('register-fullname').value.trim());
const username = sanitizeInput(document.getElementById('register-username').value.trim());
const role = document.getElementById('register-role').value;
const password = document.getElementById('register-password').value;
const confirmPassword = document.getElementById('register-confirm-password').value;
// Enforce secure password length
if (password.length < 6) {
if (registerErrorMsg) {
registerErrorMsg.textContent = "La contraseña debe tener al menos 6 caracteres.";
registerErrorMsg.classList.remove('hidden');
}
authSynth.beep(150, 'sawtooth', 0.35);
return;
}
// Verify passwords match
if (password !== confirmPassword) {
if (registerErrorMsg) {
registerErrorMsg.textContent = "Las contraseñas no coinciden.";
registerErrorMsg.classList.remove('hidden');
}
authSynth.beep(150, 'sawtooth', 0.35);
return;
}
// Verify username conflict
const users = getUsers();
const userExists = users.some(u => u.username.toLowerCase() === username.toLowerCase());
if (userExists) {
if (registerErrorMsg) {
registerErrorMsg.textContent = "El nombre de usuario ya está registrado.";
registerErrorMsg.classList.remove('hidden');
}
authSynth.beep(150, 'sawtooth', 0.35);
return;
}
// Save and Login
if (registerErrorMsg) registerErrorMsg.classList.add('hidden');
const newUser = { fullname, username, role, password: hashPassword(password) };
saveUser(newUser);
setActiveSession(newUser);
updateSessionUI(newUser);
hideModal(registerModal);
// Victory/Success chime
authSynth.beep(523.25, 'sine', 0.1); // C5
setTimeout(() => authSynth.beep(659.25, 'sine', 0.1), 100); // E5
setTimeout(() => authSynth.beep(783.99, 'sine', 0.15), 200); // G5
setTimeout(() => authSynth.beep(1046.50, 'sine', 0.3), 300); // C6
authSynth.speak(`Registro exitoso. Se ha activado tu cuenta de ${fullname}.`);
});
}
// Logout Click
if (btnLogout) {
btnLogout.addEventListener('click', () => {
const session = getActiveSession();
const name = session ? session.fullname.split(' ')[0] : 'operador';
removeActiveSession();
updateSessionUI(null);