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
37 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 ae=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var Fe=Object.getOwnPropertyNames;var xe=Object.prototype.hasOwnProperty;var Se=(w,t)=>{for(var e in t)ae(w,e,{get:t[e],enumerable:!0})},Ie=(w,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Fe(t))!xe.call(w,i)&&i!==e&&ae(w,i,{get:()=>t[i],enumerable:!(n=Te(t,i))||n.enumerable});return w};var De=w=>Ie(ae({},"__esModule",{value:!0}),w);var Ve={};Se(Ve,{default:()=>oe});module.exports=De(Ve);var Ce=require("obsidian");var k=require("obsidian");var ee=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 ce=require("obsidian"),B=class{static getFilePathWithNewExtension(t,e){return(0,ce.normalizePath)(t.parent.path+"/"+t.basename+"."+e)}static getFilePathExcludingExtension(t){return(0,ce.normalizePath)(t.parent.path+"/"+t.basename)}};var u=class{static setActive(t){u.isActive=t,u.isActive||this.clear()}static setAutoExpire(t){u.baseMinutesToExpire=t!=null?t:0,u.updateExpiryTime()}static setLevel(t){u.level!=t&&(u.allLevels.contains(t)&&(u.level=t),u.level=u.LevelFilename,this.clear())}static updateExpiryTime(){u.baseMinutesToExpire==0||u.baseMinutesToExpire==null?u.expiryTime=null:u.expiryTime=Date.now()+u.baseMinutesToExpire*1e3*60}static putByFile(t,e){if(!u.isActive)return;let n=u.getFileCacheKey(e);this.cache.put(n,t),u.updateExpiryTime()}static getByFile(t){if(!u.isActive)return u.blankPasswordAndHint;this.clearIfExpired(),u.updateExpiryTime();let e=u.getFileCacheKey(t);return this.cache.get(e,u.blankPasswordAndHint)}static putByPath(t,e){if(!u.isActive)return;let n=u.getPathCacheKey(e);this.cache.put(n,t),u.updateExpiryTime()}static getByPath(t){if(!u.isActive)return u.blankPasswordAndHint;this.clearIfExpired(),u.updateExpiryTime();let e=u.getPathCacheKey(t);return this.cache.get(e,u.blankPasswordAndHint)}static getPathCacheKey(t){let e=t.split("/").slice(0,-1).join("/");switch(u.level){case u.LevelParentPath:return e;default:return t}}static getFileCacheKey(t){switch(u.level){case u.LevelParentPath:return t.parent.path;default:return B.getFilePathExcludingExtension(t)}}static clearIfExpired(){u.expiryTime!=null&&(Date.now()<u.expiryTime||this.clear())}static clearForFile(t){let e=u.getFileCacheKey(t);this.cache.removeKey(e)}static clearForPath(t){let e=u.getPathCacheKey(t);this.cache.removeKey(e)}static clear(){this.cache.clear()}},g=u;g.isActive=!0,g.blankPasswordAndHint={password:"",hint:""},g.cache=new ee,g.baseMinutesToExpire=0,g.expiryTime=null,g.LevelFilename="filename",g.LevelParentPath="parentPath",g.allLevels=[u.LevelFilename,u.LevelParentPath],g.level=u.LevelFilename;var W=class extends k.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 k.Setting(e).setHeading().setName("Common Settings"),new k.Setting(e).setName("Confirm password?").setDesc("Confirm password when encrypting. (Recommended)").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="Until Obsidian is closed"),i.setName(`Remember Password (${o})`)};new k.Setting(e).setName("Remember password?").setDesc("Remember the last used passwords when encrypting or decrypting. Passwords are remembered until they timeout or Obsidian is closed").addToggle(r=>{r.setValue(this.settings.rememberPassword).onChange(async o=>{this.settings.rememberPassword=o,await this.plugin.saveSettings(),g.setActive(this.settings.rememberPassword),n()})});let i=new k.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(),g.setAutoExpire(this.settings.rememberPasswordTimeout),n()})}),s=new k.Setting(e).setDesc("Remember passwords by using a notes file name or parent folder").addDropdown(r=>{r.addOption(g.LevelFilename,"File Name").addOption(g.LevelParentPath,"Parent Folder").setValue(this.settings.rememberPasswordLevel).onChange(async o=>{this.settings.rememberPasswordLevel=o,await this.plugin.saveSettings(),g.setLevel(this.settings.rememberPasswordLevel),n()})});n(),this.features.forEach(r=>{r.buildSettingsUi(e,async()=>await this.plugin.saveSettings())})}};var T=require("obsidian");var L=require("obsidian"),R=class extends L.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 L.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 L.Setting(e);s.addButton(o=>{o.setButtonText("Copy").onClick(a=>{navigator.clipboard.writeText(n.getValue()),new L.Notice("Copied!")})}),this.canDecryptInPlace&&s.addButton(o=>{o.setWarning().setButtonText("Decrypt in-place").onClick(a=>{this.decryptInPlace=!0,this.close()})})}};var P=require("obsidian");var X=require("obsidian"),E=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 h=new X.Setting(t).setName(e).setDesc(n).addButton(f=>{f.setIcon("reading-glasses").onClick(d=>{let l=h.components.find((c,p,m)=>c instanceof X.TextComponent);l instanceof X.TextComponent&&(l.inputEl.type=l.inputEl.type=="password"?"text":"password")})}).addText(f=>{f.setPlaceholder(s),f.setValue(r),f.inputEl.type="password",o!=null&&f.onChange(o),a!=null&&(f.inputEl.onkeydown=d=>{d.key==="Enter"&&(d.preventDefault(),a(f.getValue()))}),i&&setTimeout(()=>f.inputEl.focus(),0)});return h}};var H=class extends P.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 d,l;let{contentEl:e}=this;e.empty(),this.invalidate();let n=(d=this.defaultPassword)!=null?d:"",i="",s=(l=this.defaultHint)!=null?l:"",r=this.showInReadingView;new P.Setting(e).setHeading().setName(this.isEncrypting?"Encrypting":"Decrypting"),E.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 p=o.components.find(m=>m instanceof P.TextComponent);p instanceof P.TextComponent&&p.inputEl.focus()}else if(a.settingEl.isShown()){let p=a.components.find(m=>m instanceof P.TextComponent);p instanceof P.TextComponent&&p.inputEl.focus()}else f()&&this.close()}});let o=E.buildPasswordSetting({container:e,name:"Confirm Password:",onChangeCallback:c=>{i=c,this.invalidate()},onEnterCallback:c=>{if(i=c,this.invalidate(),i.length>0&&f()&&a.settingEl.isShown()){let p=a.components.find(m=>m instanceof P.TextComponent);p instanceof P.TextComponent&&p.inputEl.focus()}}});this.confirmPassword||o.settingEl.hide();let a=new P.Setting(e).setName("Optional Password Hint").addText(c=>{c.inputEl.placeholder="Password Hint",c.setValue(s),c.onChange(p=>s=p),c.inputEl.on("keypress","*",(p,m)=>{p.key=="Enter"&&m instanceof HTMLInputElement&&m.value.length>0&&(p.preventDefault(),f()&&this.close())})});this.isEncrypting||a.settingEl.hide();let h=new P.Setting(e).setName("Show encrypted marker in Reading view").addToggle(c=>{c.setValue(r).onChange(p=>{r=p})});this.isEncrypting||h.settingEl.hide(),new P.Setting(e).addButton(c=>{c.setButtonText("Confirm").onClick(p=>{f()&&this.close()})});let f=()=>(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 le=new TextEncoder,ke=new TextDecoder,Ae=1e3,Ne=le.encode("XHWnDAT6ehMVY2zD"),Y=class{async deriveKey(t){let e=le.encode(t),n=await crypto.subtle.importKey("raw",e,{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",hash:{name:"SHA-256"},iterations:Ae,salt:Ne},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async encryptToBytes(t,e){let n=await this.deriveKey(e),i=le.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 ke.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 O=class{constructor(t,e,n){this.vectorSize=t,this.saltSize=e,this.iterations=n}async deriveKey(t,e){let i=new TextEncoder().encode(t),s=await crypto.subtle.importKey("raw",i,"PBKDF2",!1,["deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",hash:"SHA-512",salt:e,iterations:this.iterations},s,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async encryptToBytes(t,e){let n=crypto.getRandomValues(new Uint8Array(this.saltSize)),i=await this.deriveKey(e,n),r=new TextEncoder().encode(t),o=crypto.getRandomValues(new Uint8Array(this.vectorSize)),a=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:o},i,r)),h=new Uint8Array(o.byteLength+n.byteLength+a.byteLength);return h.set(o,0),h.set(n,o.byteLength),h.set(a,o.byteLength+n.byteLength),h}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,i;n=0,i=n+this.vectorSize;let s=t.slice(n,i);n=i,i=n+this.saltSize;let r=t.slice(n,i);n=i,i=void 0;let o=t.slice(n),a=await this.deriveKey(e,r),h=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},a,o);return new TextDecoder().decode(h)}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 de={name:"AES-GCM",iv:new Uint8Array([196,190,240,190,188,78,41,132,15,220,84,211]),tagLength:128},te=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,de,!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(de,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(de,i,n);return new TextDecoder().decode(s)}catch(n){return null}}};var C=class{static BuildDefault(){return new O(16,16,21e4)}static BuildFromFileDataOrThrow(t){let e=C.BuildFromFileDataOrNull(t);if(e!=null)return e;throw new Error(`Unable to determine ICryptoHelper for File ver ${t.version}`)}static BuildFromFileDataOrNull(t){return t.version=="1.0"?new Y:t.version=="2.0"?new O(16,16,21e4):null}static BuildFromDecryptableOrThrow(t){let e=C.BuildFromDecryptableOrNull(t);if(e!=null)return e;throw new Error(`Unable to determine ICryptoHelper for Decryptable ver ${t.version}`)}static BuildFromDecryptableOrNull(t){return t.version==0?new te:t.version==1?new Y:t.version==2?new O(16,16,21e4):null}};var ne=class{};var ie="%%\u{1F510}\u03B2 ",U="\u{1F510}\u03B2 ",pe="%%\u{1F510}\u03B1 ",z="\u{1F510}\u03B1 ",ue="%%\u{1F510} ",Pe=ie,be=U,F=[ie,U,pe,z,ue],he=" \u{1F510}%%",ge=" \u{1F510}",A=[he,ge],x="\u{1F4A1}";var $=class{constructor(t){this.process(t)}process(t){var e,n;if(this.processedText=t,this.isEmpty=t.length===0,this.prefix=(e=F.find(i=>t.startsWith(i)))!=null?e:"",this.suffix=(n=A.find(i=>t.endsWith(i)))!=null?n:"",this.hasEncryptedPrefix=this.prefix.length>0,this.hasEncryptedSuffix=this.suffix.length>0,this.hasObsoleteEncryptedPrefix=this.prefix===ue,this.containsEncryptedMarkers=[...F,...A].some(i=>t.includes(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 ne;if(!this.hasEncryptedPrefix||!this.hasEncryptedSuffix)return null;this.hasObsoleteEncryptedPrefix?e.version=0:this.prefix==ie||this.prefix==U?e.version=2:(this.prefix==pe||this.prefix==z)&&(e.version=1);let n=t.substring(this.prefix.length,t.length-this.suffix.length);if([...F,...A].some(i=>n.includes(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}};var G=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(){}async processEncryptedCodeBlockProcessor(t,e){let n=e.getSectionInfo(t);if(n==null)return;let i=N.extractTextLines(n.text,n.lineStart,n.lineEnd),s=N.findFirstMarker(F,i);if(s==null||!(s.marker==z||s.marker==U))return;let r=N.findFirstMarker(A,i,s.position+s.marker.length);if(r==null)return;let o=N.removeMarkers(i,s,r),a=new $(o);if(!a.canDecrypt)return;let h=N.extractTextBeforeMarker(i,s),f=N.extractTextAfterMarker(i,r),d=h+'<span class="meld-encrypt-inline-reading-marker">\u{1F510}</span>'+f;t.empty(),await T.MarkdownRenderer.renderMarkdown(d,t,e.sourcePath,this.plugin);let l=t.querySelector(".meld-encrypt-inline-reading-marker");l==null||l.onClickEvent(async()=>await this.handleReadingIndicatorClick(e.sourcePath,a.decryptable))}async handleReadingIndicatorClick(t,e){if(e==null){new T.Notice("\u274C Decryption failed!");return}if(await this.showDecryptedTextIfPasswordKnown(t,e))return;let n=await this.fetchPasswordFromUser(e.hint);n!=null&&(await this.showDecryptedResultForPassword(e,n)?g.putByPath({password:n,hint:e.hint},t):new T.Notice("\u274C Decryption failed!"))}async showDecryptedResultForPassword(t,e){let i=await C.BuildFromDecryptableOrThrow(t).decryptFromBase64(t.base64CipherText,e);return i===null?!1:new Promise(s=>{let r=new R(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 H(this.plugin.app,!1,!1,this.featureSettings.showMarkerWhenReadingDefault,"",t);n.onClose=()=>{e(n.resultPassword)},n.open()})}async showDecryptedTextIfPasswordKnown(t,e){let n=g.getByPath(t);return n.password==null?!1:await this.showDecryptedResultForPassword(e,n.password)}buildSettingsUi(t,e){new T.Setting(t).setHeading().setName("In-place Encryption Settings"),new T.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 T.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&&E.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,h=e.getLine(a);s={line:a,ch:h.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=F.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 F){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=F.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 A){let h=r+a.length,f=t.offsetToPos(h);if(t.getRange(o,f)==a)return f}}return null}processSelection(t,e,n,i,s,r,o=!0){var p;let a=new $(n);if(a.isEmpty)return t||new T.Notice("Nothing to Encrypt."),!1;if(!a.canDecrypt&&!a.canEncrypt)return t||new T.Notice("Unable to Encrypt or Decrypt that."),!1;if(a.canEncrypt&&!o)return!1;let h=this.plugin.app.workspace.getActiveFile();if(h==null)return!1;if(t)return!0;let f="",d=(p=a.decryptable)==null?void 0:p.hint;if(this.pluginSettings.rememberPassword){let m=g.getByPath(h.path);f=m.password,d=d!=null?d:m.hint}let l=a.canEncrypt&&this.pluginSettings.confirmPassword,c=new H(this.plugin.app,a.canEncrypt,l,this.featureSettings.showMarkerWhenReadingDefault,f,d);return c.onClose=async()=>{var we,ye,Ee;if(!c.resultConfirmed)return;let m=(we=c.resultPassword)!=null?we:"",V=(ye=c.resultHint)!=null?ye:"";if(a.canEncrypt){let Z=new fe;Z.text=n,Z.hint=V,this.encryptSelection(e,Z,m,i,s,(Ee=c.resultShowInReadingView)!=null?Ee:this.featureSettings.showMarkerWhenReadingDefault),g.putByPath({password:m,hint:V},h.path)}else a.decryptable&&await this.decryptSelection(e,a.decryptable,m,i,s,r)&&g.putByPath({password:m,hint:V},h.path)},c.open(),!0}async encryptSelection(t,e,n,i,s,r){let o=C.BuildDefault(),a=this.encodeEncryption(await o.encryptToBase64(e.text,n),e.hint,r);t.setSelection(i,s),t.replaceSelection(a)}async decryptSelection(t,e,n,i,s,r){let a=await C.BuildFromDecryptableOrThrow(e).decryptFromBase64(e.base64CipherText,n);if(a===null)return new T.Notice("\u274C Decryption failed!"),!1;if(r)t.setSelection(i,s),t.replaceSelection(a);else{let h=new R(this.plugin.app,"\u{1F513}",a);h.onClose=()=>{t.focus(),h.decryptInPlace&&(t.setSelection(i,s),t.replaceSelection(a))},h.open()}return!0}encodeEncryption(t,e,n){if(!F.some(i=>t.includes(i))&&!A.some(i=>t.includes(i))){let i=n?be:Pe,s=n?ge:he;return e.length>0?i.concat(x,e,x,t,s):i.concat(t,s)}return t}},fe=class{},N=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 D=require("obsidian");var y=require("obsidian");var _=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 se=class{constructor(t,e,n){this.version="1.0";this.version=t,this.hint=e,this.encodedData=n}},me=class{static async encode(t,e,n){let s=await C.BuildDefault().encryptToBase64(n,t);return new se(me.DEFAULT_VERSION,e,s)}static async decrypt(t,e){return t.encodedData==""?"":await C.BuildFromFileDataOrThrow(t).decryptFromBase64(t.encodedData,e)}},S=me;S.DEFAULT_VERSION="2.0";var I=class{static encode(t){return JSON.stringify(t,null,2)}static decode(t){return t===""?new se(S.DEFAULT_VERSION,"",""):JSON.parse(t)}};var Me="encrypted",ve="mdenc",re=ve,M=[ve,Me];var j="meld-encrypted-file-content-view",q=class extends y.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.toggleReadingView()),this.elActionReadingView=this.addAction(this.iconReadingView,"Reading",()=>this.toggleReadingView()),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")}toggleReadingView(){this.currentView==2&&(this.currentEditNoteMode=="Reading"?this.currentEditNoteMode="Source":this.currentEditNoteMode=="Source"&&(this.currentEditNoteMode="Reading"),this.refreshView(2))}actionLockFile(){this.encryptionPassword="",g.clearForFile(this.file),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.toggleReadingView())}),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"}),_.showInlineTitle&&e.createDiv({text:(i=this.file)==null?void 0:i.basename,cls:"inline-title"})}validatePassword(e){return""}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 y.Setting(n).setDesc("Please provide a password and hint to start editing this note.");let i=async(l,c,p)=>{let m=this.validatePassword(l),V=this.validateConfirm(l,c);h.setDesc(m),f.setDesc(V),m.length===0&&V.length===0&&(this.encryptionPassword=l,this.hint=p,_.showInlineTitle||(this.currentEditorSourceText=`# ${this.file.basename}
`),await this.encodeAndSave(),g.putByFile({password:l,hint:p},this.file),this.currentEditNoteMode="Source",this.refreshView(2))},s=g.getByFile(this.file),r=s.password,o="",a=s.hint,h=E.buildPasswordSetting({container:n,name:"Password:",autoFocus:!0,initialValue:r,onChangeCallback:l=>{r=l,h.setDesc(this.validatePassword(r)),f.setDesc(this.validateConfirm(r,o))},onEnterCallback:l=>{var c;r=l,r.length>0&&((c=f.controlEl.querySelector("input"))==null||c.focus())}}),f=E.buildPasswordSetting({container:n,name:"Confirm:",autoFocus:!1,onChangeCallback:l=>{o=l,h.setDesc(this.validatePassword(r)),f.setDesc(this.validateConfirm(r,o))},onEnterCallback:l=>{var p;o=l,r===o&&((p=d.controlEl.querySelector("input"))==null||p.focus())}}),d=new y.Setting(n).setName("Hint:").addText(l=>{l.setValue(a),l.onChange(c=>{a=c})});d.controlEl.on("keydown","*",l=>{l.key==="Enter"&&(l.preventDefault(),i(r,o,a))}),new y.Setting(n).addButton(l=>{l.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 y.Setting(n).setDesc("Please provide a password to unlock this note.");let i=E.buildPasswordSetting({container:n,name:"Password:",autoFocus:!0,placeholder:this.formatHint(this.hint),onChangeCallback:r=>{this.encryptionPassword=r,i.setDesc(this.validatePassword(this.encryptionPassword))},onEnterCallback:async()=>await this.handleDecryptButtonClick()});new y.Setting(n).addButton(r=>{r.setCta().setIcon("checkmark").setTooltip("Unlock & Edit").onClick(o=>this.handleDecryptButtonClick())});let s=g.getByFile(this.file);this.encryptionPassword=s.password,s.password.length>0&&this.decryptWithPassword(s.password).then(r=>{r!=null&&(this.currentEditorSourceText=r,this.refreshView(2),new y.Notice("Decrypted using remembered password",2e3))})}async encodeAndSave(){try{let e=await S.encode(this.encryptionPassword,this.hint,this.currentEditorSourceText);this.data=I.encode(e),this.requestSave()}catch(e){console.error(e),new y.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="plaintext-only",n.innerText=this.currentEditorSourceText,n.focus(),n.on("input","*",async(i,s)=>{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"});y.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(d,l,c)=>{let p=this.validatePassword(d),m=this.validateConfirm(d,l);a.setDesc(p),h.setDesc(m),p.length===0&&m.length===0&&(this.encryptionPassword=d,this.hint=c,this.encodeAndSave(),this.refreshView(2),g.putByFile({password:d,hint:c},this.file),new y.Notice("Password and Hint were changed"))},a=E.buildPasswordSetting({container:n,name:"New Password:",autoFocus:!0,onChangeCallback:d=>{i=d,a.setDesc(this.validatePassword(i)),h.setDesc(this.validateConfirm(i,s))},onEnterCallback:d=>{var l;i=d,i.length>0&&((l=h.controlEl.querySelector("input"))==null||l.focus())}}),h=E.buildPasswordSetting({container:n,name:"Confirm:",onChangeCallback:d=>{s=d,a.setDesc(this.validatePassword(i)),h.setDesc(this.validateConfirm(i,s))},onEnterCallback:d=>{var c;s=d,i===s&&((c=f.controlEl.querySelector("input"))==null||c.focus())}}),f=new y.Setting(n).setName("New Hint:").addText(d=>{d.onChange(l=>{r=l})});f.controlEl.on("keydown","*",d=>{d.key==="Enter"&&(d.preventDefault(),o(i,s,r))}),new y.Setting(n).addButton(d=>{d.removeCta().setIcon("cross").setTooltip("Cancel").onClick(()=>{this.refreshView(2)})}).addButton(d=>{d.setCta().setIcon("checkmark").setTooltip("Change Password").setWarning().onClick(l=>{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(),_.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){let n=I.decode(this.data);return await S.decrypt(n,e)}async handleDecryptButtonClick(){let e=await this.decryptWithPassword(this.encryptionPassword);e===null?new y.Notice("Decryption failed"):(g.putByFile({password:this.encryptionPassword,hint:this.hint},this.file),this.currentEditorSourceText=e,this.refreshView(2))}canAcceptExtension(e){return M.contains(e)}getViewType(){return j}setViewData(e,n){if(n){let i;e===""?i=4:i=1,this.encryptionPassword="";let s=I.decode(this.data);this.hint=s.hint,this.refreshView(i)}else this.leaf.detach(),new y.Notice("Multiple views of the same encrypted note isn't supported")}getViewData(){return this.data}clear(){}};var J=class{async onload(t,e){this.plugin=t,this.settings=e.featureWholeNoteEncrypt,this.plugin.addRibbonIcon("file-lock-2","New encrypted note",n=>{this.processCreateNewEncryptedNoteCommand()}),this.plugin.registerView(j,n=>new q(n,this.settings)),this.plugin.registerExtensions(M,j),this.plugin.addCommand({id:"meld-encrypt-create-new-note",name:"Create new encrypted note",icon:"file-lock-2",callback:()=>this.processCreateNewEncryptedNoteCommand()}),this.plugin.addCommand({id:"meld-encrypt-toggle-reading-view",name:"Toggle Reading View",icon:"edit",callback:()=>this.processToggleReadingViewCommand()})}onunload(){this.plugin.app.workspace.detachLeavesOfType(j)}processToggleReadingViewCommand(){let t=this.plugin.app.workspace.getActiveViewOfType(q);t==null||t.toggleReadingView()}processCreateNewEncryptedNoteCommand(){try{let t=(0,D.moment)().format(`[Untitled] YYYYMMDD hhmmss[.${re}]`),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,D.normalizePath)(e.path+"/"+t);this.plugin.app.vault.create(i,"").then(async s=>{await this.plugin.app.workspace.getLeaf(!0).openFile(s)}).catch(s=>{new D.Notice(s,1e4)})}catch(t){console.error(t),new D.Notice(t,1e4)}}buildSettingsUi(t,e){new D.Setting(t).setHeading().setName("Whole Note Encryption Settings"),new D.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()})})}};var v=require("obsidian");var b=require("obsidian");var K=class extends b.Modal{constructor(e,n,i,s,r){super(e);this.resultConfirmed=!1;this.title=n,this.defaultPassword=r,this.confirmPassword=s,this.isEncrypting=i}onOpen(){var h,f,d,l;let{contentEl:e}=this;e.empty(),this.invalidate();let n=(f=(h=this.defaultPassword)==null?void 0:h.password)!=null?f:"",i="",s=(l=(d=this.defaultPassword)==null?void 0:d.hint)!=null?l:"";new b.Setting(e).setHeading().setName(this.title),E.buildPasswordSetting({container:e,name:"Password:",placeholder:this.isEncrypting?"":`Hint: ${s}`,initialValue:n,autoFocus:n=="",onChangeCallback:c=>{n=c,this.invalidate()},onEnterCallback:c=>{if(n=c,this.invalidate(),n.length>0)if(r.settingEl.isShown()){let p=r.components.find(m=>m instanceof b.TextComponent);p instanceof b.TextComponent&&p.inputEl.focus()}else if(o.settingEl.isShown()){let p=o.components.find(m=>m instanceof b.TextComponent);p instanceof b.TextComponent&&p.inputEl.focus()}else a()&&this.close()}});let r=E.buildPasswordSetting({container:e,name:"Confirm Password:",autoFocus:n!="",onChangeCallback:c=>{i=c,this.invalidate()},onEnterCallback:c=>{if(i=c,this.invalidate(),i.length>0&&a()&&o.settingEl.isShown()){let p=o.components.find(m=>m instanceof b.TextComponent);p instanceof b.TextComponent&&p.inputEl.focus()}}});this.confirmPassword||r.settingEl.hide();let o=new b.Setting(e).setName("Optional Password Hint").addText(c=>{c.inputEl.placeholder="Password Hint",c.setValue(s),c.onChange(p=>s=p),c.inputEl.on("keypress","*",(p,m)=>{p.key=="Enter"&&m instanceof HTMLInputElement&&m.value.length>0&&(p.preventDefault(),a()&&this.close())})});this.isEncrypting||o.settingEl.hide(),new b.Setting(e).addButton(c=>{c.setButtonText("Confirm").onClick(p=>{a()&&this.close()})});let a=()=>(this.invalidate(),r.setDesc(""),this.confirmPassword&&n!=i?(r.setDesc("Passwords don't match"),!1):(this.resultConfirmed=!0,this.resultPassword={password:n,hint:s},!0))}openAsync(){return new Promise((e,n)=>{this.onClose=()=>{this.resultConfirmed==!0?e(this.resultPassword):n()},this.open()})}invalidate(){this.resultConfirmed=!1,this.resultPassword={password:"",hint:""}}};var Q=class{async onload(t,e){this.plugin=t,this.plugin.addCommand({id:"meld-encrypt-convert-to-or-from-encrypted-note",name:"Convert to or from an Encrypted note",icon:"file-lock",checkCallback:n=>this.processCommandConvertActiveNote(n)}),this.plugin.addRibbonIcon("file-lock","Convert to or from an Encrypted note",n=>this.processCommandConvertActiveNote(!1)),this.plugin.registerEvent(this.plugin.app.workspace.on("file-menu",(n,i)=>{i instanceof v.TFile&&(i.extension=="md"&&n.addItem(s=>{s.setTitle("Encrypt note").setIcon("file-lock").onClick(()=>this.processCommandEncryptNote(i))}),M.contains(i.extension)&&n.addItem(s=>{s.setTitle("Decrypt note").setIcon("file").onClick(()=>this.processCommandDecryptNote(i))}))}))}onunload(){}buildSettingsUi(t,e){}checkCanEncryptFile(t){return t==null?!1:t.extension=="md"}checkCanDecryptFile(t){return t==null?!1:M.contains(t.extension)}processCommandEncryptNote(t){this.getPasswordAndEncryptFile(t).catch(e=>{e&&new v.Notice(e,1e4)})}processCommandDecryptNote(t){this.getPasswordAndDecryptFile(t).catch(e=>{e&&new v.Notice(e,1e4)})}processCommandConvertActiveNote(t){let e=this.plugin.app.workspace.getActiveFile();if(t)return this.checkCanEncryptFile(e)||this.checkCanDecryptFile(e);(e==null?void 0:e.extension)=="md"&&this.getPasswordAndEncryptFile(e).catch(n=>{n&&new v.Notice(n,1e4)}),e&&M.contains(e.extension)&&this.getPasswordAndDecryptFile(e).catch(n=>{n&&new v.Notice(n,1e4)})}async getPasswordAndEncryptFile(t){if(!this.checkCanEncryptFile(t))throw new Error("Unable to encrypt file");let e=g.getByFile(t),n=new K(app,"Encrypt Note",!0,!0,e);try{let i=await n.openAsync(),s=await this.encryptFile(t,i);await this.closeUpdateRememberPasswordThenReopen(t,re,s,i),new v.Notice("\u{1F510} Note was encrypted \u{1F510}")}catch(i){i&&new v.Notice(i,1e4)}}async getPasswordAndDecryptFile(t){if(!this.checkCanDecryptFile(t))throw new Error("Unable to decrypt file");let e=g.getByFile(t);if(e.password!=""){let r=await this.decryptFile(t,e.password);if(r!=null){await this.closeUpdateRememberPasswordThenReopen(t,"md",r,e);return}}let n=await app.vault.read(t),i=I.decode(n),s=new K(app,"Decrypt Note",!1,!1,{password:"",hint:i.hint});try{if(e=await s.openAsync(),!s.resultConfirmed)return;let r=await this.decryptFile(t,e.password);if(r==null)throw new Error("Decryption failed");await this.closeUpdateRememberPasswordThenReopen(t,"md",r,e),new v.Notice("\u{1F513} Note was decrypted \u{1F513}")}catch(r){r&&new v.Notice(r,1e4)}}async closeUpdateRememberPasswordThenReopen(t,e,n,i){let s=!1;this.plugin.app.workspace.iterateAllLeaves(r=>{r.view instanceof v.TextFileView&&r.view.file==t&&(r.detach(),s=!0)});try{let r=B.getFilePathWithNewExtension(t,e);await app.fileManager.renameFile(t,r),await app.vault.modify(t,n),g.putByFile(i,t)}finally{s&&await app.workspace.getLeaf().openFile(t)}}async encryptFile(t,e){let n=await app.vault.read(t),i=await S.encode(e.password,e.hint,n);return I.encode(i)}async decryptFile(t,e){let n=await app.vault.read(t),i=I.decode(n);return await S.decrypt(i,e)}};var oe=class extends Ce.Plugin{constructor(){super(...arguments);this.enabledFeatures=[]}async onload(){await this.loadSettings(),this.enabledFeatures.push(new J,new Q,new G),this.addSettingTab(new W(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:g.LevelFilename,featureWholeNoteEncrypt:{defaultView:"Source".toString()},featureInplaceEncrypt:{expandToWholeLines:!1,showMarkerWhenReadingDefault:!0}};this.settings=Object.assign(e,await this.loadData()),g.setActive(this.settings.rememberPassword),g.setAutoExpire(this.settings.rememberPasswordTimeout==0?null:this.settings.rememberPasswordTimeout),g.setLevel(this.settings.rememberPasswordLevel)}async saveSettings(){await this.saveData(this.settings)}};