hexo-blog-encrypt 4.0.3 → 4.2.0

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.
@@ -10,18 +10,21 @@
10
10
  {{hbeEncryptedData}}
11
11
  </script>
12
12
  <div class="hbe hbe-content">
13
- <form id="hbeForm" class="hbe hbe-form" onsubmit="return false">
14
- <div class="hbe hbe-input hbe-input-surge">
15
- <input class="hbe hbe-input-field hbe-input-field-surge" type="password" id="hbePass">
16
- <label class="hbe hbe-input-label hbe-input-label-surge" for="hbePass">
17
- <span class="hbe hbe-input-label-content hbe-input-label-content-surge" data-content="{{hbeMessage}}">{{hbeMessage}}</span>
18
- </label>
19
- <svg class="hbe hbe-graphic hbe-graphic-surge" width="300%" height="100%" viewBox="0 0 1200 60" preserveAspectRatio="none">
20
- <path d="M1200,9c0,0-305.005,0-401.001,0C733,9,675.327,4.969,598,4.969C514.994,4.969,449.336,9,400.333,9C299.666,9,0,9,0,9v43c0,0,299.666,0,400.333,0c49.002,0,114.66,3.484,197.667,3.484c77.327,0,135-3.484,200.999-3.484C894.995,52,1200,52,1200,52V9z"></path>
21
- </svg>
22
- </div>
23
- <button class="hbe hbe-button{{hbeButtonClass}}" type="submit">{{hbeButtonText}}</button>
24
- <div class="hbe hbe-error" role="alert" aria-live="polite"></div>
13
+ <form id="hbeForm" class="hbe hbe-form">
14
+ <div class="hbe hbe-input hbe-input-surge hbe-classic">
15
+ <input class="hbe hbe-input-field hbe-input-field-surge" type="password" id="hbePass">
16
+ <label class="hbe hbe-input-label hbe-input-label-surge" for="hbePass">
17
+ <span class="hbe hbe-input-label-content hbe-input-label-content-surge">{{hbeMessage}}</span>
18
+ <span class="hbe-roll" aria-hidden="true">{{hbeMessage}}</span>
19
+ </label>
20
+ <span class="hbe-track" aria-hidden="true">
21
+ <svg aria-hidden="true" focusable="false" class="hbe hbe-graphic hbe-graphic-surge" width="300%" height="100%" viewBox="0 0 1200 60" preserveAspectRatio="none">
22
+ <path d="M1200,9c0,0-305.005,0-401.001,0C733,9,675.327,4.969,598,4.969C514.994,4.969,449.336,9,400.333,9C299.666,9,0,9,0,9v43c0,0,299.666,0,400.333,0c49.002,0,114.66,3.484,197.667,3.484c77.327,0,135-3.484,200.999-3.484C894.995,52,1200,52,1200,52V9z"></path>
23
+ </svg>
24
+ </span>
25
+ </div>
26
+ <button class="hbe hbe-button{{hbeButtonClass}}" type="submit"><span class="hbe hbe-button-text">{{hbeButtonText}}</span></button>
27
+ <div class="hbe hbe-error" role="alert"></div>
25
28
  </form>
26
29
  </div>
27
30
  </div>
@@ -0,0 +1,24 @@
1
+ <div class="hbe hbe-container" id="hexo-blog-encrypt"
2
+ data-hbe-format="{{hbeFormat}}"
3
+ data-wpm="{{hbeWrongPassMessage}}"
4
+ data-whm="{{hbeWrongHashMessage}}"
5
+ data-salt="{{hbeSalt}}"
6
+ data-nonce="{{hbeNonce}}"
7
+ data-kdf-iterations="{{hbeKdfIterations}}"
8
+ data-auto-save="{{hbeAutoSave}}">
9
+ <script id="hbeData" type="hbeData">
10
+ {{hbeEncryptedData}}
11
+ </script>
12
+ <div class="hbe hbe-content">
13
+ <form id="hbeForm" class="hbe hbe-form">
14
+ <div class="hbe hbe-input hbe-input-terminal">
15
+ <input class="hbe hbe-input-field hbe-input-field-terminal" type="password" id="hbePass">
16
+ <label class="hbe hbe-input-label hbe-input-label-terminal" for="hbePass">
17
+ <span class="hbe hbe-input-label-content hbe-input-label-content-terminal">{{hbeMessage}}</span>
18
+ </label>
19
+ </div>
20
+ <button class="hbe hbe-button{{hbeButtonClass}}" type="submit"><span class="hbe hbe-button-text">{{hbeButtonText}}</span></button>
21
+ <div class="hbe hbe-error" role="alert"></div>
22
+ </form>
23
+ </div>
24
+ </div>
package/lib/hbe.up.html CHANGED
@@ -10,15 +10,16 @@
10
10
  {{hbeEncryptedData}}
