Repository navigation
Expand file tree
/
Copy pathscripts.js
More file actions
4716 lines (4406 loc) · 162 KB
/
Copy pathscripts.js
File metadata and controls
4716 lines (4406 loc) · 162 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
(() => {
'use strict';
const DB_NAME = 'pwm-local-vault';
const DB_VERSION = 1;
const STORE_NAME = 'vault';
const INDEX_KEY = 'vault-index';
const LEGACY_RECORD_KEY = 'current';
const VAULT_RECORD_PREFIX = 'vault:';
const SYNC_CHECKPOINT_PREFIX = '__pwm_internal:sync-checkpoint:';
const PBKDF2_ITERATIONS = 600_000;
const AUTO_LOCK_MS = 15 * 60 * 1000;
const CLIPBOARD_CLEAR_MS = 20_000;
const THEME_STORAGE_KEY = 'pwm-theme';
const USB_KEY_FORMAT = 'pwm-usb-key';
const USB_KEY_VERSION = 1;
const USB_KEY_MAX_BYTES = 16 * 1024;
const BACKUP_MAX_BYTES = 50 * 1024 * 1024;
const DEK_BYTES = 32;
const GENERATED_PASSWORD_LENGTH = 20;
const HISTORY_LIMIT = 200;
const SYNC_PAYLOAD_VERSION = 1;
const HOME_BACKGROUND_INTERVAL_MS = 10_000;
// El índice de bóvedas también es compartido: una única exclusión para todo el
// origen evita que dos pestañas escriban índices desde snapshots viejos.
const VAULT_ACCESS_LOCK_NAME = 'pwm-vault-open';
// Registro interno: nunca forma parte del índice ni de una bóveda exportada.
// IndexedDB serializa las transacciones readwrite de este store, por lo que es
// la autoridad atómica cuando Web Locks no está disponible.
const VAULT_ACCESS_LEASE_RECORD_KEY = '__pwm_internal:access-lease';
// Compatibilidad temporal con pestañas que todavía ejecutan una versión que
// usaba localStorage. No autoriza escrituras: IndexedDB sigue siendo la fuente
// de verdad y el cercado se verifica allí dentro de cada transacción.
const LEGACY_VAULT_ACCESS_LEASE_KEY = 'pwm-vault-lease';
const VAULT_ACCESS_LEASE_MS = 15_000;
const VAULT_ACCESS_REFRESH_MS = 5_000;
const TAB_INSTANCE_ID = crypto.randomUUID();
const HOME_BACKGROUNDS = Object.freeze([
'home-niebla',
'home-papel',
'home-salvia',
'home-arena',
'home-cielo',
'home-pizarra',
]);
const APPEARANCE_PRESETS = Object.freeze([
{ id: 'default', name: 'Predeterminado', group: 'Colores' },
{ id: 'color-niebla', name: 'Niebla', group: 'Colores' },
{ id: 'color-cielo', name: 'Cielo', group: 'Colores' },
{ id: 'color-salvia', name: 'Salvia', group: 'Colores' },
{ id: 'color-lavanda', name: 'Lavanda', group: 'Colores' },
{ id: 'color-arena', name: 'Arena', group: 'Colores' },
{ id: 'color-rosa', name: 'Rosa tenue', group: 'Colores' },
{ id: 'color-pizarra', name: 'Pizarra', group: 'Colores' },
{ id: 'color-grafito', name: 'Grafito', group: 'Colores' },
{ id: 'gradient-aurora', name: 'Aurora', group: 'Gradientes' },
{ id: 'gradient-brisa', name: 'Brisa marina', group: 'Gradientes' },
{ id: 'gradient-crepusculo', name: 'Crepúsculo', group: 'Gradientes' },
{ id: 'gradient-bosque', name: 'Bosque suave', group: 'Gradientes' },
{ id: 'gradient-lila', name: 'Lila', group: 'Gradientes' },
{ id: 'gradient-coral', name: 'Coral', group: 'Gradientes' },
{ id: 'gradient-nocturno', name: 'Noche azul', group: 'Gradientes' },
{ id: 'gradient-amanecer', name: 'Amanecer', group: 'Gradientes' },
{ id: 'gradient-menta', name: 'Menta', group: 'Gradientes' },
{ id: 'gradient-tinta', name: 'Tinta', group: 'Gradientes' },
{ id: 'pattern-cuadricula', name: 'Cuadrícula', group: 'Patrones' },
{ id: 'pattern-puntos', name: 'Puntos', group: 'Patrones' },
{ id: 'pattern-lineas', name: 'Líneas', group: 'Patrones' },
{ id: 'pattern-ondas', name: 'Ondas', group: 'Patrones' },
{ id: 'pattern-papel', name: 'Papel', group: 'Patrones' },
{ id: 'pattern-trama', name: 'Trama', group: 'Patrones' },
{ id: 'pattern-confeti', name: 'Confeti', group: 'Patrones' },
{ id: 'pattern-mosaico', name: 'Mosaico', group: 'Patrones' },
{ id: 'pattern-topografia', name: 'Topografía', group: 'Patrones' },
{ id: 'pattern-lunares', name: 'Lunares', group: 'Patrones' },
{ id: 'photo-montanas', name: 'Montañas serenas', group: 'Fotos' },
{ id: 'photo-oceano', name: 'Océano profundo', group: 'Fotos' },
{ id: 'photo-dunas', name: 'Dunas doradas', group: 'Fotos' },
{ id: 'photo-botanicas', name: 'Sombras botánicas', group: 'Fotos' },
{ id: 'photo-bosque', name: 'Bosque en niebla', group: 'Fotos' },
{ id: 'photo-cielo', name: 'Cielo nocturno', group: 'Fotos' },
]);
const APPEARANCE_PRESET_IDS = new Set(APPEARANCE_PRESETS.map((preset) => preset.id));
const HISTORY_TYPES = new Set([
'vault-created',
'vault-migrated',
'credential-created',
'credential-updated',
'credential-deleted',
'credential-favorited',
'credential-unfavorited',
'master-password-changed',
'usb-key-created',
'usb-key-disabled',
'sync-merged',
'sync-undone',
]);
const LOCAL_ONLY_SYNC_HISTORY_TYPES = new Set(['sync-merged', 'sync-undone']);
const PASSWORD_CHARACTER_GROUPS = Object.freeze({
uppercase: 'ABCDEFGHJKLMNPQRSTUVWXYZ',
lowercase: 'abcdefghijkmnopqrstuvwxyz',
numbers: '23456789',
symbols: '!@#$%&*+-_=?.',
});
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const VAULT_AS_KEY_MESSAGE = 'Ese archivo es una bóveda, no una llave USB. Usá “Importar bóveda”.';
const KEY_AS_VAULT_MESSAGE = 'Ese archivo es una llave USB, no una bóveda. Usá “Importar llave”.';
const BACKUP_REQUIRED_TITLE = 'Se requiere crear una copia de su bóveda, lo antes posible';
const BACKUP_FOLDER_RECOMMENDATION = 'Recomendamos guardar las copias de todas tus bóvedas en una misma carpeta dedicada y mantener los archivos llave separados.';
const BACKUP_REMINDERS = Object.freeze({
credentials: {
title: BACKUP_REQUIRED_TITLE,
text: 'Cambiaste contraseñas. Exportá la bóveda y guardá la copia nueva en tu USB ahora. Si perdés este navegador antes, podrías perder credenciales recientes.',
},
favorites: {
title: BACKUP_REQUIRED_TITLE,
text: 'Actualizaste tus favoritos. Exportá la bóveda y guardá la copia nueva en tu USB para conservar este orden.',
},
master: {
title: BACKUP_REQUIRED_TITLE,
text: 'Cambiaste la clave maestra. Es necesario exportar la bóveda a tu USB ahora: las copias previas sólo abrirán con la clave anterior.',
},
usb: {
title: BACKUP_REQUIRED_TITLE,
text: 'Cambiaste la llave USB. Guardá una copia nueva en tu USB.',
criticalText: 'Sin una copia nueva, tu llave actual no abrirá tus respaldos.',
},
migration: {
title: BACKUP_REQUIRED_TITLE,
text: 'La bóveda se actualizó. Exportá una copia nueva a tu USB para conservar un respaldo compatible.',
},
sync: {
title: BACKUP_REQUIRED_TITLE,
text: 'Combinaste cambios de otro dispositivo. Guardá una copia nueva. Después, en el otro dispositivo usá Sincronizar → Fusionar copia para que ambos queden iguales.',
},
});
const state = {
key: null,
keyBytes: null,
entries: [],
tombstones: [],
history: [],
appearance: { version: 1, background: 'default' },
appearanceDraft: null,
homeBackground: null,
homeBackgroundTimer: null,
record: null,
vaultId: null,
vaultName: '',
index: {
format: 'pwm-vault-index',
version: 2,
deviceId: TAB_INSTANCE_ID,
activeVaultId: null,
vaults: [],
},
autoLockTimer: null,
noticeTimer: null,
pendingBackupAction: null,
pendingBackupExport: null,
pendingUsbKey: null,
leaveBackupReminderTimer: null,
beforeUnloadWarningActive: false,
dismissedBackupReminderRecord: null,
vaultAccess: null,
pendingVaultAccessRelease: null,
pageSession: 0,
usbKeyBusy: false,
pendingSync: null,
};
const $ = (id) => document.getElementById(id);
const encoder = new TextEncoder();
const decoder = new TextDecoder();
function showNotice(message, type = 'success') {
const notice = $('notice');
notice.textContent = message;
notice.className = `notice ${type}`;
window.clearTimeout(state.noticeTimer);
state.noticeTimer = window.setTimeout(() => notice.classList.add('hidden'), 5000);
}
function vaultAccessName() {
return VAULT_ACCESS_LOCK_NAME;
}
function validVaultLease(lease) {
return Boolean(
lease
&& typeof lease === 'object'
&& lease.format === 'pwm-access-lease'
&& typeof lease.owner === 'string'
&& typeof lease.token === 'string'
&& Number.isFinite(lease.expiresAt),
);
}
function accessOwnsLease(access, lease, now = Date.now()) {
return Boolean(
validVaultLease(lease)
&& lease.owner === TAB_INSTANCE_ID
&& lease.token === access.token
&& lease.expiresAt > now,
);
}
function readLegacyVaultLease() {
try {
const lease = JSON.parse(localStorage.getItem(LEGACY_VAULT_ACCESS_LEASE_KEY));
if (
lease
&& typeof lease.owner === 'string'
&& typeof lease.token === 'string'
&& Number.isFinite(lease.expiresAt)
) return lease;
} catch (_) {
// El espejo opcional puede no estar disponible.
}
return null;
}
function liveLegacyVaultLease(lease, now = Date.now()) {
return Boolean(lease && lease.expiresAt > now);
}
function legacyLeaseConflicts() {
const lease = readLegacyVaultLease();
// Una lease viva de la versión anterior se trata como ajena, aun si el
// identificador de pestaña coincidiera por casualidad.
return liveLegacyVaultLease(lease);
}
function publishLegacyVaultLease(access) {
try {
const existing = readLegacyVaultLease();
if (
liveLegacyVaultLease(existing)
&& (existing.owner !== TAB_INSTANCE_ID || existing.token !== access.token)
) {
return false;
}
localStorage.setItem(LEGACY_VAULT_ACCESS_LEASE_KEY, JSON.stringify({
owner: TAB_INSTANCE_ID,
token: access.token,
expiresAt: access.leaseExpiresAt,
}));
const confirmed = readLegacyVaultLease();
return Boolean(
confirmed
&& confirmed.owner === TAB_INSTANCE_ID
&& confirmed.token === access.token
&& confirmed.expiresAt >= access.leaseExpiresAt,
);
} catch (_) {
// El espejo no es necesario para la seguridad de esta versión.
return true;
}
}
function removeLegacyVaultLease(access) {
try {
const lease = readLegacyVaultLease();
if (lease?.owner === TAB_INSTANCE_ID && lease.token === access.token) {
localStorage.removeItem(LEGACY_VAULT_ACCESS_LEASE_KEY);
}
} catch (_) {
// La lease de IndexedDB expira aunque el espejo no pueda limpiarse.
}
}
function ownsVaultAccess(vaultId = state.vaultId) {
const access = state.vaultAccess;
if (!access || access.invalidated || (!access.temporary && (!vaultId || access.vaultId !== vaultId))) return false;
// La comprobación autoritativa del token ocurre dentro de cada transacción
// readwrite. Esta guarda rápida evita operar tras una concesión ya vencida.
return access.leaseExpiresAt > Date.now();
}
function waitForPendingVaultAccessRelease() {
const pending = state.pendingVaultAccessRelease;
return pending || Promise.resolve();
}
function releaseVaultAccess() {
const access = state.vaultAccess;
state.vaultAccess = null;
if (!access) return waitForPendingVaultAccessRelease();
const release = Promise.resolve(disposeVaultAccess(access)).catch(() => undefined);
const previous = state.pendingVaultAccessRelease;
const pending = previous
? Promise.allSettled([previous, release]).then(() => undefined)
: release;
state.pendingVaultAccessRelease = pending;
void pending.then(() => {
if (state.pendingVaultAccessRelease === pending) {
state.pendingVaultAccessRelease = null;
}
});
return pending;
}
function disposeVaultAccess(access) {
if (!access) return Promise.resolve();
if (access.releasePromise) return access.releasePromise;
access.invalidated = true;
// Una escritura que ya estaba en curso no debe poder terminar después de
// bloquear la bóveda o abandonar la página.
access.transactions?.forEach((transaction) => {
try { transaction.abort(); } catch (_) { /* ya terminó */ }
});
access.transactions?.clear();
window.clearInterval(access.refreshTimer);
access.releasePromise = Promise.resolve(releaseVaultLease(access))
.catch(() => undefined)
.then(() => {
// El Web Lock se conserva hasta terminar de liberar la lease
// transaccional, para no abrir una ventana de doble adquisicion.
if (access.kind === 'web-lock') {
try { access.release(); } catch (_) { /* ya fue liberado */ }
}
});
return access.releasePromise;
}
function handleLostVaultAccess() {
// También puede ocurrir durante una operación temporal (crear, importar o
// desbloquear), antes de que state.key exista. En ese caso se invalida la
// sesión y se limpian formularios igual que al abandonar la página.
if (state.key) lockVault();
else lockVaultOnPageExit();
showNotice(
'Esta bóveda se abrió en otra pestaña. Se bloqueó aquí para evitar cambios en conflicto.',
'error',
);
}
async function acquireIndexedDbLease(vaultId, temporary = false, kind = 'lease', release = null) {
if (legacyLeaseConflicts()) return { status: 'busy', access: null };
const token = crypto.randomUUID();
let expiresAt = 0;
let database;
try {
database = await openDatabase();
} catch (_) {
return { status: 'unavailable', access: null };
}
return new Promise((resolve) => {
let transaction;
let store;
let request;
try {
transaction = database.transaction(STORE_NAME, 'readwrite');
store = transaction.objectStore(STORE_NAME);
request = store.get(VAULT_ACCESS_LEASE_RECORD_KEY);
} catch (_) {
database.close();
resolve({ status: 'unavailable', access: null });
return;
}
let granted = false;
let outcome = 'unavailable';
const stop = (status = 'unavailable') => {
outcome = status;
try { transaction.abort(); } catch (_) { /* ya terminó */ }
};
request.onsuccess = () => {
try {
const existing = request.result;
// Una concesión viva, incluso de esta misma pestaña, se respeta. Así
// dos solicitudes concurrentes no pueden reemplazarse entre sí.
if (validVaultLease(existing) && existing.expiresAt > Date.now()) {
stop('busy');
return;
}
// La apertura de IndexedDB puede haber esperado detrás de otra
// transacción: el vencimiento se calcula recién al reclamarla.
expiresAt = Date.now() + VAULT_ACCESS_LEASE_MS;
store.put({
format: 'pwm-access-lease',
owner: TAB_INSTANCE_ID,
token,
expiresAt,
}, VAULT_ACCESS_LEASE_RECORD_KEY);
granted = true;
} catch (_) {
stop('unavailable');
}
};
request.onerror = () => stop('unavailable');
transaction.oncomplete = () => {
database.close();
if (!granted) {
resolve({ status: outcome, access: null });
return;
}
const access = {
kind,
vaultId,
temporary,
token,
leaseExpiresAt: expiresAt,
refreshTimer: null,
refreshInFlight: false,
transactions: new Set(),
session: state.pageSession,
release,
};
if (!publishLegacyVaultLease(access)) {
access.invalidated = true;
void releaseVaultLease(access).finally(() => {
resolve({ status: 'busy', access: null });
});
return;
}
access.refreshTimer = window.setInterval(
() => { void refreshVaultLease(access); },
VAULT_ACCESS_REFRESH_MS,
);
resolve({ status: 'acquired', access });
};
transaction.onerror = () => {
database.close();
resolve({ status: 'unavailable', access: null });
};
transaction.onabort = () => {
database.close();
resolve({ status: granted ? 'unavailable' : outcome, access: null });
};
});
}
async function renewVaultLease(access) {
let database;
try {
database = await openDatabase();
} catch (_) {
return false;
}
return new Promise((resolve) => {
let transaction;
let store;
let request;
try {
transaction = database.transaction(STORE_NAME, 'readwrite');
store = transaction.objectStore(STORE_NAME);
request = store.get(VAULT_ACCESS_LEASE_RECORD_KEY);
} catch (_) {
database.close();
resolve(false);
return;
}
let nextExpiresAt = 0;
let renewed = false;
const stop = () => {
try { transaction.abort(); } catch (_) { /* ya terminó */ }
};
request.onsuccess = () => {
try {
if (!accessOwnsLease(access, request.result)) {
stop();
return;
}
nextExpiresAt = Date.now() + VAULT_ACCESS_LEASE_MS;
store.put({ ...request.result, expiresAt: nextExpiresAt }, VAULT_ACCESS_LEASE_RECORD_KEY);
renewed = true;
} catch (_) {
stop();
}
};
request.onerror = stop;
transaction.oncomplete = () => {
database.close();
if (renewed) {
access.leaseExpiresAt = nextExpiresAt;
renewed = publishLegacyVaultLease(access);
}
resolve(renewed);
};
transaction.onerror = () => {
database.close();
resolve(false);
};
transaction.onabort = () => {
database.close();
resolve(false);
};
});
}
async function releaseVaultLease(access) {
let database;
try {
database = await openDatabase();
return await new Promise((resolve) => {
let completed = false;
const finish = (released) => {
if (completed) return;
completed = true;
database.close();
if (released) removeLegacyVaultLease(access);
resolve(released);
};
let transaction;
try {
transaction = database.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.get(VAULT_ACCESS_LEASE_RECORD_KEY);
let deleted = false;
request.onsuccess = () => {
try {
if (accessOwnsLease(access, request.result)) {
store.delete(VAULT_ACCESS_LEASE_RECORD_KEY);
deleted = true;
}
} catch (_) {
try { transaction.abort(); } catch (_) { /* ya terminó */ }
}
};
request.onerror = () => {
try { transaction.abort(); } catch (_) { /* ya terminó */ }
};
transaction.oncomplete = () => finish(deleted);
transaction.onerror = () => finish(false);
transaction.onabort = () => finish(false);
} catch (_) {
finish(false);
}
});
} catch (_) {
try { database?.close(); } catch (_) { /* ya cerrada */ }
return false;
}
}
async function refreshVaultLease(access) {
if (
access.refreshInFlight
|| state.vaultAccess !== access
|| access.invalidated
|| !ownsVaultAccess(access.vaultId)
) {
if (state.vaultAccess === access && !access.refreshInFlight) handleLostVaultAccess();
return;
}
access.refreshInFlight = true;
let renewed = false;
try {
renewed = await renewVaultLease(access);
} catch (_) {
renewed = false;
} finally {
access.refreshInFlight = false;
}
if (!renewed && state.vaultAccess === access) handleLostVaultAccess();
}
function handleLegacyVaultLeaseStorage(event) {
if (event.key !== LEGACY_VAULT_ACCESS_LEASE_KEY) return;
const access = state.vaultAccess;
const lease = readLegacyVaultLease();
if (
!access
|| access.invalidated
|| !lease
|| lease.expiresAt <= Date.now()
|| (lease.owner === TAB_INSTANCE_ID && lease.token === access.token)
) return;
// Una pestaña antigua no conoce el cercado IndexedDB; se bloquea esta
// pestaña inmediatamente para mantener la compatibilidad durante el cambio.
handleLostVaultAccess();
}
async function acquireFallbackVaultAccess(vaultId, temporary = false) {
const result = await acquireIndexedDbLease(vaultId, temporary);
return result.access;
}
async function acquireWebVaultAccess(vaultId, temporary = false) {
return new Promise((resolve) => {
let release;
const hold = new Promise((releaseLock) => {
release = releaseLock;
});
try {
navigator.locks.request(
vaultAccessName(),
{ mode: 'exclusive', ifAvailable: true },
async (lock) => {
if (!lock) {
// Otra pestaña ya tiene el bloqueo fuerte. No se inicia una
// segunda vía de adquisición mientras siga ocupado.
resolve({ status: 'busy', access: null });
return;
}
// Incluso Web Locks mantiene una lease en IndexedDB. Así distintas
// capacidades del navegador no pueden eludir el mismo cercado.
const lease = await acquireIndexedDbLease(vaultId, temporary, 'web-lock', release);
resolve(lease);
if (!lease.access) return;
await hold;
},
).catch(() => resolve({ status: 'unavailable', access: null }));
} catch (_) {
resolve({ status: 'unavailable', access: null });
}
});
}
async function acquireVaultAccess(vaultId, temporary = false) {
if (ownsVaultAccess(vaultId)) return true;
// Se captura antes de esperar una liberación: pagehide puede ocurrir durante
// esa espera y no debe permitir instalar un acceso después de abandonar.
const session = state.pageSession;
if (state.vaultAccess) await releaseVaultAccess();
await waitForPendingVaultAccessRelease();
if (session !== state.pageSession) return false;
let access = null;
const webLocksAvailable = typeof navigator.locks?.request === 'function';
if (webLocksAvailable) {
const webLock = await acquireWebVaultAccess(vaultId, temporary);
access = webLock.access;
// Si Web Locks está disponible pero no funciona, mantenemos la aplicación
// utilizable con la lease transaccional. Si está ocupado, no hacemos fallback.
if (!access && webLock.status === 'unavailable') {
access = await acquireFallbackVaultAccess(vaultId, temporary);
}
} else {
access = await acquireFallbackVaultAccess(vaultId, temporary);
}
if (!access || session !== state.pageSession) {
await disposeVaultAccess(access);
return false;
}
access.session = session;
state.vaultAccess = access;
return true;
}
async function withTemporaryVaultAccess(callback) {
if (state.vaultAccess) return callback(captureVaultAccess());
const acquired = await acquireVaultAccess('temporary', true);
if (!acquired) throw new Error('Otra pestaña está actualizando las bóvedas. Intentá de nuevo.');
const access = captureVaultAccess();
try {
return await callback(access);
} finally {
if (state.vaultAccess === access) await releaseVaultAccess();
}
}
function captureVaultAccess() {
const access = state.vaultAccess;
if (!access || access.invalidated || !ownsVaultAccess(access.vaultId)) {
throw new Error('La bóveda está abierta en otra pestaña o la sesión terminó.');
}
return access;
}
function assertVaultAccess(access, requireUnlocked = false) {
if (
!access
|| state.vaultAccess !== access
|| access.invalidated
|| access.session !== state.pageSession
|| !ownsVaultAccess(access.vaultId)
|| (requireUnlocked && (!state.key || !state.vaultId || state.vaultId !== access.vaultId))
) {
throw new Error('La sesión de la bóveda terminó antes de completar la operación.');
}
}
function applyTheme(theme) {
const isDark = theme === 'dark';
document.documentElement.dataset.theme = isDark ? 'dark' : 'light';
$('themeToggle').setAttribute('aria-pressed', String(isDark));
$('themeToggle').setAttribute('aria-label', isDark ? 'Activar modo claro' : 'Activar modo oscuro');
$('themeIcon').textContent = isDark ? '☀' : '☾';
$('themeToggleLabel').textContent = isDark ? 'Modo claro' : 'Modo oscuro';
}
function loadTheme() {
const savedTheme = localStorage.getItem(THEME_STORAGE_KEY);
if (savedTheme === 'dark' || savedTheme === 'light') return savedTheme;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function toggleTheme() {
const nextTheme = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
localStorage.setItem(THEME_STORAGE_KEY, nextTheme);
applyTheme(nextTheme);
}
function normalizeAppearance(appearance) {
const background = appearance && typeof appearance === 'object' && APPEARANCE_PRESET_IDS.has(appearance.background)
? appearance.background
: 'default';
return { version: 1, background };
}
function applyVaultBackground(appearance = state.appearance) {
const background = normalizeAppearance(appearance).background;
if (background === 'default') {
delete document.documentElement.dataset.vaultBackground;
return;
}
document.documentElement.dataset.vaultBackground = background;
}
function clearVaultBackground() {
delete document.documentElement.dataset.vaultBackground;
}
function prefersReducedMotion() {
return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
}
function nextHomeBackground() {
const choices = HOME_BACKGROUNDS.filter((background) => background !== state.homeBackground);
return choices[Math.floor(Math.random() * choices.length)] || HOME_BACKGROUNDS[0];
}
function applyHomeBackground(background) {
if (!HOME_BACKGROUNDS.includes(background)) return;
state.homeBackground = background;
document.documentElement.dataset.homeBackground = background;
}
function startHomeBackgroundRotation() {
if (state.homeBackgroundTimer) return;
applyHomeBackground(nextHomeBackground());
if (prefersReducedMotion()) return;
state.homeBackgroundTimer = window.setInterval(() => {
applyHomeBackground(nextHomeBackground());
}, HOME_BACKGROUND_INTERVAL_MS);
}
function stopHomeBackgroundRotation() {
window.clearInterval(state.homeBackgroundTimer);
state.homeBackgroundTimer = null;
delete document.documentElement.dataset.homeBackground;
}
function renderAppearanceOptions() {
const container = $('appearanceOptions');
emptyElement(container);
const groups = [...new Set(APPEARANCE_PRESETS.map((preset) => preset.group))];
groups.forEach((group) => {
const section = document.createElement('section');
section.className = 'appearance-group';
const title = document.createElement('h3');
title.textContent = group;
const choices = document.createElement('div');
choices.className = 'appearance-choice-grid';
APPEARANCE_PRESETS.filter((preset) => preset.group === group).forEach((preset) => {
const button = document.createElement('button');
button.className = 'appearance-option';
button.type = 'button';
button.dataset.background = preset.id;
button.setAttribute('role', 'radio');
button.setAttribute('aria-checked', 'false');
const swatch = document.createElement('span');
swatch.className = 'appearance-swatch';
swatch.dataset.background = preset.id;
swatch.setAttribute('aria-hidden', 'true');
const label = document.createElement('span');
label.textContent = preset.name;
button.append(swatch, label);
choices.append(button);
});
section.append(title, choices);
container.append(section);
});
}
function setAppearanceSelection(background) {
const safeBackground = APPEARANCE_PRESET_IDS.has(background) ? background : 'default';
state.appearanceDraft = { version: 1, background: safeBackground };
$('appearanceOptions').querySelectorAll('.appearance-option').forEach((button) => {
const selected = button.dataset.background === safeBackground;
button.classList.toggle('selected', selected);
button.setAttribute('aria-checked', String(selected));
});
applyVaultBackground(state.appearanceDraft);
}
function openAppearanceDialog() {
if (!state.key || !state.vaultId) return;
state.appearanceDraft = normalizeAppearance(state.appearance);
renderAppearanceOptions();
setAppearanceSelection(state.appearanceDraft.background);
$('appearanceDialog').showModal();
$('appearanceOptions').querySelector('.appearance-option.selected')?.focus();
resetAutoLock();
}
function closeAppearanceDialog(restore = true) {
if (restore) applyVaultBackground(state.appearance);
state.appearanceDraft = null;
if ($('appearanceDialog').open) $('appearanceDialog').close();
}
async function saveAppearance() {
if (!state.key || !state.record || state.record.version !== 2 || !state.vaultId) {
throw new Error('Bóveda bloqueada');
}
const access = captureVaultAccess();
assertVaultAccess(access, true);
const expectedSnapshot = vaultRecordSnapshot(state.record);
const encrypted = await encryptPayloadV2(state.key, {
syncVersion: SYNC_PAYLOAD_VERSION,
entries: state.entries,
tombstones: state.tombstones,
history: state.history,
appearance: state.appearance,
});
const record = { ...state.record, ...encrypted, updatedAt: new Date().toISOString() };
const committed = await commitVaultSnapshot(
access,
state.vaultId,
expectedSnapshot,
() => true,
(index) => ({
record,
index: updateVaultMetadata(index, state.vaultId, state.vaultName, record.updatedAt),
deleteKeys: [syncCheckpointKey(state.vaultId)],
}),
);
assertVaultAccess(access, true);
state.record = record;
state.index = committed.index;
}
async function applyAppearance() {
const previous = state.appearance;
const next = normalizeAppearance(state.appearanceDraft);
const access = state.vaultAccess;
const session = state.pageSession;
state.appearance = next;
applyVaultBackground(next);
$('applyAppearanceButton').disabled = true;
try {
await saveAppearance();
closeAppearanceDialog(false);
showNotice('Apariencia guardada para esta bóveda.');
} catch (_) {
if (state.pageSession === session && state.vaultAccess === access && state.key) {
state.appearance = previous;
applyVaultBackground(previous);
}
showNotice('No se pudo guardar la apariencia.', 'error');
} finally {
$('applyAppearanceButton').disabled = false;
}
}
function setScreen(name) {
$('setupScreen').classList.toggle('hidden', name !== 'setup');
$('unlockScreen').classList.toggle('hidden', name !== 'unlock');
$('vaultScreen').classList.toggle('hidden', name !== 'vault');
$('appearanceButton').classList.toggle('hidden', name !== 'vault' || !state.key);
if (name === 'vault') stopHomeBackgroundRotation();
else {
clearVaultBackground();
startHomeBackgroundRotation();
}
if (name === 'vault') $('currentVaultName').textContent = state.vaultName;
updateBackupReminder();
}
function showSetup(isAdditionalVault = false) {
$('setupForm').reset();
$('setupEyebrow').textContent = isAdditionalVault ? 'Nueva bóveda' : 'Empezar';
$('setupTitle').textContent = isAdditionalVault ? 'Creá otra bóveda.' : 'Creá tu primera bóveda.';
$('setupLead').textContent = isAdditionalVault
? 'Tendrá su propio nombre, clave maestra y contraseñas.'
: 'Ponéle un nombre y protegela con una clave maestra que no uses en otro lugar.';
$('cancelSetupButton').classList.toggle('hidden', !state.index.vaults.length);
setScreen('setup');
$('setupVaultName').focus();
}
function resetAutoLock() {
window.clearTimeout(state.autoLockTimer);
if (!state.key) return;
state.autoLockTimer = window.setTimeout(() => lockVault(true), AUTO_LOCK_MS);
}
function base64FromBytes(bytes) {
let binary = '';
bytes.forEach((byte) => { binary += String.fromCharCode(byte); });
return btoa(binary);
}
function bytesFromBase64(value) {
if (typeof value !== 'string' || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
throw new Error('Base64 inválido');
}
const binary = atob(value);
const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0));
if (base64FromBytes(bytes) !== value) throw new Error('Base64 inválido');
return bytes;
}
function hasBase64Length(value, length) {
try {
return bytesFromBase64(value).byteLength === length;
} catch (_) {
return false;
}
}
function hasBase64AtLeast(value, minimum) {
try {
return bytesFromBase64(value).byteLength >= minimum;
} catch (_) {
return false;
}
}
function newSalt() {
const salt = new Uint8Array(16);
crypto.getRandomValues(salt);
return salt;
}
function newIv() {
const iv = new Uint8Array(12);
crypto.getRandomValues(iv);
return iv;
}
async function deriveKey(masterPassword, salt, iterations) {
const keyMaterial = await crypto.subtle.importKey(
'raw',
encoder.encode(masterPassword),
'PBKDF2',
false,
['deriveKey'],
);
return crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt, iterations, hash: 'SHA-256' },
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt'],
);
}
function aad(kind, keyId = '') {
return encoder.encode(`pwm-local-vault|v2|${kind}${keyId ? `|${keyId}` : ''}`);
}
async function importAesKey(bytes) {
if (!(bytes instanceof Uint8Array) || bytes.byteLength !== DEK_BYTES) {
throw new Error('Clave de cifrado inválida');
}
return crypto.subtle.importKey('raw', bytes, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']);
}
function randomDek() {
const bytes = new Uint8Array(DEK_BYTES);
crypto.getRandomValues(bytes);
return bytes;
}
async function encryptPayloadV1(key, payload) {
const iv = newIv();
const cipher = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
encoder.encode(JSON.stringify(payload)),
);
return {
iv: base64FromBytes(iv),
ciphertext: base64FromBytes(new Uint8Array(cipher)),
};
}
async function decryptPayloadV1(key, record) {
const plaintext = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv: bytesFromBase64(record.iv) },
key,
bytesFromBase64(record.ciphertext),
);
const payload = JSON.parse(decoder.decode(plaintext));
if (!Array.isArray(payload.entries)) throw new Error('Formato de bóveda inválido');
return payload;
}
async function encryptPayloadV2(key, payload) {