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.
@@ -2,6 +2,7 @@
2
2
 
3
3
  const fs = require('node:fs');
4
4
  const crypto = require('node:crypto');
5
+ const { Readable } = require('node:stream');
5
6
 
6
7
  const HASH_BYTES = 5;
7
8
 
@@ -9,28 +10,33 @@ function hex10(buf) {
9
10
  return crypto.createHash('sha256').update(buf).digest('hex').slice(0, HASH_BYTES * 2);
10
11
  }
11
12
 
12
- /**
13
- * Build the v4 Hexo generator function. Returns a function that, when
14
- * invoked by Hexo's generator pipeline, yields:
15
- * - `css/hbe.style.css` — the plugin stylesheet (lazy fs.createReadStream)
16
- * - `lib/hbe.<hex10>.js` — the browser bundle, named with a content hash
17
- * (first 10 lowercase hex chars of SHA-256(bundle bytes))
18
- * - `lib/hbe.<hex10>.js.map` — sourcemap, ONLY if `sourcemapPath` is provided
19
- * AND that file exists on disk
20
- *
21
- * Bundle bytes (and therefore the hash) are read **lazily on each generation
22
- * call** rather than at module load. This avoids ENOENT crashes on a fresh
23
- * clone before `npm run build` has run, and lets the hash track edits to the
24
- * bundle file across hot-reload cycles in `hexo server`.
25
- *
26
- * @param {object} opts
27
- * @param {string} opts.bundlePath Absolute path to the browser bundle JS.
28
- * @param {string} opts.cssPath Absolute path to the plugin stylesheet.
29
- * @param {string} [opts.sourcemapPath] Absolute path to the bundle sourcemap.
30
- * Optional; if absent or file missing,
31
- * no `.map` route is emitted.
32
- * @returns {() => Array<{path: string, data: Function}>}
33
- */
13
+ // esbuild ends the bundle with `//# sourceMappingURL=hbe.bundle.js.map`, a
14
+ // file that is never served (#262). Point it at the emitted hashed map, or
15
+ // strip it when no map route is emitted, so browsers never request a 404.
16
+ const SOURCEMAP_COMMENT_RE = /\n?\/\/# sourceMappingURL=\S+\s*$/;
17
+
18
+ function linkSourcemap(bytes, mapName) {
19
+ const text = bytes.toString('utf8');
20
+ if (!SOURCEMAP_COMMENT_RE.test(text)) return bytes;
21
+ const replacement = mapName ? `\n//# sourceMappingURL=${mapName}\n` : '\n';
22
+ return Buffer.from(text.replace(SOURCEMAP_COMMENT_RE, replacement), 'utf8');
23
+ }
24
+
25
+ const integrity = bytes => 'sha384-' + crypto.createHash('sha384').update(bytes).digest('base64');
26
+
27
+ function reader(file) {
28
+ let cache;
29
+ return () => {
30
+ const { mtimeMs, size } = fs.statSync(file);
31
+ if (!cache || cache.mtimeMs !== mtimeMs || cache.size !== size) {
32
+ const bytes = fs.readFileSync(file);
33
+ cache = { mtimeMs, size, bytes, hash: hex10(bytes) };
34
+ }
35
+ return cache;
36
+ };
37
+ }
38
+
39
+ // Generated routes are ordered CSS, JS, then optional map; data() owns its generation's snapshot.
34
40
  function createGenerator(opts) {
35
41
  if (!opts || typeof opts.bundlePath !== 'string' || !opts.bundlePath) {
36
42
  throw new Error('createGenerator: bundlePath is required');
@@ -45,51 +51,22 @@ function createGenerator(opts) {
45
51
  ? opts.sourcemapPath
46
52
  : null;
47
53
 
48
- // Memoization cell — populated on first call and refreshed when the
49
- // bundle file's mtime/size changes. See the in-function comment below
50
- // for why this is correct.
51
- let cache = null;
52
-
54
+ const bundle = reader(bundlePath), css = reader(cssPath);
53
55
  return function generate() {
54
- // Memoize bundle bytes by mtime: in `hexo generate` (single build) the
55
- // file never changes, so all calls return the cached buffer + hash. In
56
- // `hexo server` watch mode, an `npm run build` mid-session updates the
57
- // mtime, invalidating the cache exactly once. This closes the
58
- // hash-mismatch window between the filter (which inlines the script
59
- // src) and the generator (which emits the bytes) — both now agree on
60
- // the same content hash within one mtime tick.
61
- const stat = fs.statSync(bundlePath);
62
- if (cache === null || cache.mtimeMs !== stat.mtimeMs || cache.size !== stat.size) {
63
- const bundleBytes = fs.readFileSync(bundlePath);
64
- cache = {
65
- mtimeMs: stat.mtimeMs,
66
- size: stat.size,
67
- bytes: bundleBytes,
68
- hash: hex10(bundleBytes),
69
- };
70
- }
71
- const { bytes: bundleBytes, hash } = cache;
72
- const jsRoutePath = `lib/hbe.${hash}.js`;
73
-
56
+ const { bytes: rawBundleBytes, hash } = bundle();
57
+ const { bytes: cssBytes, hash: cssHash } = css();
58
+ const hasMap = Boolean(sourcemapPath && fs.existsSync(sourcemapPath));
59
+ const digit = (parseInt(hash[9], 16) & ~1) | (hasMap ? 1 : 0);
60
+ const name = `hbe.${hash.slice(0, 9)}${digit.toString(16)}.js`;
61
+ const jsBytes = linkSourcemap(rawBundleBytes, hasMap ? name + '.map' : null);
74
62
  const routes = [
75
- {
76
- path: 'css/hbe.style.css',
77
- data: () => fs.createReadStream(cssPath),
78
- },
79
- {
80
- path: jsRoutePath,
81
- data: () => bundleBytes,
82
- },
63
+ { path: `css/hbe.${cssHash}.css`, integrity: integrity(cssBytes), data: () => Readable.from([cssBytes]) },
64
+ { path: 'lib/' + name, integrity: integrity(jsBytes), data: () => jsBytes },
83
65
  ];
84
-
85
- if (sourcemapPath && fs.existsSync(sourcemapPath)) {
86
- const mapBytes = fs.readFileSync(sourcemapPath);
87
- routes.push({
88
- path: `lib/hbe.${hash}.js.map`,
89
- data: () => mapBytes,
90
- });
66
+ if (hasMap) {
67
+ const bytes = fs.readFileSync(sourcemapPath);
68
+ routes.push({ path: 'lib/' + name + '.map', integrity: integrity(bytes), data: () => bytes });
91
69
  }
92
-
93
70
  return routes;
94
71
  };
95
72
  }
@@ -15,14 +15,14 @@ const CSS_PATH = path.join(REPO_ROOT, 'lib', 'hbe.style.css');
15
15
  const BUNDLE_PATH = path.join(REPO_ROOT, 'lib', 'hbe.bundle.js');
16
16
  const BUNDLE_SOURCEMAP_PATH = path.join(REPO_ROOT, 'lib', 'hbe.bundle.js.map');
17
17
 
18
- const FORMAT_VERSION = '4';
19
- const STABLE_SALT_NAMESPACE = 'hexo-blog-encrypt:v4:stableSalt:';
18
+ const FORMAT_VERSION = '5';
19
+ const STABLE_SALT_NAMESPACE = 'hexo-blog-encrypt:v5:stableSalt:';
20
20
 
21
21
  // Per-instance Symbol so user front-matter keys can never collide with our
22
22
  // idempotence marker. We deliberately do NOT use Symbol.for(...) (a global
23
23
  // registry) — a per-process Symbol guarantees external code cannot fabricate
24
24
  // the marker even by accident.
25
- const HBE_ENCRYPTED = Symbol('hexo-blog-encrypt.v4.encrypted');
25
+ const HBE_ENCRYPTED = Symbol('hexo-blog-encrypt.v5.encrypted');
26
26
 
27
27
  function normalizeRoot(root) {
28
28
  if (typeof root !== 'string') return '/';
@@ -91,7 +91,7 @@ function register(hexo) {
91
91
  sourcemapPath: BUNDLE_SOURCEMAP_PATH,
92
92
  });
93
93
 
94
- hexo.extend.filter.register('after_post_render', function v4Filter(data) {
94
+ hexo.extend.filter.register('after_post_render', async function v5Filter(data) {
95
95
  // Idempotence: stamp a per-instance Symbol on `data` after a successful
96
96
  // pass so re-entry on the same object is a no-op. We deliberately do NOT
97
97
  // use `data.encrypt === true` (a user-set "please encrypt" front-matter
@@ -109,11 +109,19 @@ function register(hexo) {
109
109
  return data;
110
110
  }
111
111
 
112
+ const titleText = (typeof data.title === 'string') ? data.title.trim() : '(untitled)';
112
113
  let effectivePostData = data;
113
114
  if (fmPassword === undefined || fmPassword === null) {
114
115
  const tagMatch = resolveTagPassword(hexo.config && hexo.config.encrypt, data.tags);
115
- if (!tagMatch || tagMatch.password === undefined || tagMatch.password === null) {
116
- return data;
116
+ if (!tagMatch) return data;
117
+ if (tagMatch.password === undefined || tagMatch.password === null) {
118
+ // Fail closed (#244): a matching tag entry without a password is a
119
+ // config mistake; publishing the post in plaintext would be silent.
120
+ throw new Error(
121
+ `hexo-blog-encrypt: post "${titleText}" matches encrypt.tags entry "${tagMatch.name}", ` +
122
+ 'but that entry has no password. Set a password on the tag entry in _config.yml, ' +
123
+ 'or add `password: ""` to the post front matter to publish it unencrypted.'
124
+ );
117
125
  }
118
126
  effectivePostData = Object.assign({}, data, { password: tagMatch.password });
119
127
  effectivePostData.__tagName = tagMatch.name;
@@ -132,7 +140,6 @@ function register(hexo) {
132
140
  logger.updateSilent(!!cfg.silent);
133
141
 
134
142
  const tagName = effectivePostData.__tagName;
135
- const titleText = (typeof data.title === 'string') ? data.title.trim() : '(untitled)';
136
143
  if (tagName) {
137
144
  logger.info(`hexo-blog-encrypt: encrypting "${titleText}" via tag "${tagName}" with theme ${cfg.theme}.`);
138
145
  } else {
@@ -146,8 +153,8 @@ function register(hexo) {
146
153
  const stableSaltEnabled = cfg.stableSalt === true
147
154
  && typeof data.permalink === 'string'
148
155
  && data.permalink.length > 0;
149
- const { salt, nonce, ciphertext } = encrypt(plaintext, cfg.password, {
150
- iterations: cfg.kdf.iterations,
156
+ const { salt, nonce, ciphertext } = await encrypt(plaintext, cfg.password, {
157
+ kdf: cfg.kdf,
151
158
  salt: stableSaltEnabled ? stableSaltFromPermalink(data.permalink) : undefined,
152
159
  });
153
160
 
@@ -168,20 +175,18 @@ function register(hexo) {
168
175
  whm: cfg.wrong_hash_message,
169
176
  buttonClass: buttonShow ? '' : ' hbe-button-hidden',
170
177
  buttonText,
171
- kdfIterations: cfg.kdf.iterations,
178
+ kdfIterations: cfg.kdf.N ?? cfg.kdf.iterations,
172
179
  autoSave: !!cfg.autoSave,
173
180
  });
174
181
 
175
182
  const root = normalizeRoot(hexo.config && hexo.config.root);
176
- const routes = assetGenerator();
177
- const jsRoute = routes.find((r) => /^lib\/hbe\.[0-9a-f]{10}\.js$/.test(r.path));
178
- const cssRoute = routes.find((r) => r.path === 'css/hbe.style.css');
183
+ const [cssRoute, jsRoute] = assetGenerator();
179
184
  const jsHref = root + jsRoute.path;
180
185
  const cssHref = root + cssRoute.path;
181
186
 
182
187
  data.content = rendered +
183
- `<script data-pjax src="${jsHref}"></script>` +
184
- `<link href="${cssHref}" rel="stylesheet" type="text/css">`;
188
+ `<script data-pjax src="${jsHref}" integrity="${jsRoute.integrity}" crossorigin="anonymous"></script>` +
189
+ `<link href="${cssHref}" rel="stylesheet" type="text/css" integrity="${cssRoute.integrity}" crossorigin="anonymous">`;
185
190
  data.encrypt = true;
186
191
  data.excerpt = data.more = cfg.abstract;
187
192
  data[HBE_ENCRYPTED] = true;
@@ -37,7 +37,8 @@ const PLACEHOLDERS = [
37
37
  { token: '{{hbeWrongHashMessage}}', field: 'whm', mode: 'attr' },
38
38
  { token: '{{hbeKdfIterations}}', field: 'kdfIterations', mode: 'attr' },
39
39
  { token: '{{hbeAutoSave}}', field: 'autoSave', mode: 'attr' },
40
- { token: '{{hbeMessage}}', field: 'message', mode: 'text' },
40
+ // attr (#247): some themes place the message inside data-content="…".
41
+ { token: '{{hbeMessage}}', field: 'message', mode: 'attr' },
41
42
  { token: '{{hbeButtonClass}}', field: 'buttonClass', mode: 'attr' },
42
43
  { token: '{{hbeButtonText}}', field: 'buttonText', mode: 'text' },
43
44
  { token: '{{hbeSalt}}', field: 'salt', mode: 'hex' },