feat(comments): 人机验证改点按式 + 分割线可配置 + 投票契约修复

- 人机验证抽成 human.js 模块,改成 Cloudflare Turnstile 风格的「点一下验证」,
  控件移到「评论一下」发送按钮左侧(不再用图形验证码那一套)
- 留言页 / 文章页两段内联脚本(友链弹窗、人机验证)抽成模块随 page-only.js 加载。
  原先内联 <script> 写在 #pjax-container 外,PJAX 只换容器内容不重新执行它,
  从首页 PJAX 进留言页会出现「申请友链卡片点了没反应」「没有人机验证控件」
- 友链申请弹窗 #flApplyBox 隐藏滚动条(内容仍可滚,避开细滚动条 + 毛玻璃的割裂感)
- 内容分割线抽成 partial divider.html,hugo.toml [params.divider] 可切
  icon(原生 uk-divider-icon)/ image(本地图片),当前用 icon
- 投票契约修复(后端 blog-admin):Artalk 客户端把方向编在 target_name 后缀
  (comment_up / comment_down / page_up / page_down)、路径只有两段,
  而原先只注册了三段 :choice 路由 → 点赞/踩一路 404、界面点了没反应。
  补 POST /votes/:target_name/:target_id,新增 parseVoteTarget() 同时兼容两套契约
  (名字里与路径里方向矛盾时判非法,不静默取其一),错误文案改用实体名
- 无身份点赞不再静默失败:artalk.js 加 __atkVoteGuard,
  未填昵称/邮箱时拦截并提示「填写昵称和邮箱后才能点赞」,
  同时把光标送到昵称框(多个同名输入框逐个试,以 focus 真生效为判据)
This commit is contained in:
zqlit committed 2026-10-04 16:26:28 +08:00
1 parent 50a906e07c
commit e0c5ac5739
12 files changed
+512 -273

No files matched your search