11
11
  </script>
12
12
  <div class="hbe hbe-content">
13
- <form id="hbeForm" class="hbe hbe-form" onsubmit="return false">
14
- <div class="hbe hbe-input hbe-input-up">
15
- <input class="hbe hbe-input-field hbe-input-field-up" type="password" id="hbePass">
16
- <label class="hbe hbe-input-label hbe-input-label-up" for="hbePass">
17
- <span class="hbe hbe-input-label-content hbe-input-label-content-up">{{hbeMessage}}</span>
18
- </label>
19
- </div>
20
- <button class="hbe hbe-button{{hbeButtonClass}}" type="submit">{{hbeButtonText}}</button>
21
- <div class="hbe hbe-error" role="alert" aria-live="polite"></div>
13
+ <form id="hbeForm" class="hbe hbe-form">
14
+ <div class="hbe hbe-input hbe-input-up hbe-classic">
15
+ <input class="hbe hbe-input-field hbe-input-field-up" type="password" id="hbePass">
16
+ <label class="hbe hbe-input-label hbe-input-label-up" for="hbePass">
17
+ <span class="hbe hbe-input-label-content hbe-input-label-content-up">{{hbeMessage}}</span>
18
+ </label>
19
+ <span class="hbe-track" aria-hidden="true"></span>
20
+ </div>
21
+ <button class="hbe hbe-button{{hbeButtonClass}}" type="submit"><span class="hbe hbe-button-text">{{hbeButtonText}}</span></button>
22
+ <div class="hbe hbe-error" role="alert"></div>
22
23
  </form>
23
24
  </div>
24
25
  </div>
package/lib/hbe.wave.html CHANGED
@@ -10,18 +10,20 @@
10
10
  {{hbeEncryptedData}}
11
11
  </script>
12
12
  <div class="hbe hbe-content">
13
- <form id="hbeForm" class="hbe hbe-form" onsubmit="return false">
14
- <div class="hbe hbe-input hbe-input-wave">
15
- <input class="hbe hbe-input-field hbe-input-field-wave" type="password" id="hbePass">
16
- <label class="hbe hbe-input-label hbe-input-label-wave" for="hbePass">
17
- <span class="hbe hbe-input-label-content hbe-input-label-content-wave">{{hbeMessage}}</span>
18
- </label>
19
- <svg class="hbe hbe-graphic hbe-graphic-wave" width="300%" height="100%" viewBox="0 0 1200 60" preserveAspectRatio="none">
20
- <path d="M0,56.5c0,0,298.666,0,399.333,0C448.336,56.5,513.994,46,597,46c77.327,0,135,10.5,200.999,10.5c95.996,0,402.001,0,402.001,0"></path>
21
- </svg>
22
- </div>
23
- <button class="hbe hbe-button{{hbeButtonClass}}" type="submit">{{hbeButtonText}}</button>
24
- <div class="hbe hbe-error" role="alert" aria-live="polite"></div>
13
+ <form id="hbeForm" class="hbe hbe-form">
14
+ <div class="hbe hbe-input hbe-input-wave hbe-classic">
15
+ <input class="hbe hbe-input-field hbe-input-field-wave" type="password" id="hbePass">
16
+ <label class="hbe hbe-input-label hbe-input-label-wave" for="hbePass">
17
+ <span class="hbe hbe-input-label-content hbe-input-label-content-wave">{{hbeMessage}}</span>
18
+ </label>
19
+ <span class="hbe-track" aria-hidden="true">
20
+ <svg aria-hidden="true" focusable="false" class="hbe hbe-graphic hbe-graphic-wave" width="300%" height="100%" viewBox="0 0 1200 60" preserveAspectRatio="none">
21
+ <path d="M0,56.5c0,0,298.666,0,399.333,0C448.336,56.5,513.994,46,597,46c77.327,0,135,10.5,200.999,10.5c95.996,0,402.001,0,402.001,0"></path>
22
+ </svg>
23
+ </span>
24
+ </div>
25
+ <button class="hbe hbe-button{{hbeButtonClass}}" type="submit"><span class="hbe hbe-button-text">{{hbeButtonText}}</span></button>
26
+ <div class="hbe hbe-error" role="alert"></div>
25
27
  </form>
26
28
  </div>
27
29
  </div>
package/lib/hbe.xray.html CHANGED
@@ -10,19 +10,21 @@
10
10
  {{hbeEncryptedData}}
11
11
  </script>
12
12
  <div class="hbe hbe-content">
