-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.js
More file actions
1231 lines (1114 loc) · 37.6 KB
/
Copy pathmain.js
File metadata and controls
1231 lines (1114 loc) · 37.6 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 obsidian = require('obsidian');
const ENCRYPTION_MARKER = '%% folder-crypto: encrypted %%';
const ENVELOPE_VERSION = 1;
const LOCK_BADGE_CLASS = 'folder-crypto-lock-badge';
const HIDDEN_ITEM_CLASS = 'folder-crypto-hidden-item';
const DEFAULT_SETTINGS = {
folderPath: '',
folderLockEnabled: false,
contentEncryptionEnabled: false,
includeSubfolders: true,
extensions: 'md',
createPlaintextBackup: false,
filesystemLockEnabled: false,
lockedFolders: []
};
function normalizeFolderPath(value) {
return obsidian.normalizePath((value || '').trim().replace(/^\/+|\/+$/g, ''));
}
function normalizeExtensions(value) {
const items = String(value || 'md')
.split(',')
.map((item) => item.trim().replace(/^\./, '').toLowerCase())
.filter(Boolean);
return Array.from(new Set(items.length ? items : ['md']));
}
function isEncryptedContent(content) {
return content.trimStart().startsWith(ENCRYPTION_MARKER);
}
function toBase64(bytes) {
const arr = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
let binary = '';
for (let i = 0; i < arr.length; i++) binary += String.fromCharCode(arr[i]);
return btoa(binary);
}
function fromBase64(str) {
const binary = atob(str);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
return bytes;
}
function randomBytes(n) {
return (globalThis.crypto || window.crypto).getRandomValues(new Uint8Array(n));
}
function buildEncryptedNote(envelope) {
return `${ENCRYPTION_MARKER}\n\n\`\`\`json\n${JSON.stringify(envelope, null, 2)}\n\`\`\`\n`;
}
function parseEncryptedNote(content) {
if (!isEncryptedContent(content)) {
throw new Error('File is not encrypted by Folder Crypto.');
}
const match = content.match(/```json\s*([\s\S]*?)\s*```/);
if (!match) {
throw new Error('Encrypted envelope is missing.');
}
return JSON.parse(match[1]);
}
function getWebCrypto() {
return globalThis.crypto || window.crypto;
}
async function importPbkdf2Key(password) {
return getWebCrypto().subtle.importKey(
'raw',
new TextEncoder().encode(password),
'PBKDF2',
false,
['deriveBits', 'deriveKey']
);
}
async function deriveBits(password, salt, iterations) {
const keyMaterial = await importPbkdf2Key(password);
const bits = await getWebCrypto().subtle.deriveBits(
{ name: 'PBKDF2', salt: salt instanceof Uint8Array ? salt : fromBase64(salt), iterations, hash: 'SHA-256' },
keyMaterial,
256
);
return new Uint8Array(bits);
}
async function deriveAesKey(password, salt, iterations) {
const keyMaterial = await importPbkdf2Key(password);
return getWebCrypto().subtle.deriveKey(
{ name: 'PBKDF2', salt: salt instanceof Uint8Array ? salt : fromBase64(salt), iterations, hash: 'SHA-256' },
keyMaterial,
{ name: 'AES-GCM', length: 256 },
false,
['encrypt', 'decrypt']
);
}
async function hashPassword(password) {
const salt = randomBytes(16);
const iterations = 210000;
const hash = await deriveBits(password, salt, iterations);
return {
kdf: 'pbkdf2-sha256',
iterations,
salt: toBase64(salt),
hash: toBase64(hash)
};
}
async function verifyPassword(password, verifier) {
const expected = fromBase64(verifier.hash);
const actual = await deriveBits(password, fromBase64(verifier.salt), Number(verifier.iterations || 210000));
if (expected.length !== actual.length) return false;
let diff = 0;
for (let i = 0; i < expected.length; i++) diff |= expected[i] ^ actual[i];
return diff === 0;
}
function pathIsInsideFolder(path, folderPath) {
const normalizedPath = obsidian.normalizePath(path || '');
const normalizedFolder = normalizeFolderPath(folderPath);
return normalizedPath === normalizedFolder || normalizedPath.startsWith(`${normalizedFolder}/`);
}
function getVaultBasePath(app) {
const adapter = app.vault.adapter;
return adapter && typeof adapter.getBasePath === 'function' ? adapter.getBasePath() : null;
}
function getNodeModule(name) {
try {
return require(name);
} catch (error) {
const nodeRequire = globalThis.window && globalThis.window.require;
if (typeof nodeRequire !== 'function') {
return null;
}
try {
return nodeRequire(name);
} catch (innerError) {
return null;
}
}
}
async function encryptText(plaintext, password) {
const salt = randomBytes(16);
const iv = randomBytes(12);
const iterations = 210000;
const key = await deriveAesKey(password, salt, iterations);
const encrypted = await getWebCrypto().subtle.encrypt(
{ name: 'AES-GCM', iv },
key,
new TextEncoder().encode(plaintext)
);
const encryptedBytes = new Uint8Array(encrypted);
const tagOffset = encryptedBytes.length - 16;
const data = encryptedBytes.slice(0, tagOffset);
const tag = encryptedBytes.slice(tagOffset);
return buildEncryptedNote({
version: ENVELOPE_VERSION,
algorithm: 'aes-256-gcm',
kdf: 'pbkdf2-sha256',
iterations,
salt: toBase64(salt),
iv: toBase64(iv),
tag: toBase64(tag),
data: toBase64(data)
});
}
async function decryptText(content, password) {
const envelope = parseEncryptedNote(content);
if (envelope.version !== ENVELOPE_VERSION || envelope.algorithm !== 'aes-256-gcm') {
throw new Error('Unsupported encrypted file version.');
}
const salt = fromBase64(envelope.salt);
const iv = fromBase64(envelope.iv);
const tag = fromBase64(envelope.tag);
const data = fromBase64(envelope.data);
// Web Crypto expects ciphertext + auth tag concatenated
const ciphertext = new Uint8Array(data.length + tag.length);
ciphertext.set(data);
ciphertext.set(tag, data.length);
const key = await deriveAesKey(password, salt, Number(envelope.iterations || 210000));
const decrypted = await getWebCrypto().subtle.decrypt(
{ name: 'AES-GCM', iv },
key,
ciphertext
);
return new TextDecoder().decode(decrypted);
}
class PasswordModal extends obsidian.Modal {
constructor(app, title, confirmText, requireRepeat) {
super(app);
this.title = title;
this.confirmText = confirmText;
this.requireRepeat = requireRepeat;
this.password = '';
this.passwordRepeat = '';
this.resolved = false;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl('h2', { text: this.title });
new obsidian.Setting(contentEl)
.setName('Password')
.addText((text) => {
text.inputEl.type = 'password';
text.inputEl.autocomplete = 'off';
text.inputEl.focus();
text.onChange((value) => {
this.password = value;
});
text.inputEl.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
this.submit();
}
});
});
if (this.requireRepeat) {
new obsidian.Setting(contentEl)
.setName('Repeat password')
.addText((text) => {
text.inputEl.type = 'password';
text.inputEl.autocomplete = 'off';
text.onChange((value) => {
this.passwordRepeat = value;
});
text.inputEl.addEventListener('keydown', (event) => {
if (event.key === 'Enter') {
this.submit();
}
});
});
}
new obsidian.Setting(contentEl)
.addButton((button) => {
button
.setButtonText(this.confirmText)
.setCta()
.onClick(() => this.submit());
})
.addButton((button) => {
button
.setButtonText('Cancel')
.onClick(() => this.close());
});
}
submit() {
if (!this.password) {
new obsidian.Notice('Password is required.');
return;
}
if (this.requireRepeat && this.password !== this.passwordRepeat) {
new obsidian.Notice('Passwords do not match.');
return;
}
this.resolved = true;
this.close();
}
waitForPassword() {
return new Promise((resolve) => {
this.onClose = () => {
this.contentEl.empty();
resolve(this.resolved ? this.password : null);
};
this.open();
});
}
}
class ConfirmModal extends obsidian.Modal {
constructor(app, title, message, confirmText) {
super(app);
this.title = title;
this.message = message;
this.confirmText = confirmText;
this.confirmed = false;
}
onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.createEl('h2', { text: this.title });
contentEl.createEl('p', { text: this.message });
new obsidian.Setting(contentEl)
.addButton((button) => {
button
.setButtonText(this.confirmText)
.setWarning()
.onClick(() => {
this.confirmed = true;
this.close();
});
})
.addButton((button) => {
button
.setButtonText('Cancel')
.onClick(() => this.close());
});
}
waitForConfirm() {
return new Promise((resolve) => {
this.onClose = () => {
this.contentEl.empty();
resolve(this.confirmed);
};
this.open();
});
}
}
class FolderCryptoSettingTab extends obsidian.PluginSettingTab {
constructor(app, plugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
// === Locked Folders ===
containerEl.createEl('h3', { text: 'Locked folders' });
if (this.plugin.settings.lockedFolders.length === 0) {
containerEl.createEl('p', {
text: 'No folders locked yet. Add a folder below or right-click any folder in the file explorer.',
cls: 'setting-item-description'
});
}
for (const lock of [...this.plugin.settings.lockedFolders]) {
const isUnlocked = this.plugin.unlockedFolders.has(lock.path);
const row = new obsidian.Setting(containerEl)
.setName(lock.path)
.setDesc(isUnlocked ? 'Unlocked this session' : 'Locked');
if (isUnlocked) {
row.addButton((btn) => {
btn.setButtonText('Lock').onClick(async () => {
await this.plugin.lockFolder(lock.path);
this.display();
});
});
} else {
row.addButton((btn) => {
btn.setButtonText('Unlock').onClick(async () => {
await this.plugin.unlockFolder(lock.path);
this.display();
});
});
}
row.addButton((btn) => {
btn.setButtonText('Remove').setWarning().onClick(async () => {
await this.plugin.removeFolderLock(lock.path);
this.display();
});
});
}
let newFolderPath = '';
new obsidian.Setting(containerEl)
.setName('Add folder lock')
.setDesc('Vault-relative path, e.g. Private or work/secret. Right-click any folder in the file explorer also works.')
.addText((text) => {
text.setPlaceholder('FolderName').onChange((value) => {
newFolderPath = value;
});
})
.addButton((btn) => {
btn.setButtonText('Lock').setCta().onClick(async () => {
const path = newFolderPath.trim();
if (!path) {
new obsidian.Notice('Enter a folder path first.');
return;
}
if (!this.plugin.settings.folderLockEnabled) {
new obsidian.Notice('Enable "Folder lock" below first.');
return;
}
await this.plugin.lockFolder(path);
this.display();
});
});
// === Options ===
containerEl.createEl('h3', { text: 'Options' });
new obsidian.Setting(containerEl)
.setName('Folder lock')
.setDesc('Master switch for the Obsidian folder lock.')
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.folderLockEnabled)
.onChange(async (value) => {
this.plugin.settings.folderLockEnabled = value;
await this.plugin.saveSettings();
if (!value) {
this.plugin.restoreAllFilesystemLocks();
this.plugin.clearFolderDecorations();
new obsidian.Notice('Folder lock disabled.');
}
this.display();
});
});
if (!obsidian.Platform.isMobile) {
new obsidian.Setting(containerEl)
.setName('Sync Finder folder lock')
.setDesc('Also hide the underlying Finder folder while Folder lock is on. This does not change read permissions, so Obsidian can still open.')
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.filesystemLockEnabled)
.onChange(async (value) => {
this.plugin.settings.filesystemLockEnabled = value;
if (value) {
this.plugin.applyFilesystemLocksForLockedFolders();
} else {
this.plugin.restoreAllFilesystemLocks();
}
await this.plugin.saveSettings();
});
});
}
// === Content Encryption ===
containerEl.createEl('h3', { text: 'Content encryption' });
new obsidian.Setting(containerEl)
.setName('Encryption target folder')
.setDesc('Vault-relative folder used by the encrypt/decrypt commands and ribbon icon.')
.addText((text) => {
text
.setPlaceholder('Private')
.setValue(this.plugin.settings.folderPath)
.onChange(async (value) => {
this.plugin.settings.folderPath = normalizeFolderPath(value);
await this.plugin.saveSettings();
});
});
new obsidian.Setting(containerEl)
.setName('Content lock')
.setDesc('Master switch for content encryption. Turning it off disables new encryption; existing encrypted files stay encrypted.')
.addToggle((toggle) => {
toggle
.setValue(this.plugin.settings.contentEncryptionEnabled)
.onChange(async (value) => {
this.plugin.settings.contentEncryptionEnabled = value;
await this.plugin.saveSettings();
if (value) {
const encrypted = await this.plugin.encryptConfiguredFolder();
if (!encrypted) {
this.plugin.settings.contentEncryptionEnabled = false;
await this.plugin.saveSettings();
}
} else {
new obsidian.Notice('Content lock disabled. Existing encrypted files are unchanged.');
}
this.display();
});
});
}
}
module.exports = class FolderCryptoPlugin extends obsidian.Plugin {
async onload() {
await this.loadSettings();
this.unlockedFolders = new Set();
this.unlockPromptPaths = new Set();
this.restoreWorkspaceOpeners = null;
this.fileExplorerObserver = null;
this.decorationTimer = null;
this.addSettingTab(new FolderCryptoSettingTab(this.app, this));
this.safeRun('apply startup filesystem locks', () => this.applyFilesystemLocksForLockedFolders());
this.addRibbonIcon('lock', 'Encrypt configured folder', () => {
this.encryptConfiguredFolder();
});
this.addCommand({
id: 'encrypt-configured-folder',
name: 'Encrypt configured folder',
callback: () => this.encryptConfiguredFolder()
});
this.addCommand({
id: 'decrypt-configured-folder',
name: 'Decrypt configured folder',
callback: () => this.decryptConfiguredFolder()
});
this.addCommand({
id: 'decrypt-all-encrypted-files',
name: 'Decrypt all Folder Crypto encrypted files in vault',
callback: () => this.decryptAllEncryptedFiles()
});
this.addCommand({
id: 'lock-configured-folder',
name: 'Lock configured folder in Obsidian',
callback: () => this.lockConfiguredFolder()
});
this.addCommand({
id: 'unlock-configured-folder',
name: 'Unlock configured folder in Obsidian',
callback: () => this.unlockConfiguredFolder()
});
this.addCommand({
id: 'lock-all-folders',
name: 'Lock all Folder Crypto folders',
callback: () => this.lockAllFolders()
});
this.addCommand({
id: 'remove-configured-folder-lock',
name: 'Remove configured folder lock',
callback: () => this.removeConfiguredFolderLock()
});
this.registerEvent(
this.app.workspace.on('file-menu', (menu, file) => {
if (!(file instanceof obsidian.TFolder)) {
return;
}
menu.addSeparator();
if (this.settings.folderLockEnabled) {
menu.addItem((item) => {
item
.setTitle('Lock folder in Obsidian')
.setIcon('lock')
.onClick(() => this.lockFolder(file.path));
});
menu.addItem((item) => {
item
.setTitle('Unlock folder in Obsidian')
.setIcon('unlock')
.onClick(() => this.unlockFolder(file.path));
});
menu.addItem((item) => {
item
.setTitle('Remove Obsidian folder lock')
.setIcon('key')
.onClick(() => this.removeFolderLock(file.path));
});
}
menu.addSeparator();
if (this.settings.contentEncryptionEnabled) {
menu.addItem((item) => {
item
.setTitle('Encrypt folder with password')
.setIcon('lock')
.onClick(() => this.encryptFolder(file.path));
});
}
menu.addItem((item) => {
item
.setTitle('Decrypt folder with password')
.setIcon('unlock')
.onClick(() => this.decryptFolder(file.path));
});
})
);
this.safeRun('install workspace gate', () => this.installWorkspaceGate());
this.safeRun('install file explorer gate', () => this.installFileExplorerGate());
this.safeRun('register file-open gate', () => {
this.registerEvent(
this.app.workspace.on('file-open', (file) => {
if (file && this.isPathLocked(file.path)) {
this.closeLockedActiveLeaf(file);
}
})
);
});
this.safeRun('start folder decorations', () => this.startFolderDecorations());
}
onunload() {
this.safeRun('restore filesystem locks', () => this.restoreAllFilesystemLocks());
if (this.restoreWorkspaceOpeners) {
this.restoreWorkspaceOpeners();
this.restoreWorkspaceOpeners = null;
}
if (this.fileExplorerObserver) {
this.fileExplorerObserver.disconnect();
this.fileExplorerObserver = null;
}
if (this.decorationTimer) {
window.clearTimeout(this.decorationTimer);
this.decorationTimer = null;
}
this.clearFolderDecorations();
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.settings.folderPath = normalizeFolderPath(this.settings.folderPath);
this.settings.folderLockEnabled = this.settings.folderLockEnabled !== false;
this.settings.contentEncryptionEnabled = this.settings.contentEncryptionEnabled !== false;
this.settings.extensions = normalizeExtensions(this.settings.extensions).join(',');
this.settings.filesystemLockEnabled = this.settings.filesystemLockEnabled !== false;
this.settings.lockedFolders = Array.isArray(this.settings.lockedFolders)
? this.settings.lockedFolders
.map((entry) => Object.assign({}, entry, { path: normalizeFolderPath(entry.path) }))
.filter((entry) => entry.path && entry.hash && entry.salt)
: [];
}
async saveSettings() {
await this.saveData(this.settings);
}
safeRun(label, fn) {
try {
return fn();
} catch (error) {
console.warn(`[folder-crypto] ${label} failed`, error);
return null;
}
}
async encryptConfiguredFolder() {
if (!this.settings.contentEncryptionEnabled) {
new obsidian.Notice('Content encryption is disabled.');
return false;
}
if (!this.settings.folderPath) {
new obsidian.Notice('Set a folder path in Folder Crypto settings first.');
return false;
}
return this.encryptFolder(this.settings.folderPath);
}
async decryptConfiguredFolder() {
if (!this.settings.folderPath) {
new obsidian.Notice('Set a folder path in Folder Crypto settings first.');
return;
}
await this.decryptFolder(this.settings.folderPath);
}
async encryptFolder(folderPath) {
if (!this.settings.contentEncryptionEnabled) {
new obsidian.Notice('Content encryption is disabled.');
return false;
}
return this.processFolder(folderPath, 'encrypt');
}
async decryptFolder(folderPath) {
await this.processFolder(folderPath, 'decrypt');
}
async decryptAllEncryptedFiles() {
const encryptedFiles = [];
const files = this.app.vault.getMarkdownFiles();
for (const file of files) {
try {
const content = await this.app.vault.read(file);
if (isEncryptedContent(content)) {
encryptedFiles.push({ file, content });
}
} catch (error) {
console.warn('[folder-crypto] Could not inspect file', file.path, error);
}
}
if (!encryptedFiles.length) {
new obsidian.Notice('No Folder Crypto encrypted files found.');
return;
}
await this.processEncryptedCandidates(encryptedFiles, {
mode: 'decrypt',
title: 'Decrypt all encrypted files',
message: `Decrypt ${encryptedFiles.length} Folder Crypto encrypted file(s) in this vault?`,
confirmText: 'Decrypt all'
});
}
async lockConfiguredFolder() {
if (!this.settings.folderLockEnabled) {
new obsidian.Notice('Folder lock is disabled.');
return false;
}
if (!this.settings.folderPath) {
new obsidian.Notice('Set a folder path in Folder Crypto settings first.');
return false;
}
return this.lockFolder(this.settings.folderPath);
}
async unlockConfiguredFolder() {
if (!this.settings.folderPath) {
new obsidian.Notice('Set a folder path in Folder Crypto settings first.');
return;
}
await this.unlockFolder(this.settings.folderPath);
}
lockAllFolders() {
if (!this.settings.folderLockEnabled) {
new obsidian.Notice('Folder lock is disabled.');
return;
}
this.unlockedFolders.clear();
for (const lock of this.settings.lockedFolders) {
this.applyFilesystemLock(lock);
}
this.decorateLockedFolders();
new obsidian.Notice('All Folder Crypto folders are locked.');
}
async removeConfiguredFolderLock() {
if (!this.settings.folderPath) {
new obsidian.Notice('Set a folder path in Folder Crypto settings first.');
return;
}
await this.removeFolderLock(this.settings.folderPath);
}
getFolderLock(folderPath) {
const normalized = normalizeFolderPath(folderPath);
return this.settings.lockedFolders.find((entry) => entry.path === normalized) || null;
}
getLockForPath(path) {
const matches = this.settings.lockedFolders
.filter((entry) => pathIsInsideFolder(path, entry.path))
.sort((a, b) => b.path.length - a.path.length);
return matches[0] || null;
}
isPathLocked(path) {
if (!this.settings.folderLockEnabled) {
return false;
}
const lock = this.getLockForPath(path);
return Boolean(lock && !this.unlockedFolders.has(lock.path));
}
async lockFolder(folderPath) {
if (!this.settings.folderLockEnabled) {
new obsidian.Notice('Folder lock is disabled.');
return false;
}
const folder = this.getFolder(folderPath);
if (!folder) {
return false;
}
let lock = this.getFolderLock(folder.path);
if (!lock) {
const password = await new PasswordModal(
this.app,
'Set folder lock password',
'Set password',
true
).waitForPassword();
if (!password) {
return false;
}
lock = Object.assign({ path: folder.path }, await hashPassword(password));
this.captureFilesystemMode(lock);
this.settings.lockedFolders.push(lock);
await this.saveSettings();
}
this.unlockedFolders.delete(lock.path);
this.applyFilesystemLock(lock);
this.decorateLockedFolders();
new obsidian.Notice(`Locked: ${folder.path}`);
return true;
}
async unlockFolder(folderPath) {
const normalized = normalizeFolderPath(folderPath);
const lock = this.getFolderLock(normalized);
if (!lock) {
new obsidian.Notice(`No folder lock exists for: ${normalized}`);
return false;
}
const unlocked = await this.promptUnlock(lock);
if (unlocked) {
new obsidian.Notice(`Unlocked for this Obsidian session: ${lock.path}`);
}
return unlocked;
}
async removeFolderLock(folderPath) {
const normalized = normalizeFolderPath(folderPath);
const lock = this.getFolderLock(normalized);
if (!lock) {
new obsidian.Notice(`No folder lock exists for: ${normalized}`);
return;
}
const unlocked = this.unlockedFolders.has(lock.path) || await this.promptUnlock(lock);
if (!unlocked) {
return;
}
this.settings.lockedFolders = this.settings.lockedFolders.filter((entry) => entry.path !== lock.path);
this.unlockedFolders.delete(lock.path);
this.restoreFilesystemLock(lock);
await this.saveSettings();
this.decorateLockedFolders();
new obsidian.Notice(`Removed folder lock: ${lock.path}`);
}
async promptUnlock(lock) {
const password = await new PasswordModal(
this.app,
`Unlock ${lock.path}`,
'Unlock',
false
).waitForPassword();
if (!password) {
return false;
}
if (!await verifyPassword(password, lock)) {
new obsidian.Notice('Wrong password.');
return false;
}
this.restoreFilesystemLock(lock);
this.unlockedFolders.add(lock.path);
this.decorateLockedFolders();
return true;
}
getAbsoluteFolderPath(folderPath) {
const path = getNodeModule('path');
if (!path) {
return null;
}
const basePath = getVaultBasePath(this.app);
if (!basePath) {
return null;
}
const absoluteBase = path.resolve(basePath);
const absoluteFolder = path.resolve(absoluteBase, normalizeFolderPath(folderPath));
if (absoluteFolder !== absoluteBase && !absoluteFolder.startsWith(`${absoluteBase}${path.sep}`)) {
return null;
}
return absoluteFolder;
}
captureFilesystemMode(lock) {
return lock;
}
applyFilesystemLocksForLockedFolders() {
if (!this.settings.filesystemLockEnabled) {
return;
}
for (const lock of this.settings.lockedFolders) {
if (!this.unlockedFolders.has(lock.path)) {
this.applyFilesystemLock(lock);
}
}
}
restoreAllFilesystemLocks() {
for (const lock of this.settings.lockedFolders) {
this.restoreFilesystemLock(lock, { force: true });
}
}
applyFilesystemLock(lock) {
if (!this.settings.filesystemLockEnabled) {
return;
}
const childProcess = getNodeModule('child_process');
if (!childProcess) {
return;
}
const absoluteFolder = this.getAbsoluteFolderPath(lock.path);
if (!absoluteFolder) {
return;
}
try {
childProcess.execFileSync('chflags', ['hidden', absoluteFolder], { stdio: 'ignore' });
} catch (error) {
console.warn('[folder-crypto] Could not hide Finder folder', lock.path, error);
new obsidian.Notice(`Could not hide Finder folder: ${lock.path}`);
}
}
restoreFilesystemLock(lock, options = {}) {
if (!this.settings.filesystemLockEnabled && !options.force) {
return;
}
const childProcess = getNodeModule('child_process');
if (!childProcess) {
return;
}
const absoluteFolder = this.getAbsoluteFolderPath(lock.path);
if (!absoluteFolder) {
return;
}
try {
childProcess.execFileSync('chflags', ['nohidden', absoluteFolder], { stdio: 'ignore' });
} catch (error) {
console.warn('[folder-crypto] Could not show Finder folder', lock.path, error);
new obsidian.Notice(`Could not show Finder folder: ${lock.path}`);
}
}
async ensureUnlockedForPath(path) {
const lock = this.getLockForPath(path);
if (!lock || this.unlockedFolders.has(lock.path)) {
return true;
}
return this.promptUnlock(lock);
}
installWorkspaceGate() {
const workspace = this.app.workspace;
const originalOpenFile = workspace.openFile.bind(workspace);
const originalOpenLinkText = workspace.openLinkText.bind(workspace);
workspace.openFile = async (file, openState) => {
if (file instanceof obsidian.TFile && !(await this.ensureUnlockedForPath(file.path))) {
return null;
}
return originalOpenFile(file, openState);
};
workspace.openLinkText = async (linktext, sourcePath, newLeaf, openState) => {
const file = this.app.metadataCache.getFirstLinkpathDest(linktext, sourcePath);
if (file instanceof obsidian.TFile && !(await this.ensureUnlockedForPath(file.path))) {
return null;
}
return originalOpenLinkText(linktext, sourcePath, newLeaf, openState);
};
this.restoreWorkspaceOpeners = () => {
workspace.openFile = originalOpenFile;
workspace.openLinkText = originalOpenLinkText;
};
}
installFileExplorerGate() {
this.registerDomEvent(document, 'click', (event) => {
const target = event.target;
if (!(target instanceof Element)) {
return;
}
const titleEl = target.closest('.nav-folder-title[data-path], .tree-item-self[data-path]');
if (!titleEl) {
return;
}
const path = normalizeFolderPath(titleEl.getAttribute('data-path'));
if (!this.isPathLocked(path) || this.unlockPromptPaths.has(path)) {
return;
}
event.preventDefault();
event.stopPropagation();
this.unlockPromptPaths.add(path);
this.ensureUnlockedForPath(path)
.finally(() => {
this.unlockPromptPaths.delete(path);
});
}, { capture: true });
}
closeLockedActiveLeaf(file) {
window.setTimeout(async () => {
if (!this.isPathLocked(file.path)) {
return;
}
const lockedLeaf = this.findOpenLeafForFile(file);
if (lockedLeaf) {
lockedLeaf.detach();
}
const unlocked = await this.ensureUnlockedForPath(file.path);