+5
View File
@@ -39,7 +39,12 @@ router.put('/comments/:id', C.updateComment);
router.del('/comments/:id', C.deleteComment); router.del('/comments/:id', C.deleteComment);
// ---------------------------------------------------------------- 投票 / 浏览量 // ---------------------------------------------------------------- 投票 / 浏览量
// ★ 投票:Artalk 客户端把「方向」编进 target_name(comment_up / comment_down /
// page_up / page_down),路径只有两段 → `POST /votes/:target_name/:target_id`。
// 早期这里只注册了三段形式(:choice),与客户端对不上,导致点赞点了 404 没反应。
// 现在两段(客户端契约)与三段(旧形式)都收。
router.get('/votes/:target_name/:target_id', P.voteGet); router.get('/votes/:target_name/:target_id', P.voteGet);
router.post('/votes/:target_name/:target_id', P.voteCreate);
router.post('/votes/:target_name/:target_id/:choice', P.voteCreate); router.post('/votes/:target_name/:target_id/:choice', P.voteCreate);
router.post('/votes/sync', P.voteSync); router.post('/votes/sync', P.voteSync);
router.post('/pages/pv', P.pagePV); router.post('/pages/pv', P.pagePV);
+46 -8
View File
@@ -205,15 +205,51 @@ export async function verifyCaptcha(ctx: Ctx): Promise<Response> {
// ==================================================================== 投票 // ==================================================================== 投票
type VoteType = 'comment' | 'page';
type VoteChoice = 'up' | 'down';
/**
* 解析投票目标,同时兼容两套契约(★ 2026-10-04 修正):
*
* 1) **Artalk 客户端实际发的**:target_name 里已经编了方向 ——
* `comment_up` / `comment_down` / `page_up` / `page_down`,路径只有两段。
* (客户端源码:`vote(`comment_${dir}`, id, userFields)`
* → `POST /votes/:target_name/:target_id`)
* 2) 本项目早期注册的三段形式:target_name = `comment`/`page` + 单独的 `:choice` 段。
*
* 之前只认第 2 种,而客户端的请求打的是第 1 种形状 → 点赞/踩一路 404,
* 界面上点了没任何反应。返回 null 表示目标名非法。
*/
function parseVoteTarget(
targetName: string,
choiceParam?: string,
): { type: VoteType; choice?: VoteChoice } | null {
const m = /^(comment|page)(?:_(up|down))?$/.exec(targetName || '');
if (!m) return null;
const type = m[1] as VoteType;
const embedded = m[2] as VoteChoice | undefined;
if (choiceParam) {
if (choiceParam !== 'up' && choiceParam !== 'down') return null;
// 名字里和路径里都写了方向却不一致 → 判非法,别静默按其中一个处理
if (embedded && embedded !== choiceParam) return null;
return { type, choice: choiceParam };
}
return { type, choice: embedded };
}
export async function voteGet(ctx: Ctx): Promise<Response> { export async function voteGet(ctx: Ctx): Promise<Response> {
const targetName = ctx.params.target_name; const targetName = ctx.params.target_name;
const targetId = parseInt(ctx.params.target_id, 10); const targetId = parseInt(ctx.params.target_id, 10);
const type = targetName === 'comment' ? 'comment' : targetName === 'page' ? 'page' : ''; // 查询只关心「是评论还是页面」,方向忽略(up/down 一起返回)
if (!type) return fail(404, 'unknown vote target name'); const parsed = parseVoteTarget(targetName, ctx.params.choice);
if (!parsed) return fail(404, 'unknown vote target name');
const type = parsed.type;
if (!Number.isFinite(targetId)) return fail(400, 'invalid vote target id'); if (!Number.isFinite(targetId)) return fail(400, 'invalid vote target id');
const row = await voteTotals(ctx.env, type, targetId); const row = await voteTotals(ctx.env, type, targetId);
if (!row) return fail(404, `${targetName} not found`); if (!row) return fail(404, `${type} not found`);
let isUp = false; let isUp = false;
let isDown = false; let isDown = false;
@@ -252,17 +288,19 @@ async function voteTotals(
export async function voteCreate(ctx: Ctx): Promise<Response> { export async function voteCreate(ctx: Ctx): Promise<Response> {
const targetName = ctx.params.target_name; const targetName = ctx.params.target_name;
const targetId = parseInt(ctx.params.target_id, 10); const targetId = parseInt(ctx.params.target_id, 10);
const choice = ctx.params.choice; // 方向可能来自名字后缀(comment_up,Artalk 客户端),也可能来自三段路径的 :choice
const type = targetName === 'comment' ? 'comment' : targetName === 'page' ? 'page' : ''; const parsed = parseVoteTarget(targetName, ctx.params.choice);
if (!type) return fail(404, 'unknown vote target name'); if (!parsed) return fail(404, 'unknown vote target name');
if (choice !== 'up' && choice !== 'down') return fail(404, 'unknown vote choice'); const type = parsed.type;
const choice = parsed.choice;
if (!choice) return fail(404, 'unknown vote choice');
if (!Number.isFinite(targetId)) return fail(400, 'invalid vote target id'); if (!Number.isFinite(targetId)) return fail(400, 'invalid vote target id');
const ip = getClientIP(ctx.req); const ip = getClientIP(ctx.req);
if (!(await rateLimit(ctx.env, `vote:${ip}`, 30, 60))) return fail(429, 'Too many requests'); if (!(await rateLimit(ctx.env, `vote:${ip}`, 30, 60))) return fail(429, 'Too many requests');
const totals = await voteTotals(ctx.env, type, targetId); const totals = await voteTotals(ctx.env, type, targetId);
if (!totals) return fail(404, `${targetName} not found`); if (!totals) return fail(404, `${type} not found`);
const body = await readBody(ctx.req); const body = await readBody(ctx.req);
let voter = ctx.user; let voter = ctx.user;
+11
View File
@@ -105,6 +105,17 @@ hasCJKLanguage = true
{ title = "Rss订阅", url = "/rss.xml", icon = "ri-rss-fill" } { title = "Rss订阅", url = "/rss.xml", icon = "ri-rss-fill" }
] ]
# ----------------------------------------------------------------------------
# 内容分割线 (Post Divider)
# style = "icon" → 原生 uk-divider-icon(圆圈 + 两侧细线)
# = "image" → 用本地图片(图片请放 static/ 下,勿引外链)
# height 仅 image 样式生效:图片高度保护上限(正常宽度下达不到,图片铺满整行)
# ----------------------------------------------------------------------------
[params.divider]
style = "icon"
image = "/image/footer-animal.webp"
height = "140px"
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
# 移动端配置 (Mobile Configuration) # 移动端配置 (Mobile Configuration)
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

+36
View File
@@ -172,6 +172,42 @@ hr {
padding: 0; padding: 0;
} }
/* ── 内容分割线:图片样式(由 hugo.toml 的 [params.divider].style 切换) ── */
.post-divider-image {
display: flex;
justify-content: center;
align-items: center;
margin: 1.6rem 0;
line-height: 0;
}
.post-divider-image img {
display: block;
width: 100%;
height: auto;
max-width: 100%;
/* --divider-max-h 仅作保护上限:正常内容宽度下高度远达不到,
不会触发收缩,图片始终铺满整行 */
max-height: var(--divider-max-h, 140px);
object-fit: contain;
opacity: 0.92;
transition: opacity 0.3s ease;
}
.post-divider-image img:hover {
opacity: 1;
}
@media screen and (max-width: 480px) {
.post-divider-image {
margin: 1.2rem 0;
}
.post-divider-image img {
max-width: 100%;
}
}
[data-theme="dark"] hr { [data-theme="dark"] hr {
border-top-color: rgba(255, 255, 255, 0.2); border-top-color: rgba(255, 255, 255, 0.2);
} }
+72 -1
View File
@@ -168,7 +168,7 @@
'.atk-svc-down .atk-main-editor{opacity:.55!important;filter:grayscale(1)!important}' + '.atk-svc-down .atk-main-editor{opacity:.55!important;filter:grayscale(1)!important}' +
'.atk-svc-down .atk-copyright{display:none!important}' + '.atk-svc-down .atk-copyright{display:none!important}' +
'.atk-svc-down .atk-main-editor *{pointer-events:none}' + '.atk-svc-down .atk-main-editor *{pointer-events:none}' +
'.atk-svc-down .atk-human-box{display:none}' + '.atk-svc-down .atk-human-tf{display:none}' +
'.atk-svc-down .atk-list-body{min-height:0!important}' + '.atk-svc-down .atk-list-body{min-height:0!important}' +
'.atk-editor-off-bar{display:flex;align-items:center;gap:8px;margin:12px 0 10px;padding:9px 14px;border-radius:8px;' + '.atk-editor-off-bar{display:flex;align-items:center;gap:8px;margin:12px 0 10px;padding:9px 14px;border-radius:8px;' +
'background:rgba(7,193,96,.06);border:1px solid rgba(7,193,96,.22);font-size:13px;line-height:1.6;color:var(--text-main,#333)}' + 'background:rgba(7,193,96,.06);border:1px solid rgba(7,193,96,.22);font-size:13px;line-height:1.6;color:var(--text-main,#333)}' +
@@ -1384,3 +1384,74 @@ artalk.on('list-loaded', function() {
listSkeletonHide(); listSkeletonHide();
} }
}; };
// ============================================================================
// 投票前的身份提示 —— 别让读者点了「赞同」却毫无反应
//
// 服务端(artalk-cf)的投票语义和 Artalk 原生一致:**票必须挂在身份上**,
// 未登录时要求 body 带 name + email,否则返回 400。而客户端只在
// `userInfo.name && userInfo.email` 都齐了才会带上身份(见 Artalk.js 的
// getUserFields)——没填过的读者点下去就是一个静默失败:
// 请求打到服务端、报错、界面上的数字纹丝不动,读者只会觉得「点坏了」。
//
// 这里在 capture 阶段把这类点击拦下来(拦在 Artalk 自己的 handler 之前),
// 给一句人话提示并把光标送到昵称输入框。填过身份的直接放行,不干扰。
// ============================================================================
(function () {
if (window.__atkVoteGuard) return; // PJAX 会重复执行本文件,只装一次
window.__atkVoteGuard = true;
var USER_KEY = 'ArtalkUser'; // Artalk 的用户存储键(nick / email / link / token)
function readUser() {
try {
var raw = localStorage.getItem(USER_KEY);
return raw ? JSON.parse(raw) : null;
} catch (e) {
return null;
}
}
// 已登录(有 token)服务端认 Authorization;游客必须昵称 + 邮箱
function hasIdentity(u) {
if (!u) return false;
if (u.token) return true;
return !!(u.nick && u.email);
}
document.addEventListener('click', function (e) {
var el = e.target;
var btn = el && el.closest ? el.closest('.atk-common-action-btn') : null;
if (!btn) return;
if (!/赞同|反对|顶|踩/.test(btn.textContent || '')) return;
if (hasIdentity(readUser())) return;
// 拦在 Artalk 之前:不发那个注定 400 的请求,也不让数字假装动一下
e.preventDefault();
e.stopPropagation();
if (window.showToast) window.showToast('填写昵称和邮箱后才能点赞', 'warning');
else if (window.Toast && window.Toast.warning) window.Toast.warning('填写昵称和邮箱后才能点赞');
// 把光标送到昵称输入框。
// ⚠️ 不能只 querySelector 第一个:Artalk 的 DOM 里存在**不止一个** nick 输入框
// (隐藏模板、未激活的回复框也算),第一个匹配到的往往不可焦点,
// 对它 focus() 会被浏览器静默忽略 —— activeElement 一点不变,很容易误判成"生效了"。
// 所以逐个候选试,并以「focus 真的落到它身上」为唯一判据。
function focusFirstUsable(sel) {
var list = document.querySelectorAll(sel);
for (var i = 0; i < list.length; i++) {
var el = list[i];
if (!(el.offsetWidth || el.offsetHeight || el.getClientRects().length)) continue;
try { el.focus({ preventScroll: true }); } catch (err) { try { el.focus(); } catch (e2) { continue; } }
if (document.activeElement === el) return el;
}
return null;
}
var nick = focusFirstUsable('.atk-header [name="nick"]') || focusFirstUsable('[name="nick"]');
if (nick) {
try { nick.scrollIntoView({ block: 'center', behavior: 'smooth' }); } catch (err) { /* 老浏览器忽略 */ }
}
}, true);
})();
+5 -5
View File
@@ -41,12 +41,12 @@
'#flSubmit:hover{filter:brightness(1.06)}' + '#flSubmit:hover{filter:brightness(1.06)}' +
'#flSubmit:disabled{opacity:.6;cursor:default}' + '#flSubmit:disabled{opacity:.6;cursor:default}' +
/* 弹窗滚动条:细一点、跟随主题,别用系统那根粗滚动条 */ /* 弹窗滚动条:细一点、跟随主题,别用系统那根粗滚动条 */
'#flApplyBox{overflow-x:hidden;scrollbar-width:thin;scrollbar-color:rgba(140,150,160,.45) transparent}' + /* 完全隐藏滚动条(内容仍可滚):细滚动条在内层圆角 + 毛玻璃上很割裂。
'#flApplyBox::-webkit-scrollbar{width:6px;height:6px}' + 三条都写:Firefox(scrollbar-width)、IE/Edge(-ms-)、Webkit(伪元素)。 */
'#flApplyBox{overflow-y:auto;overflow-x:hidden;scrollbar-width:none;-ms-overflow-style:none}' +
'#flApplyBox::-webkit-scrollbar{width:0;height:0;display:none}' +
'#flApplyBox::-webkit-scrollbar-track{background:transparent}' + '#flApplyBox::-webkit-scrollbar-track{background:transparent}' +
'#flApplyBox::-webkit-scrollbar-thumb{background:rgba(140,150,160,.45);border-radius:3px}' + '#flApplyBox::-webkit-scrollbar-thumb{background:transparent}';
'[data-theme="dark"] #flApplyBox{scrollbar-color:rgba(200,205,212,.35) transparent}' +
'[data-theme="dark"] #flApplyBox::-webkit-scrollbar-thumb{background:rgba(200,205,212,.35)}';
document.head.appendChild(style); document.head.appendChild(style);
mask = document.createElement('div'); mask = document.createElement('div');
+301
View File
@@ -0,0 +1,301 @@
/* 人机验证(自研「一键验证」)—— 服务端见 blog-admin/src/lib/human.ts
*
* 交互仿 Cloudflare Turnstile:编辑器底部、`.atk-send-btn`(评论一下)左侧一个
* 方形勾选框。读者大多数时候无感 —— 浏览器在后台静默算一个 PoW,够了就直接打勾;
* 信号不足时方框保持可点,用户点一下就通过。
*
* 为什么不再用「图形验证码」:用户明确不要「输字符」那种交互。前端已移除图形
* 验证码入口;服务端 humanGate 的 captcha 兜底仍然保留(不影响),遇到
* need_captcha 时前端展示可重试的失败态。
*
* 通行证按 IP 记在服务端 KV(30 分钟),前端不传任何 token,
* 所以不需要改 Artalk 客户端。文章页 / 留言页共用本模块。
*
* 历史:本逻辑原先内联在 layouts/page/comment.html 里 —— 只有留言页有,
* 而文章页评论同样走服务端 humanGate → 新访客在文章页会 403。抽成模块
* 进 page-only bundle 后两处一致。
*/
(function () {
var BASE = window.rssApiBase ||
(window.artalkConfig && window.artalkConfig.server) ||
'https://api.200181.xyz';
BASE = String(BASE).replace(/\/+$/, '');
var API = BASE + '/api/v2';
var DIFFICULTY = 4;
var PREFIX = new Array(DIFFICULTY + 1).join('0');
var CHECK_SVG = '<svg viewBox="0 0 24 24"><path d="M5 13l4 4L19 7"/></svg>';
var started = Date.now();
var events = 0, honey = '', busy = false;
var state = 'idle'; // idle | busy | pass | fail
var failMsg = '';
var proof = null, autoTried = false;
// ── 行为信号:人类随手动一下就会有,脚本环境常常一个都没有
['mousemove', 'pointerdown', 'keydown', 'keyup', 'input', 'focusin', 'scroll', 'wheel',
'touchstart', 'click'].forEach(function (ev) {
document.addEventListener(ev, function () { events++; }, { passive: true });
});
function injectCss() {
if (document.getElementById('atk-human-css')) return;
var st = document.createElement('style');
st.id = 'atk-human-css';
st.textContent =
/* 容器:与 .atk-send-btn 同高 30px,紧贴其左侧 */
'.atk-human-tf{display:inline-flex;align-items:center;gap:7px;height:30px;box-sizing:border-box;' +
'margin-right:8px;padding:0 10px;border:1px solid var(--border-main,#e5e7eb);border-radius:4px;' +
'background:var(--bg-card,#fafafa);font-size:12px;line-height:1;color:var(--text-main,#4b5563);' +
'cursor:pointer;user-select:none;white-space:nowrap;flex:none;' +
'transition:border-color .2s ease,background .2s ease,box-shadow .2s ease}' +
'.atk-human-tf.is-idle:hover{border-color:var(--theme-main,#07c160);' +
'box-shadow:0 0 0 3px var(--theme-main-20,rgba(7,193,96,.15))}' +
'.atk-human-tf.is-busy{cursor:default;opacity:.85}' +
'.atk-human-tf.is-pass{cursor:default;border-color:var(--theme-main,#07c160);' +
'background:var(--theme-main-10,rgba(7,193,96,.08))}' +
'.atk-human-tf.is-fail{cursor:pointer;border-color:#e05a5a;background:rgba(224,90,90,.08);color:#c0392b}' +
/* 左侧方形勾选框 */
'.atk-human-tf-box{flex:none;width:18px;height:18px;border-radius:3px;box-sizing:border-box;' +
'border:1.5px solid #c8ccd4;background:#fff;display:flex;align-items:center;justify-content:center;' +
'transition:background .2s ease,border-color .2s ease}' +
'.atk-human-tf.is-pass .atk-human-tf-box{background:var(--theme-main,#07c160);' +
'border-color:var(--theme-main,#07c160)}' +
'.atk-human-tf.is-fail .atk-human-tf-box{background:#e05a5a;border-color:#e05a5a;color:#fff;' +
'font-weight:700;font-size:12px;line-height:1}' +
'.atk-human-tf-box svg{width:12px;height:12px;display:block}' +
'.atk-human-tf-box svg path{stroke:#fff;stroke-width:2.6;fill:none;stroke-linecap:round;stroke-linejoin:round}' +
'.atk-human-tf-spin{width:12px;height:12px;border-radius:50%;box-sizing:border-box;' +
'border:2px solid var(--theme-main-30,rgba(7,193,96,.3));border-top-color:var(--theme-main,#07c160);' +
'animation:atkHumanSpin .7s linear infinite}' +
'@keyframes atkHumanSpin{to{transform:rotate(360deg)}}' +
'.atk-human-tf-tx{white-space:nowrap}' +
'[data-theme="dark"] .atk-human-tf{border-color:rgba(255,255,255,.14);background:rgba(255,255,255,.04)}' +
'[data-theme="dark"] .atk-human-tf-box{border-color:rgba(255,255,255,.28);background:rgba(255,255,255,.08)}' +
'@media (max-width:640px){.atk-human-tf{padding:0 8px;margin-right:6px}.atk-human-tf-tx{font-size:11px}}' +
'@media (prefers-reduced-motion:reduce){.atk-human-tf-spin{animation-duration:2s}}';
document.head.appendChild(st);
}
function hex(buf) {
var b = new Uint8Array(buf), out = '';
for (var i = 0; i < b.length; i++) out += ('0' + b[i].toString(16)).slice(-2);
return out;
}
function sha256(str) {
return crypto.subtle.digest('SHA-256', new TextEncoder().encode(str)).then(hex);
}
/* 找 nonce 让 sha256(challenge+nonce) 以 N 个 0 开头。
crypto.subtle 是异步的,逐次 await 的 promise 开销远大于哈希本身:
所以按 CHUNK 串一条链、每 CHUNK*YIELD_EVERY 次让出一次主线程,
页面保持流畅,总耗时压到 1 秒上下(全程后台,读者无感)。 */
var CHUNK = 512, YIELD_EVERY = 8;
function solve(challenge) {
var i = 0;
function step() {
var chain = Promise.resolve(null);
var found0 = null;
var limit = i + CHUNK * YIELD_EVERY;
while (i < limit && i < 3000000) {
(function (n) {
chain = chain.then(function () {
if (found0 !== null) return found0; // 已找到 → 后面的直接短路
return sha256(challenge + n).then(function (h) {
if (h.slice(0, DIFFICULTY) === PREFIX) { found0 = n; return n; }
return null;
});
});
})(i++);
}
return chain.then(function (found) {
if (found !== null) return found;
if (i >= 4000000) return null;
return new Promise(function (r) { setTimeout(r, 0); }).then(step);
});
}
return step();
}
function api(path, body) {
return fetch(API + path, {
method: body ? 'POST' : 'GET',
headers: body ? { 'Content-Type': 'application/json' } : undefined,
body: body ? JSON.stringify(body) : undefined,
}).then(function (r) { return r.json().catch(function () { return {}; }); });
}
// ── 控件
function sendBtn() {
return document.querySelector('.atk-bottom .atk-send-btn') ||
document.querySelector('.atk-send-btn');
}
function editorEl() {
return document.querySelector('.atk-main-editor');
}
/** 把控件插到「评论一下」按钮左侧(同一个 .atk-item 内,天然左邻) */
function ensureWidget() {
var btn = sendBtn();
if (!btn || !btn.parentElement) return null;
var host = btn.parentElement;
var w = null;
for (var i = 0; i < host.children.length; i++) {
if (host.children[i].classList && host.children[i].classList.contains('atk-human-tf')) {
w = host.children[i]; break;
}
}
if (!w) {
w = document.createElement('div');
w.className = 'atk-human-tf is-idle';
w.setAttribute('role', 'button');
w.setAttribute('tabindex', '0');
w.setAttribute('title', '人机验证');
w.addEventListener('click', onWidgetClick);
w.addEventListener('keydown', function (e) {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onWidgetClick(); }
});
host.insertBefore(w, btn);
injectCss();
}
render(w);
if (!autoTried) { autoTried = true; setTimeout(function () { run(false); }, 60); }
return w;
}
function onWidgetClick() {
if (busy || state === 'busy' || state === 'pass') return;
run(true); // 点击本身就是强人类信号(服务端 clicked 直接放行)
}
function render(w) {
w = w || ensureWidget();
if (!w) return;
var key = state + '|' + failMsg;
if (w.dataset.hk === key) return; // 状态没变就别重建 DOM(避免转圈动画被重置)
w.dataset.hk = key;
w.className = 'atk-human-tf is-' + state;
if (state === 'pass') {
w.innerHTML = '<span class="atk-human-tf-box">' + CHECK_SVG + '</span>' +
'<span class="atk-human-tf-tx">已通过验证</span>';
} else if (state === 'busy') {
w.innerHTML = '<span class="atk-human-tf-box"><span class="atk-human-tf-spin"></span></span>' +
'<span class="atk-human-tf-tx">验证中…</span>';
} else if (state === 'fail') {
w.innerHTML = '<span class="atk-human-tf-box">!</span>' +
'<span class="atk-human-tf-tx">' + (failMsg || '验证失败,点击重试') + '</span>';
} else {
w.innerHTML = '<span class="atk-human-tf-box"></span>' +
'<span class="atk-human-tf-tx">点击验证</span>';
}
}
function setState(s, msg) {
state = s;
if (s === 'fail') failMsg = msg || '';
render();
}
function ensureHoneypot() {
if (document.getElementById('atk-human-hp')) return;
var ed = editorEl();
if (!ed) return;
var i = document.createElement('input');
i.id = 'atk-human-hp'; i.type = 'text'; i.tabIndex = -1; i.autocomplete = 'off';
i.setAttribute('aria-hidden', 'true');
i.style.cssText = 'position:absolute;left:-9999px;top:0;width:1px;height:1px;opacity:0';
i.addEventListener('input', function () { honey = i.value; });
ed.appendChild(i);
}
// ── 主流程
// 证明只算一次并缓存:点「点击验证」复用同一个 nonce 重发(补上 clicked 信号),
// 所以点击是**瞬间完成**的,不会让访客再等一次算力。
function ensureProof() {
if (proof && proof.exp > Date.now() + 5000) return Promise.resolve(proof);
return api('/human/challenge').then(function (ch) {
if (!ch || ch.enabled === false || ch.pass) return null;
return solve(ch.challenge).then(function (nonce) {
if (nonce === null) return null;
proof = { challenge: ch.challenge, nonce: nonce, exp: ch.exp, sig: ch.sig };
return proof;
});
});
}
function run(clicked) {
if (busy || state === 'pass') return Promise.resolve();
busy = true;
setState('busy');
return api('/human/status').then(function (st) {
if (!st || st.enabled === false || st.pass) { setState('pass'); return null; }
if (!window.crypto || !crypto.subtle) {
setState('fail', '浏览器不支持验证');
return null;
}
return ensureProof().then(function (pr) {
if (!pr) { setState('fail', '验证服务不可用'); return null; }
return api('/human/verify', {
challenge: pr.challenge, nonce: pr.nonce, exp: pr.exp, sig: pr.sig,
elapsedMs: Date.now() - started, events: events,
webdriver: navigator.webdriver === true, honeypot: honey, clicked: !!clicked,
}).then(function (res) {
if (res && res.pass) { setState('pass'); return; }
// need_captcha(高风险:蜜罐被填 / webdriver)不再弹图形验证码,给可重试的失败态
if (res && res.need_captcha) { setState('fail', '未通过验证,点击重试'); return; }
// need_click:只是还缺人类信号 —— 这不是错误,回到可点的未验证态即可
setState('idle');
});
});
}).catch(function () {
/* 网络异常不打扰读者:回到可点状态,服务端提交时仍有门禁兜底 */
setState('idle');
}).then(function () { busy = false; });
}
// ── 编辑器会被 Artalk 反复重建(pjax / 回复模式 / 提交后),用 observer 补挂
var mo = null, moTimer = null;
function watch() {
if (mo || typeof MutationObserver === 'undefined' || !document.body) return;
mo = new MutationObserver(function () {
if (moTimer) return;
moTimer = setTimeout(function () {
moTimer = null;
var btn = sendBtn();
if (!btn || !btn.parentElement) return;
var w = null;
for (var i = 0; i < btn.parentElement.children.length; i++) {
if (btn.parentElement.children[i].classList &&
btn.parentElement.children[i].classList.contains('atk-human-tf')) { w = btn.parentElement.children[i]; break; }
}
// 控件丢了 / 挂错位置 / 不在按钮左侧 → 重新挂
if (!w || w.nextElementSibling !== btn) ensureWidget();
}, 200);
});
mo.observe(document.body, { childList: true, subtree: true });
}
function init() {
// 评论页才有意义;文章页/留言页都有 .comments-area
if (!document.querySelector('.comments-area')) return;
started = Date.now(); events = 0; busy = false; proof = null; failMsg = '';
autoTried = false;
if (state !== 'pass') state = 'idle';
ensureHoneypot();
ensureWidget(); // 挂上即触发一次静默验证(见 ensureWidget 里的 autoTried)
watch();
}
/* 调试/自测钩子(线上留着也无害) */
window.__humanCheck = {
state: function () {
return { state: state, busy: busy, events: events, honey: honey, hasPass: state === 'pass' };
},
run: run,
widget: function () { return document.querySelector('.atk-human-tf'); },
};
document.addEventListener('pjax:complete', function () { setTimeout(init, 300); });
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
else init();
})();
+1 -1
View File
@@ -78,7 +78,7 @@
</article> </article>
<hr class="uk-divider-icon"> {{ partial "divider.html" . }}
<!-- 打赏模块 --> <!-- 打赏模块 -->
{{ if .Site.Params.reward.enable }} {{ if .Site.Params.reward.enable }}
+9 -256
View File
@@ -11,7 +11,7 @@
- 图标:{{ .Site.Params.message_info.icon | default .Site.Params.author.avatar }} - 图标:{{ .Site.Params.message_info.icon | default .Site.Params.author.avatar }}
</div> </div>
</div> </div>
<hr class="uk-divider-icon"> {{ partial "divider.html" . }}
<div class="comments-area"> <div class="comments-area">
<!-- 评论区内容 --> <!-- 评论区内容 -->
{{ partial "artalk.html" . }} {{ partial "artalk.html" . }}
@@ -20,260 +20,13 @@
</div> </div>
{{/* 友链自助申请弹窗已抽到 assets/js/modules/friendlink.js(随 page-only.js 加载)。 {{/* 本页原先的两段内联脚本都已抽成模块(随 page-only.js 加载)。
原先这段内联脚本写在 #pjax-container 外面:PJAX 只换容器内容、不会重新执行它, 抽出的原因:内联 <script> 写在 #pjax-container 外面,PJAX 只替换容器内容、
从首页 PJAX 进留言页时 window.flApplyOpenModal 未定义 → 「申请友链」卡片点了没反应; 不会重新执行它 —— 从首页 PJAX 进本页时脚本根本没跑,于是出现
直接刷新(整页加载)才正常。抽成模块后两种进入方式行为一致。 */}} 「申请友链卡片点了没反应」「没有人机验证控件」;直接刷新(整页加载)才正常。
<script> · 友链自助申请弹窗 → assets/js/modules/friendlink.js
/* 人机验证(自研「一键验证」)—— 服务端见 artalk-cf/src/lib/human.ts · 人机验证控件 → assets/js/modules/human.js
读者体验:默认什么都不用做(浏览器静默算一个 PoW,约 0.1~2 秒,后台完成); (文章页与留言页共用:文章页评论同样走服务端 humanGate,
信号不足时才出现「点一下验证」小方块;再可疑才弹图形验证码。 而验证脚本原先只在本页,新访客在文章页会 403) */}}
通行证按 IP 记在服务端(KV,30 分钟),前端不传任何 token,所以不需要改 Artalk 客户端。 */
(function () {
var BASE = '{{ $rssBase := site.Params.rssapi.base | default "https://api.200181.xyz" }}{{ $rssBase }}';
var API = BASE + '/api/v2';
var DIFFICULTY = 4;
var PREFIX = new Array(DIFFICULTY + 1).join('0');
var started = Date.now();
var events = 0, honey = '', hasPass = false, busy = false, widget = null, tries = 0;
// ── 行为信号:人类随手动一下就会有,脚本环境常常一个都没有
['mousemove', 'pointerdown', 'keydown', 'keyup', 'input', 'focusin', 'scroll', 'wheel',
'touchstart', 'click'].forEach(function (ev) {
document.addEventListener(ev, function () { events++; }, { passive: true });
});
function injectCss() {
if (document.getElementById('atk-human-css')) return;
var st = document.createElement('style');
st.id = 'atk-human-css';
st.textContent =
'.atk-human-box{display:flex;align-items:center;gap:8px;margin:0 0 10px;padding:8px 12px;' +
'border:1px solid var(--border-main,#eee);border-radius:8px;background:var(--bg-card,#fff);' +
'font-size:13px;color:var(--text-main,#333);transition:border-color .2s,background .2s}' +
'.atk-human-box.is-click{cursor:pointer}' +
'.atk-human-box.is-click:hover{border-color:var(--theme-main,#07c160)}' +
'.atk-human-box.is-busy{opacity:.7;cursor:default}' +
'.atk-human-box-ic{flex:none;width:18px;height:18px;border-radius:50%;display:flex;align-items:center;' +
'justify-content:center;font-size:12px;color:#fff;background:var(--theme-main,#07c160)}' +
'.atk-human-box.is-captcha .atk-human-box-ic{background:#d9534f}' +
'.atk-human-box-tx{flex:1;min-width:0}' +
'.atk-human-img{flex:none;height:34px;width:102px;border-radius:4px;cursor:pointer}' +
'.atk-human-inp{flex:none;width:78px;padding:4px 6px;border:1px solid var(--border-main,#ddd);' +
'border-radius:4px;font-size:13px;box-sizing:border-box;outline:none;background:transparent;color:inherit}' +
'.atk-human-btn{flex:none;padding:4px 10px;border:none;border-radius:4px;cursor:pointer;' +
'background:var(--theme-main,#07c160);color:#fff;font-size:12px}' +
'[data-theme="dark"] .atk-human-box{border-color:rgba(255,255,255,.14)}';
document.head.appendChild(st);
}
function hex(buf) {
var b = new Uint8Array(buf), out = '';
for (var i = 0; i < b.length; i++) out += ('0' + b[i].toString(16)).slice(-2);
return out;
}
function sha256(str) {
return crypto.subtle.digest('SHA-256', new TextEncoder().encode(str)).then(hex);
}
/* 找 nonce 让 sha256(challenge+nonce) 以 N 个 0 开头。
crypto.subtle 是异步的,逐次 await 的 promise 开销远大于哈希本身:
所以按 CHUNK 串一条链、每 CHUNK*YIELD_EVERY 次让出一次主线程,
页面保持流畅,总耗时压到 1 秒上下(全程后台,读者无感)。 */
var CHUNK = 512, YIELD_EVERY = 8;
function solve(challenge) {
var i = 0;
function step() {
var chain = Promise.resolve(null);
var found0 = null;
var limit = i + CHUNK * YIELD_EVERY;
while (i < limit && i < 3000000) {
(function (n) {
chain = chain.then(function () {
if (found0 !== null) return found0; // 已找到 → 后面的直接短路
return sha256(challenge + n).then(function (h) {
if (h.slice(0, DIFFICULTY) === PREFIX) { found0 = n; return n; }
return null;
});
});
})(i++);
}
return chain.then(function (found) {
if (found !== null) return found;
if (i >= 4000000) return null;
return new Promise(function (r) { setTimeout(r, 0); }).then(step);
});
}
return step();
}
function api(path, body) {
return fetch(API + path, {
method: body ? 'POST' : 'GET',
headers: body ? { 'Content-Type': 'application/json' } : undefined,
body: body ? JSON.stringify(body) : undefined,
}).then(function (r) { return r.json().catch(function () { return {}; }); });
}
// ── 控件
function editorEl() {
return document.querySelector('.atk-main-editor') || document.querySelector('.atk-comment-wrap');
}
function ensureWidget() {
if (widget && widget.isConnected) return widget;
var ed = editorEl();
if (!ed || !ed.parentNode) return null;
widget = document.createElement('div');
widget.className = 'atk-human-box';
ed.parentNode.insertBefore(widget, ed);
injectCss();
return widget;
}
function dropWidget() {
if (widget && widget.parentNode) widget.parentNode.removeChild(widget);
widget = null;
}
function ensureHoneypot() {
if (document.getElementById('atk-human-hp')) return;
var ed = editorEl();
if (!ed) return;
var i = document.createElement('input');
i.id = 'atk-human-hp'; i.type = 'text'; i.tabIndex = -1; i.autocomplete = 'off';
i.setAttribute('aria-hidden', 'true');
i.style.cssText = 'position:absolute;left:-9999px;top:0;width:1px;height:1px;opacity:0';
i.addEventListener('input', function () { honey = i.value; });
ed.appendChild(i);
}
function done() {
var w = ensureWidget();
if (!w) { hasPass = true; return; }
w.className = 'atk-human-box';
w.onclick = null;
w.innerHTML = '<span class="atk-human-box-ic">✓</span><span class="atk-human-box-tx">已通过人机验证</span>';
setTimeout(dropWidget, 1600);
}
function showCaptcha() {
var w = ensureWidget();
if (!w) { if (tries++ < 20) setTimeout(showCaptcha, 800); return; }
w.className = 'atk-human-box is-captcha';
w.onclick = null;
w.innerHTML = '<span class="atk-human-box-ic">!</span>' +
'<span class="atk-human-box-tx">请输入图中的字符(点图片可换一张)</span>' +
'<img class="atk-human-img" alt="验证码"><input class="atk-human-inp" maxlength="6" autocomplete="off">' +
'<button class="atk-human-btn" type="button">确认</button>';
var img = w.querySelector('.atk-human-img');
var inp = w.querySelector('.atk-human-inp');
function refresh() {
img.style.display = '';
api('/captcha').then(function (c) {
if (c && c.img_data) { img.src = c.img_data; }
else { fail('验证码暂时取不到'); }
}).catch(function () { fail('验证码暂时取不到'); });
}
// 图形验证码取不到(接口抖动/数据库不可用)时给个可重试的提示,别留一张破图
function fail(msg) {
img.style.display = 'none';
var t = w.querySelector('.atk-human-box-tx');
if (t) { t.innerHTML = msg + ',<b style="cursor:pointer;text-decoration:underline">点这里重试</b>'; }
}
w.addEventListener('click', function (e) {
if (e.target && e.target.tagName === 'B') refresh();
});
refresh();
img.onclick = refresh;
function submit() {
var v = (inp.value || '').trim();
if (!v) return;
api('/captcha/verify', { value: v }).then(function (r) {
if (r && r.msg === 'Success') { hasPass = true; done(); }
else { inp.value = ''; refresh(); }
});
}
w.querySelector('.atk-human-btn').onclick = submit;
inp.addEventListener('keydown', function (e) { if (e.key === 'Enter') submit(); });
inp.focus();
}
function showClick() {
var w = ensureWidget();
if (!w) { if (tries++ < 20) setTimeout(showClick, 800); return; }
w.className = 'atk-human-box is-click';
w.innerHTML = '<span class="atk-human-box-ic">✓</span>' +
'<span class="atk-human-box-tx">点一下完成验证,然后就能发评论了</span>';
w.onclick = function () {
if (busy) return;
w.className = 'atk-human-box is-busy';
w.querySelector('.atk-human-box-tx').textContent = '验证中…';
run(true);
};
}
// ── 主流程
// 证明只算一次并缓存:点「点一下验证」复用同一个 nonce 重发(补上 clicked 信号),
// 所以点击是**瞬间完成**的,不会让访客再等一次算力。
var proof = null;
function ensureProof() {
if (proof && proof.exp > Date.now() + 5000) return Promise.resolve(proof);
return api('/human/challenge').then(function (ch) {
if (!ch || ch.enabled === false || ch.pass) return null;
return solve(ch.challenge).then(function (nonce) {
if (nonce === null) return null;
proof = { challenge: ch.challenge, nonce: nonce, exp: ch.exp, sig: ch.sig };
return proof;
});
});
}
function run(clicked) {
if (busy) return Promise.resolve();
if (hasPass) return Promise.resolve();
busy = true;
return api('/human/status').then(function (st) {
if (!st || st.enabled === false || st.pass) { hasPass = true; dropWidget(); return null; }
if (!window.crypto || !crypto.subtle) { showCaptcha(); return null; }
return ensureProof().then(function (pr) {
if (!pr) { showCaptcha(); return null; }
return api('/human/verify', {
challenge: pr.challenge, nonce: pr.nonce, exp: pr.exp, sig: pr.sig,
elapsedMs: Date.now() - started, events: events,
webdriver: navigator.webdriver === true, honeypot: honey, clicked: !!clicked,
}).then(function (res) {
if (res && res.pass) { hasPass = true; done(); return; }
if (res && res.need_captcha) { showCaptcha(); return; }
showClick();
});
});
}).catch(function () { /* 网络异常就不打扰读者,服务端仍有图形验证码兜底 */ })
.then(function () { busy = false; });
}
function init() {
if (!document.querySelector('.comments-area')) return; // 非评论页不打扰
started = Date.now(); events = 0; hasPass = false; busy = false; tries = 0; proof = null;
dropWidget();
ensureHoneypot();
run(false);
// 编辑器获得焦点时再确认一次(通行证 30 分钟,长了就续)
setTimeout(function () {
var ed = editorEl();
if (ed) ed.addEventListener('focusin', function () { if (!hasPass) run(false); });
}, 1500);
}
/* 调试/自测钩子(线上留着也无害,方便需要时手动触发两种控件看一眼) */
window.__humanCheck = {
state: function () { return { hasPass: hasPass, busy: busy, events: events, honey: honey }; },
run: run, showClick: showClick, showCaptcha: showCaptcha, drop: dropWidget,
};
document.addEventListener('pjax:complete', function () { setTimeout(init, 300); });
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
else init();
})();
</script>
{{ end }} {{ end }}
+20
View File
@@ -0,0 +1,20 @@
{{/* 内容分割线。样式在 hugo.toml 的 [params.divider] 里切换:
[params.divider]
style = "icon" # icon = 主题原生 uk-divider-icon(圆圈 + 两侧细线)
# image = 使用本地图片
image = "/image/footer-animal.webp" # image 样式生效;图片放 static/ 下
height = "110px" # image 样式生效;图片最大高度
图片必须本地化(放 static/),不要直接引外链。 */}}
{{- $d := site.Params.divider | default dict -}}
{{- $style := $d.style | default "icon" -}}
{{- if eq $style "image" -}}
{{- $src := $d.image | default "/image/footer-animal.webp" -}}
{{- $h := $d.height | default "110px" -}}
<div class="post-divider post-divider-image" aria-hidden="true">
<img src="{{ $src }}" alt="" loading="lazy" decoding="async" style="--divider-max-h:{{ $h }}">
</div>
{{- else -}}
<hr class="uk-divider-icon">
{{- end -}}
+6 -2
View File
@@ -142,10 +142,12 @@
{{/* 友链申请弹窗放最前:artalk.js 渲染申请卡片时会调 window.flApplyOpenModal */}} {{/* 友链申请弹窗放最前:artalk.js 渲染申请卡片时会调 window.flApplyOpenModal */}}
{{ $friendlink := resources.Get "js/modules/friendlink.js" }} {{ $friendlink := resources.Get "js/modules/friendlink.js" }}
{{ $artalkModule := resources.Get "js/modules/artalk.js" }} {{ $artalkModule := resources.Get "js/modules/artalk.js" }}
{{/* 人机验证控件(Turnstile 风格),文章页与留言页共用 */}}
{{ $human := resources.Get "js/modules/human.js" }}
{{ $paragraphComments := resources.Get "js/modules/paragraph-comments.js" }} {{ $paragraphComments := resources.Get "js/modules/paragraph-comments.js" }}
{{ $reward := resources.Get "js/modules/reward.js" }} {{ $reward := resources.Get "js/modules/reward.js" }}
{{ $pageScripts := slice $friendlink $artalkModule $paragraphComments $reward | resources.Concat "js/page-only.js" | resources.Minify | resources.Fingerprint }} {{ $pageScripts := slice $friendlink $artalkModule $human $paragraphComments $reward | resources.Concat "js/page-only.js" | resources.Minify | resources.Fingerprint }}
<script defer src="{{ $pageScripts.RelPermalink }}"></script> <script defer src="{{ $pageScripts.RelPermalink }}"></script>
<script>window._pageOnlyScriptUrl = '{{ $pageScripts.RelPermalink }}';</script> <script>window._pageOnlyScriptUrl = '{{ $pageScripts.RelPermalink }}';</script>
@@ -153,10 +155,12 @@
{{/* 非文章页面:仍然计算URL,但不加载,用于PJAX动态加载 */}} {{/* 非文章页面:仍然计算URL,但不加载,用于PJAX动态加载 */}}
{{ $friendlink := resources.Get "js/modules/friendlink.js" }} {{ $friendlink := resources.Get "js/modules/friendlink.js" }}
{{ $artalkModule := resources.Get "js/modules/artalk.js" }} {{ $artalkModule := resources.Get "js/modules/artalk.js" }}
{{/* 人机验证控件(Turnstile 风格),文章页与留言页共用 */}}
{{ $human := resources.Get "js/modules/human.js" }}
{{ $paragraphComments := resources.Get "js/modules/paragraph-comments.js" }} {{ $paragraphComments := resources.Get "js/modules/paragraph-comments.js" }}
{{ $reward := resources.Get "js/modules/reward.js" }} {{ $reward := resources.Get "js/modules/reward.js" }}
{{ $pageScripts := slice $friendlink $artalkModule $paragraphComments $reward | resources.Concat "js/page-only.js" | resources.Minify | resources.Fingerprint }} {{ $pageScripts := slice $friendlink $artalkModule $human $paragraphComments $reward | resources.Concat "js/page-only.js" | resources.Minify | resources.Fingerprint }}
<script>window._pageOnlyScriptUrl = '{{ $pageScripts.RelPermalink }}';</script> <script>window._pageOnlyScriptUrl = '{{ $pageScripts.RelPermalink }}';</script>
{{ end }} {{ end }}