13
- <form id="hbeForm" class="hbe hbe-form" onsubmit="return false">
14
- <div class="hbe hbe-input hbe-input-xray">
15
- <input class="hbe hbe-input-field hbe-input-field-xray" type="password" id="hbePass">
16
- <label class="hbe hbe-input-label hbe-input-label-xray" for="hbePass">
17
- <span class="hbe hbe-input-label-content hbe-input-label-content-xray">{{hbeMessage}}</span>
18
- </label>
19
- <svg class="hbe hbe-graphic hbe-graphic-xray" width="300%" height="100%" viewBox="0 0 1200 60" preserveAspectRatio="none">
20
- <path d="M0,56.5c0,0,298.666,0,399.333,0C448.336,56.5,513.994,46,597,46c77.327,0,135,10.5,200.999,10.5c95.996,0,402.001,0,402.001,0"></path>
21
- <path d="M0,2.5c0,0,298.666,0,399.333,0C448.336,2.5,513.994,13,597,13c77.327,0,135-10.5,200.999-10.5c95.996,0,402.001,0,402.001,0"></path>
22
- </svg>
23
- </div>
24
- <button class="hbe hbe-button{{hbeButtonClass}}" type="submit">{{hbeButtonText}}</button>
25
- <div class="hbe hbe-error" role="alert" aria-live="polite"></div>
13
+ <form id="hbeForm" class="hbe hbe-form">
14
+ <div class="hbe hbe-input hbe-input-xray hbe-classic">
15
+ <input class="hbe hbe-input-field hbe-input-field-xray" type="password" id="hbePass">
16
+ <label class="hbe hbe-input-label hbe-input-label-xray" for="hbePass">
17
+ <span class="hbe hbe-input-label-content hbe-input-label-content-xray">{{hbeMessage}}</span>
18
+ </label>
19
+ <span class="hbe-track" aria-hidden="true">
20
+ <svg aria-hidden="true" focusable="false" class="hbe hbe-graphic hbe-graphic-xray" width="300%" height="100%" viewBox="0 0 1200 60" preserveAspectRatio="none">
21
+ <path d="M0,56.5c0,0,298.666,0,399.333,0C448.336,56.5,513.994,46,597,46c77.327,0,135,10.5,200.999,10.5c95.996,0,402.001,0,402.001,0"></path>
22
+ <path d="M0,2.5c0,0,298.666,0,399.333,0C448.336,2.5,513.994,13,597,13c77.327,0,135-10.5,200.999-10.5c95.996,0,402.001,0,402.001,0"></path>
23
+ </svg>
24
+ </span>
25
+ </div>
26
+ <button class="hbe hbe-button{{hbeButtonClass}}" type="submit"><span class="hbe hbe-button-text">{{hbeButtonText}}</span></button>
27
+ <div class="hbe hbe-error" role="alert"></div>
26
28
  </form>
27
29
  </div>
28
30
  </div>
package/package.json CHANGED
@@ -36,12 +36,12 @@
36
36
  "prepare": "node build/prepare.js",
37
37
  "pretest:server": "npm run build",
38
38
  "test": "npm run lint && npm run test:server && npm run test:e2e",
39
- "test:server": "node tests/helpers/install-fixture.js && c8 --reporter=text --reporter=lcov --include=index.js --include=src/server/**/*.js --check-coverage --lines=100 --functions=100 --branches=100 --statements=100 node --test tests/server/*.test.js tests/docs.test.js",
40
- "test:e2e": "cd tests/fixtures/hexo-site && (test -d node_modules || npm install --no-audit --no-fund) && cd ../../.. && playwright install --with-deps chromium && playwright test --config tests/e2e/playwright.config.js",
41
- "test:docs": "node --test tests/docs.test.js",
42
- "lint": "eslint --ext .js ./"
39
+ "test:server": "node tests/helpers/install-fixture.js && c8 --reporter=text --reporter=lcov --include=index.js --include=src/server/**/*.js --check-coverage --lines=100 --functions=100 --branches=100 --statements=100 node --test tests/server/*.test.js tests/docs.test.js tests/skills.test.js",
40
+ "test:e2e": "cd tests/fixtures/hexo-site && (test -d node_modules || npm install --no-audit --no-fund) && cd ../../.. && playwright install --with-deps chromium firefox webkit && playwright test --config tests/e2e/playwright.config.js",
41
+ "test:docs": "node --test tests/docs.test.js tests/skills.test.js",
42
+ "lint": "eslint ."
43
43
  },
44
- "version": "4.0.3",
44
+ "version": "4.2.0",
45
45
  "engines": {
46
46
  "node": ">=18"
47
47
  },
@@ -49,11 +49,20 @@
49
49
  "hexo": ">=5"
50
50
  },
