You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
12 lines
29 KiB
12 lines
29 KiB
/*
|
|
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
|
|
if you want to view the source, please visit the github repository of this plugin
|
|
*/
|
|
|
|
var z=Object.defineProperty;var le=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var pe=Object.prototype.hasOwnProperty;var ue=(w,t)=>{for(var e in t)z(w,e,{get:t[e],enumerable:!0})},he=(w,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of de(t))!pe.call(w,i)&&i!==e&&z(w,i,{get:()=>t[i],enumerable:!(n=le(t,i))||n.enumerable});return w};var ge=w=>he(z({},"__esModule",{value:!0}),w);var Ee={};ue(Ee,{default:()=>q});module.exports=ge(Ee);var ce=require("obsidian");var T=require("obsidian");var W=class{constructor(){this.values=new Map}put(t,e){this.values.set(t,e)}get(t,e){var n;return(n=this.values.get(t))!=null?n:e}getFirst(t,e){for(let n=0;n<t.length;n++){let i=t[n];if(this.containsKey(i))return this.get(i,e)}return e}containsKey(t){return this.values.has(t)}getKeys(){return Array.from(this.values.keys())}removeKey(t){return this.values.delete(t)}clear(){this.values.clear()}};var f=class{static setActive(t){f.isActive=t,f.isActive||this.clear()}static setAutoExpire(t){f.baseMinutesToExpire=t!=null?t:0,f.updateExpiryTime()}static setLevel(t){f.level!=t&&(f.level=t,this.clear())}static updateExpiryTime(){f.baseMinutesToExpire==0||f.baseMinutesToExpire==null?f.expiryTime=null:f.expiryTime=Date.now()+f.baseMinutesToExpire*1e3*60}static putByPath(t,e){if(!f.isActive)return;let n=f.getPathCacheKey(e);this.cache.put(n,t),f.updateExpiryTime()}static getByPath(t){if(!f.isActive)return f.blankPasswordAndHint;this.clearIfExpired(),f.updateExpiryTime();let e=f.getPathCacheKey(t);return this.cache.get(e,f.blankPasswordAndHint)}static getPathCacheKey(t){let e=t.split("/").slice(0,-1).join("/");switch(f.level){case f.LevelParentPath:return e;default:return t}}static clearIfExpired(){f.expiryTime!=null&&(Date.now()<f.expiryTime||this.clear())}static clearForPath(t){let e=f.getPathCacheKey(t);this.cache.removeKey(e)}static clear(){this.cache.clear()}},h=f;h.isActive=!0,h.blankPasswordAndHint={password:"",hint:""},h.cache=new W,h.baseMinutesToExpire=0,h.expiryTime=null,h.LevelFullPath="fullPath",h.LevelParentPath="parentPath",h.level=f.LevelFullPath;var L=class extends T.PluginSettingTab{constructor(e,n,i,s){super(e,n);this.plugin=n,this.settings=i,this.features=s}display(){let{containerEl:e}=this;e.empty(),e.createEl("h1",{text:"Settings for Meld Encrypt"}),new T.Setting(e).setHeading().setName("Common Settings"),new T.Setting(e).setName("Confirm password?").setDesc("Confirm password when encrypting.").addToggle(r=>{r.setValue(this.settings.confirmPassword).onChange(async o=>{this.settings.confirmPassword=o,await this.plugin.saveSettings()})});let n=()=>{if(!this.settings.rememberPassword){i.settingEl.hide(),s.settingEl.hide();return}i.settingEl.show(),s.settingEl.show();let r=this.settings.rememberPasswordTimeout,o=`For ${r} minutes`;r==0&&(o="Always"),i.setName(`Remember Password (${o})`)};new T.Setting(e).setName("Remember password?").setDesc("Remember the last used passwords when encrypting or decrypting.").addToggle(r=>{r.setValue(this.settings.rememberPassword).onChange(async o=>{this.settings.rememberPassword=o,await this.plugin.saveSettings(),h.setActive(this.settings.rememberPassword),n()})});let i=new T.Setting(e).setDesc("The number of minutes to remember passwords.").addSlider(r=>{r.setLimits(0,120,5).setValue(this.settings.rememberPasswordTimeout).onChange(async o=>{this.settings.rememberPasswordTimeout=o,await this.plugin.saveSettings(),h.setAutoExpire(this.settings.rememberPasswordTimeout),n()})}),s=new T.Setting(e).setDesc("Remember passwords by using").addDropdown(r=>{r.addOption(h.LevelFullPath,"Full Path").addOption(h.LevelParentPath,"Parent Path").setValue(this.settings.rememberPasswordLevel).onChange(async o=>{this.settings.rememberPasswordLevel=o,await this.plugin.saveSettings(),h.setLevel(this.settings.rememberPasswordLevel),n()})});n(),this.features.forEach(r=>{r.buildSettingsUi(e,async()=>await this.plugin.saveSettings())})}};var v=require("obsidian");var j=new TextEncoder,fe=new TextDecoder,we=1e3,ye=j.encode("XHWnDAT6ehMVY2zD"),C=class{async deriveKey(t){let e=j.encode(t),n=await crypto.subtle.importKey("raw",e,{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",hash:{name:"SHA-256"},iterations:we,salt:ye},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async encryptToBytes(t,e){let n=await this.deriveKey(e),i=j.encode(t),s=crypto.getRandomValues(new Uint8Array(16)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},n,i)),o=new Uint8Array(s.byteLength+r.byteLength);return o.set(s,0),o.set(r,s.byteLength),o}convertToString(t){let e="";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e}async encryptToBase64(t,e){let n=await this.encryptToBytes(t,e);return btoa(this.convertToString(n))}stringToArray(t){let e=[];for(let n=0;n<t.length;n++)e.push(t.charCodeAt(n));return new Uint8Array(e)}async decryptFromBytes(t,e){try{let n=t.slice(0,16),i=t.slice(16),s=await this.deriveKey(e),r=await crypto.subtle.decrypt({name:"AES-GCM",iv:n},s,i);return fe.decode(r)}catch(n){return null}}async decryptFromBase64(t,e){try{let n=this.stringToArray(atob(t));return await this.decryptFromBytes(n,e)}catch(n){return null}}};var _={name:"AES-GCM",iv:new Uint8Array([196,190,240,190,188,78,41,132,15,220,84,211]),tagLength:128},K=class{async buildKey(t){let n=new TextEncoder().encode(t),i=await crypto.subtle.digest({name:"SHA-256"},n);return await crypto.subtle.importKey("raw",i,_,!1,["encrypt","decrypt"])}async encryptToBase64(t,e){let n=await this.buildKey(e),s=new TextEncoder().encode(t),r=new Uint8Array(await crypto.subtle.encrypt(_,n,s));return btoa(String.fromCharCode(...r))}stringToArray(t){let e=[];for(let n=0;n<t.length;n++)e.push(t.charCodeAt(n));return new Uint8Array(e)}async decryptFromBase64(t,e){try{let n=this.stringToArray(atob(t)),i=await this.buildKey(e),s=await crypto.subtle.decrypt(_,i,n);return new TextDecoder().decode(s)}catch(n){return null}}};var I=require("obsidian"),D=class extends I.Modal{constructor(e,n,i=""){super(e);this.decryptInPlace=!1;this.canDecryptInPlace=!0;this.titleEl.setText(n),this.text=i}onOpen(){var r;let{contentEl:e}=this;e.empty(),e.classList.add("meld-encrypt-decrypt-modal");let n;(r=new I.Setting(e).addTextArea(o=>{n=o,o.setValue(this.text),o.inputEl.setSelectionRange(0,0),o.inputEl.readOnly=!0,o.inputEl.rows=10}).settingEl.querySelector(".setting-item-info"))==null||r.remove();let s=new I.Setting(e);s.addButton(o=>{o.setButtonText("Copy").onClick(a=>{navigator.clipboard.writeText(n.getValue()),new I.Notice("Copied!")})}),this.canDecryptInPlace&&s.addButton(o=>{o.setWarning().setButtonText("Decrypt in-place").onClick(a=>{this.decryptInPlace=!0,this.close()})})}};var E=require("obsidian");var H=require("obsidian"),P=class{static isSettingsModalOpen(){return document.querySelector(".mod-settings")!==null}static buildPasswordSetting({container:t,name:e,desc:n="",autoFocus:i=!1,placeholder:s="",initialValue:r="",onChangeCallback:o,onEnterCallback:a}){let p=new H.Setting(t).setName(e).setDesc(n).addButton(u=>{u.setIcon("reading-glasses").onClick(l=>{let d=p.components.find((c,g,y)=>c instanceof H.TextComponent);d instanceof H.TextComponent&&(d.inputEl.type=d.inputEl.type=="password"?"text":"password")})}).addText(u=>{u.setPlaceholder(s),u.setValue(r),u.inputEl.type="password",o!=null&&u.onChange(o),a!=null&&(u.inputEl.onkeydown=l=>{l.key==="Enter"&&(l.preventDefault(),a(u.getValue()))}),i&&setTimeout(()=>u.inputEl.focus(),0)});return p}};var A=class extends E.Modal{constructor(e,n,i,s,r=null,o=null){super(e);this.defaultPassword=null;this.defaultHint=null;this.resultConfirmed=!1;this.resultPassword=null;this.resultHint=null;this.resultShowInReadingView=null;this.defaultPassword=r,this.confirmPassword=i,this.showInReadingView=s,this.isEncrypting=n,this.defaultHint=o}onOpen(){var l,d;let{contentEl:e}=this;e.empty(),this.invalidate();let n=(l=this.defaultPassword)!=null?l:"",i="",s=(d=this.defaultHint)!=null?d:"",r=this.showInReadingView;new E.Setting(e).setHeading().setName(this.isEncrypting?"Encrypting":"Decrypting"),P.buildPasswordSetting({container:e,name:"Password:",placeholder:this.isEncrypting?"":`Hint: ${this.defaultHint}`,initialValue:n,autoFocus:!0,onChangeCallback:c=>{n=c,this.invalidate()},onEnterCallback:c=>{if(n=c,this.invalidate(),n.length>0)if(o.settingEl.isShown()){let g=o.components.find(y=>y instanceof E.TextComponent);g instanceof E.TextComponent&&g.inputEl.focus()}else if(a.settingEl.isShown()){let g=a.components.find(y=>y instanceof E.TextComponent);g instanceof E.TextComponent&&g.inputEl.focus()}else u()&&this.close()}});let o=P.buildPasswordSetting({container:e,name:"Confirm Password:",onChangeCallback:c=>{i=c,this.invalidate()},onEnterCallback:c=>{if(i=c,this.invalidate(),i.length>0&&u()&&a.settingEl.isShown()){let g=a.components.find(y=>y instanceof E.TextComponent);g instanceof E.TextComponent&&g.inputEl.focus()}}});this.confirmPassword||o.settingEl.hide();let a=new E.Setting(e).setName("Optional Password Hint").addText(c=>{c.inputEl.placeholder="Password Hint",c.setValue(s),c.onChange(g=>s=g),c.inputEl.on("keypress","*",(g,y)=>{g.key=="Enter"&&y instanceof HTMLInputElement&&y.value.length>0&&(g.preventDefault(),u()&&this.close())})});this.isEncrypting||a.settingEl.hide();let p=new E.Setting(e).setName("Show encrypted marker in Reading view").addToggle(c=>{c.setValue(r).onChange(g=>{r=g})});this.isEncrypting||p.settingEl.hide(),new E.Setting(e).addButton(c=>{c.setButtonText("Confirm").onClick(g=>{u()&&this.close()})});let u=()=>(this.invalidate(),o.setDesc(""),this.confirmPassword&&n!=i?(o.setDesc("Passwords don't match"),!1):(this.resultConfirmed=!0,this.resultPassword=n,this.resultHint=s,this.resultShowInReadingView=r,!0))}invalidate(){this.resultConfirmed=!1,this.resultPassword=null,this.resultHint=null}};var se="%%\u{1F510}\u03B1 ",J="\u{1F510}\u03B1 ",re="%%\u{1F510} ",M=[se,J,re],oe=" \u{1F510}%%",ae=" \u{1F510}",F=[oe,ae],x="\u{1F4A1}",B=class{async onload(t,e){this.plugin=t,this.pluginSettings=e,this.featureSettings=e.featureInplaceEncrypt,this.plugin.registerMarkdownPostProcessor((n,i)=>this.processEncryptedCodeBlockProcessor(n,i)),t.addCommand({id:"meld-encrypt",name:"Encrypt/Decrypt",icon:"lock",editorCheckCallback:(n,i,s)=>this.processEncryptDecryptCommand(n,i,!1)}),t.addCommand({id:"meld-encrypt-in-place",name:"Encrypt/Decrypt In-place",icon:"lock",editorCheckCallback:(n,i,s)=>this.processEncryptDecryptCommand(n,i,!0)})}onunload(){}processEncryptedCodeBlockProcessor(t,e){let n=e.getSectionInfo(t);if(n==null)return;let i=S.extractTextLines(n.text,n.lineStart,n.lineEnd),s=S.findFirstMarker(M,i);if(s==null||s.marker!=J)return;let r=S.findFirstMarker(F,i,s.position+s.marker.length);if(r==null)return;let o=S.removeMarkers(i,s,r),a=new G(o);if(!a.canDecrypt)return;let p=S.extractTextBeforeMarker(i,s),u=S.extractTextAfterMarker(i,r),l=createSpan({text:p}),d=createSpan({text:u}),c=createSpan({text:"\u{1F510}",cls:"meld-encrypt-inline-reading-marker"});c.onClickEvent(async()=>await this.handleReadingIndicatorClick(e.sourcePath,a.decryptable)),t.empty(),t.append(l,c,d)}async handleReadingIndicatorClick(t,e){if(await this.showDecryptedTextIfPasswordKnown(t,e))return;let n=await this.fetchPasswordFromUser(e.hint);n!=null&&(await this.showDecryptedResultForPassword(e,n)?h.putByPath({password:n,hint:e.hint},t):new v.Notice("\u274C Decryption failed!"))}async showDecryptedResultForPassword(t,e){let i=await new C().decryptFromBase64(t.base64CipherText,e);return i===null?!1:new Promise(s=>{let r=new D(this.plugin.app,"\u{1F513}",i);r.canDecryptInPlace=!1,r.onClose=()=>{s(!0)},r.open()})}async fetchPasswordFromUser(t){return new Promise(e=>{let n=new A(this.plugin.app,!1,!1,this.featureSettings.showMarkerWhenReadingDefault,"",t);n.onClose=()=>{e(n.resultPassword)},n.open()})}async showDecryptedTextIfPasswordKnown(t,e){let n=h.getByPath(t);return n.password==null?!1:await this.showDecryptedResultForPassword(e,n.password)}buildSettingsUi(t,e){new v.Setting(t).setHeading().setName("In-place Encryption Settings"),new v.Setting(t).setName("Expand selection to whole line?").setDesc("Partial selections will get expanded to the whole line.").addToggle(n=>{n.setValue(this.featureSettings.expandToWholeLines).onChange(async i=>{this.featureSettings.expandToWholeLines=i,await e()})}),new v.Setting(t).setName("By default, show encrypted marker when reading").setDesc("When encrypting inline text, should the default be to have a visible marker in Reading view?").addToggle(n=>{n.setValue(this.featureSettings.showMarkerWhenReadingDefault).onChange(async i=>{this.featureSettings.showMarkerWhenReadingDefault=i,await e()})})}processEncryptDecryptCommand(t,e,n){if(t&&P.isSettingsModalOpen())return!0;let i=e.getCursor("from"),s=e.getCursor("to");if(this.featureSettings.expandToWholeLines){i={line:i.line,ch:0};let a=s.line,p=e.getLine(a);s={line:a,ch:p.length}}else if(!e.somethingSelected()){let o=this.getClosestPrefixCursorPos(e);if(o==null)return!1;i=o;let a=this.getClosestSuffixCursorPos(e);if(a==null)return!1;s=a}let r=e.getRange(i,s);return this.processSelection(t,e,r,i,s,n)}getClosestPrefixCursorPos(t){let e=M.reduce((i,s,r)=>r==0||s.length>i.length?s:i),n=t.posToOffset(t.getCursor("from"))+e.length;for(let i=n;i>=0;i--){let s=t.offsetToPos(i);for(let r of M){let o=i-r.length,a=t.offsetToPos(o);if(t.getRange(a,s)==r)return t.offsetToPos(o)}}return null}getClosestSuffixCursorPos(t){let e=M.reduce((r,o,a)=>a==0||o.length>r.length?o:r),n=t.posToOffset(t.getCursor("from"))-e.length+1,i=t.lastLine(),s=t.posToOffset({line:i,ch:t.getLine(i).length});for(let r=n;r<=s;r++){let o=t.offsetToPos(r);for(let a of F){let p=r+a.length,u=t.offsetToPos(p);if(t.getRange(o,u)==a)return u}}return null}processSelection(t,e,n,i,s,r,o=!0){var g;let a=new G(n);if(a.isEmpty)return t||new v.Notice("Nothing to Encrypt."),!1;if(!a.canDecrypt&&!a.canEncrypt)return t||new v.Notice("Unable to Encrypt or Decrypt that."),!1;if(a.canEncrypt&&!o)return!1;let p=this.plugin.app.workspace.getActiveFile();if(p==null)return!1;if(t)return!0;let u="",l=(g=a.decryptable)==null?void 0:g.hint;if(this.pluginSettings.rememberPassword){let y=h.getByPath(p.path);u=y.password,l=l!=null?l:y.hint}let d=a.canEncrypt&&this.pluginSettings.confirmPassword,c=new A(this.plugin.app,a.canEncrypt,d,this.featureSettings.showMarkerWhenReadingDefault,u,l);return c.onClose=async()=>{var ee,te,ne,ie;if(!c.resultConfirmed)return;let y=(ee=c.resultPassword)!=null?ee:"",N=(te=c.resultHint)!=null?te:"";if(a.canEncrypt){let k=new Q;k.text=n,k.hint=N,this.encryptSelection(e,k,y,i,s,(ne=c.resultShowInReadingView)!=null?ne:this.featureSettings.showMarkerWhenReadingDefault),h.putByPath({password:y,hint:N},p.path)}else{let k;((ie=a.decryptable)==null?void 0:ie.version)==1?k=await this.decryptSelection_a(e,a.decryptable,y,i,s,r):k=await this.decryptSelectionObsolete(e,a,y,i,s,r),k&&h.putByPath({password:y,hint:N},p.path)}},c.open(),!0}async encryptSelection(t,e,n,i,s,r){let o=new C,a=this.encodeEncryption(await o.encryptToBase64(e.text,n),e.hint,r);t.setSelection(i,s),t.replaceSelection(a)}async decryptSelection_a(t,e,n,i,s,r){let a=await new C().decryptFromBase64(e.base64CipherText,n);if(a===null)return new v.Notice("\u274C Decryption failed!"),!1;if(r)t.setSelection(i,s),t.replaceSelection(a);else{let p=new D(this.plugin.app,"\u{1F513}",a);p.onClose=()=>{t.focus(),p.decryptInPlace&&(t.setSelection(i,s),t.replaceSelection(a))},p.open()}return!0}async decryptSelectionObsolete(t,e,n,i,s,r){let o=e.decryptable.base64CipherText,p=await new K().decryptFromBase64(o,n);if(p===null)return new v.Notice("\u274C Decryption failed!"),!1;if(r)t.setSelection(i,s),t.replaceSelection(p);else{let u=new D(this.plugin.app,"\u{1F513}",p);u.onClose=()=>{t.focus(),u.decryptInPlace&&(t.setSelection(i,s),t.replaceSelection(p))},u.open()}return!0}encodeEncryption(t,e,n){if(!M.some(i=>t.contains(i))&&!F.some(i=>t.contains(i))){let i=n?J:se,s=n?ae:oe;return e.length>0?i.concat(x,e,x,t,s):i.concat(t,s)}return t}},G=class{constructor(t){this.process(t)}process(t){var e,n;if(this.processedText=t,this.isEmpty=t.length===0,this.prefix=(e=M.find(i=>t.startsWith(i)))!=null?e:"",this.suffix=(n=F.find(i=>t.endsWith(i)))!=null?n:"",this.hasEncryptedPrefix=this.prefix.length>0,this.hasEncryptedSuffix=this.suffix.length>0,this.hasObsoleteEncryptedPrefix=this.prefix===re,this.containsEncryptedMarkers=[...M,...F].some(i=>t.contains(i)),this.canDecrypt=this.hasEncryptedPrefix&&this.hasEncryptedSuffix,this.canEncrypt=!this.hasEncryptedPrefix&&!this.containsEncryptedMarkers,this.canDecrypt){let i=this.parseDecryptableContent(t);i!=null?this.decryptable=i:this.canDecrypt=!1}}parseDecryptableContent(t){let e=new Z;if(!this.hasEncryptedPrefix||!this.hasEncryptedSuffix)return null;e.version=this.hasObsoleteEncryptedPrefix?0:1;let n=t.substring(this.prefix.length,t.length-this.suffix.length);if([...M,...F].some(i=>n.contains(i)))return null;if(n.substring(0,x.length)==x){let i=n.indexOf(x,x.length);if(i<0)return null;e.hint=n.substring(x.length,i),e.base64CipherText=n.substring(i+x.length)}else e.base64CipherText=n;return e}},Q=class{},Z=class{},S=class{static extractTextBeforeMarker(t,e){return t.substring(0,e.position)}static extractTextAfterMarker(t,e){return t.substring(e.position+e.marker.length)}static removeMarkers(t,e,n){return t.substring(e.position,n.position+n.marker.length)}static extractTextLines(t,e,n){return t.split(`
|
|
`).slice(e,n+1).join(`
|
|
`)}static findFirstMarker(t,e,n=0){let i=null,s=null;return t.forEach(r=>{let o=e.indexOf(r,n);o!=-1&&(i==null||o<i)&&(i=o,s=r)}),s==null||i==null?null:{marker:s,position:i}}};var b=require("obsidian");var m=require("obsidian");var V=class{static get showInlineTitle(){var t;return(t=app.vault.getConfig("showInlineTitle"))!=null?t:!0}static get readableLineLength(){var t;return(t=app.vault.getConfig("readableLineLength"))!=null?t:!0}};var O="meld-encrypted-file-content-view",Y=class extends m.TextFileView{constructor(e,n){var i;super(e);this.iconReadingView="book-open";this.iconSourceView="code";this.iconToggleEditView="edit";this.iconLockFile="lock";this.iconChangePassword="key";this.currentView=0;this.encryptionPassword="";this.hint="";this.currentEditorSourceText="";this.settings=n,this.defaultEditNoteView=(i=n.defaultView)!=null?i:"Source",this.currentEditNoteMode=this.defaultEditNoteView,this.elActionEditView=this.addAction(this.iconSourceView,"Source",()=>this.actionToggleEditMode()),this.elActionReadingView=this.addAction(this.iconReadingView,"Reading",()=>this.actionToggleEditMode()),this.elActionIconLockNote=this.addAction(this.iconLockFile,"Lock",()=>this.actionLockFile()),this.elActionChangePassword=this.addAction(this.iconChangePassword,"Change Password",()=>this.actionChangePassword()),this.elActionEditView.hide(),this.elActionReadingView.hide(),this.elActionIconLockNote.hide(),this.elActionChangePassword.hide(),this.containerEl.classList.add("meld-encrypt-encrypted-note-view"),this.contentEl.classList.add("meld-encrypt-encrypted-note-view-content")}actionToggleEditMode(){this.currentView==2&&(this.currentEditNoteMode=="Reading"?this.currentEditNoteMode="Source":this.currentEditNoteMode=="Source"&&(this.currentEditNoteMode="Reading"),this.refreshView(2))}actionLockFile(){this.encryptionPassword="",h.clearForPath(this.file.path),this.refreshView(1)}actionChangePassword(){this.refreshView(3)}onPaneMenu(e,n){n=="tab-header"&&this.currentView==2&&(e.addItem(i=>{i.setSection("action").setIcon(this.iconToggleEditView).setTitle("Toggle Editing/Reading").onClick(()=>this.actionToggleEditMode())}),e.addItem(i=>{i.setSection("action").setIcon(this.iconLockFile).setTitle("Lock").onClick(()=>this.actionLockFile())}),e.addItem(i=>{i.setSection("action").setIcon(this.iconChangePassword).setTitle("Change Password").onClick(()=>this.actionChangePassword())})),super.onPaneMenu(e,n)}addHeader(e,n){var i;e.createDiv({text:`\u{1F510} ${n} \u{1F510}`,cls:"encrypted-note-message"}),V.showInlineTitle&&e.createDiv({text:(i=this.file)==null?void 0:i.basename,cls:"inline-title"})}validatePassword(e){return e.length==0?"Password is too short":""}validateConfirm(e,n){return e===n?"":"Password doesn't match"}addNewNoteView(e){this.addHeader(e,"This note will be encrypted");let n=this.addUserInputContainer(e);new m.Setting(n).setDesc("Please provide a password and hint to start editing this note.");let i=async(d,c,g)=>{let y=this.validatePassword(d),N=this.validateConfirm(d,c);p.setDesc(y),u.setDesc(N),y.length===0&&N.length===0&&(this.encryptionPassword=d,this.hint=g,V.showInlineTitle||(this.currentEditorSourceText=`# ${this.file.basename}
|
|
|
|
|
|
`),await this.encodeAndSave(),h.putByPath({password:d,hint:g},this.file.path),this.currentEditNoteMode="Source",this.refreshView(2))},s=h.getByPath(this.file.path),r=s.password,o="",a=s.hint,p=P.buildPasswordSetting({container:n,name:"Password:",autoFocus:!0,initialValue:r,onChangeCallback:d=>{r=d,p.setDesc(this.validatePassword(r)),u.setDesc(this.validateConfirm(r,o))},onEnterCallback:d=>{var c;r=d,r.length>0&&((c=u.controlEl.querySelector("input"))==null||c.focus())}}),u=P.buildPasswordSetting({container:n,name:"Confirm:",autoFocus:!1,onChangeCallback:d=>{o=d,p.setDesc(this.validatePassword(r)),u.setDesc(this.validateConfirm(r,o))},onEnterCallback:d=>{var g;o=d,r===o&&((g=l.controlEl.querySelector("input"))==null||g.focus())}}),l=new m.Setting(n).setName("Hint:").addText(d=>{d.setValue(a),d.onChange(c=>{a=c})});l.controlEl.on("keydown","*",d=>{d.key==="Enter"&&(d.preventDefault(),i(r,o,a))}),new m.Setting(n).addButton(d=>{d.setCta().setIcon("go-to-file").setTooltip("Edit").onClick(c=>i(r,o,a))})}addDecryptNoteView(e){this.addHeader(e,"This note is encrypted");let n=this.addUserInputContainer(e);new m.Setting(n).setDesc("Please provide a password to unlock this note."),P.buildPasswordSetting({container:n,name:"Password:",autoFocus:!0,placeholder:this.formatHint(this.hint),onChangeCallback:s=>{this.encryptionPassword=s},onEnterCallback:async()=>await this.handleDecryptButtonClick()}),new m.Setting(n).addButton(s=>{s.setCta().setIcon("checkmark").setTooltip("Unlock & Edit").onClick(r=>this.handleDecryptButtonClick())});let i=h.getByPath(this.file.path);this.encryptionPassword=i.password,this.decryptWithPassword(i.password).then(s=>{s!=null&&(this.currentEditorSourceText=s,this.refreshView(2),new m.Notice("Decrypted using remembered password",2e3))})}async encodeAndSave(){try{let e=await X.encode(this.encryptionPassword,this.hint,this.currentEditorSourceText);this.data=R.encode(e),this.requestSave()}catch(e){console.error(e),new m.Notice(e,1e4)}}addEditorSourceView(e){this.elActionReadingView.show(),this.elActionIconLockNote.show(),this.elActionChangePassword.show(),this.addHeader(e,"Editing an encrypted note");let n=e.createDiv({cls:"editor-source-view"});n.spellcheck=!0,n.autocapitalize="on",n.translate=!1,n.contentEditable="true",n.innerText=this.currentEditorSourceText,n.focus(),n.on("input","*",async(i,s)=>{console.debug({container:n}),this.currentEditorSourceText=n.innerText,await this.encodeAndSave()})}addEditorReadingView(e){this.elActionEditView.show(),this.elActionIconLockNote.show(),this.elActionChangePassword.show(),this.addHeader(e,"Reading an encrypted note");let n=e.createDiv({cls:"editor-reading-view"});m.MarkdownRenderer.renderMarkdown(this.currentEditorSourceText,n,this.file.path,this).catch(i=>{console.error(i)})}addUserInputContainer(e){return e.createDiv({cls:"input-container"})}addChangePasswordView(e){this.addHeader(e,"Change encrypted note password");let n=this.addUserInputContainer(e),i="",s="",r="",o=async(l,d,c)=>{let g=this.validatePassword(l),y=this.validateConfirm(l,d);a.setDesc(g),p.setDesc(y),g.length===0&&y.length===0&&(this.encryptionPassword=l,this.hint=c,this.encodeAndSave(),this.refreshView(2),h.putByPath({password:l,hint:c},this.file.path),new m.Notice("Password and Hint were changed"))},a=P.buildPasswordSetting({container:n,name:"New Password:",autoFocus:!0,onChangeCallback:l=>{i=l,a.setDesc(this.validatePassword(i)),p.setDesc(this.validateConfirm(i,s))},onEnterCallback:l=>{var d;i=l,i.length>0&&((d=p.controlEl.querySelector("input"))==null||d.focus())}}),p=P.buildPasswordSetting({container:n,name:"Confirm:",onChangeCallback:l=>{s=l,a.setDesc(this.validatePassword(i)),p.setDesc(this.validateConfirm(i,s))},onEnterCallback:l=>{var c;s=l,i===s&&((c=u.controlEl.querySelector("input"))==null||c.focus())}}),u=new m.Setting(n).setName("New Hint:").addText(l=>{l.onChange(d=>{r=d})});u.controlEl.on("keydown","*",l=>{l.key==="Enter"&&(l.preventDefault(),o(i,s,r))}),new m.Setting(n).addButton(l=>{l.removeCta().setIcon("cross").setTooltip("Cancel").onClick(()=>{this.refreshView(2)})}).addButton(l=>{l.setCta().setIcon("checkmark").setTooltip("Change Password").setWarning().onClick(d=>{o(i,s,r)})})}formatHint(e){return e.length>0?`Hint: ${e}`:""}refreshView(e){this.currentView=e,this.elActionEditView.hide(),this.elActionReadingView.hide(),this.elActionIconLockNote.hide(),this.elActionChangePassword.hide(),this.contentEl.empty(),V.readableLineLength?this.contentEl.classList.add("is-readable-line-width"):this.contentEl.classList.remove("is-readable-line-width");let n=this.contentEl.createDiv({cls:"content-container"});switch(this.currentView){case 4:this.addNewNoteView(n);break;case 1:this.addDecryptNoteView(n);break;case 2:this.currentEditNoteMode=="Source"?this.addEditorSourceView(n):this.addEditorReadingView(n);break;case 3:this.addChangePasswordView(n);break}}async decryptWithPassword(e){if(e.length==0)return null;let n=R.decode(this.data);return await X.decrypt(n,e)}async handleDecryptButtonClick(){let e=await this.decryptWithPassword(this.encryptionPassword);e===null?new m.Notice("Decryption failed"):(h.putByPath({password:this.encryptionPassword,hint:this.hint},this.file.path),this.currentEditorSourceText=e,this.refreshView(2))}canAcceptExtension(e){return e=="encrypted"}getViewType(){return O}setViewData(e,n){if(n){let i;e===""?i=4:i=1,this.encryptionPassword="";let s=R.decode(this.data);this.hint=s.hint,this.refreshView(i)}else this.leaf.detach(),new m.Notice("Multiple views of the same encrypted note isn't supported")}getViewData(){return this.data}clear(){}},$=class{constructor(t,e){this.version="1.0";this.hint=t,this.encodedData=e}},X=class{static async encode(t,e,n){let s=await new C().encryptToBase64(n,t);return new $(e,s)}static async decrypt(t,e){return t.encodedData==""?"":await new C().decryptFromBase64(t.encodedData,e)}},R=class{static encode(t){return JSON.stringify(t,null,2)}static decode(t){return t===""?new $("",""):JSON.parse(t)}};var U=class{async onload(t,e){this.plugin=t,this.settings=e.featureWholeNoteEncrypt,this.updateUiForSettings(),this.plugin.registerView(O,n=>new Y(n,this.settings)),this.plugin.registerExtensions(["encrypted"],O),this.plugin.addCommand({id:"meld-encrypt-create-new-note",name:"Create new encrypted note",icon:"lock",callback:()=>this.processCreateNewEncryptedNoteCommand()})}onunload(){this.plugin.app.workspace.detachLeavesOfType(O)}processCreateNewEncryptedNoteCommand(){try{let t=(0,b.moment)().format("[Untitled] YYYYMMDD hhmmss[.encrypted]"),e,n=this.plugin.app.workspace.getActiveFile();n!=null?e=this.plugin.app.fileManager.getNewFileParent(n.path):e=this.plugin.app.fileManager.getNewFileParent("");let i=(0,b.normalizePath)(e.path+"/"+t);return this.plugin.app.vault.create(i,"").then(async s=>{await this.plugin.app.workspace.getLeaf(!1).openFile(s)}).catch(s=>{new b.Notice(s,1e4)}),!0}catch(t){return console.error(t),new b.Notice(t,1e4),!1}}buildSettingsUi(t,e){new b.Setting(t).setHeading().setName("Whole Note Encryption Settings"),new b.Setting(t).setName("Add ribbon icon to create note").setDesc("Adds a ribbon icon to the left bar to create an encrypted note.").addToggle(n=>{n.setValue(this.settings.addRibbonIconToCreateNote).onChange(async i=>{this.settings.addRibbonIconToCreateNote=i,await e(),this.updateUiForSettings()})}),new b.Setting(t).setName("Default view for new tabs").setDesc("The default view that a new encrypted note tab gets opened in").addDropdown(n=>{var i;n.addOption(`${"Source"}`,"Source view").addOption(`${"Reading"}`,"Reading view").setValue(`${(i=this.settings.defaultView)!=null?i:"Source"}`).onChange(async s=>{this.settings.defaultView=s,await e()})})}updateUiForSettings(){this.settings.addRibbonIconToCreateNote?this.ribbonIconCreateNewNote==null&&(this.ribbonIconCreateNewNote=this.plugin.addRibbonIcon("lock","Create new encrypted note",t=>{this.processCreateNewEncryptedNoteCommand()})):this.ribbonIconCreateNewNote!=null&&(this.ribbonIconCreateNewNote.remove(),this.ribbonIconCreateNewNote=null)}};var q=class extends ce.Plugin{constructor(){super(...arguments);this.enabledFeatures=[]}async onload(){await this.loadSettings(),this.enabledFeatures.push(new U,new B),this.addSettingTab(new L(this.app,this,this.settings,this.enabledFeatures)),this.enabledFeatures.forEach(async e=>{await e.onload(this,this.settings)})}onunload(){this.enabledFeatures.forEach(async e=>{e.onunload()})}async loadSettings(){let e={confirmPassword:!0,rememberPassword:!0,rememberPasswordTimeout:30,rememberPasswordLevel:h.LevelFullPath,featureWholeNoteEncrypt:{addRibbonIconToCreateNote:!0,defaultView:"Source".toString()},featureInplaceEncrypt:{expandToWholeLines:!1,showMarkerWhenReadingDefault:!0}};this.settings=Object.assign(e,await this.loadData()),h.setActive(this.settings.rememberPassword),h.setAutoExpire(this.settings.rememberPasswordTimeout==0?null:this.settings.rememberPasswordTimeout),h.setLevel(this.settings.rememberPasswordLevel)}async saveSettings(){await this.saveData(this.settings)}};
|