-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1179 lines (985 loc) · 41 KB
/
app.js
File metadata and controls
1179 lines (985 loc) · 41 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
/* ============================================================
FileKrypt – app.js
AES-256-GCM + PBKDF2-SHA256 · Web Crypto API only
No data ever leaves the browser.
============================================================ */
'use strict';
// Force scroll to top on reload for Android view only
if (window.matchMedia('(max-width: 1024px)').matches) {
window.scrollTo(0, 0);
const mci = document.querySelector('.main-card-inner');
if (mci) mci.scrollTop = 0;
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
}
function esc(s) {
if (s == null) return '';
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''');
}
// Apply saved tab immediately on load
const lastTab = localStorage.getItem('fk_active_tab');
if (lastTab) {
// Use a small delay or check for body readiness to ensure elements exist
const restoreTab = () => {
if (document.getElementById('panel-encrypt')) {
switchTab(lastTab);
} else {
setTimeout(restoreTab, 0);
}
};
restoreTab();
}
// ─── State ────────────────────────────────────────────────
const state = {
enc: { files: [], blob: null, filename: null, isEncrypting: false, abort: false },
dec: { file: null, blob: null, filename: null, unzippedFiles: null },
recents: { enc: [], dec: [] }
};
// Load recents from storage
try {
const stored = localStorage.getItem('fk_recents');
if (stored) {
const parsed = JSON.parse(stored);
if (parsed.enc) state.recents.enc = parsed.enc;
if (parsed.dec) state.recents.dec = parsed.dec;
}
} catch (e) { }
// Magic bytes to identify .enc format (ASCII "FKRYPT1")
const MAGIC = new Uint8Array([0x46, 0x4B, 0x52, 0x59, 0x50, 0x54, 0x31]);
const PBKDF2_ITERS = 310_000;
const SALT_LEN = 32;
const IV_LEN = 12;
const ICON_EYE = `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:block;"><path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0z"/><circle cx="12" cy="12" r="3"/></svg>`;
const ICON_EYE_OFF = `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:block;"><path d="M10.73 5.08A10.43 10.43 0 0 1 12 5c7 0 10 7 10 7a13.16 13.16 0 0 1-1.67 2.68"/><path d="M6.61 6.61A13.52 13.52 0 0 0 2 12s3 7 10 7a9.74 9.74 0 0 0 1.55-.12"/><path d="M22 22 2 2"/><path d="M9.88 9.88a3 3 0 1 0 4.24 4.24"/></svg>`;
// ─── Tab switching ────────────────────────────────────────
function switchTab(tab) {
const isEnc = tab === 'encrypt';
document.getElementById('panel-encrypt').classList.toggle('hidden', !isEnc);
document.getElementById('panel-decrypt').classList.toggle('hidden', isEnc);
document.getElementById('tab-encrypt').classList.toggle('active', isEnc);
document.getElementById('tab-decrypt').classList.toggle('active', !isEnc);
document.querySelector('.tab-bar').classList.toggle('dec-mode', !isEnc);
document.querySelector('.tab-slider').style.transform = isEnc ? '' : 'translateX(calc(100% + 2px))';
document.body.classList.toggle('decrypt-mode', !isEnc);
// Update header buttons color based on mode
const githubBtn = document.getElementById('nav-github-btn');
const shareBtn = document.getElementById('nav-share-btn');
if (githubBtn) githubBtn.style.color = isEnc ? '#8EB69B' : '#E8DCC4';
if (shareBtn) shareBtn.style.color = isEnc ? '#8EB69B' : '#E8DCC4';
// Reset card scroll on tab switch for Android view
if (window.matchMedia('(max-width: 1024px)').matches) {
const cardInner = document.querySelector('.main-card-inner');
if (cardInner) cardInner.scrollTop = 0;
}
// Toggle sidebar recents panels
const encSidebar = document.getElementById('sidebar-enc-recents');
const decSidebar = document.getElementById('sidebar-dec-recents');
if (encSidebar) encSidebar.classList.toggle('hidden', !isEnc);
if (decSidebar) decSidebar.classList.toggle('hidden', isEnc);
const cpTitle = document.getElementById('cp-title-text');
if (cpTitle) cpTitle.textContent = isEnc ? 'Change Password' : 'RECOVER AND DOWNLOAD';
const encPreviewCard = document.getElementById('enc-preview-card');
const decPreviewCard = document.getElementById('dec-preview-card');
if (encPreviewCard) encPreviewCard.classList.add('hidden');
if (decPreviewCard) decPreviewCard.classList.add('hidden');
localStorage.setItem('fk_active_tab', tab);
}
// ─── Drag & drop ──────────────────────────────────────────
function onDragOver(e) {
e.preventDefault();
e.currentTarget.classList.add('drag-over');
}
function onDragLeave(e) {
e.currentTarget.classList.remove('drag-over');
}
const MAX_FILES = 1;
const MAX_SIZE_BYTES = 2 * 1024 * 1024 * 1024; // 2GB limit
function onDrop(e, mode) {
e.preventDefault();
e.currentTarget.classList.remove('drag-over');
const fileList = e.dataTransfer.files;
if (fileList.length) { applyFiles(fileList, mode); }
}
function onFileSelect(e, mode) {
const fileList = e.target.files;
if (fileList.length) { applyFiles(fileList, mode); }
}
function applyFiles(fileList, mode, append = false) {
if (mode === 'enc') {
let newFiles = Array.from(fileList).filter(f => {
if (f.size > MAX_SIZE_BYTES) {
toast('error', `"${f.name}" exceeds the 2GB limit. Please select a smaller file.`);
return false;
}
return true;
});
if (newFiles.length === 0) return;
let combined = append ? [...state.enc.files, ...newFiles] : newFiles;
if (combined.length > MAX_FILES) {
combined = combined.slice(0, MAX_FILES);
}
state.enc.files = combined;
showEncPreview(state.enc.files);
} else {
const file = fileList[0];
if (file && !file.name.toLowerCase().endsWith('.enc')) {
toast('error', 'Please select a valid .enc file for decryption.');
return;
}
state.dec.file = file;
showDecPreview(state.dec.file);
}
}
function clearFile(mode) {
if (mode === 'enc' && state.enc.isEncrypting) state.enc.abort = true;
state[mode].file = null;
const input = document.getElementById(mode + '-file-input');
if (input) input.value = '';
if (mode === 'enc') {
updateEncSidebarPreview(null);
document.getElementById('enc-preview-container').classList.add('hidden');
document.getElementById('enc-file-list').classList.add('hidden');
const outNameInput = document.getElementById('enc-outname');
if (outNameInput) outNameInput.value = '';
const outnameGroup = document.getElementById('enc-outname-group');
if (outnameGroup) outnameGroup.classList.add('hidden');
const chevron = document.getElementById('enc-fp-chevron');
if (chevron) chevron.style.transform = '';
const imgPreview = document.getElementById('enc-img-preview');
if (imgPreview) imgPreview.classList.add('hidden');
document.getElementById('enc-drop').classList.remove('hidden');
const metaBox = document.getElementById('enc-meta');
if (metaBox) metaBox.classList.add('hidden');
hideProgress('enc');
const disclaimer = document.getElementById('enc-disclaimer');
if (disclaimer) disclaimer.style.display = 'block';
const successBox = document.getElementById('enc-success');
if (successBox) successBox.classList.add('hidden');
const encBtn = document.getElementById('enc-btn');
if (encBtn) encBtn.classList.remove('hidden');
const pwdInput = document.getElementById('enc-pwd');
if (pwdInput) {
pwdInput.value = '';
onPwdInput(pwdInput, 'enc-strength');
const strengthLabel = document.getElementById('enc-strength-label');
if (strengthLabel) strengthLabel.textContent = '';
}
state.enc.files = [];
state.enc.blob = null;
state.enc.filename = null;
if (typeof syncToolsFile === 'function') syncToolsFile(null, null);
} else {
document.getElementById('dec-preview').classList.add('hidden');
document.getElementById('dec-drop').classList.remove('hidden');
hideProgress('dec');
const disclaimer = document.getElementById('dec-disclaimer');
if (disclaimer) disclaimer.style.display = 'block';
const successBox = document.getElementById('dec-success');
if (successBox) successBox.classList.add('hidden');
const viewBtn = document.getElementById('dec-view-bundle-btn');
if (viewBtn) viewBtn.classList.add('hidden');
const bundleList = document.getElementById('dec-bundle-list');
if (bundleList) bundleList.classList.add('hidden');
const decBtn = document.getElementById('dec-btn');
if (decBtn) decBtn.classList.remove('hidden');
document.getElementById('dec-pwd').value = '';
state.dec.blob = null;
state.dec.filename = null;
state.dec.unzippedFiles = null;
window.lastPreviewBlob = null;
updateDecSidebarPreview(null);
// Clear sync tool
if (typeof syncToolsFile === 'function') syncToolsFile(null, null);
}
}
// ─── File previews ────────────────────────────────────────
const FILE_ICONS = {};
const _FILE_ICON = `<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#6b7280" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><path d="M13 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9z"/><polyline points="13 2 13 9 20 9"/></svg>`;
FILE_ICONS.image = FILE_ICONS.video = FILE_ICONS.audio = FILE_ICONS.pdf =
FILE_ICONS.zip = FILE_ICONS.text = FILE_ICONS.code = FILE_ICONS.sheet =
FILE_ICONS.pptx = FILE_ICONS.unknown = _FILE_ICON;
function getFileIcon(file) { return _FILE_ICON; }
function openMainExternalPreview(e) {
if (e) e.stopPropagation();
const card = document.getElementById('enc-preview-card');
if (card && !card.classList.contains('hidden')) {
updateEncSidebarPreview(null);
return;
}
if (state.enc.files && state.enc.files.length > 0) {
const file = state.enc.files[0];
updateEncSidebarPreview(file, file.name);
}
}
function fmtSize(n) {
if (n < 1024) return n + ' B';
if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
return (n / 1024 / 1024).toFixed(2) + ' MB';
}
function truncateName(name, limit = 14, show = 11) {
if (!name) return '';
return name.length > limit ? name.substring(0, show) + '...' : name;
}
// ─── Password strength ────────────────────────────────────
function onPwdInput(input, barId) {
const pwd = input.value;
const { score, label, color } = measureStrength(pwd);
// Update border based on strength
if (!pwd) {
input.style.borderColor = '';
} else {
input.style.borderColor = color;
}
if (!barId) return;
const fill = document.getElementById(barId);
if (fill) {
fill.style.width = score + '%';
fill.style.background = color;
}
// Derive label/hint IDs from barId (e.g. "enc-strength" → "enc-strength-label", "enc-pwd-hint")
const prefix = barId.replace('-strength', '');
const lbl = document.getElementById(barId + '-label');
if (lbl) {
lbl.textContent = pwd ? label : '';
// Increase only the brightness of the "Excellent" text without affecting the connected border color
if (pwd && label === 'Excellent') {
lbl.style.color = '#8EB69B';
} else {
lbl.style.color = pwd ? color : '';
}
}
// Show hint when user has typed something but it's under 8 chars
const hint = document.getElementById(prefix + '-pwd-hint');
if (hint) {
hint.style.opacity = (pwd.length > 0 && pwd.length < 8) ? '1' : '0';
}
}
function measureStrength(pwd) {
if (!pwd) return { score: 0, label: '', color: '#444' };
let score = 0;
if (pwd.length >= 8) score += 20;
if (pwd.length >= 12) score += 15;
if (pwd.length >= 14) score += 10;
if (/[a-z]/.test(pwd)) score += 10;
if (/[A-Z]/.test(pwd)) score += 15;
if (/\d/.test(pwd)) score += 15;
if (/[!"#$%&'()*+,-./:;<=>?@[\\]^_`{|}]/.test(pwd)) score += 15;
score = Math.min(score, 100);
if (score < 40) return { score, label: 'Weak', color: '#ff4d6d' };
if (score < 65) return { score, label: 'Fair', color: '#f7b731' };
if (score < 85) return { score, label: 'Strong', color: '#00e5a0' };
return { score: 100, label: 'Excellent', color: '#8EB69B' };
}
function checkPwdStrengthBorder(input) {
// Redundant - functionality moved to onPwdInput
}
// ─── Toggle password visibility ───────────────────────────
function togglePwd(inputId, btn) {
const input = document.getElementById(inputId);
const showing = input.type === 'text';
input.type = showing ? 'password' : 'text';
btn.title = showing ? 'Show password' : 'Hide password';
btn.innerHTML = showing ? ICON_EYE : ICON_EYE_OFF;
}
function setBtn(id, disabled, text) {
const btn = document.getElementById(id);
btn.disabled = disabled;
if (text) btn.querySelector('svg + span, :last-child');
}
// ─── Crypto helpers ───────────────────────────────────────
async function deriveKey(password, salt) {
const enc = new TextEncoder();
const raw = enc.encode(password);
const keyMat = await crypto.subtle.importKey('raw', raw, 'PBKDF2', false, ['deriveKey']);
return crypto.subtle.deriveKey(
{ name: 'PBKDF2', salt, iterations: PBKDF2_ITERS, hash: 'SHA-256' },
keyMat,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
}
function readFileAsBuffer(file) {
return new Promise((res, rej) => {
const reader = new FileReader();
reader.onload = (e) => res(e.target.result);
reader.onerror = () => rej(new Error('Failed to read file.'));
reader.readAsArrayBuffer(file);
});
}
// ─── Lockfile format ──────────────────────────────────────
// Layout (bytes):
// [7] MAGIC
// [4] original filename length (Uint32LE)
// [N] original filename (UTF-8)
// [4] original MIME type length (Uint32LE)
// [M] original MIME type (UTF-8)
// [SALT_LEN] salt
// [IV_LEN] IV
// [rest] ciphertext (AES-GCM)
const MAGIC2 = new Uint8Array([0x46, 0x4B, 0x52, 0x59, 0x50, 0x54, 0x32]);
const WRAPPED_KEY_LEN = 32 + 16; // 32 bytes key + 16 bytes GCM tag
function buildLockfile(filename, mime, salt, iv, ciphertext, wrappedKeyPwd = null, wrappedKeyRec = null, wrapIv = null) {
const te = new TextEncoder();
const fnBytes = te.encode(filename);
const mimeBytes = te.encode(mime || '');
// Use MAGIC2 if we have wrapped keys (new secure format)
const magicToUse = wrappedKeyPwd ? MAGIC2 : MAGIC;
let headerSize = magicToUse.byteLength + 4 + fnBytes.byteLength + 4 + mimeBytes.byteLength + SALT_LEN + IV_LEN;
if (wrappedKeyPwd) {
headerSize += IV_LEN + (WRAPPED_KEY_LEN * 2);
}
const header = new ArrayBuffer(headerSize);
const view = new DataView(header);
let offset = 0;
// Magic
new Uint8Array(header).set(magicToUse, offset);
offset += magicToUse.byteLength;
// Filename
view.setUint32(offset, fnBytes.byteLength, true); offset += 4;
new Uint8Array(header).set(fnBytes, offset); offset += fnBytes.byteLength;
// MIME
view.setUint32(offset, mimeBytes.byteLength, true); offset += 4;
new Uint8Array(header).set(mimeBytes, offset); offset += mimeBytes.byteLength;
// Salt + IV
new Uint8Array(header).set(salt, offset); offset += SALT_LEN;
new Uint8Array(header).set(iv, offset); offset += IV_LEN;
// New fields for FKRYPT2
if (wrappedKeyPwd && wrappedKeyRec && wrapIv) {
new Uint8Array(header).set(wrapIv, offset); offset += IV_LEN;
new Uint8Array(header).set(new Uint8Array(wrappedKeyPwd), offset); offset += WRAPPED_KEY_LEN;
new Uint8Array(header).set(new Uint8Array(wrappedKeyRec), offset); offset += WRAPPED_KEY_LEN;
}
// Combine
const combined = new Uint8Array(header.byteLength + ciphertext.byteLength);
combined.set(new Uint8Array(header), 0);
combined.set(new Uint8Array(ciphertext), header.byteLength);
return combined;
}
function parseLockfile(buffer) {
const view = new DataView(buffer);
const bytes = new Uint8Array(buffer);
let offset = 0;
// Verify magic
const magic = bytes.slice(0, MAGIC.byteLength);
let version = 1;
let isV2 = true;
for (let i = 0; i < MAGIC.byteLength; i++) {
if (magic[i] !== MAGIC2[i]) isV2 = false;
}
if (isV2) {
version = 2;
} else {
// Check if it's V1
let isV1 = true;
for (let i = 0; i < MAGIC.byteLength; i++) {
if (magic[i] !== MAGIC[i]) isV1 = false;
}
if (!isV1) throw new Error('Not a valid .enc file – magic bytes mismatch.');
version = 1;
}
offset += MAGIC.byteLength;
// Filename
const fnLen = view.getUint32(offset, true); offset += 4;
const filename = new TextDecoder().decode(bytes.slice(offset, offset + fnLen)); offset += fnLen;
// MIME
const mimeLen = view.getUint32(offset, true); offset += 4;
const mime = new TextDecoder().decode(bytes.slice(offset, offset + mimeLen)); offset += mimeLen;
// Salt + IV
const salt = bytes.slice(offset, offset + SALT_LEN); offset += SALT_LEN;
const iv = bytes.slice(offset, offset + IV_LEN); offset += IV_LEN;
let wrappedKeyPwd = null;
let wrappedKeyRec = null;
let wrapIv = null;
if (version === 2) {
wrapIv = bytes.slice(offset, offset + IV_LEN); offset += IV_LEN;
wrappedKeyPwd = bytes.slice(offset, offset + WRAPPED_KEY_LEN).buffer; offset += WRAPPED_KEY_LEN;
wrappedKeyRec = bytes.slice(offset, offset + WRAPPED_KEY_LEN).buffer; offset += WRAPPED_KEY_LEN;
}
const ciphertext = buffer.slice(offset);
return { filename, mime, salt, iv, ciphertext, version, wrappedKeyPwd, wrappedKeyRec, wrapIv };
}
// ─── Encrypt ──────────────────────────────────────────────
// ─── Download helper ──────────────────────────────────────
async function triggerDownload(blob, filename) {
const safeFilename = (filename || 'file.enc').replace(/[/\\?%*:|"<>]/g, '-');
// Direct download using hidden anchor element
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = safeFilename;
document.body.appendChild(a);
a.click();
// Delayed removal is crucial: removing immediately drops the filename in some browsers.
// Using a longer timeout (10s) and ensuring no revocation happens until long after.
setTimeout(() => {
if (a.parentNode) a.parentNode.removeChild(a);
// Don't revoke immediately to be safe for slow downloads
setTimeout(() => URL.revokeObjectURL(url), 10000);
}, 1000);
}
// ─── Metadata display ─────────────────────────────────────
function copyMeta(mode) {
const box = document.getElementById(mode + '-meta');
const data = JSON.parse(box.dataset.meta || '{}');
const text = Object.entries(data).map(([k, v]) => `${k}: ${v}`).join('\n');
navigator.clipboard.writeText(text).then(() => {
toast('info', 'Metadata copied to clipboard.');
}).catch(() => {
toast('error', 'Failed to copy metadata.');
});
}
// ─── Toast notifications ──────────────────────────────────
function toast(type, msg, duration = 4500) {
const stack = document.getElementById('toast-stack');
const el = document.createElement('div');
el.className = `toast ${type}`;
el.innerHTML = `
<span class="toast-icon"></span>
<span class="toast-msg">${esc(msg)}</span>
<button class="toast-close" onclick="dismissToast(this.parentElement)">✕</button>
`;
// Swipe to dismiss
let startX = 0;
let currentX = 0;
el.addEventListener('touchstart', (e) => {
startX = e.touches[0].clientX;
el.style.transition = 'none';
}, { passive: true });
el.addEventListener('touchmove', (e) => {
currentX = e.touches[0].clientX - startX;
if (Math.abs(currentX) > 10) {
el.style.transform = `translateX(${currentX}px)`;
el.style.opacity = 1 - Math.abs(currentX) / 200;
}
}, { passive: true });
el.addEventListener('touchend', () => {
el.style.transition = 'all 0.3s ease';
if (Math.abs(currentX) > 100) {
el.style.transform = `translateX(${currentX > 0 ? 200 : -200}px)`;
el.style.opacity = '0';
setTimeout(() => dismissToast(el), 300);
} else {
el.style.transform = 'translateX(0)';
el.style.opacity = '1';
}
currentX = 0;
});
stack.appendChild(el);
setTimeout(() => dismissToast(el), duration);
}
function dismissToast(el) {
if (!el || el.classList.contains('removing')) return;
el.classList.add('removing');
setTimeout(() => el.remove(), 400);
}
// Global Touch Hover / Drag Support
document.addEventListener('touchstart', handleTouchHover, { passive: false });
document.addEventListener('touchmove', handleTouchHover, { passive: false });
function handleTouchHover(e) {
const touch = e.touches[0];
const target = document.elementFromPoint(touch.clientX, touch.clientY);
if (!target) return;
const btn = target.closest('button, .sidebar-card, .btn-primary');
if (btn) {
// If it has a ripple, update its position
const ripple = btn.querySelector('.water-ripple');
if (ripple) {
const rect = btn.getBoundingClientRect();
const x = touch.clientX - rect.left;
const y = touch.clientY - rect.top;
ripple.style.opacity = '1';
ripple.style.left = `${x}px`;
ripple.style.top = `${y}px`;
}
// Simulate hover for custom logic
if (btn.onmousemove && !btn._touchInjected) {
// Create a fake mouse event for any inline onmousemove handlers
const fakeEvent = {
clientX: touch.clientX,
clientY: touch.clientY,
target: btn,
getBoundingClientRect: () => btn.getBoundingClientRect(),
querySelector: (sel) => btn.querySelector(sel)
};
// For simple inline handlers that use 'event'
window.event = fakeEvent;
}
}
}
document.addEventListener('touchend', (e) => {
document.querySelectorAll('.water-ripple').forEach(r => r.style.opacity = '0');
});
// ─── Init ─────────────────────────────────────────────────
(function init() {
// Monkey typing listener
['enc-pwd', 'dec-pwd'].forEach(id => {
const input = document.getElementById(id);
const eyeBtn = document.getElementById(id.replace('-pwd', '-eye-btn'));
if (!input || !eyeBtn) return;
input.addEventListener('input', () => {
const span = eyeBtn.querySelector('.pwd-emoji');
if (span && input.type === 'text') {
span.textContent = input.value.length > 0 ? '👀' : '🐵';
}
if (id === 'dec-pwd') {
input.classList.toggle('dec-valid', input.value.length >= 8);
}
});
});
// Check Web Crypto support
if (!window.crypto?.subtle) {
toast('error', 'Web Crypto API not supported. Please use a modern browser over HTTPS.');
}
// Swipe to switch tabs on mobile
let touchStartX = 0;
let touchStartY = 0;
const mainCard = document.getElementById('main-card');
if (mainCard) {
mainCard.addEventListener('touchstart', e => {
touchStartX = e.changedTouches[0].screenX;
touchStartY = e.changedTouches[0].screenY;
}, { passive: true });
mainCard.addEventListener('touchend', e => {
const touchEndX = e.changedTouches[0].screenX;
const touchEndY = e.changedTouches[0].screenY;
const dx = touchEndX - touchStartX;
const dy = touchEndY - touchStartY;
// Only switch if it's primarily a horizontal swipe and meets threshold
if (Math.abs(dx) > 70 && Math.abs(dx) > Math.abs(dy)) {
if (dx < 0) switchTab('decrypt'); // Swipe left -> Decrypt
else switchTab('encrypt'); // Swipe right -> Encrypt
}
}, { passive: true });
}
// Init tab slider position
document.querySelector('.tab-slider').style.transform = '';
// Initial render of recents
renderRecents('enc');
renderRecents('dec');
})();
// ─── Recents ──────────────────────────────────────────────
function addRecent(mode, data) {
const item = { ...data, id: Date.now() };
state.recents[mode].unshift(item);
state.recents[mode] = state.recents[mode].slice(0, 30); // Keep last 30
localStorage.setItem('fk_recents', JSON.stringify(state.recents));
renderRecents(mode);
}
function renderRecents(mode) {
const list = document.getElementById(`${mode}-recents-list`);
if (!list) return;
const items = state.recents[mode];
if (items.length === 0) {
list.innerHTML = '<div class="recent-empty">No activity yet</div>';
return;
}
list.innerHTML = items.map(item => {
const now = Date.now();
const diff = now - item.time;
let timeStr;
if (diff < 60000) timeStr = 'just now';
else if (diff < 3600000) timeStr = Math.floor(diff / 60000) + 'm ago';
else if (diff < 86400000) timeStr = Math.floor(diff / 3600000) + 'h ago';
else timeStr = new Date(item.time).toLocaleDateString([], { month: 'short', day: 'numeric' });
return `
<div class="recent-item">
<div class="recent-info">
<span class="recent-name" title="${esc(item.name)}">${esc(truncateName(item.name))}</span>
<span class="recent-meta">${esc(fmtSize(item.size))} · ${esc(timeStr)}</span>
</div>
<div style="display: flex; align-items: center;">
<button class="recent-delete-btn" onclick="removeRecent('${mode}', ${item.id})" title="Remove from history">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
<polyline points="3 6 5 6 21 6"></polyline>
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
</svg>
</button>
</div>
</div>
`;
}).join('');
}
function clearRecents(mode) {
state.recents[mode] = [];
localStorage.setItem('fk_recents', JSON.stringify(state.recents));
renderRecents(mode);
}
function removeRecent(mode, id) {
state.recents[mode] = state.recents[mode].filter(item => item.id !== id);
localStorage.setItem('fk_recents', JSON.stringify(state.recents));
renderRecents(mode);
toast('info', 'Item removed from history.');
}
// ─── NEW FEATURES: RECOVERY KEY & CHANGE PASSWORD ─────────
const MIX_MAP = {
'A': '!', 'B': '@', 'C': '#', 'D': '$', 'E': '%', 'F': '^', 'G': '&', 'H': '*',
'I': '(', 'J': ')', 'K': '-', 'L': '_', 'M': '=', 'N': '+', 'O': '[', 'P': ']',
'Q': '{', 'R': '}', 'S': '|', 'T': ':', 'U': ';', 'V': '<', 'W': '>', 'X': ',',
'Y': '.', 'Z': '?', 'a': '~', 'b': 'A', 'c': 'B', 'd': 'C', 'e': 'D', 'f': 'E',
'g': 'F', 'h': 'G', 'i': 'H', 'j': 'I', 'k': 'J', 'l': 'K', 'm': 'L', 'n': 'M',
'o': 'N', 'p': 'O', 'q': 'P', 'r': 'Q', 's': 'R', 't': 'S', 'u': 'T', 'v': 'U',
'w': 'V', 'x': 'W', 'y': 'X', 'z': 'Y', '0': 'Z', '1': 'a', '2': 'b', '3': 'c',
'4': 'd', '5': 'e', '6': 'f', '7': 'g', '8': 'h', '9': 'i', '+': 'j', '/': 'k',
'=': 'l'
};
const UNMIX_MAP = Object.fromEntries(Object.entries(MIX_MAP).map(([k, v]) => [v, k]));
function encodeMix(str) { return str.split('').map(c => MIX_MAP[c] || c).join(''); }
function decodeMix(str) { return str.split('').map(c => UNMIX_MAP[c] || c).join(''); }
async function handleReEncrypt(file, oldPwd, newPwd, btnId, successMsg) {
const btn = document.getElementById(btnId);
if (!btn) return;
btn.disabled = true;
const oldText = btn.innerHTML;
btn.innerHTML = 'Processing...';
try {
const buffer = await readFileAsBuffer(file);
let parsed;
try {
parsed = parseLockfile(buffer);
} catch (e) {
throw new Error('Invalid file. Provide a valid .enc file.');
}
const { filename, mime, salt, iv, ciphertext } = parsed;
const oldKey = await deriveKey(oldPwd, salt);
let plaintext;
try {
plaintext = await crypto.subtle.decrypt({ name: 'AES-GCM', iv }, oldKey, ciphertext);
} catch {
throw new Error('Verification failed. Invalid current password.');
}
if (newPwd === oldPwd) {
throw new Error('The new password must be different from the current one.');
}
// Re-encrypt with new password
const newSalt = crypto.getRandomValues(new Uint8Array(SALT_LEN));
const newIv = crypto.getRandomValues(new Uint8Array(IV_LEN));
const newKey = await deriveKey(newPwd, newSalt);
const newCiphertext = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: newIv }, newKey, plaintext);
const lockData = buildLockfile(filename, mime, newSalt, newIv, newCiphertext);
const blob = new Blob([lockData], { type: 'application/octet-stream' });
const outFilename = file.name.endsWith('.enc') ? file.name : file.name + '.enc';
triggerDownload(blob, outFilename);
toast('success', successMsg);
// Clear fields automatically after success (except file inputs)
if (btnId === 'cp-btn') {
document.getElementById('cp-old-pwd').value = '';
document.getElementById('cp-new-pwd').value = '';
} else if (btnId === 'rec-btn') {
document.getElementById('rec-key-text').value = '';
document.getElementById('rec-key-file').value = '';
document.getElementById('rec-new-pwd').value = '';
}
} catch (err) {
console.error(err);
toast('error', err.message);
} finally {
btn.disabled = false;
btn.innerHTML = oldText;
}
}
function resetInputValidation(input) {
if (!input) return;
input.style.borderColor = '';
input.style.boxShadow = '';
}
function syncToolsFile(blob, filename) {
if (!blob || !filename) {
clearToolsFileBox('cp');
return;
}
const dt = new DataTransfer();
const file = new File([blob], filename, { type: 'application/octet-stream' });
dt.items.add(file);
const applyToFileBox = (prefix) => {
const input = document.getElementById(`${prefix}-file`);
const disp = document.getElementById(`${prefix}-file-display`);
const nameEl = document.getElementById(`${prefix}-file-name`);
if (input && disp && nameEl) {
input.files = dt.files;
nameEl.textContent = filename;
disp.classList.remove('hidden');
const instr = document.getElementById(`${prefix}-file-instructions`);
if (instr) instr.classList.add('hidden');
}
};
applyToFileBox('cp');
const useRecBtn = document.getElementById('use-recovery-btn');
if (useRecBtn) useRecBtn.disabled = false;
}
function clearToolsFileBox(prefix) {
const input = document.getElementById(`${prefix}-file`);
const disp = document.getElementById(`${prefix}-file-display`);
if (input && disp) {
input.value = '';
// Natively reset file list to unblock onchange events for identical files
try { input.files = new DataTransfer().files; } catch (e) { }
disp.classList.add('hidden');
const instr = document.getElementById(`${prefix}-file-instructions`);
if (instr) instr.classList.remove('hidden');
}
if (prefix === 'cp') {
const useRecBtn = document.getElementById('use-recovery-btn');
if (useRecBtn) useRecBtn.disabled = true;
const recFlow = document.getElementById('recovery-flow-section');
if (recFlow) recFlow.classList.add('hidden');
const oldPwdInput = document.getElementById('cp-old-pwd');
if (oldPwdInput) {
oldPwdInput.value = '';
oldPwdInput.style.borderColor = '';
}
const newPwdInput = document.getElementById('cp-new-pwd');
if (newPwdInput) {
newPwdInput.value = '';
onPwdInput(newPwdInput, 'cp-new-strength');
}
// Reset Preview State also for CP
window.lastPreviewBlob = null;
window.lastPreviewFilename = null;
updateDecSidebarPreview(null);
}
}
function syncManualFile(input, prefix) {
if (input.files && input.files.length > 0) {
const file = input.files[0];
if (prefix === 'cp' && !file.name.toLowerCase().endsWith('.enc')) {
toast('error', 'Please select a valid .enc file.');
input.value = '';
return;
}
const disp = document.getElementById(`${prefix}-file-display`);
const nameEl = document.getElementById(`${prefix}-file-name`);
if (disp && nameEl) {
nameEl.textContent = input.files[0].name;
disp.classList.remove('hidden');
const instr = document.getElementById(`${prefix}-file-instructions`);
if (instr) instr.classList.add('hidden');
if (prefix === 'cp') {
const useRecBtn = document.getElementById('use-recovery-btn');
if (useRecBtn) useRecBtn.disabled = false;
}
}
} else {
clearToolsFileBox(prefix);
}
}
function toggleClearPopup(type) {
const popup = document.getElementById(type + '-confirm-popup');
if (!popup) return;
const isHidden = popup.classList.toggle('hidden');
// Toggle blur class on the parent card
const card = popup.closest('.sidebar-card');
if (card) card.classList.toggle('show-popup', !isHidden);
if (!isHidden) {
const handler = (e) => {
const btn = e.target.closest('.text-btn');
if (!popup.contains(e.target) && !btn) {
popup.classList.add('hidden');
if (card) card.classList.remove('show-popup');
document.removeEventListener('click', handler);
}
};
setTimeout(() => document.addEventListener('click', handler), 500);
}
}
// ─── Output Filename Handlers ───
function handleOutNameInput(input) {
const tick = document.getElementById('enc-outname-tick');
if (input.value !== input.dataset.old) {
tick.classList.remove('hidden');
} else {
tick.classList.add('hidden');
}
}
function confirmOutName() {
const input = document.getElementById('enc-outname');
const tick = document.getElementById('enc-outname-tick');
const val = input.value.trim();
if (!val) {
toast('error', 'No file name');
return;
}
input.dataset.old = val;
tick.classList.add('hidden');
toast('success', 'Filename confirmed!');
}
function handleOutNameBlur(event, input) {
// If we clicked the tick button, don't reset
if (event.relatedTarget && event.relatedTarget.id === 'enc-outname-tick') return;
const tick = document.getElementById('enc-outname-tick');
if (input.value !== input.dataset.old) {
input.value = input.dataset.old;
tick.classList.add('hidden');
}
}
// ─── Keyboard Shortcuts ───
document.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
const active = document.activeElement;
if (!active) return;
// Encrypt Panel
if (active.id === 'enc-pwd') {
startEncrypt();
}
// Decrypt Panel
else if (active.id === 'dec-pwd') {
startDecrypt();
}
// Change Password Tool