hexo-blog-encrypt 3.1.9 → 4.0.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.
- package/LICENSE +1 -1
- package/ReadMe.md +117 -16
- package/ReadMe.zh.md +103 -15
- package/index.js +2 -169
- package/lib/hbe.blink.html +16 -3
- package/lib/hbe.bundle.js +2 -0
- package/lib/hbe.bundle.js.map +7 -0
- package/lib/hbe.default.html +16 -3
- package/lib/hbe.flip.html +16 -3
- package/lib/hbe.shrink.html +16 -3
- package/lib/hbe.style.css +105 -0
- package/lib/hbe.surge.html +16 -3
- package/lib/hbe.up.html +16 -3
- package/lib/hbe.wave.html +16 -3
- package/lib/hbe.xray.html +16 -3
- package/package.json +27 -4
- package/src/server/config.js +162 -0
- package/src/server/crypto.js +67 -0
- package/src/server/generator.js +97 -0
- package/src/server/index.js +180 -0
- package/src/server/logger.js +60 -0
- package/src/server/template.js +135 -0
- package/.editorconfig +0 -14
- package/.eslintrc.js +0 -11
- package/.github/CONTRIBUTING.md +0 -22
- package/.github/ISSUE_TEMPLATE.md +0 -15
- package/.github/PULL_REQUEST_TEMPLATE.md +0 -10
- package/lib/hbe.js +0 -297
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const crypto = require('node:crypto');
|
|
5
|
+
|
|
6
|
+
const HASH_BYTES = 5;
|
|
7
|
+
|
|
8
|
+
function hex10(buf) {
|
|
9
|
+
return crypto.createHash('sha256').update(buf).digest('hex').slice(0, HASH_BYTES * 2);
|
|
10
|
+
}
|
|
11
|
+
|
|
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
|
+
*/
|
|
34
|
+
function createGenerator(opts) {
|
|
35
|
+
if (!opts || typeof opts.bundlePath !== 'string' || !opts.bundlePath) {
|
|
36
|
+
throw new Error('createGenerator: bundlePath is required');
|
|
37
|
+
}
|
|
38
|
+
if (typeof opts.cssPath !== 'string' || !opts.cssPath) {
|
|
39
|
+
throw new Error('createGenerator: cssPath is required');
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const bundlePath = opts.bundlePath;
|
|
43
|
+
const cssPath = opts.cssPath;
|
|
44
|
+
const sourcemapPath = typeof opts.sourcemapPath === 'string' && opts.sourcemapPath
|
|
45
|
+
? opts.sourcemapPath
|
|
46
|
+
: null;
|
|
47
|
+
|
|
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
|
+
|
|
53
|
+
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
|
+
|
|
74
|
+
const routes = [
|
|
75
|
+
{
|
|
76
|
+
path: 'css/hbe.style.css',
|
|
77
|
+
data: () => fs.createReadStream(cssPath),
|
|
78
|
+
},
|
|
79
|
+
{
|
|
80
|
+
path: jsRoutePath,
|
|
81
|
+
data: () => bundleBytes,
|
|
82
|
+
},
|
|
83
|
+
];
|
|
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
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return routes;
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
module.exports = { createGenerator };
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
|
|
5
|
+
const { resolve } = require('./config');
|
|
6
|
+
const { encrypt } = require('./crypto');
|
|
7
|
+
const { createRenderer } = require('./template');
|
|
8
|
+
const { createGenerator } = require('./generator');
|
|
9
|
+
const { createLogger } = require('./logger');
|
|
10
|
+
|
|
11
|
+
const REPO_ROOT = path.resolve(__dirname, '..', '..');
|
|
12
|
+
const TEMPLATE_DIR = path.join(REPO_ROOT, 'lib');
|
|
13
|
+
const CSS_PATH = path.join(REPO_ROOT, 'lib', 'hbe.style.css');
|
|
14
|
+
const BUNDLE_PATH = path.join(REPO_ROOT, 'lib', 'hbe.bundle.js');
|
|
15
|
+
const BUNDLE_SOURCEMAP_PATH = path.join(REPO_ROOT, 'lib', 'hbe.bundle.js.map');
|
|
16
|
+
|
|
17
|
+
const FORMAT_VERSION = '4';
|
|
18
|
+
|
|
19
|
+
// Per-instance Symbol so user front-matter keys can never collide with our
|
|
20
|
+
// idempotence marker. We deliberately do NOT use Symbol.for(...) (a global
|
|
21
|
+
// registry) — a per-process Symbol guarantees external code cannot fabricate
|
|
22
|
+
// the marker even by accident.
|
|
23
|
+
const HBE_ENCRYPTED = Symbol('hexo-blog-encrypt.v4.encrypted');
|
|
24
|
+
|
|
25
|
+
function normalizeRoot(root) {
|
|
26
|
+
if (typeof root !== 'string') return '/';
|
|
27
|
+
return root.endsWith('/') ? root : root + '/';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function normalizePostTags(postTags) {
|
|
31
|
+
// Real Hexo posts: `data.tags` is a Warehouse Query (NOT a plain array).
|
|
32
|
+
// `Array.isArray(query) === false`, but `query.toArray()` and
|
|
33
|
+
// `query.forEach(tag => …)` both work. v3 used `data.tags.forEach(…)`;
|
|
34
|
+
// we replicate that contract here while ALSO accepting plain arrays so
|
|
35
|
+
// synthetic test data and other plugins that pre-flatten still work.
|
|
36
|
+
// Returning [] means "no tag-encryption applies" — the post is left
|
|
37
|
+
// unencrypted IFF it also has no front-matter password (which is the
|
|
38
|
+
// correct behaviour for a post that genuinely has no tags).
|
|
39
|
+
if (postTags == null) return [];
|
|
40
|
+
if (Array.isArray(postTags)) return postTags;
|
|
41
|
+
if (typeof postTags.toArray === 'function') return postTags.toArray();
|
|
42
|
+
if (typeof postTags.forEach === 'function') {
|
|
43
|
+
const out = [];
|
|
44
|
+
postTags.forEach((t) => out.push(t));
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
return [];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function resolveTagPassword(hexoEncrypt, postTags) {
|
|
51
|
+
if (!hexoEncrypt || !Array.isArray(hexoEncrypt.tags)) return null;
|
|
52
|
+
const tags = normalizePostTags(postTags);
|
|
53
|
+
if (tags.length === 0) return null;
|
|
54
|
+
const map = Object.create(null);
|
|
55
|
+
for (const t of hexoEncrypt.tags) {
|
|
56
|
+
if (t && typeof t.name === 'string') map[t.name] = t.password;
|
|
57
|
+
}
|
|
58
|
+
for (const t of tags) {
|
|
59
|
+
if (t && typeof t.name === 'string' && Object.prototype.hasOwnProperty.call(map, t.name)) {
|
|
60
|
+
return { name: t.name, password: map[t.name] };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function register(hexo) {
|
|
67
|
+
if (!hexo) throw new Error('hexo-blog-encrypt: hexo instance is required');
|
|
68
|
+
|
|
69
|
+
const logger = createLogger({ hexo, silent: false });
|
|
70
|
+
const renderer = createRenderer({ templateDir: TEMPLATE_DIR, logger });
|
|
71
|
+
// Single shared generator instance — used by both the filter (for
|
|
72
|
+
// computing the script src hash) and Hexo's generator pipeline (for
|
|
73
|
+
// emitting the bytes). The generator memoizes the bundle bytes/hash by
|
|
74
|
+
// mtime, so all calls within one generation cycle agree on the same
|
|
75
|
+
// content hash, eliminating the per-call disk re-read AND the
|
|
76
|
+
// hash-mismatch window between filter and generator (see
|
|
77
|
+
// `src/server/generator.js`).
|
|
78
|
+
const assetGenerator = createGenerator({
|
|
79
|
+
bundlePath: BUNDLE_PATH,
|
|
80
|
+
cssPath: CSS_PATH,
|
|
81
|
+
sourcemapPath: BUNDLE_SOURCEMAP_PATH,
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
hexo.extend.filter.register('after_post_render', function v4Filter(data) {
|
|
85
|
+
// Idempotence: stamp a per-instance Symbol on `data` after a successful
|
|
86
|
+
// pass so re-entry on the same object is a no-op. We deliberately do NOT
|
|
87
|
+
// use `data.encrypt === true` (a user-set "please encrypt" front-matter
|
|
88
|
+
// signal) or `data.origin` (a generic property name another plugin or
|
|
89
|
+
// user could legitimately populate) as the marker — both have caused
|
|
90
|
+
// silent-skip footguns in earlier designs.
|
|
91
|
+
if (data[HBE_ENCRYPTED] === true) {
|
|
92
|
+
return data;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Resolve effective password from front-matter > tag > nothing.
|
|
96
|
+
const fmPassword = data.password;
|
|
97
|
+
if (fmPassword === '') {
|
|
98
|
+
// Empty FM password explicitly disables encryption (criterion 4).
|
|
99
|
+
return data;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let effectivePostData = data;
|
|
103
|
+
if (fmPassword === undefined || fmPassword === null) {
|
|
104
|
+
const tagMatch = resolveTagPassword(hexo.config && hexo.config.encrypt, data.tags);
|
|
105
|
+
if (!tagMatch || tagMatch.password === undefined || tagMatch.password === null) {
|
|
106
|
+
return data;
|
|
107
|
+
}
|
|
108
|
+
effectivePostData = Object.assign({}, data, { password: tagMatch.password });
|
|
109
|
+
effectivePostData.__tagName = tagMatch.name;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// resolve() throws on misconfiguration (e.g. kdf.iterations below floor).
|
|
113
|
+
// Let it propagate — the original stack is the most actionable thing for
|
|
114
|
+
// the user, and Hexo will surface the error through its own logger.
|
|
115
|
+
const cfg = resolve(hexo.config, effectivePostData, logger);
|
|
116
|
+
if (cfg === null) {
|
|
117
|
+
// Defensive: resolve() returns null when the resolved password collapses
|
|
118
|
+
// to undefined/empty (e.g. a tag entry with `password: ''`). Bypass.
|
|
119
|
+
return data;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
logger.updateSilent(!!cfg.silent);
|
|
123
|
+
|
|
124
|
+
const tagName = effectivePostData.__tagName;
|
|
125
|
+
const titleText = (typeof data.title === 'string') ? data.title.trim() : '(untitled)';
|
|
126
|
+
if (tagName) {
|
|
127
|
+
logger.info(`hexo-blog-encrypt: encrypting "${titleText}" via tag "${tagName}" with theme ${cfg.theme}.`);
|
|
128
|
+
} else {
|
|
129
|
+
logger.info(`hexo-blog-encrypt: encrypting "${titleText}" via front-matter password with theme ${cfg.theme}.`);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Preserve original plaintext so themes (TOC, etc.) can still introspect it.
|
|
133
|
+
data.origin = data.content;
|
|
134
|
+
|
|
135
|
+
const plaintext = String(data.content == null ? '' : data.content);
|
|
136
|
+
const { salt, nonce, ciphertext } = encrypt(plaintext, cfg.password, {
|
|
137
|
+
iterations: cfg.kdf.iterations,
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
const buttonShow = !cfg.decryptButton || cfg.decryptButton.show !== false;
|
|
141
|
+
const buttonText = (cfg.decryptButton && typeof cfg.decryptButton.text === 'string')
|
|
142
|
+
? cfg.decryptButton.text
|
|
143
|
+
: 'Decrypt';
|
|
144
|
+
|
|
145
|
+
const themeName = String(cfg.theme || 'default').trim().toLowerCase();
|
|
146
|
+
const rendered = renderer.render({
|
|
147
|
+
theme: themeName,
|
|
148
|
+
format: FORMAT_VERSION,
|
|
149
|
+
ciphertext: ciphertext.toString('hex'),
|
|
150
|
+
salt: salt.toString('hex'),
|
|
151
|
+
nonce: nonce.toString('hex'),
|
|
152
|
+
message: cfg.message,
|
|
153
|
+
wpm: cfg.wrong_pass_message,
|
|
154
|
+
whm: cfg.wrong_hash_message,
|
|
155
|
+
buttonText: buttonShow ? buttonText : '',
|
|
156
|
+
kdfIterations: cfg.kdf.iterations,
|
|
157
|
+
autoSave: !!cfg.autoSave,
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
const root = normalizeRoot(hexo.config && hexo.config.root);
|
|
161
|
+
const routes = assetGenerator();
|
|
162
|
+
const jsRoute = routes.find((r) => /^lib\/hbe\.[0-9a-f]{10}\.js$/.test(r.path));
|
|
163
|
+
const cssRoute = routes.find((r) => r.path === 'css/hbe.style.css');
|
|
164
|
+
const jsHref = root + jsRoute.path;
|
|
165
|
+
const cssHref = root + cssRoute.path;
|
|
166
|
+
|
|
167
|
+
data.content = rendered +
|
|
168
|
+
`<script data-pjax src="${jsHref}"></script>` +
|
|
169
|
+
`<link href="${cssHref}" rel="stylesheet" type="text/css">`;
|
|
170
|
+
data.encrypt = true;
|
|
171
|
+
data.excerpt = data.more = cfg.abstract;
|
|
172
|
+
data[HBE_ENCRYPTED] = true;
|
|
173
|
+
|
|
174
|
+
return data;
|
|
175
|
+
}, 1000);
|
|
176
|
+
|
|
177
|
+
hexo.extend.generator.register('hexo-blog-encrypt', assetGenerator);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
module.exports = { register };
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Silent-aware wrapper around `hexo.log` (or `console` when running outside
|
|
5
|
+
* a Hexo process — e.g. unit tests).
|
|
6
|
+
*
|
|
7
|
+
* Silent semantics (matches v3 behavior in legacy `index.js`):
|
|
8
|
+
* - `silent: true` → `info` and `debug` calls are dropped
|
|
9
|
+
* - `silent: true` → `warn` and `error` ALWAYS pass through
|
|
10
|
+
* - `silent: false` → all four levels pass through
|
|
11
|
+
*
|
|
12
|
+
* Rationale: `silent` was always intended to suppress build-time chatter,
|
|
13
|
+
* not to hide warnings (deprecations, fallback themes) or errors. Hiding
|
|
14
|
+
* warnings would let real configuration mistakes ship to production.
|
|
15
|
+
*
|
|
16
|
+
* @param {object} opts
|
|
17
|
+
* @param {object} [opts.hexo] Hexo instance (uses `hexo.log.{info,warn,error,debug}`)
|
|
18
|
+
* @param {boolean} [opts.silent=false]
|
|
19
|
+
* @returns {{
|
|
20
|
+
* info: (msg: string) => void,
|
|
21
|
+
* warn: (msg: string) => void,
|
|
22
|
+
* error: (msg: string) => void,
|
|
23
|
+
* debug: (msg: string) => void,
|
|
24
|
+
* updateSilent: (next: boolean) => void,
|
|
25
|
+
* }}
|
|
26
|
+
*/
|
|
27
|
+
function createLogger(opts) {
|
|
28
|
+
const o = opts || {};
|
|
29
|
+
let silent = !!o.silent;
|
|
30
|
+
const log = o.hexo && o.hexo.log ? o.hexo.log : null;
|
|
31
|
+
|
|
32
|
+
function emit(level, msg) {
|
|
33
|
+
if (silent && (level === 'info' || level === 'debug')) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (log && typeof log[level] === 'function') {
|
|
37
|
+
log[level](msg);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
if (level === 'warn') {
|
|
41
|
+
console.warn(msg);
|
|
42
|
+
} else if (level === 'error') {
|
|
43
|
+
console.error(msg);
|
|
44
|
+
} else if (level === 'debug') {
|
|
45
|
+
console.debug(msg);
|
|
46
|
+
} else {
|
|
47
|
+
console.log(msg);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return {
|
|
52
|
+
info: (m) => emit('info', m),
|
|
53
|
+
warn: (m) => emit('warn', m),
|
|
54
|
+
error: (m) => emit('error', m),
|
|
55
|
+
debug: (m) => emit('debug', m),
|
|
56
|
+
updateSilent: (next) => { silent = !!next; },
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { createLogger };
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('node:fs');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
|
|
6
|
+
const THEME_FILE_RE = /^hbe\.([a-z0-9-]+)\.html$/;
|
|
7
|
+
|
|
8
|
+
const ATTR_ESCAPE_MAP = {
|
|
9
|
+
'&': '&',
|
|
10
|
+
'<': '<',
|
|
11
|
+
'>': '>',
|
|
12
|
+
'"': '"',
|
|
13
|
+
"'": ''',
|
|
14
|
+
'`': '`',
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
function escapeAttr(value) {
|
|
18
|
+
return String(value).replace(/[&<>"'`]/g, (ch) => ATTR_ESCAPE_MAP[ch]);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function escapeText(value) {
|
|
22
|
+
return String(value).replace(/[&<>]/g, (ch) => {
|
|
23
|
+
if (ch === '&') return '&';
|
|
24
|
+
if (ch === '<') return '<';
|
|
25
|
+
return '>';
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Substitution table.
|
|
30
|
+
// - 'attr': escape with the attribute-context escape (covers all six special chars + backtick).
|
|
31
|
+
// - 'text': escape with the text-context escape (& < > only).
|
|
32
|
+
// - 'raw' : insert verbatim. Used ONLY for already-hex-encoded crypto material whose
|
|
33
|
+
// character set is a strict subset of [0-9a-fA-F]+ (validated below).
|
|
34
|
+
const PLACEHOLDERS = [
|
|
35
|
+
{ token: '{{hbeFormat}}', field: 'format', mode: 'attr' },
|
|
36
|
+
{ token: '{{hbeWrongPassMessage}}', field: 'wpm', mode: 'attr' },
|
|
37
|
+
{ token: '{{hbeWrongHashMessage}}', field: 'whm', mode: 'attr' },
|
|
38
|
+
{ token: '{{hbeKdfIterations}}', field: 'kdfIterations', mode: 'attr' },
|
|
39
|
+
{ token: '{{hbeAutoSave}}', field: 'autoSave', mode: 'attr' },
|
|
40
|
+
{ token: '{{hbeMessage}}', field: 'message', mode: 'text' },
|
|
41
|
+
{ token: '{{hbeButtonText}}', field: 'buttonText', mode: 'text' },
|
|
42
|
+
{ token: '{{hbeSalt}}', field: 'salt', mode: 'hex' },
|
|
43
|
+
{ token: '{{hbeNonce}}', field: 'nonce', mode: 'hex' },
|
|
44
|
+
{ token: '{{hbeEncryptedData}}', field: 'ciphertext', mode: 'hex' },
|
|
45
|
+
];
|
|
46
|
+
|
|
47
|
+
function valueOf(opts, field) {
|
|
48
|
+
const v = opts[field];
|
|
49
|
+
if (field === 'kdfIterations') return String(v);
|
|
50
|
+
if (field === 'autoSave') return v ? 'true' : 'false';
|
|
51
|
+
return v === undefined || v === null ? '' : v;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function substitute(template, opts) {
|
|
55
|
+
let out = template;
|
|
56
|
+
for (const { token, field, mode } of PLACEHOLDERS) {
|
|
57
|
+
const raw = valueOf(opts, field);
|
|
58
|
+
let replacement;
|
|
59
|
+
if (mode === 'attr') replacement = escapeAttr(raw);
|
|
60
|
+
else if (mode === 'text') replacement = escapeText(raw);
|
|
61
|
+
else if (mode === 'hex') {
|
|
62
|
+
// Defence-in-depth: refuse to splice anything that isn't hex.
|
|
63
|
+
const s = String(raw);
|
|
64
|
+
if (s.length > 0 && !/^[0-9a-fA-F]+$/.test(s)) {
|
|
65
|
+
throw new Error(`hexo-blog-encrypt: refusing to render non-hex value into ${field} slot`);
|
|
66
|
+
}
|
|
67
|
+
replacement = s;
|
|
68
|
+
}
|
|
69
|
+
out = out.split(token).join(replacement);
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function discoverThemes(templateDir) {
|
|
75
|
+
let entries;
|
|
76
|
+
try {
|
|
77
|
+
entries = fs.readdirSync(templateDir);
|
|
78
|
+
} catch (_e) {
|
|
79
|
+
return new Map();
|
|
80
|
+
}
|
|
81
|
+
const map = new Map();
|
|
82
|
+
for (const name of entries) {
|
|
83
|
+
const m = THEME_FILE_RE.exec(name);
|
|
84
|
+
if (!m) continue;
|
|
85
|
+
map.set(m[1], path.join(templateDir, name));
|
|
86
|
+
}
|
|
87
|
+
return map;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function createRenderer(args) {
|
|
91
|
+
const templateDir = args && args.templateDir;
|
|
92
|
+
if (!templateDir) throw new Error('createRenderer requires templateDir');
|
|
93
|
+
// Only `warn` is ever called from this module (unknown-theme fallback).
|
|
94
|
+
const log = (args && args.logger) || { warn: () => {} };
|
|
95
|
+
|
|
96
|
+
const themes = discoverThemes(templateDir);
|
|
97
|
+
const cache = new Map();
|
|
98
|
+
|
|
99
|
+
function readTheme(name) {
|
|
100
|
+
if (cache.has(name)) return cache.get(name);
|
|
101
|
+
const file = themes.get(name);
|
|
102
|
+
if (!file) return null;
|
|
103
|
+
const body = fs.readFileSync(file, 'utf8');
|
|
104
|
+
cache.set(name, body);
|
|
105
|
+
return body;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function render(opts) {
|
|
109
|
+
const requested = (opts && opts.theme) || 'default';
|
|
110
|
+
let body = readTheme(requested);
|
|
111
|
+
if (body === null) {
|
|
112
|
+
log.warn(
|
|
113
|
+
`hexo-blog-encrypt: theme "${requested}" is not in the allowlist; falling back to default. ` +
|
|
114
|
+
'Available themes: ' + [...themes.keys()].sort().join(', ')
|
|
115
|
+
);
|
|
116
|
+
body = readTheme('default');
|
|
117
|
+
if (body === null) {
|
|
118
|
+
throw new Error('hexo-blog-encrypt: default theme not found in ' + templateDir);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return substitute(body, opts || {});
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function listThemes() {
|
|
125
|
+
return [...themes.keys()].sort();
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
return { render, listThemes };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
module.exports = {
|
|
132
|
+
createRenderer,
|
|
133
|
+
// Exported for unit testing of the escape primitives.
|
|
134
|
+
_internal: { escapeAttr, escapeText, discoverThemes, THEME_FILE_RE },
|
|
135
|
+
};
|
package/.editorconfig
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
root = true
|
|
2
|
-
|
|
3
|
-
[*]
|
|
4
|
-
indent_style = space
|
|
5
|
-
indent_size = 2
|
|
6
|
-
charset = utf-8
|
|
7
|
-
trim_trailing_whitespace = true
|
|
8
|
-
insert_final_newline = true
|
|
9
|
-
end_of_line = lf
|
|
10
|
-
# editorconfig-tools is unable to ignore longs strings or urls
|
|
11
|
-
max_line_length = null
|
|
12
|
-
|
|
13
|
-
[*.md]
|
|
14
|
-
trim_trailing_whitespace = false
|
package/.eslintrc.js
DELETED
package/.github/CONTRIBUTING.md
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
# How to Contribute to This Project
|
|
2
|
-
|
|
3
|
-
## **Did You Find a Bug?**
|
|
4
|
-
|
|
5
|
-
- **Ensure the bug was not already reported** by searching on GitHub under [Issues].
|
|
6
|
-
- If you're unable to find an open issue addressing the problem, [open a new one]. Be sure to include a **title and clear description**, as much relevant information as possible, and a **code sample** or an **executable test case** demonstrating the expected behavior that is not occurring.
|
|
7
|
-
|
|
8
|
-
## **Did You Write a Patch That Fixes a Bug?**
|
|
9
|
-
|
|
10
|
-
- Open a new GitHub pull request with the patch.
|
|
11
|
-
1. Fork this project
|
|
12
|
-
2. Create your feature branch: `git checkout -b my-new-feature`
|
|
13
|
-
3. Commit your changes: `git commit -am 'Add some feature'`
|
|
14
|
-
4. Push to the branch: `git push origin my-new-feature`
|
|
15
|
-
5. Submit a pull request :tada:
|
|
16
|
-
- Ensure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable.
|
|
17
|
-
|
|
18
|
-
## **Do You Intend to Add a New Feature or Change an Existing One?**
|
|
19
|
-
|
|
20
|
-
- Suggest your change as a new [issue] using the label `enhancement` **BEFORE** you start writing code.
|
|
21
|
-
|
|
22
|
-
Thanks for contributing! :heart:
|