hexo-blog-encrypt 4.0.2 → 4.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/ReadMe.md +34 -19
- package/ReadMe.zh.md +30 -19
- package/lib/hbe.bundle.js +1 -1
- package/lib/hbe.bundle.js.map +3 -3
- package/package.json +1 -1
- package/src/server/template.js +7 -3
package/ReadMe.md
CHANGED
|
@@ -264,36 +264,51 @@ It will be called after the blog is decrypted.
|
|
|
264
264
|
Demo: [Callback Example](https://d0n9x1n.github.io/hexo-blog-encrypt/demo/callback/).
|
|
265
265
|
|
|
266
266
|
### After Decrypt Event
|
|
267
|
-
Thanks to @[f-dong](https://github.com/f-dong), we now will trigger a event named `hexo-blog-decrypt`, so you can add a call back to listen to that event.
|
|
268
267
|
|
|
268
|
+
The plugin dispatches `hexo-blog-decrypt` once on `window` after decryption.
|
|
269
|
+
`event.detail.mode` is `manual` (password entered) or `cached` (saved key).
|
|
270
|
+
Listen for the event rather than dispatching it yourself:
|
|
271
|
+
|
|
272
|
+
```js
|
|
273
|
+
window.addEventListener('hexo-blog-decrypt', function (event) {
|
|
274
|
+
// Reinitialize your theme's table of contents, syntax highlighting, etc.
|
|
275
|
+
console.log('Decrypted:', event.detail.mode);
|
|
276
|
+
});
|
|
269
277
|
```
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
278
|
+
|
|
279
|
+
Since **4.0.3**, ordinary external scripts load in document order before the
|
|
280
|
+
following inline scripts run. This fixes library-dependent initialization such
|
|
281
|
+
as DPlayer. The decrypt event waits for restored external scripts to load, fail,
|
|
282
|
+
or reach a **15-second per-script deadline**. Existing `onload` / `onerror`
|
|
283
|
+
handlers are preserved. A timeout does not cancel a script; it can execute later.
|
|
284
|
+
Explicit `async` scripts still load independently; restored `defer` scripts do
|
|
285
|
+
not recreate a document parsing phase. Inline `type="module"` scripts and
|
|
286
|
+
asynchronous work inside scripts retain native scheduling and are not guaranteed
|
|
287
|
+
to finish before the decrypt event. Use their own readiness signals when needed.
|
|
288
|
+
|
|
289
|
+
Try the [script-loading demo](https://d0n9x1n.github.io/hexo-blog-encrypt/demo/script-order/)
|
|
290
|
+
(password `hello`) for both manual and cached-key decryption.
|
|
274
291
|
|
|
275
292
|
### Encrypt TOC
|
|
276
293
|
|
|
277
|
-
|
|
294
|
+
**Do not render an encrypted post's `post.origin` into generated HTML.** It is
|
|
295
|
+
plaintext retained for legacy Hexo integrations. Hiding a generated TOC with
|
|
296
|
+
`display:none` still exposes its headings. Search and feed integrations must also
|
|
297
|
+
exclude plaintext fields from encrypted posts.
|
|
278
298
|
|
|
279
|
-
|
|
280
|
-
+ Find the code like <% post.content %>, which is usually at line 30.
|
|
281
|
-
+ Replace the <% post.content %> with the following code block:
|
|
299
|
+
Generate a server-side TOC only for unencrypted posts. For example:
|
|
282
300
|
|
|
283
|
-
```
|
|
284
|
-
<% if(post.toc
|
|
285
|
-
<div
|
|
286
|
-
<strong class="toc-title">Index</strong>
|
|
287
|
-
<% if (post.encrypt == true) { %>
|
|
288
|
-
<%- toc(post.origin, {list_number: true}) %>
|
|
289
|
-
<% } else { %>
|
|
290
|
-
<%- toc(post.content, {list_number: true}) %>
|
|
291
|
-
<% } %>
|
|
292
|
-
</div>
|
|
301
|
+
```ejs
|
|
302
|
+
<% if (post.toc === true && !post.encrypt) { %>
|
|
303
|
+
<div class="toc-article"><%- toc(post.content, {list_number: true}) %></div>
|
|
293
304
|
<% } %>
|
|
294
305
|
<%- post.content %>
|
|
295
306
|
```
|
|
296
307
|
|
|
308
|
+
For encrypted posts, use your theme's client-side TOC initializer inside the
|
|
309
|
+
`hexo-blog-decrypt` callback, reading the revealed `#hexo-blog-encrypt` content
|
|
310
|
+
rather than publishing a hidden plaintext TOC.
|
|
311
|
+
|
|
297
312
|
### Disable logging
|
|
298
313
|
If you want to disable the logging, you can add a silent property in `_config.yml` and set it to true.
|
|
299
314
|
|
package/ReadMe.zh.md
CHANGED
|
@@ -252,36 +252,47 @@ It will be called after the blog decrypted.
|
|
|
252
252
|
例子在: [Callback 例子](https://d0n9x1n.github.io/hexo-blog-encrypt/demo/callback/).
|
|
253
253
|
|
|
254
254
|
### 解密后的触发事件
|
|
255
|
-
感谢 @[f-dong](https://github.com/f-dong), 我们现在会在解密完成后触发一个 `hexo-blog-decrypt` 事件, 你们可以编写 callback 来监听该事件.
|
|
256
255
|
|
|
256
|
+
插件在解密后向 `window` 发送一次 `hexo-blog-decrypt` 事件。
|
|
257
|
+
`event.detail.mode` 为 `manual`(输入密码)或 `cached`(使用缓存密钥)。
|
|
258
|
+
请监听事件,而不是手动触发:
|
|
259
|
+
|
|
260
|
+
```js
|
|
261
|
+
window.addEventListener('hexo-blog-decrypt', function (event) {
|
|
262
|
+
// 在这里重新初始化主题中的目录、代码高亮等功能。
|
|
263
|
+
console.log('Decrypted:', event.detail.mode);
|
|
264
|
+
});
|
|
257
265
|
```
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
266
|
+
|
|
267
|
+
从 **4.0.3** 起,普通外部脚本按文章中的顺序加载完成后,才执行后续内联脚本。
|
|
268
|
+
这解决了 DPlayer 等组件在其依赖库尚未加载时就初始化的问题。
|
|
269
|
+
外部脚本加载成功、失败或达到每个脚本 **15 秒** 的等待上限后,才发送解密事件;
|
|
270
|
+
原有 `onload` / `onerror` 处理函数保持不变。超时不等于取消,脚本可能稍后执行。
|
|
271
|
+
带有显式 `async` 的外部脚本仍独立加载;动态恢复的 `defer` 不会重新产生页面解析阶段。
|
|
272
|
+
内联 `type="module"` 脚本及脚本内部的异步任务保留浏览器原生时序,不保证在解密事件前完成。
|
|
273
|
+
依赖这些任务时,请使用它们自己的就绪信号。
|
|
274
|
+
|
|
275
|
+
[脚本加载顺序示例](https://d0n9x1n.github.io/hexo-blog-encrypt/demo/script-order/)
|
|
276
|
+
(密码 `hello`)同时展示普通解密与缓存密钥解密。
|
|
262
277
|
|
|
263
278
|
### 对 TOC 进行加密
|
|
264
279
|
|
|
265
|
-
|
|
280
|
+
**不要在生成页面时将加密文章的 `post.origin` 渲染到 HTML 中。**
|
|
281
|
+
它是供旧版 Hexo 集成使用的明文;即使用 `display:none` 隐藏目录,标题仍会泄露。
|
|
282
|
+
搜索和 feed 插件也必须排除加密文章的明文字段。
|
|
266
283
|
|
|
267
|
-
|
|
268
|
-
+ 然后找到 <% post.content %> 这段代码,通常在30行左右。
|
|
269
|
-
+ 使用如下的代码来替代它:
|
|
284
|
+
在主题模板中,仅为未加密文章生成服务端目录。例如:
|
|
270
285
|
|
|
271
|
-
```
|
|
272
|
-
<% if(post.toc
|
|
273
|
-
<div
|
|
274
|
-
<strong class="toc-title">Index</strong>
|
|
275
|
-
<% if (post.encrypt == true) { %>
|
|
276
|
-
<%- toc(post.origin, {list_number: true}) %>
|
|
277
|
-
<% } else { %>
|
|
278
|
-
<%- toc(post.content, {list_number: true}) %>
|
|
279
|
-
<% } %>
|
|
280
|
-
</div>
|
|
286
|
+
```ejs
|
|
287
|
+
<% if (post.toc === true && !post.encrypt) { %>
|
|
288
|
+
<div class="toc-article"><%- toc(post.content, {list_number: true}) %></div>
|
|
281
289
|
<% } %>
|
|
282
290
|
<%- post.content %>
|
|
283
291
|
```
|
|
284
292
|
|
|
293
|
+
加密文章的目录应在 `hexo-blog-decrypt` 回调中,使用解密后的
|
|
294
|
+
`#hexo-blog-encrypt` 内容和主题的客户端目录功能生成,而不是发布隐藏的明文目录。
|
|
295
|
+
|
|
285
296
|
### 禁用 Log
|
|
286
297
|
If you want to disable the logging, you can add a silent property in `_config.yml` and set it to true.
|
|
287
298
|
如果你想要禁止使用 Log, 你可以在 `_config.yml` 中增加一个 silent 属性, 并将其设置为 true.
|
package/lib/hbe.bundle.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";(()=>{var
|
|
1
|
+
"use strict";(()=>{var p=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var m=p((ot,x)=>{"use strict";function D(e,t){if(!e)return;e.setAttribute("aria-busy",t?"true":"false");let n=e.querySelector(".hbe-button");n&&(n.disabled=!!t);let r=e.querySelector("#hbePass");r&&(r.disabled=!!t)}function B(e,t){let n=e.querySelector('[role="alert"]');if(!n){n=document.createElement("div"),n.setAttribute("role","alert"),n.className="hbe hbe-error";let r=e.querySelector("#hbeForm");r?r.parentNode.insertBefore(n,r.nextSibling):e.appendChild(n)}n.textContent=t}function k(e){let t=e.querySelector('[role="alert"]');t&&(t.textContent="")}function M(e){let t=e.querySelector("#hbePass");return t?t.value:""}function P(e,t){e&&e.addEventListener("submit",n=>{n.preventDefault(),t()})}x.exports={setBusy:D,showError:B,clearError:k,readPassword:M,attachSubmit:P}});var b=p((at,w)=>{"use strict";var O=new TextDecoder("utf-8",{fatal:!0}),K=new TextEncoder;function u(e){let t=e.length;if(t%2!==0)throw new Error("hexo-blog-encrypt: hex string has odd length");let n=new Uint8Array(t/2);for(let r=0;r<n.length;r++)n[r]=parseInt(e.substr(r*2,2),16);return n}async function g(e,t,n){let r=await crypto.subtle.importKey("raw",K.encode(e),{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:t,iterations:n,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!0,["decrypt"])}async function y(e,t,n){let r=await crypto.subtle.decrypt({name:"AES-GCM",iv:t,tagLength:128},e,n);return O.decode(r)}async function L({password:e,saltHex:t,nonceHex:n,ciphertextHex:r,iterations:o}){try{let a=u(t),c=u(n),i=u(r);if(i.length<16)return{ok:!1};let d=await g(e,a,o);return{ok:!0,plaintext:await y(d,c,i),key:d}}catch(a){return{ok:!1}}}async function R({key:e,nonceHex:t,ciphertextHex:n}){try{let r=u(t),o=u(n);return o.length<16?{ok:!1}:{ok:!0,plaintext:await y(e,r,o)}}catch(r){return{ok:!1}}}w.exports={tryDecryptWithPassword:L,tryDecryptWithKey:R,deriveKey:g,decryptWithKey:y,hexToBytes:u}});var T=p((ct,v)=>{"use strict";var q=/^(?:application|text)\/(?:x-)?(?:java|ecma)script$|^text\/(?:javascript1\.[0-5]|jscript|livescript)$/i;function S(e){let t=document.createElement("script");for(let n of e.attributes)t.setAttribute(n.name,n.value);return e.nonce&&(t.nonce=e.nonce),t.text=e.text,t}function E(e){let t=document.createElement("div");return t.innerHTML=e,t}function N(e){let t=e.getAttribute("type");if(t===null){let o=e.getAttribute("language");t=o?"text/"+o:""}let n=t.toLowerCase();if(n==="module")return"module";if(n==="importmap"||n==="speculationrules")return"declarative";let r=t.replace(/^[\t\n\f\r ]+|[\t\n\f\r ]+$/g,"");return t===""||q.test(r)?"classic":"data"}function G(e,t,n){return n?new Promise(r=>{let o=()=>{clearTimeout(a),t.removeEventListener("load",o),t.removeEventListener("error",o),r()},a=setTimeout(()=>{console.warn("hexo-blog-encrypt: timed out waiting for a decrypted script to load."),o()},15e3);t.addEventListener("load",o),t.addEventListener("error",o),e.parentNode.replaceChild(t,e)}):(e.parentNode.replaceChild(t,e),Promise.resolve())}async function F(e){let t=[],n="noModule"in document.createElement("script");for(let r of e.querySelectorAll("script")){if(!e.contains(r))continue;let o=N(r);if(o==="data"||o==="classic"&&r.noModule&&n||o==="module"&&!n)continue;let a=S(r),c=o!=="declarative"&&a.hasAttribute("src"),i=c&&a.hasAttribute("async");o==="classic"&&c&&!i&&(a.async=!1);let d=G(r,a,c);i?t.push(d):await d}await Promise.all(t)}async function W(e,t){let n=E(t);return n.id="hexo-blog-encrypt",n.classList.add("hbe","hbe-decrypted-content"),e.parentNode.replaceChild(n,e),await F(n),n}v.exports={getExecutableScript:S,convertHTMLToElement:E,swapInDecryptedDOM:W}});var I=p((st,_)=>{"use strict";var A="hbe.v4.";function l(e){return A+e}function Y(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function U(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}async function V({pageKey:e,key:t,saltHex:n,nonceHex:r,autoSave:o}){if(o)try{let a=await crypto.subtle.exportKey("raw",t),c={version:4,dk:Y(new Uint8Array(a)),salt:n,nonce:r};localStorage.setItem(l(e),JSON.stringify(c))}catch(a){}}async function j({pageKey:e,expectedSaltHex:t}){let n;try{let r=localStorage.getItem(l(e));if(!r)return null;n=JSON.parse(r)}catch(r){return null}if(!n||n.version!==4||typeof n.dk!="string"||typeof n.salt!="string"||typeof n.nonce!="string"||"hmk"in n||"hmacDigest"in n){try{localStorage.removeItem(l(e))}catch(r){}return null}if(n.salt!==t){try{localStorage.removeItem(l(e))}catch(r){}return null}try{let r=U(n.dk);return await crypto.subtle.importKey("raw",r,{name:"AES-GCM"},!0,["decrypt"])}catch(r){try{localStorage.removeItem(l(e))}catch(o){}return null}}function J(e){try{localStorage.removeItem(l(e))}catch(t){}}_.exports={save:V,load:j,clear:J,STORAGE_KEY_PREFIX:A,SCHEMA_VERSION:4}});var s=m(),C=b(),X=T(),f=I(),$="4";function z(e){let t=e.dataset,n=e.querySelector("script#hbeData");return{format:t.hbeFormat,wpm:t.wpm||"Wrong password.",whm:t.whm||t.wpm||"Wrong password.",saltHex:t.salt,nonceHex:t.nonce,iterations:parseInt(t.kdfIterations,10)||25e4,autoSave:t.autoSave==="true",ciphertextHex:n?n.textContent.trim():""}}function Q(e){try{window.dispatchEvent(new CustomEvent("hexo-blog-decrypt",{detail:{mode:e}}))}catch(t){try{window.dispatchEvent(new Event("hexo-blog-decrypt"))}catch(n){}}}function h(){return location.pathname+location.search}async function Z(e,t,n){await X.swapInDecryptedDOM(e,t),Q(n)}async function tt(e,t,n){if(!t.autoSave)return!1;let r=await f.load({pageKey:h(),expectedSaltHex:t.saltHex});if(!r)return!1;let o=await C.tryDecryptWithKey({key:r,nonceHex:t.nonceHex,ciphertextHex:t.ciphertextHex});return o.ok?(await n(o.plaintext,"cached"),!0):(f.clear(h()),!1)}async function et(e,t,n,r){s.clearError(e),s.setBusy(n,!0);let o=s.readPassword(n);if(!o){s.setBusy(n,!1),s.showError(e,t.wpm);return}let a;try{a=await C.tryDecryptWithPassword({password:o,saltHex:t.saltHex,nonceHex:t.nonceHex,ciphertextHex:t.ciphertextHex,iterations:t.iterations})}finally{s.setBusy(n,!1)}if(!a.ok){s.showError(e,t.wpm);return}t.autoSave&&await f.save({pageKey:h(),key:a.key,saltHex:t.saltHex,nonceHex:t.nonceHex,autoSave:!0}),await r(a.plaintext,"manual")}async function H(){let e=document.getElementById("hexo-blog-encrypt");if(!e)return;let t=z(e);if(t.format!==$){s.showError(e,"hexo-blog-encrypt: this page was built with an incompatible plugin version. Rebuild the site after upgrading the plugin.");return}let n=!1,r=async(c,i)=>{n||(n=!0,await Z(e,c,i))},o=e.querySelector("#hbeForm");if(s.attachSubmit(o,()=>et(e,t,o,r)),!await tt(e,t,r)&&!n){let c=e.querySelector("#hbePass");c&&c.focus()}}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",H):H();})();
|
|
2
2
|
//# sourceMappingURL=hbe.bundle.js.map
|
package/lib/hbe.bundle.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/browser/ui.js", "../src/browser/crypto.js", "../src/browser/dom.js", "../src/browser/storage.js", "../src/browser/main.js"],
|
|
4
|
-
"sourcesContent": ["'use strict';\n\n// Wires the encrypted-post UI: form submit (Enter + click both fire),\n// `aria-busy` during async derivation, and an inline `[role=\"alert\"]` for\n// errors (NO `alert()` calls \u2014 feature-crew critique blocked dialog UX).\n\nfunction setBusy(form, busy) {\n if (!form) return;\n form.setAttribute('aria-busy', busy ? 'true' : 'false');\n const button = form.querySelector('.hbe-button');\n if (button) {\n button.disabled = !!busy;\n }\n const input = form.querySelector('#hbePass');\n if (input) {\n input.disabled = !!busy;\n }\n}\n\nfunction showError(mainElement, message) {\n let alert = mainElement.querySelector('[role=\"alert\"]');\n if (!alert) {\n alert = document.createElement('div');\n alert.setAttribute('role', 'alert');\n alert.className = 'hbe hbe-error';\n const form = mainElement.querySelector('#hbeForm');\n if (form) form.parentNode.insertBefore(alert, form.nextSibling);\n else mainElement.appendChild(alert);\n }\n alert.textContent = message;\n}\n\nfunction clearError(mainElement) {\n const alert = mainElement.querySelector('[role=\"alert\"]');\n if (alert) alert.textContent = '';\n}\n\nfunction readPassword(form) {\n const input = form.querySelector('#hbePass');\n return input ? input.value : '';\n}\n\nfunction attachSubmit(form, handler) {\n if (!form) return;\n form.addEventListener('submit', (event) => {\n event.preventDefault();\n handler();\n });\n}\n\nmodule.exports = {\n setBusy,\n showError,\n clearError,\n readPassword,\n attachSubmit,\n};\n", "'use strict';\n\n// Browser-side AES-256-GCM decryption with PBKDF2-SHA256 key derivation.\n// Mirrors the server-side parameters in `src/server/crypto.js`:\n// - PBKDF2: SHA-256, configurable iterations (read from data-kdf-iterations)\n// - AES: 256-bit key, GCM mode, 12-byte nonce, 16-byte auth tag\n//\n// Unified failure path: ANY thrown value (DOMException OperationError,\n// TypeError, etc.) collapses to {ok: false}. Wrong-password and\n// tampered-ciphertext are indistinguishable under GCM by design.\n\nconst KEY_BITS = 256;\nconst TAG_BITS = 128;\nconst TAG_BYTES = TAG_BITS / 8;\nconst TEXT_DECODER = new TextDecoder('utf-8', { fatal: true });\nconst TEXT_ENCODER = new TextEncoder();\n\nfunction hexToBytes(hex) {\n const len = hex.length;\n if (len % 2 !== 0) {\n throw new Error('hexo-blog-encrypt: hex string has odd length');\n }\n const out = new Uint8Array(len / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.substr(i * 2, 2), 16);\n }\n return out;\n}\n\nasync function deriveKey(password, salt, iterations) {\n const baseKey = await crypto.subtle.importKey(\n 'raw',\n TEXT_ENCODER.encode(password),\n { name: 'PBKDF2' },\n false,\n ['deriveKey']\n );\n return crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt,\n iterations,\n hash: 'SHA-256',\n },\n baseKey,\n { name: 'AES-GCM', length: KEY_BITS },\n true, // extractable=true so storage.js can persist the raw key bytes when autoSave is on\n ['decrypt']\n );\n}\n\nasync function decryptWithKey(key, nonce, ciphertextWithTag) {\n // Web Crypto AES-GCM expects ciphertext||tag as a single buffer (same as Node's\n // `decipher.update + setAuthTag(tag); decipher.final()` flow when concatenated).\n const plainBuf = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: nonce, tagLength: TAG_BITS },\n key,\n ciphertextWithTag\n );\n return TEXT_DECODER.decode(plainBuf);\n}\n\n// High-level: derive a key from the password + decrypt in one shot.\n// Returns {ok: true, plaintext, key} or {ok: false}.\nasync function tryDecryptWithPassword({ password, saltHex, nonceHex, ciphertextHex, iterations }) {\n try {\n const salt = hexToBytes(saltHex);\n const nonce = hexToBytes(nonceHex);\n const ciphertext = hexToBytes(ciphertextHex);\n if (ciphertext.length < TAG_BYTES) return { ok: false };\n const key = await deriveKey(password, salt, iterations);\n const plaintext = await decryptWithKey(key, nonce, ciphertext);\n return { ok: true, plaintext, key };\n } catch (_e) {\n return { ok: false };\n }\n}\n\n// Same shape, but reuses an already-derived key (autosave fast path).\nasync function tryDecryptWithKey({ key, nonceHex, ciphertextHex }) {\n try {\n const nonce = hexToBytes(nonceHex);\n const ciphertext = hexToBytes(ciphertextHex);\n if (ciphertext.length < TAG_BYTES) return { ok: false };\n const plaintext = await decryptWithKey(key, nonce, ciphertext);\n return { ok: true, plaintext };\n } catch (_e) {\n return { ok: false };\n }\n}\n\nmodule.exports = {\n tryDecryptWithPassword,\n tryDecryptWithKey,\n deriveKey,\n decryptWithKey,\n hexToBytes,\n};\n", "'use strict';\n\n// DOM helpers preserved from v3 (`getExecutableScript` + `convertHTMLToElement`):\n// when ciphertext decrypts to HTML containing `<script>` tags, the browser does\n// NOT execute scripts inserted via `innerHTML`. We re-create them as live <script>\n// elements so the decrypted post behaves like a normal Hexo-rendered post.\n\nfunction getExecutableScript(oldScriptElement) {\n const newScript = document.createElement('script');\n for (const attr of oldScriptElement.attributes) {\n newScript.setAttribute(attr.name, attr.value);\n }\n newScript.text = oldScriptElement.text;\n return newScript;\n}\n\nfunction convertHTMLToElement(htmlString) {\n const wrapper = document.createElement('div');\n wrapper.innerHTML = htmlString;\n // Replace each <script> with a live, executable element.\n for (const oldScript of wrapper.querySelectorAll('script')) {\n oldScript.parentNode.replaceChild(getExecutableScript(oldScript), oldScript);\n }\n return wrapper;\n}\n\n// Replace the encrypted wrapper with the decrypted DOM. Returns the new container\n// so callers can inspect / dispatch events on it.\nfunction swapInDecryptedDOM(mainElement, plaintextHTML) {\n const decrypted = convertHTMLToElement(plaintextHTML);\n decrypted.id = 'hexo-blog-encrypt';\n decrypted.classList.add('hbe', 'hbe-decrypted-content');\n mainElement.parentNode.replaceChild(decrypted, mainElement);\n return decrypted;\n}\n\nmodule.exports = {\n getExecutableScript,\n convertHTMLToElement,\n swapInDecryptedDOM,\n};\n", "'use strict';\n\n// Per-post localStorage entry storing the derived AES key + the salt/nonce that\n// produced the corresponding ciphertext. On reload we re-import the key and\n// attempt decryption silently; the user is never re-prompted.\n//\n// Schema (v4):\n// {\n// version: 4,\n// dk: base64(rawKeyBytes), // 32 bytes\n// salt: <hex64>, // matches data-salt\n// nonce: <hex24>, // retained for v4 schema compatibility\n// }\n//\n// IMPORTANT: when `autoSave` is false, save() is a no-op. When reading, any\n// entry with a non-4 version (or v3 leftovers like `hmk`/`hmacDigest`) is\n// purged + ignored.\n\nconst STORAGE_KEY_PREFIX = 'hbe.v4.';\nconst SCHEMA_VERSION = 4;\n\nfunction storageKey(pageKey) {\n return STORAGE_KEY_PREFIX + pageKey;\n}\n\nfunction bytesToBase64(bytes) {\n let bin = '';\n for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);\n return btoa(bin);\n}\n\nfunction base64ToBytes(b64) {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nasync function save({ pageKey, key, saltHex, nonceHex, autoSave }) {\n if (!autoSave) return;\n try {\n const raw = await crypto.subtle.exportKey('raw', key);\n const entry = {\n version: SCHEMA_VERSION,\n dk: bytesToBase64(new Uint8Array(raw)),\n salt: saltHex,\n nonce: nonceHex,\n };\n localStorage.setItem(storageKey(pageKey), JSON.stringify(entry));\n } catch (_e) {\n // localStorage.setItem can throw QuotaExceededError or SecurityError\n // (private mode, disabled storage). Silently ignore \u2014 autoSave is\n // best-effort UX.\n }\n}\n\nasync function load({ pageKey, expectedSaltHex }) {\n let entry;\n try {\n const raw = localStorage.getItem(storageKey(pageKey));\n if (!raw) return null;\n entry = JSON.parse(raw);\n } catch (_e) {\n return null;\n }\n\n // Purge stale or v3 entries.\n if (\n !entry\n || entry.version !== SCHEMA_VERSION\n || typeof entry.dk !== 'string'\n || typeof entry.salt !== 'string'\n || typeof entry.nonce !== 'string'\n || 'hmk' in entry\n || 'hmacDigest' in entry\n ) {\n try { localStorage.removeItem(storageKey(pageKey)); } catch (_e) { /* ignore */ }\n return null;\n }\n\n // If the encrypted page's salt changed, the cached key is stale. Nonce is\n // not part of PBKDF2 key derivation; decrypt still uses the current page's\n // nonce and ciphertext, and failure clears the cache in main.js.\n if (entry.salt !== expectedSaltHex) {\n try { localStorage.removeItem(storageKey(pageKey)); } catch (_e) { /* ignore */ }\n return null;\n }\n\n try {\n const rawBytes = base64ToBytes(entry.dk);\n const key = await crypto.subtle.importKey(\n 'raw',\n rawBytes,\n { name: 'AES-GCM' },\n true,\n ['decrypt']\n );\n return key;\n } catch (_e) {\n try { localStorage.removeItem(storageKey(pageKey)); } catch (_e2) { /* ignore */ }\n return null;\n }\n}\n\nfunction clear(pageKey) {\n try { localStorage.removeItem(storageKey(pageKey)); } catch (_e) { /* ignore */ }\n}\n\nmodule.exports = {\n save,\n load,\n clear,\n STORAGE_KEY_PREFIX,\n SCHEMA_VERSION,\n};\n", "'use strict';\n\n// Browser entry point. Reads the wire-format from the encrypted-post wrapper,\n// drives the UI via `ui.js`, derives & decrypts via `crypto.js`, and persists\n// the derived key (when autoSave is on) via `storage.js`.\n\nconst ui = require('./ui');\nconst cryptoMod = require('./crypto');\nconst dom = require('./dom');\nconst storage = require('./storage');\n\nconst SUPPORTED_FORMAT = '4';\n\nfunction readWireFormat(mainElement) {\n const ds = mainElement.dataset;\n const ciphertextNode = mainElement.querySelector('script#hbeData');\n return {\n format: ds.hbeFormat,\n wpm: ds.wpm || 'Wrong password.',\n whm: ds.whm || ds.wpm || 'Wrong password.',\n saltHex: ds.salt,\n nonceHex: ds.nonce,\n iterations: parseInt(ds.kdfIterations, 10) || 250000,\n autoSave: ds.autoSave === 'true',\n ciphertextHex: ciphertextNode ? ciphertextNode.textContent.trim() : '',\n };\n}\n\nfunction dispatchDecryptEvent(mode) {\n // Fire on `window` for v3 back-compat \u2014 both READMEs document\n // `window.addEventListener('hexo-blog-decrypt', fn)` as the public API.\n // Old listeners that only access `e.type` continue to work; new listeners\n // can additionally read `e.detail.mode` ('manual' | 'cached').\n try {\n window.dispatchEvent(new CustomEvent('hexo-blog-decrypt', { detail: { mode } }));\n } catch (_e) {\n // CustomEvent constructor unavailable on very old browsers \u2014 fall back\n // to plain Event (no detail).\n try {\n window.dispatchEvent(new Event('hexo-blog-decrypt'));\n } catch (_e2) { /* ignore \u2014 no event API at all */ }\n }\n}\n\nfunction pageKey() {\n // Per-URL bucket so different encrypted posts don't collide in localStorage.\n return location.pathname + location.search;\n}\n\nasync function reveal(mainElement, plaintext, mode) {\n dom.swapInDecryptedDOM(mainElement, plaintext);\n dispatchDecryptEvent(mode);\n}\n\nasync function tryAutoDecrypt(mainElement, wire, guardedReveal) {\n if (!wire.autoSave) return false;\n const cachedKey = await storage.load({\n pageKey: pageKey(),\n expectedSaltHex: wire.saltHex,\n });\n if (!cachedKey) return false;\n const result = await cryptoMod.tryDecryptWithKey({\n key: cachedKey,\n nonceHex: wire.nonceHex,\n ciphertextHex: wire.ciphertextHex,\n });\n if (!result.ok) {\n storage.clear(pageKey());\n return false;\n }\n await guardedReveal(result.plaintext, 'cached');\n return true;\n}\n\nasync function handleSubmit(mainElement, wire, form, guardedReveal) {\n ui.clearError(mainElement);\n ui.setBusy(form, true);\n const password = ui.readPassword(form);\n if (!password) {\n ui.setBusy(form, false);\n ui.showError(mainElement, wire.wpm);\n return;\n }\n let result;\n try {\n result = await cryptoMod.tryDecryptWithPassword({\n password,\n saltHex: wire.saltHex,\n nonceHex: wire.nonceHex,\n ciphertextHex: wire.ciphertextHex,\n iterations: wire.iterations,\n });\n } finally {\n ui.setBusy(form, false);\n }\n if (!result.ok) {\n ui.showError(mainElement, wire.wpm);\n return;\n }\n if (wire.autoSave) {\n await storage.save({\n pageKey: pageKey(),\n key: result.key,\n saltHex: wire.saltHex,\n nonceHex: wire.nonceHex,\n autoSave: true,\n });\n }\n await guardedReveal(result.plaintext, 'manual');\n}\n\nasync function bootstrap() {\n const mainElement = document.getElementById('hexo-blog-encrypt');\n if (!mainElement) return;\n const wire = readWireFormat(mainElement);\n\n if (wire.format !== SUPPORTED_FORMAT) {\n ui.showError(\n mainElement,\n 'hexo-blog-encrypt: this page was built with an incompatible plugin version. ' +\n 'Rebuild the site after upgrading the plugin.'\n );\n return;\n }\n\n // Single-shot reveal guard: with autoSave on, `tryAutoDecrypt` runs in\n // parallel with the form submit handler. If the user types fast enough\n // to submit BEFORE auto-decrypt resolves, both paths can call `reveal`\n // on the same `mainElement` \u2014 the second `replaceChild` would throw\n // because the wrapper is already detached. The guard makes whoever\n // wins the race the sole DOM-mutator.\n let revealed = false;\n const guardedReveal = async (plaintext, mode) => {\n if (revealed) return;\n revealed = true;\n await reveal(mainElement, plaintext, mode);\n };\n\n const form = mainElement.querySelector('#hbeForm');\n ui.attachSubmit(form, () => handleSubmit(mainElement, wire, form, guardedReveal));\n\n const auto = await tryAutoDecrypt(mainElement, wire, guardedReveal);\n if (!auto && !revealed) {\n const input = mainElement.querySelector('#hbePass');\n if (input) input.focus();\n }\n}\n\nif (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', bootstrap);\n} else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AE,GAAI,EAAM,CACrB,CACF,CAGA,eAAeC,EAAkB,CAAE,IAAAV,EAAK,SAAAM,EAAU,cAAAC,CAAc,EAAG,CACjE,GAAI,CACF,IAAMN,EAAQZ,EAAWiB,CAAQ,EAC3BE,EAAanB,EAAWkB,CAAa,EAC3C,OAAIC,EAAW,OAAS,GAAkB,CAAE,GAAI,EAAM,EAE/C,CAAE,GAAI,GAAM,UADD,MAAMT,EAAeC,EAAKC,EAAOO,CAAU,CAChC,CAC/B,OAASC,EAAI,CACX,MAAO,CAAE,GAAI,EAAM,CACrB,CACF,CAEAvB,EAAO,QAAU,CACf,uBAAAkB,EACA,kBAAAM,EACA,UAAAhB,EACA,eAAAK,EACA,WAAAV,CACF,ICjGA,IAAAsB,EAAAC,EAAA,CAAAC,GAAAC,IAAA,
|
|
6
|
-
"names": ["require_ui", "__commonJSMin", "exports", "module", "setBusy", "form", "busy", "button", "input", "showError", "mainElement", "message", "alert", "clearError", "readPassword", "attachSubmit", "handler", "event", "require_crypto", "__commonJSMin", "exports", "module", "TEXT_DECODER", "TEXT_ENCODER", "hexToBytes", "hex", "len", "out", "i", "deriveKey", "password", "salt", "iterations", "baseKey", "decryptWithKey", "key", "nonce", "ciphertextWithTag", "plainBuf", "tryDecryptWithPassword", "saltHex", "nonceHex", "ciphertextHex", "ciphertext", "_e", "tryDecryptWithKey", "require_dom", "__commonJSMin", "exports", "module", "getExecutableScript", "oldScriptElement", "newScript", "attr", "convertHTMLToElement", "htmlString", "wrapper", "oldScript", "swapInDecryptedDOM", "mainElement", "plaintextHTML", "decrypted", "require_storage", "__commonJSMin", "exports", "module", "STORAGE_KEY_PREFIX", "storageKey", "pageKey", "bytesToBase64", "bytes", "bin", "i", "base64ToBytes", "b64", "out", "save", "key", "saltHex", "nonceHex", "autoSave", "raw", "entry", "_e", "load", "expectedSaltHex", "rawBytes", "_e2", "clear", "ui", "cryptoMod", "dom", "storage", "SUPPORTED_FORMAT", "readWireFormat", "mainElement", "ds", "ciphertextNode", "dispatchDecryptEvent", "mode", "_e", "_e2", "pageKey", "reveal", "plaintext", "tryAutoDecrypt", "wire", "guardedReveal", "cachedKey", "result", "handleSubmit", "form", "password", "bootstrap", "revealed", "input"]
|
|
4
|
+
"sourcesContent": ["'use strict';\n\n// Wires the encrypted-post UI: form submit (Enter + click both fire),\n// `aria-busy` during async derivation, and an inline `[role=\"alert\"]` for\n// errors (NO `alert()` calls \u2014 feature-crew critique blocked dialog UX).\n\nfunction setBusy(form, busy) {\n if (!form) return;\n form.setAttribute('aria-busy', busy ? 'true' : 'false');\n const button = form.querySelector('.hbe-button');\n if (button) {\n button.disabled = !!busy;\n }\n const input = form.querySelector('#hbePass');\n if (input) {\n input.disabled = !!busy;\n }\n}\n\nfunction showError(mainElement, message) {\n let alert = mainElement.querySelector('[role=\"alert\"]');\n if (!alert) {\n alert = document.createElement('div');\n alert.setAttribute('role', 'alert');\n alert.className = 'hbe hbe-error';\n const form = mainElement.querySelector('#hbeForm');\n if (form) form.parentNode.insertBefore(alert, form.nextSibling);\n else mainElement.appendChild(alert);\n }\n alert.textContent = message;\n}\n\nfunction clearError(mainElement) {\n const alert = mainElement.querySelector('[role=\"alert\"]');\n if (alert) alert.textContent = '';\n}\n\nfunction readPassword(form) {\n const input = form.querySelector('#hbePass');\n return input ? input.value : '';\n}\n\nfunction attachSubmit(form, handler) {\n if (!form) return;\n form.addEventListener('submit', (event) => {\n event.preventDefault();\n handler();\n });\n}\n\nmodule.exports = {\n setBusy,\n showError,\n clearError,\n readPassword,\n attachSubmit,\n};\n", "'use strict';\n\n// Browser-side AES-256-GCM decryption with PBKDF2-SHA256 key derivation.\n// Mirrors the server-side parameters in `src/server/crypto.js`:\n// - PBKDF2: SHA-256, configurable iterations (read from data-kdf-iterations)\n// - AES: 256-bit key, GCM mode, 12-byte nonce, 16-byte auth tag\n//\n// Unified failure path: ANY thrown value (DOMException OperationError,\n// TypeError, etc.) collapses to {ok: false}. Wrong-password and\n// tampered-ciphertext are indistinguishable under GCM by design.\n\nconst KEY_BITS = 256;\nconst TAG_BITS = 128;\nconst TAG_BYTES = TAG_BITS / 8;\nconst TEXT_DECODER = new TextDecoder('utf-8', { fatal: true });\nconst TEXT_ENCODER = new TextEncoder();\n\nfunction hexToBytes(hex) {\n const len = hex.length;\n if (len % 2 !== 0) {\n throw new Error('hexo-blog-encrypt: hex string has odd length');\n }\n const out = new Uint8Array(len / 2);\n for (let i = 0; i < out.length; i++) {\n out[i] = parseInt(hex.substr(i * 2, 2), 16);\n }\n return out;\n}\n\nasync function deriveKey(password, salt, iterations) {\n const baseKey = await crypto.subtle.importKey(\n 'raw',\n TEXT_ENCODER.encode(password),\n { name: 'PBKDF2' },\n false,\n ['deriveKey']\n );\n return crypto.subtle.deriveKey(\n {\n name: 'PBKDF2',\n salt,\n iterations,\n hash: 'SHA-256',\n },\n baseKey,\n { name: 'AES-GCM', length: KEY_BITS },\n true, // extractable=true so storage.js can persist the raw key bytes when autoSave is on\n ['decrypt']\n );\n}\n\nasync function decryptWithKey(key, nonce, ciphertextWithTag) {\n // Web Crypto AES-GCM expects ciphertext||tag as a single buffer (same as Node's\n // `decipher.update + setAuthTag(tag); decipher.final()` flow when concatenated).\n const plainBuf = await crypto.subtle.decrypt(\n { name: 'AES-GCM', iv: nonce, tagLength: TAG_BITS },\n key,\n ciphertextWithTag\n );\n return TEXT_DECODER.decode(plainBuf);\n}\n\n// High-level: derive a key from the password + decrypt in one shot.\n// Returns {ok: true, plaintext, key} or {ok: false}.\nasync function tryDecryptWithPassword({ password, saltHex, nonceHex, ciphertextHex, iterations }) {\n try {\n const salt = hexToBytes(saltHex);\n const nonce = hexToBytes(nonceHex);\n const ciphertext = hexToBytes(ciphertextHex);\n if (ciphertext.length < TAG_BYTES) return { ok: false };\n const key = await deriveKey(password, salt, iterations);\n const plaintext = await decryptWithKey(key, nonce, ciphertext);\n return { ok: true, plaintext, key };\n } catch (_e) {\n return { ok: false };\n }\n}\n\n// Same shape, but reuses an already-derived key (autosave fast path).\nasync function tryDecryptWithKey({ key, nonceHex, ciphertextHex }) {\n try {\n const nonce = hexToBytes(nonceHex);\n const ciphertext = hexToBytes(ciphertextHex);\n if (ciphertext.length < TAG_BYTES) return { ok: false };\n const plaintext = await decryptWithKey(key, nonce, ciphertext);\n return { ok: true, plaintext };\n } catch (_e) {\n return { ok: false };\n }\n}\n\nmodule.exports = {\n tryDecryptWithPassword,\n tryDecryptWithKey,\n deriveKey,\n decryptWithKey,\n hexToBytes,\n};\n", "'use strict';\n\n// innerHTML leaves scripts inert. Attach the complete decrypted DOM first, then\n// restore executable scripts so initializers can find both content and libraries.\nconst SCRIPT_LOAD_TIMEOUT = 15000;\nconst JAVASCRIPT_TYPE = /^(?:application|text)\\/(?:x-)?(?:java|ecma)script$|^text\\/(?:javascript1\\.[0-5]|jscript|livescript)$/i;\n\nfunction getExecutableScript(oldScriptElement) {\n const newScript = document.createElement('script');\n for (const attr of oldScriptElement.attributes) {\n newScript.setAttribute(attr.name, attr.value);\n }\n // CSP hides the nonce attribute after attachment; the property retains it.\n if (oldScriptElement.nonce) newScript.nonce = oldScriptElement.nonce;\n newScript.text = oldScriptElement.text;\n return newScript;\n}\n\nfunction convertHTMLToElement(htmlString) {\n const wrapper = document.createElement('div');\n wrapper.innerHTML = htmlString;\n return wrapper;\n}\n\nfunction scriptType(script) {\n let type = script.getAttribute('type');\n if (type === null) {\n const language = script.getAttribute('language');\n type = language ? 'text/' + language : '';\n }\n const keyword = type.toLowerCase();\n if (keyword === 'module') return 'module';\n if (keyword === 'importmap' || keyword === 'speculationrules') return 'declarative';\n const mime = type.replace(/^[\\t\\n\\f\\r ]+|[\\t\\n\\f\\r ]+$/g, '');\n if (type === '' || JAVASCRIPT_TYPE.test(mime)) return 'classic';\n return 'data';\n}\n\nfunction restoreScript(oldScript, newScript, waitForLoad) {\n if (!waitForLoad) {\n oldScript.parentNode.replaceChild(newScript, oldScript);\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n const finish = () => {\n clearTimeout(timer);\n newScript.removeEventListener('load', finish);\n newScript.removeEventListener('error', finish);\n resolve();\n };\n // A broken third-party dependency must not prevent the decrypt callback\n // forever. A timed-out script can still execute later; this is not a cancel.\n const timer = setTimeout(() => {\n console.warn('hexo-blog-encrypt: timed out waiting for a decrypted script to load.');\n finish();\n }, SCRIPT_LOAD_TIMEOUT);\n // Do not overwrite onload/onerror attributes copied from the original tag.\n newScript.addEventListener('load', finish);\n newScript.addEventListener('error', finish);\n oldScript.parentNode.replaceChild(newScript, oldScript);\n });\n}\n\nasync function restoreScripts(container) {\n const pending = [];\n const supportsModules = 'noModule' in document.createElement('script');\n for (const oldScript of container.querySelectorAll('script')) {\n // Earlier user scripts may remove later nodes. Do not execute detached ones.\n if (!container.contains(oldScript)) continue;\n const type = scriptType(oldScript);\n if (type === 'data' || (type === 'classic' && oldScript.noModule && supportsModules)) continue;\n if (type === 'module' && !supportsModules) continue;\n\n const newScript = getExecutableScript(oldScript);\n // Inline modules have no native load event. Keep their native async\n // semantics instead of adding a false timeout or rewriting their source.\n const waitForLoad = type !== 'declarative' && newScript.hasAttribute('src');\n const independent = waitForLoad && newScript.hasAttribute('async');\n // Dynamically created classics default to async even without the attribute.\n if (type === 'classic' && waitForLoad && !independent) newScript.async = false;\n const loaded = restoreScript(oldScript, newScript, waitForLoad);\n if (independent) pending.push(loaded);\n else await loaded;\n }\n await Promise.all(pending);\n}\n\n// Resolve after restored scripts load, fail, or time out. Native module load\n// events do not await arbitrary async work such as top-level await continuations.\nasync function swapInDecryptedDOM(mainElement, plaintextHTML) {\n const decrypted = convertHTMLToElement(plaintextHTML);\n decrypted.id = 'hexo-blog-encrypt';\n decrypted.classList.add('hbe', 'hbe-decrypted-content');\n mainElement.parentNode.replaceChild(decrypted, mainElement);\n await restoreScripts(decrypted);\n return decrypted;\n}\n\nmodule.exports = {\n getExecutableScript,\n convertHTMLToElement,\n swapInDecryptedDOM,\n};\n", "'use strict';\n\n// Per-post localStorage entry storing the derived AES key + the salt/nonce that\n// produced the corresponding ciphertext. On reload we re-import the key and\n// attempt decryption silently; the user is never re-prompted.\n//\n// Schema (v4):\n// {\n// version: 4,\n// dk: base64(rawKeyBytes), // 32 bytes\n// salt: <hex64>, // matches data-salt\n// nonce: <hex24>, // retained for v4 schema compatibility\n// }\n//\n// IMPORTANT: when `autoSave` is false, save() is a no-op. When reading, any\n// entry with a non-4 version (or v3 leftovers like `hmk`/`hmacDigest`) is\n// purged + ignored.\n\nconst STORAGE_KEY_PREFIX = 'hbe.v4.';\nconst SCHEMA_VERSION = 4;\n\nfunction storageKey(pageKey) {\n return STORAGE_KEY_PREFIX + pageKey;\n}\n\nfunction bytesToBase64(bytes) {\n let bin = '';\n for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);\n return btoa(bin);\n}\n\nfunction base64ToBytes(b64) {\n const bin = atob(b64);\n const out = new Uint8Array(bin.length);\n for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);\n return out;\n}\n\nasync function save({ pageKey, key, saltHex, nonceHex, autoSave }) {\n if (!autoSave) return;\n try {\n const raw = await crypto.subtle.exportKey('raw', key);\n const entry = {\n version: SCHEMA_VERSION,\n dk: bytesToBase64(new Uint8Array(raw)),\n salt: saltHex,\n nonce: nonceHex,\n };\n localStorage.setItem(storageKey(pageKey), JSON.stringify(entry));\n } catch (_e) {\n // localStorage.setItem can throw QuotaExceededError or SecurityError\n // (private mode, disabled storage). Silently ignore \u2014 autoSave is\n // best-effort UX.\n }\n}\n\nasync function load({ pageKey, expectedSaltHex }) {\n let entry;\n try {\n const raw = localStorage.getItem(storageKey(pageKey));\n if (!raw) return null;\n entry = JSON.parse(raw);\n } catch (_e) {\n return null;\n }\n\n // Purge stale or v3 entries.\n if (\n !entry\n || entry.version !== SCHEMA_VERSION\n || typeof entry.dk !== 'string'\n || typeof entry.salt !== 'string'\n || typeof entry.nonce !== 'string'\n || 'hmk' in entry\n || 'hmacDigest' in entry\n ) {\n try { localStorage.removeItem(storageKey(pageKey)); } catch (_e) { /* ignore */ }\n return null;\n }\n\n // If the encrypted page's salt changed, the cached key is stale. Nonce is\n // not part of PBKDF2 key derivation; decrypt still uses the current page's\n // nonce and ciphertext, and failure clears the cache in main.js.\n if (entry.salt !== expectedSaltHex) {\n try { localStorage.removeItem(storageKey(pageKey)); } catch (_e) { /* ignore */ }\n return null;\n }\n\n try {\n const rawBytes = base64ToBytes(entry.dk);\n const key = await crypto.subtle.importKey(\n 'raw',\n rawBytes,\n { name: 'AES-GCM' },\n true,\n ['decrypt']\n );\n return key;\n } catch (_e) {\n try { localStorage.removeItem(storageKey(pageKey)); } catch (_e2) { /* ignore */ }\n return null;\n }\n}\n\nfunction clear(pageKey) {\n try { localStorage.removeItem(storageKey(pageKey)); } catch (_e) { /* ignore */ }\n}\n\nmodule.exports = {\n save,\n load,\n clear,\n STORAGE_KEY_PREFIX,\n SCHEMA_VERSION,\n};\n", "'use strict';\n\n// Browser entry point. Reads the wire-format from the encrypted-post wrapper,\n// drives the UI via `ui.js`, derives & decrypts via `crypto.js`, and persists\n// the derived key (when autoSave is on) via `storage.js`.\n\nconst ui = require('./ui');\nconst cryptoMod = require('./crypto');\nconst dom = require('./dom');\nconst storage = require('./storage');\n\nconst SUPPORTED_FORMAT = '4';\n\nfunction readWireFormat(mainElement) {\n const ds = mainElement.dataset;\n const ciphertextNode = mainElement.querySelector('script#hbeData');\n return {\n format: ds.hbeFormat,\n wpm: ds.wpm || 'Wrong password.',\n whm: ds.whm || ds.wpm || 'Wrong password.',\n saltHex: ds.salt,\n nonceHex: ds.nonce,\n iterations: parseInt(ds.kdfIterations, 10) || 250000,\n autoSave: ds.autoSave === 'true',\n ciphertextHex: ciphertextNode ? ciphertextNode.textContent.trim() : '',\n };\n}\n\nfunction dispatchDecryptEvent(mode) {\n // Fire on `window` for v3 back-compat \u2014 both READMEs document\n // `window.addEventListener('hexo-blog-decrypt', fn)` as the public API.\n // Old listeners that only access `e.type` continue to work; new listeners\n // can additionally read `e.detail.mode` ('manual' | 'cached').\n try {\n window.dispatchEvent(new CustomEvent('hexo-blog-decrypt', { detail: { mode } }));\n } catch (_e) {\n // CustomEvent constructor unavailable on very old browsers \u2014 fall back\n // to plain Event (no detail).\n try {\n window.dispatchEvent(new Event('hexo-blog-decrypt'));\n } catch (_e2) { /* ignore \u2014 no event API at all */ }\n }\n}\n\nfunction pageKey() {\n // Per-URL bucket so different encrypted posts don't collide in localStorage.\n return location.pathname + location.search;\n}\n\nasync function reveal(mainElement, plaintext, mode) {\n await dom.swapInDecryptedDOM(mainElement, plaintext);\n dispatchDecryptEvent(mode);\n}\n\nasync function tryAutoDecrypt(mainElement, wire, guardedReveal) {\n if (!wire.autoSave) return false;\n const cachedKey = await storage.load({\n pageKey: pageKey(),\n expectedSaltHex: wire.saltHex,\n });\n if (!cachedKey) return false;\n const result = await cryptoMod.tryDecryptWithKey({\n key: cachedKey,\n nonceHex: wire.nonceHex,\n ciphertextHex: wire.ciphertextHex,\n });\n if (!result.ok) {\n storage.clear(pageKey());\n return false;\n }\n await guardedReveal(result.plaintext, 'cached');\n return true;\n}\n\nasync function handleSubmit(mainElement, wire, form, guardedReveal) {\n ui.clearError(mainElement);\n ui.setBusy(form, true);\n const password = ui.readPassword(form);\n if (!password) {\n ui.setBusy(form, false);\n ui.showError(mainElement, wire.wpm);\n return;\n }\n let result;\n try {\n result = await cryptoMod.tryDecryptWithPassword({\n password,\n saltHex: wire.saltHex,\n nonceHex: wire.nonceHex,\n ciphertextHex: wire.ciphertextHex,\n iterations: wire.iterations,\n });\n } finally {\n ui.setBusy(form, false);\n }\n if (!result.ok) {\n ui.showError(mainElement, wire.wpm);\n return;\n }\n if (wire.autoSave) {\n await storage.save({\n pageKey: pageKey(),\n key: result.key,\n saltHex: wire.saltHex,\n nonceHex: wire.nonceHex,\n autoSave: true,\n });\n }\n await guardedReveal(result.plaintext, 'manual');\n}\n\nasync function bootstrap() {\n const mainElement = document.getElementById('hexo-blog-encrypt');\n if (!mainElement) return;\n const wire = readWireFormat(mainElement);\n\n if (wire.format !== SUPPORTED_FORMAT) {\n ui.showError(\n mainElement,\n 'hexo-blog-encrypt: this page was built with an incompatible plugin version. ' +\n 'Rebuild the site after upgrading the plugin.'\n );\n return;\n }\n\n // Single-shot reveal guard: with autoSave on, `tryAutoDecrypt` runs in\n // parallel with the form submit handler. If the user types fast enough\n // to submit BEFORE auto-decrypt resolves, both paths can call `reveal`\n // on the same `mainElement` \u2014 the second `replaceChild` would throw\n // because the wrapper is already detached. The guard makes whoever\n // wins the race the sole DOM-mutator.\n let revealed = false;\n const guardedReveal = async (plaintext, mode) => {\n if (revealed) return;\n revealed = true;\n await reveal(mainElement, plaintext, mode);\n };\n\n const form = mainElement.querySelector('#hbeForm');\n ui.attachSubmit(form, () => handleSubmit(mainElement, wire, form, guardedReveal));\n\n const auto = await tryAutoDecrypt(mainElement, wire, guardedReveal);\n if (!auto && !revealed) {\n const input = mainElement.querySelector('#hbePass');\n if (input) input.focus();\n }\n}\n\nif (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', bootstrap);\n} else {\n bootstrap();\n}\n"],
|
|
5
|
+
"mappings": "iFAAA,IAAAA,EAAAC,EAAA,CAAAC,GAAAC,IAAA,cAMA,SAASC,EAAQC,EAAMC,EAAM,CAC3B,GAAI,CAACD,EAAM,OACXA,EAAK,aAAa,YAAaC,EAAO,OAAS,OAAO,EACtD,IAAMC,EAASF,EAAK,cAAc,aAAa,EAC3CE,IACFA,EAAO,SAAW,CAAC,CAACD,GAEtB,IAAME,EAAQH,EAAK,cAAc,UAAU,EACvCG,IACFA,EAAM,SAAW,CAAC,CAACF,EAEvB,CAEA,SAASG,EAAUC,EAAaC,EAAS,CACvC,IAAIC,EAAQF,EAAY,cAAc,gBAAgB,EACtD,GAAI,CAACE,EAAO,CACVA,EAAQ,SAAS,cAAc,KAAK,EACpCA,EAAM,aAAa,OAAQ,OAAO,EAClCA,EAAM,UAAY,gBAClB,IAAMP,EAAOK,EAAY,cAAc,UAAU,E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AEF,EACA,MACF,CAQA,IAAImB,EAAW,GACTP,EAAgB,MAAOH,EAAWL,IAAS,CAC3Ce,IACJA,EAAW,GACX,MAAMX,EAAOR,EAAaS,EAAWL,CAAI,EAC3C,EAEMY,EAAOhB,EAAY,cAAc,UAAU,EAIjD,GAHAN,EAAG,aAAasB,EAAM,IAAMD,GAAaf,EAAaW,EAAMK,EAAMJ,CAAa,CAAC,EAG5E,CADS,MAAMF,GAAeV,EAAaW,EAAMC,CAAa,GACrD,CAACO,EAAU,CACtB,IAAMC,EAAQpB,EAAY,cAAc,UAAU,EAC9CoB,GAAOA,EAAM,MAAM,CACzB,CACF,CAEI,SAAS,aAAe,UAC1B,SAAS,iBAAiB,mBAAoBF,CAAS,EAEvDA,EAAU",
|
|
6
|
+
"names": ["require_ui", "__commonJSMin", "exports", "module", "setBusy", "form", "busy", "button", "input", "showError", "mainElement", "message", "alert", "clearError", "readPassword", "attachSubmit", "handler", "event", "require_crypto", "__commonJSMin", "exports", "module", "TEXT_DECODER", "TEXT_ENCODER", "hexToBytes", "hex", "len", "out", "i", "deriveKey", "password", "salt", "iterations", "baseKey", "decryptWithKey", "key", "nonce", "ciphertextWithTag", "plainBuf", "tryDecryptWithPassword", "saltHex", "nonceHex", "ciphertextHex", "ciphertext", "_e", "tryDecryptWithKey", "require_dom", "__commonJSMin", "exports", "module", "JAVASCRIPT_TYPE", "getExecutableScript", "oldScriptElement", "newScript", "attr", "convertHTMLToElement", "htmlString", "wrapper", "scriptType", "script", "type", "language", "keyword", "mime", "restoreScript", "oldScript", "waitForLoad", "resolve", "finish", "timer", "restoreScripts", "container", "pending", "supportsModules", "independent", "loaded", "swapInDecryptedDOM", "mainElement", "plaintextHTML", "decrypted", "require_storage", "__commonJSMin", "exports", "module", "STORAGE_KEY_PREFIX", "storageKey", "pageKey", "bytesToBase64", "bytes", "bin", "i", "base64ToBytes", "b64", "out", "save", "key", "saltHex", "nonceHex", "autoSave", "raw", "entry", "_e", "load", "expectedSaltHex", "rawBytes", "_e2", "clear", "ui", "cryptoMod", "dom", "storage", "SUPPORTED_FORMAT", "readWireFormat", "mainElement", "ds", "ciphertextNode", "dispatchDecryptEvent", "mode", "_e", "_e2", "pageKey", "reveal", "plaintext", "tryAutoDecrypt", "wire", "guardedReveal", "cachedKey", "result", "handleSubmit", "form", "password", "bootstrap", "revealed", "input"]
|
|
7
7
|
}
|
package/package.json
CHANGED
package/src/server/template.js
CHANGED
|
@@ -45,6 +45,8 @@ const PLACEHOLDERS = [
|
|
|
45
45
|
{ token: '{{hbeEncryptedData}}', field: 'ciphertext', mode: 'hex' },
|
|
46
46
|
];
|
|
47
47
|
|
|
48
|
+
const PLACEHOLDER_RE = new RegExp(PLACEHOLDERS.map(({ token }) => token).join('|'), 'g');
|
|
49
|
+
|
|
48
50
|
function valueOf(opts, field) {
|
|
49
51
|
const v = opts[field];
|
|
50
52
|
if (field === 'kdfIterations') return String(v);
|
|
@@ -53,7 +55,7 @@ function valueOf(opts, field) {
|
|
|
53
55
|
}
|
|
54
56
|
|
|
55
57
|
function substitute(template, opts) {
|
|
56
|
-
|
|
58
|
+
const replacements = new Map();
|
|
57
59
|
for (const { token, field, mode } of PLACEHOLDERS) {
|
|
58
60
|
const raw = valueOf(opts, field);
|
|
59
61
|
let replacement;
|
|
@@ -67,9 +69,11 @@ function substitute(template, opts) {
|
|
|
67
69
|
}
|
|
68
70
|
replacement = s;
|
|
69
71
|
}
|
|
70
|
-
|
|
72
|
+
replacements.set(token, replacement);
|
|
71
73
|
}
|
|
72
|
-
|
|
74
|
+
// Match only the original template. Replacement text may contain tokens of
|
|
75
|
+
// its own and must never be expanded again in a different escaping context.
|
|
76
|
+
return template.replace(PLACEHOLDER_RE, (token) => replacements.get(token));
|
|
73
77
|
}
|
|
74
78
|
|
|
75
79
|
function discoverThemes(templateDir) {
|