51
51
  "devDependencies": {
52
- "@playwright/test": "^1.45",
53
- "c8": "^10",
54
- "esbuild": "^0.25.12",
55
- "eslint": "^6.2.2",
52
+ "@eslint/js": "^10.0.1",
53
+ "@playwright/test": "^1.64.0",
54
+ "c8": "^12.0.0",
55
+ "esbuild": "^0.28.2",
56
+ "eslint": "^10.12.0",
57
+ "globals": "^17.13.0",
56
58
  "hexo": "^7",
57
- "hexo-renderer-marked": "^7"
59
+ "hexo-renderer-marked": "^7",
60
+ "js-yaml": "^4.1.0"
61
+ },
62
+ "overrides": {
63
+ "test-exclude@8.0.0": {
64
+ "glob": "14.0.6",
65
+ "minimatch": "11.0.10"
66
+ }
58
67
  }
59
68
  }
@@ -1,7 +1,15 @@
1
1
  'use strict';
2
2
 
3
- const FLOOR = 100000;
4
- const RECOMMENDED = 600000;
3
+ const { checkKdf } = require('./format');
4
+
5
+ const SCRYPT = 'scrypt';
6
+ const SHA256 = 'pbkdf2-sha256';
7
+ const SHA512 = 'pbkdf2-sha512';
8
+ const presets = Object.freeze({
9
+ [SCRYPT]: Object.freeze({ algorithm: SCRYPT, N: 32768, r: 8, p: 3 }),
10
+ [SHA256]: Object.freeze({ algorithm: SHA256, iterations: 600000 }),
11
+ [SHA512]: Object.freeze({ algorithm: SHA512, iterations: 220000 }),
12
+ });
5
13
 
6
14
  const DEFAULTS = Object.freeze({
7
15
  abstract: 'Here\'s something encrypted, password is required to continue reading.',
@@ -18,11 +26,42 @@ const DEFAULTS = Object.freeze({
18
26
  show: true,
19
27
  text: 'Decrypt',
20
28
  }),
21
- kdf: Object.freeze({
22
- iterations: 250000,
29
+ kdf: presets[SCRYPT],
30
+ });
31
+
32
+ // Localized user-facing defaults (#259). English lives in DEFAULTS; other
33
+ // locales override only these strings. Explicit config always wins.
34
+ const LOCALIZED_DEFAULTS = Object.freeze({
35
+ 'zh-CN': Object.freeze({
36
+ abstract: '有东西被加密了, 请输入密码查看.',
37
+ message: '您好, 这里需要密码.',
38
+ wrong_pass_message: '抱歉, 这个密码看着不太对, 请再试试.',
39
+ decryptButton: Object.freeze({ text: '解密' }),
23
40
  }),
24
41
  });
25
42
 
43
+ // Map a language tag to a supported locale key. `zh`, `zh-CN`, `zh_CN` and
44
+ // `zh-Hans` select Simplified Chinese; everything else falls back to English.
45
+ function pickLocale(lang) {
46
+ const tag = typeof lang === 'string' ? lang.trim().toLowerCase().replace(/_/g, '-') : '';
47
+ if (tag === 'zh' || tag === 'zh-cn' || tag === 'zh-hans' || tag.startsWith('zh-hans-')) return 'zh-CN';
48
+ return 'en';
49
+ }
50
+
51
+ // Post `lang` / `language` front matter wins over the site `language`
52
+ // (which Hexo allows to be a list; the first entry is the primary language).
53
+ function languageOf(hexoConfig, post) {
54
+ if (typeof post.lang === 'string' && post.lang) return post.lang;
55
+ if (typeof post.language === 'string' && post.language) return post.language;
56
+ const site = hexoConfig && hexoConfig.language;
57
+ return Array.isArray(site) ? site[0] : site;
58
+ }
59
+
60
+ function localizedDefaults(hexoConfig, post) {
61
+ const locale = pickLocale(languageOf(hexoConfig, post));
62
+ return locale === 'en' ? DEFAULTS : deepMerge(DEFAULTS, LOCALIZED_DEFAULTS[locale]);
63
+ }
64
+
26
65
  function clone(value) {
27
66
  if (value === null || typeof value !== 'object') return value;
28
67
  if (typeof structuredClone === 'function') return structuredClone(value);
@@ -54,6 +93,33 @@ function shallowPickKnown(source, knownKeys) {
54
93
  return out;
55
94
  }
56
95
 
96
+ // A layer can inherit costs only from the same algorithm. Bare iterations
97
+ // preserve the PBKDF2 hash, or select SHA-256 when switching from scrypt.
98
+ function kdfLayer(base, layer) {
99
+ if (layer == null) return base;
100
+ if (typeof layer !== 'object' || Array.isArray(layer)) throw new Error('kdf must be an object');
101
+ const iterations = 'iterations' in layer;
102
+ const cost = ['N', 'r', 'p'].some(key => key in layer);
103
+ let algorithm = base.algorithm;
104
+ if ('algorithm' in layer) algorithm = layer.algorithm;
105
+ else if (iterations) algorithm = base.algorithm === SHA512 ? SHA512 : SHA256;
106
+ else if (cost) algorithm = SCRYPT;
107
+ if (!Object.hasOwn(presets, algorithm) || (algorithm === SCRYPT ? iterations : cost)) {
108
+ throw new Error('conflicting or unknown KDF');
109
+ }
110
+ const preset = presets[algorithm];
111
+ return checkKdf({
112
+ ...(algorithm === base.algorithm ? base : preset),
113
+ ...shallowPickKnown(layer, Object.keys(preset)),
114
+ });
115
+ }
116
+
117
+ // normalizeBooleans returns a fresh object; keep KDF layers out of deepMerge.
118
+ function withoutKdf(picked) {
119
+ delete picked.kdf;
120
+ return picked;
121
+ }
122
+
57
123
  // Keys allowed to flow from the front-matter `post` object into `resolve()`'s
58
124
  // deep merge. Deliberately EXCLUDES `tags`: Hexo materializes `post.tags` as a
59
125
  // Warehouse Query containing functions/methods, which `structuredClone` cannot
@@ -81,6 +147,71 @@ const KNOWN_KEYS = [
81
147
  'tags',
82
148
  ];
83
149
 
150
+ const BOOLEAN_KEYS = ['autoSave', 'stableSalt', 'silent'];
151
+
152
+ // Strict boolean parsing (#249). YAML `autoSave: "false"` is a truthy string;
153
+ // treating it by truthiness would silently enable key storage.
154
+ function toBoolean(value, label, log) {
155
+ if (typeof value === 'boolean') return value;
156
+ if (typeof value === 'string') {
157
+ const s = value.trim().toLowerCase();
158
+ if (s === 'true' || s === 'false') {
159
+ log.warn(
160
+ `hexo-blog-encrypt: ${label} is the string ${JSON.stringify(value)}; ` +
161
+ `treating it as ${s}. Remove the quotes to use a YAML boolean.`
162
+ );
163
+ return s === 'true';
164
+ }
165
+ }
166
+ throw new Error(
167
+ `hexo-blog-encrypt: ${label} must be a boolean (true or false), got ${JSON.stringify(value)}.`
168
+ );
169
+ }
170
+
171
+ // Returns a shallow copy of `picked` with boolean options validated.
172
+ // `prefix` names the config layer in messages ("encrypt." or "front-matter ").
173
+ function normalizeBooleans(picked, prefix, log) {
174
+ const out = Object.assign({}, picked);
175
+ for (const key of BOOLEAN_KEYS) {
176
+ if (out[key] !== undefined && out[key] !== null) {
177
+ out[key] = toBoolean(out[key], `${prefix}${key}`, log);
178
+ }
179
+ }
180
+ const btn = out.decryptButton;
181
+ if (btn && typeof btn === 'object' && !Array.isArray(btn)
182
+ && btn.show !== undefined && btn.show !== null) {
183
+ out.decryptButton = Object.assign({}, btn, {
184
+ show: toBoolean(btn.show, `${prefix}decryptButton.show`, log),
185
+ });
186
+ }
187
+ return out;
188
+ }
189
+
190
+ // Resolve a password value (#251). Literals (string/number/boolean) are used
191
+ // as-is; `{ env: NAME }` reads process.env[NAME] at build time. A missing or
192
+ // empty variable fails the build. Error messages name the variable, never the
193
+ // value, and the resolved value is never logged.
194
+ function resolvePasswordRef(value, postTitle) {
195
+ if (typeof value !== 'object') return String(value);
196
+ if (Array.isArray(value) || typeof value.env !== 'string' || value.env === '') {
197
+ throw new Error(
198
+ 'hexo-blog-encrypt: password must be a string, a number, or { env: NAME } ' +
199
+ '(an object with a non-empty "env" variable name).'
200
+ );
201
+ }
202
+ const secret = process.env[value.env];
203
+ if (typeof secret !== 'string' || secret === '') {
204
+ const where = typeof postTitle === 'string' && postTitle.trim()
205
+ ? ` for post "${postTitle.trim()}"`
206
+ : '';
207
+ throw new Error(
208
+ `hexo-blog-encrypt: password references environment variable ${value.env}${where}, ` +
209
+ 'but it is not set or is empty. Set it in the build environment.'
210
+ );
211
+ }
212
+ return secret;
213
+ }
214
+
84
215
  function resolve(hexoConfig, postData, logger) {
85
216
  // Only `warn` is ever called from this module; keep the no-op default minimal.
86
217
  const log = logger || { warn: () => {} };
@@ -97,13 +228,15 @@ function resolve(hexoConfig, postData, logger) {
97
228
  const post = postData || {};
98
229
 
99
230
  // Layer 1: defaults → hexo encrypt block (for top-level shared keys, NOT password/theme overrides per-post).
100
- let merged = deepMerge(DEFAULTS, shallowPickKnown(hexoEncrypt, KNOWN_KEYS));
231
+ let merged = deepMerge(localizedDefaults(hexoConfig, post),
232
+ withoutKdf(normalizeBooleans(shallowPickKnown(hexoEncrypt, KNOWN_KEYS), 'encrypt.', log)));
101
233
 
102
234
  // Layer 2: post front-matter wins. Use POST_KNOWN_KEYS (which excludes
103
235
  // `tags`) to avoid pulling Hexo's Warehouse Query for `post.tags` into
104
236
  // the deep-merge — `structuredClone` would throw DataCloneError on the
105
237
  // function-bearing internals.
106
- merged = deepMerge(merged, shallowPickKnown(post, POST_KNOWN_KEYS));
238
+ merged = deepMerge(merged,
239
+ withoutKdf(normalizeBooleans(shallowPickKnown(post, POST_KNOWN_KEYS), 'front-matter ', log)));
107
240
 
108
241
  // Deprecation: template → theme.
109
242
  if (merged.template !== undefined && merged.template !== null) {
@@ -119,23 +252,14 @@ function resolve(hexoConfig, postData, logger) {
119
252
 
120
253
  // Password: undefined or empty-string disables encryption (caller short-circuits).
121
254
  if (merged.password === undefined || merged.password === null) return null;
122
- merged.password = String(merged.password);
255
+ merged.password = resolvePasswordRef(merged.password, post.title);
123
256
  if (merged.password === '') return null;
124
257
 
125
- // KDF iteration floor + warn band. (deepMerge always populates merged.kdf
126
- // from DEFAULTS.kdf when the user does not set it, so we only need to
127
- // validate the resolved value here.)
128
- if (!Number.isInteger(merged.kdf.iterations) || merged.kdf.iterations < FLOOR) {
129
- throw new Error(
130
- `hexo-blog-encrypt: kdf.iterations must be an integer ≥ ${FLOOR.toLocaleString('en-US').replace(/,/g, '_')} ` +
131
- `(got ${merged.kdf.iterations}). 100_000 is the absolute floor; ${RECOMMENDED.toLocaleString('en-US').replace(/,/g, '_')}+ is recommended (OWASP 2023).`
132
- );
133
- }
134
- if (merged.kdf.iterations < RECOMMENDED) {
135
- log.warn(
136
- `hexo-blog-encrypt: kdf.iterations=${merged.kdf.iterations} is below the OWASP-recommended 600_000. ` +
137
- 'Consider raising it for stronger brute-force resistance.'
138
- );
258
+ merged.kdf = { ...kdfLayer(kdfLayer(DEFAULTS.kdf, hexoEncrypt.kdf), post.kdf) };
259
+ const k = merged.kdf;
260
+ const preset = presets[k.algorithm];
261
+ if (k.algorithm === SCRYPT ? k.r < 8 || k.N * k.r * k.p < 655360 : k.iterations < preset.iterations) {
262
+ log.warn(`KDF cost below recommended ${preset.iterations || 'scrypt profile'}`);
139
263
  }
140
264
 
141
265
  // wrong_hash_message handling under GCM:
@@ -159,6 +283,4 @@ function resolve(hexoConfig, postData, logger) {
159
283
  module.exports = {
160
284
  resolve,
161
285
  DEFAULTS,
162
- FLOOR,
163
- RECOMMENDED,
164
286
  };
@@ -1,75 +1,72 @@
1
1
  'use strict';
2
2
 
3
3
  const crypto = require('node:crypto');
4
+ const { promisify } = require('node:util');
5
+ const { frameLength, checkKdf, headerFor } = require('./format');
6
+ const { DEFAULTS } = require('./config');
7
+
8
+ const pbkdf2 = promisify(crypto.pbkdf2);
9
+ const scryptAsync = promisify(crypto.scrypt);
4
10
 
5
- const DEFAULT_ITERATIONS = 250000;
6
11
  const SALT_BYTES = 32;
7
12
  const NONCE_BYTES = 12;
8
13
  const KEY_BYTES = 32;
9
- const TAG_BYTES = 16;
10
- const HASH = 'sha256';
11
- const CIPHER = 'aes-256-gcm';
12
14
 
13
- function deriveKey(password, salt, iterations) {
14
- const passwordBuf = typeof password === 'string'
15
- ? Buffer.from(password, 'utf8')
16
- : Buffer.from(String(password), 'utf8');
17
- return crypto.pbkdf2Sync(passwordBuf, salt, iterations, KEY_BYTES, HASH);
15
+ function makeFrame(text) {
16
+ const n = Buffer.byteLength(text, 'utf8');
17
+ const frame = Buffer.alloc(frameLength(n));
18
+ frame.writeUInt32BE(n, 0);
19
+ frame.write(text, 4, n, 'utf8');
20
+ return frame;
18
21
  }
19
22
 
20
- function encrypt(plaintext, password, opts) {
21
- const iterations = (opts && Number.isInteger(opts.iterations) && opts.iterations > 0)
22
- ? opts.iterations
23
- : DEFAULT_ITERATIONS;
24
- let salt;
25
- if (opts && opts.salt !== undefined) {
26
- if (!Buffer.isBuffer(opts.salt) || opts.salt.length !== SALT_BYTES) {
27
- throw new Error('salt must be a 32-byte Buffer');
23
+ async function deriveIKM(password, salt, kdf) {
24
+ checkKdf(kdf);
25
+ const pw = Buffer.from(String(password), 'utf8');
26
+ try {
27
+ if (kdf.algorithm !== 'scrypt') {
28
+ return await pbkdf2(pw, salt, kdf.iterations, KEY_BYTES, kdf.algorithm.slice(7));
28
29
  }
29
- salt = Buffer.from(opts.salt);
30
- } else {
31
- salt = crypto.randomBytes(SALT_BYTES);
30
+ const { N, r, p } = kdf;
31
+ const maxmem = Math.max(32 * 2 ** 20, 256 * r * (N + p + 2));
32
+ return await scryptAsync(pw, salt, KEY_BYTES, { N, r, p, maxmem });
33
+ } finally {
34
+ pw.fill(0);
35
+ }
36
+ }
37
+
38
+ function seal(frame, ikm, header, salt, nonce) {
39
+ const aad = Buffer.concat([header, salt, nonce]);
40
+ const expand = label => Buffer.from(crypto.hkdfSync('sha256', ikm, aad, `hexo-blog-encrypt:v5:${label}`, KEY_BYTES));
41
+ const key = expand('enc');
42
+ try {
43
+ const commitment = expand('cmt');
44
+ const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce);
45
+ cipher.setAAD(Buffer.concat([aad, commitment]));
46
+ return Buffer.concat([header, commitment, cipher.update(frame), cipher.final(), cipher.getAuthTag()]);
47
+ } finally {
48
+ key.fill(0);
32
49
  }
33
- const nonce = crypto.randomBytes(NONCE_BYTES);
34
- const dk = deriveKey(password, salt, iterations);
35
- const cipher = crypto.createCipheriv(CIPHER, dk, nonce);
36
- const enc = Buffer.concat([
37
- cipher.update(Buffer.from(String(plaintext), 'utf8')),
38
- cipher.final(),
39
- ]);
40
- const tag = cipher.getAuthTag();
41
- const ciphertext = Buffer.concat([enc, tag]);
42
- return { salt, nonce, ciphertext };
43
50
  }
44
51
 
45
- function decrypt(salt, nonce, ciphertext, password, opts) {
46
- const iterations = (opts && Number.isInteger(opts.iterations) && opts.iterations > 0)
47
- ? opts.iterations
48
- : DEFAULT_ITERATIONS;
52
+ async function encrypt(plaintext, password, { kdf = DEFAULTS.kdf, salt = crypto.randomBytes(SALT_BYTES) } = {}) {
49
53
  if (!Buffer.isBuffer(salt) || salt.length !== SALT_BYTES) {
50
54
  throw new Error('salt must be a 32-byte Buffer');
51
55
  }
52
- if (!Buffer.isBuffer(nonce) || nonce.length !== NONCE_BYTES) {
53
- throw new Error('nonce must be a 12-byte Buffer');
54
- }
55
- if (!Buffer.isBuffer(ciphertext) || ciphertext.length < TAG_BYTES) {
56
- throw new Error('ciphertext must be a Buffer of length ≥ 16');
56
+ salt = Buffer.from(salt);
57
+ const header = headerFor(kdf);
58
+ const nonce = crypto.randomBytes(NONCE_BYTES);
59
+ const frame = makeFrame(String(plaintext));
60
+ try {
61
+ const ikm = await deriveIKM(password, salt, kdf);
62
+ try {
63
+ return { salt, nonce, ciphertext: seal(frame, ikm, header, salt, nonce) };
64
+ } finally {
65
+ ikm.fill(0);
66
+ }
67
+ } finally {
68
+ frame.fill(0);
57
69
  }
58
- const dk = deriveKey(password, salt, iterations);
59
- const enc = ciphertext.slice(0, ciphertext.length - TAG_BYTES);
60
- const tag = ciphertext.slice(ciphertext.length - TAG_BYTES);
61
- const decipher = crypto.createDecipheriv(CIPHER, dk, nonce);
62
- decipher.setAuthTag(tag);
63
- const out = Buffer.concat([decipher.update(enc), decipher.final()]);
64
- return out.toString('utf8');
65
70
  }
66
71
 
67
- module.exports = {
68
- encrypt,
69
- decrypt,
70
- DEFAULT_ITERATIONS,
71
- SALT_BYTES,
72
- NONCE_BYTES,
73
- KEY_BYTES,
74
- TAG_BYTES,
75
- };
72
+ module.exports = { encrypt, seal, makeFrame, deriveIKM };
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ // Array indices are the on-wire KDF IDs; zero is reserved.
4
+ const algorithms = ['', 'pbkdf2-sha256', 'pbkdf2-sha512', 'scrypt'];
5
+ const inRange = (x, min, max) => Number.isInteger(x) && x >= min && x <= max;
6
+
7
+ function need(ok, message) {
8
+ if (!ok) throw new Error(message);
9
+ }
10
+
11
+ function checkKdf(k) {
12
+ const id = algorithms.indexOf(k.algorithm);
13
+ need(id > 0, 'unknown KDF');
14
+ if (id < 3) {
15
+ need(inRange(k.iterations, 100000, 10000000), 'kdf.iterations must be an integer 100000–10000000');
16
+ } else {
17
+ const { N, r, p } = k;
18
+ const logN = Math.log2(N);
19
+ need(inRange(N, 8192, 262144) && Number.isInteger(logN) &&
20
+ inRange(r, 1, 32) && inRange(p, 1, 16) && logN < 16 * r &&
21
+ 128 * r * N <= 128 * 2 ** 20 && N * r * p <= 2 ** 20, 'invalid scrypt cost');
22
+ }
23
+ return k;
24
+ }
25
+
26
+ function headerFor(k) {
27
+ checkKdf(k);
28
+ const id = algorithms.indexOf(k.algorithm);
29
+ const h = Uint8Array.of(72, 66, 69, 53, 5, id, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0);
30
+ const view = new DataView(h.buffer);
31
+ if (id === 3) {
32
+ h[8] = Math.log2(k.N);
33
+ view.setUint16(9, k.r);
34
+ view.setUint16(11, k.p);
35
+ } else {
36
+ view.setUint32(8, k.iterations);
37
+ }
38
+ return h;
39
+ }
40
+
41
+ function readHeader(h) {
42
+ need(h.length === 16, 'header length');
43
+ const view = new DataView(h.buffer, h.byteOffset, 16);
44
+ const algorithm = algorithms[h[5]];
45
+ let k;
46
+ if (h[5] === 3) {
47
+ need(inRange(h[8], 13, 18), 'scrypt log2N');
48
+ k = { algorithm, N: 2 ** h[8], r: view.getUint16(9), p: view.getUint16(11) };
49
+ } else {
50
+ k = { algorithm, iterations: view.getUint32(8) };
51
+ }
52
+ // Re-encoding validates costs as well as all fixed and reserved bytes.
53
+ need(headerFor(k).every((byte, i) => byte === h[i]), 'noncanonical header');
54
+ return k;
55
+ }
56
+
57
+ function frameLength(n) {
58
+ need(inRange(n, 0, 2 ** 24), 'plaintext length');
59
+ const length = n + 4;
60
+ if (length <= 256) return 256;
61
+
62
+ // Padmé: round up after keeping as many mantissa bits as the exponent's bit length.
63
+ const exponent = 31 - Math.clz32(length);
64
+ const bits = 32 - Math.clz32(exponent);
65
+ const mask = (1 << (exponent - bits)) - 1;
66
+ return (length + mask) & ~mask;
67
+ }
68
+
69
+ function unframe(f) {
70
+ const n = new DataView(f.buffer, f.byteOffset, f.byteLength).getUint32(0);
71
+ const canonical = frameLength(n);
72
+ need(n <= f.length - 4 && canonical === f.length, 'frame length');
73
+ need(!f.subarray(4 + n).some(byte => byte !== 0), 'padding');
74
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(f.subarray(4, 4 + n));
75
+ }
76
+
77
+ module.exports = { checkKdf, headerFor, readHeader, frameLength, unframe };