Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions packages/say/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -503,34 +503,34 @@ QQ、企业微信、公众号、飞书和外部 API 的处理失败会返回经

## 碎语评论

评论在 Say 插件内实现,无需修改 Firekylin 核心或新增数据库表。每条碎语有独立详情地址 `/says/<数字 ID>`,公开列表中的“详情 / 评论”可以进入该页面。
Say 管理碎语评论的可用性,Firekylin 核心处理评论提交、审核与通知,无需新增数据库表。每条碎语有独立详情地址 `/says/<数字 ID>`,公开列表中的“详情 / 评论”可以进入该页面。

### 开启与审核

1. 新发布碎语默认允许评论,无需开启全局评论开关。旧的 `commentsEnabled` 配置不再生效。
2. 每条碎语保留「允许评论」开关,可随时关闭或开启;API 发布可明确传入 `allowComments: false` 禁止评论。历史碎语的单条设置不变,不批量开启;私密和隐藏碎语仍不可公开评论。
3. 打开公开碎语的 `/says/ID` 页面提交评论。访客填写昵称;邮箱、网站和字数要求沿用站点评论设置。站点开启强制登录时,先通过博客登录页登录。身份由服务器验证,客户端不能指定评论作者或审核状态。
4. 在 Firekylin 后台「评论管理」中审核。**包括管理员在内的所有新评论都先进入待审核**;命中站点禁用词的评论进入垃圾评论。只有审核通过的评论公开展示。拒绝、转垃圾或删除后,不再公开展示。
5. 关闭任一评论开关会隐藏该条碎语的评论及表单,但保留记录;重新开启后可再次展示。碎语设为私密、隐藏或插件关闭后,详情与评论接口不再公开访问。
4. 普通评论是否需要审核,由 Firekylin 后台的站点评论设置决定。管理员、禁用词及启用了的 AI 审核也遵循核心规则。只有已公开的评论对访客可见;待审核和垃圾评论可在后台「评论管理」处理。
5. 关闭评论会隐藏详情页的评论区域,并禁止新评论;历史记录会保留。碎语设为私密、隐藏或插件关闭后,Say 详情页和旧版 Say 评论接口不再公开访问。

正文按纯文本展示,不执行 HTML,也不渲染 Markdown。邮箱、IP、User-Agent、账号 ID 不会出现在公开评论响应中。列表每页 20 条;公开模板仍可用 `say.list` / `Widget_Plugin_Say` 读取 `allowComments`、`commentCount`,并自行链接到 `/says/ID`。
详情页使用原生 Waline 评论界面。旧插件接口仍返回每页 20 条公开评论的纯文本字段,不包含邮箱、IP、User-Agent 或账号 ID。公开模板仍可用 `say.list` / `Widget_Plugin_Say` 读取 `allowComments`、`commentCount`,并自行链接到 `/says/ID`。

### 验证码和接口

沿用站点「评论」区域的 Turnstile / reCAPTCHA v3 配置;使用现有验证码服务验证,不需要另配一套密钥。验证码脚本需要浏览器能访问对应服务;reCAPTCHA v3 使用 `social` action。已登录身份沿用核心的验证码豁免规则。禁用 IP、必填信息与字数限制也会校验。

- `GET /api/plugins/say/comments/ID?page=1`:返回 `{success:true,data:{page,pageSize,total,items}}`;每项仅包含 `id`、`nick`、`comment`、`createdAt`。
- `POST /api/plugins/say/comments/ID`:同源 JSON 请求,字段为 `comment`、`nick`、`mail`、`link`、`captcha`。需要准确的本站 `Origin` 请求头;浏览器表单自动提供。跨站发布 API Key 不能绕过评论身份或审核。成功仅表示已入库等待审核。
- 写入有重复评论检查、IP 冷却(至少 10 秒,默认 60 秒,沿用站点 `ipQps`),以及同进程同 IP 在途提交锁。多实例之间不提供严格的全局并发锁;仍需入口层限流防止滥用。网络失败后不要自动重试,先核实提交情况。
- `POST /api/plugins/say/comments/ID`:同源 JSON 请求,字段为 `comment`、`nick`、`mail`、`link`、`captcha`。需要准确的本站 `Origin` 请求头;浏览器表单自动提供。跨站发布 API Key 不能绕过评论身份或审核。返回格式仍为 `{success:true,data:{message}}`,成功表示已提交,是否公开由核心决定,不在此接口回传审核状态。
- 重复提交检查、IP 冷却和黑名单沿用核心规则;旧接口另外保留同进程同 IP 在途提交锁。多实例之间不提供严格的全局并发锁;仍需入口层限流防止滥用。网络失败后不要自动重试,先核实提交情况。

### 首版边界与兼容性

- 使用现有 `post.allow_comment`、`post.comment_num` 与 `comment.post_id`,不改文章类型,不接管 `/api/comment`。依赖当前 Firekylin 的内部 `comment` 身份/输入校验服务和 `captcha` 服务;缺少接口时评论提交会安全失败,不会退回无验证写入。保持插件现有核心版本要求,启用前建议在测试站验证安装版本。
- 使用现有 `post.allow_comment`、`post.comment_num` 与 `comment.post_id`,不改文章类型,不接管 `/api/comment`。依赖 Firekylin 的内部 `comment` 创建、校验与计数服务(在 Core 2.19.2 验证),以及用于详情页配置的 `captcha` 服务;缺少接口时评论提交会安全失败,不会退回无验证写入。保持插件现有核心版本要求,启用前建议在测试站验证安装版本。
- 使用后台已有的审核、编辑和删除能力。当前核心后台会把 type-3 碎语的「原文」链接按文章生成,这个链接可能 404;请从微博列表或 `/says/ID` 查看。该 PR 不修改核心以修正这个链接。
- 首版提供平铺评论,**不支持楼中楼或后台「回复」按钮**(核心回复入口仍按文章/页面解析)。不提供访客自助编辑、删除或插件内登录/OAuth 界面;登录复用博客现有会话。
- 插件直接保存待审核评论,不调用核心文章评论创建流程,因此不触发其创建事件、AI 自动审核或新评论邮件通知。后台审核仍走核心原有审核流程。不要依赖文章评论的创建钩子处理碎语评论。
- 旧插件接口只支持首层评论,不新增回复或访客自助编辑、删除接口。详情页使用原生 Waline,与旧接口共享评论归属;登录仍复用博客现有会话。
- 新旧评论入口均调用核心创建流程,沿用站点的创建事件、审核(含已配置的 AI 审核)、邮件通知及公开评论计数。历史评论不迁移,仍按原有 `comment.post_id` 归属读取。
- 有任何关联评论(包括待审核、垃圾评论)的碎语禁止合并、删除,避免评论失去归属。可以先设为私密,或在评论管理中删除关联评论后再操作;复制碎语不会复制评论。评论开关不会清理历史数据。
- 尚未进行真实站点、真实验证码服务和浏览器完整端到端验证。仓库测试覆盖插件提交/公开隔离/输入校验/表单转义,设置 `FIREKYLIN_CORE_PATH=/path/to/firekylin` 可额外验证真实核心服务的登录身份、审核及数据互通:
- 仓库测试覆盖插件提交、公开隔离、输入校验和表单转义。设置 `FIREKYLIN_CORE_PATH=/path/to/firekylin` 可额外验证核心的登录身份、审核、验证码分支及公开计数(测试不连接真实 AI 或验证码服务):

```sh
FIREKYLIN_CORE_PATH=/path/to/firekylin node --test packages/say/test/comments.test.js
Expand Down
10 changes: 3 additions & 7 deletions packages/say/lib/comment-render.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';
const {escapeHtml: esc} = require('./render');
const {detailUrl} = require('./urls');
const {commentUrl} = require('./urls');

function renderComments(id, result, config) {
const captcha = config.captcha;
Expand All @@ -14,7 +14,7 @@ function renderComments(id, result, config) {
${result.items.map(item => `<article class="say-item"><b>${esc(item.nick)}</b> <time>${esc(item.createdAt)}</time><p style="white-space:pre-wrap;overflow-wrap:anywhere">${esc(item.comment)}</p></article>`).join('')}
<nav>${result.page > 1 ? `<a href="?page=${result.page - 1}#comments-title">上一页评论</a>` : ''}
${result.page * result.pageSize < result.total ? `<a href="?page=${result.page + 1}#comments-title">下一页评论</a>` : ''}</nav>
<p>评论审核通过后显示。${config.forceLogin ? '本站要求登录后评论。' : ''}<a href="/admin/login">登录博客</a></p>
<p>评论是否立即公开取决于站点的审核设置。${config.forceLogin ? '本站要求登录后评论。' : ''}<a href="/admin/login">登录博客</a></p>
<form id="say-comment-form" data-endpoint="/api/plugins/say/comments/${Number(id)}" data-provider="${esc(provider)}" data-key="${esc(key)}">
<p><label>昵称 <input name="nick" maxlength="80" autocomplete="nickname"></label></p>
<p><label>邮箱(不会公开)<input name="mail" type="email" maxlength="255" autocomplete="email"></label></p>
Expand Down Expand Up @@ -59,15 +59,11 @@ function renderComments(id, result, config) {
module.exports = {renderComments};

function renderWalineComments(item, {options, public: publicConfig}) {
if (typeof item.pathname !== 'string' || !item.pathname.trim()) {
throw new TypeError('A stored Say pathname is required for native comments');
}
// Waline 3.16 decodes path once before sending it. Protect query-value escapes
// so core receives the stored pathname, not an ID or a partially decoded value.
const path = `${detailUrl(item.id)}?pathname=${encodeURIComponent(item.pathname)}&type=3`;
const settings = options.comment || {};
const config = {
path: encodeURI(path),
path: encodeURI(commentUrl(item)),
login: publicConfig.forceLogin ? 'force' : 'enable',
lang: settings.locale && settings.locale !== 'auto' ? settings.locale : 'zh-CN',
pageSize: Number(settings.pageSize) || 10,
Expand Down
90 changes: 49 additions & 41 deletions packages/say/lib/comments.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

const {strings} = require('./say-service');
const {detailUrl} = require('./urls');
const {SAY_TYPE} = require('./say-service');
const {commentUrl} = require('./urls');

function fail(status, message) { throw Object.assign(new Error(message), {status, publicCommentError: true}) }
function idOf(value) {
Expand All @@ -11,11 +11,10 @@ function idOf(value) {

// Plugin-owned targets; no changes to the native article/page URL resolver.
class SayComments {
constructor({say, getModel, getService, now, logger}) {
constructor({say, getModel, getService, logger}) {
this.say = say;
this.getModel = getModel;
this.getService = getService;
this.now = now;
this.logger = logger;
this.pending = new Map();
}
Expand All @@ -29,18 +28,17 @@ class SayComments {
return item;
}

// Native Waline submissions bypass submit()/create() below. Apply Say's
// enablement/comment switches and review-before-publication policy here.
// Other post types keep the core's policy; existing spam stays spam.
// Say owns target availability. Firekylin owns moderation for every post type.
// Keep the original data, including status set by core or earlier filters.
async beforeNativeCreate(data) {
const host = require('firekylin/src/service/comment');
const options = await this.getModel('options').getOptions();
const id = await host.resolveCommentPostId({model: this.getModel}, data.url, options);
if (!id) return data;
const row = await this.getModel('post').where({id}).field('id,type').find();
if (Number(row.type) !== require('./say-service').SAY_TYPE) return data;
if (Number(row.type) !== SAY_TYPE) return data;
await this.target(id, true);
return {...data, status: data.status === 'spam' ? 'spam' : 'waiting'};
return data;
}

async configuration() {
Expand Down Expand Up @@ -80,19 +78,25 @@ class SayComments {

async create(id, body, request) {
const item = await this.target(id, true);
const path = detailUrl(item.id);
const {options, captcha, captchaConfig} = await this.configuration();
const host = this.getService('comment');
if (!host?.create || !host?.context || !host?.validateCommentInput) fail(503, '当前核心缺少兼容的评论服务。');
// Use the host's authenticated comment identity, not an author ID supplied by the client.
request.state.jwtSecret ||= options.jwt_secret || options.comment_jwt_secret;
const controller = {ctx: request, model: this.getModel, service: this.getService,
get: name => request.query?.[name]};
if (!host?.create || !host?.context || !host?.validateCommentTarget ||
!host?.validateCommentInput || !host?.syncCount) {
fail(503, '当前核心缺少兼容的评论服务。');
}
const controller = {
ctx: request, model: this.getModel, service: this.getService,
get: name => request.query?.[name]
};
const runtime = await host.create(controller);
if (!runtime?.core?.comment?.create || !runtime.options || !runtime.config) {
fail(503, '当前核心缺少兼容的评论服务。');
}
// Authenticate through the same cookie/token context as /api/comment.
request.state.jwtSecret ||= runtime.options.jwt_secret || runtime.options.comment_jwt_secret;
const context = await host.context(controller, runtime.users, runtime.core, runtime.tokenService, runtime.avatarService);
const user = context.state.userInfo;
const config = options.comment || {};
if (!user && config.forceLogin) fail(401, '请先登录博客账号再评论。');
// Keep the legacy endpoint's authentication error ahead of form validation.
if (!user && runtime.config.forceLogin) fail(401, '请先登录博客账号再评论。');
const data = {};
for (const field of ['comment', 'nick', 'mail', 'link', 'captcha']) {
if (body[field] !== undefined && typeof body[field] !== 'string') fail(400, '评论字段格式不正确。');
Expand All @@ -110,30 +114,34 @@ class SayComments {
try { url = new URL(data.link) } catch { fail(400, '网站地址格式不正确。') }
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) fail(400, '网站地址需要 HTTP 或 HTTPS。');
}
try { host.validateCommentInput(data, context, config) } catch { fail(400, '评论不符合站点的字数或必填信息要求。') }
if (strings(config.disallowIPList).includes(request.ip)) fail(403, '当前地址不允许评论。');
if (!user && !await captcha.verify(captchaConfig, data.captcha, request.ip, 'comment')) fail(403, '验证码校验失败,请刷新页面后重试。');
const model = () => this.getModel('comment');
const interval = Math.max(10, Number(config.ipQps) || 60);
const since = this.now(new Date(Date.now() - interval * 1000));
if (Number(await model().where({ip: request.ip || '', inserted_at: ['>', since]}).count())) fail(429, '评论过于频繁,请稍后再试。');
if (Number(await model().where({post_id: item.id, comment: data.comment, nick: data.nick, mail: data.mail}).count())) {
fail(409, '这条评论已提交,请勿重复发送。');
}
await this.target(id, true);
const timestamp = this.now();
const spam = strings(config.forbiddenWords).some(word => data.comment.toLowerCase().includes(word.toLowerCase()));
const saved = await model().add({post_id: item.id, url: path, comment: data.comment,
nick: data.nick, mail: data.mail, link: data.link, user_id: user ? String(user.objectId) : null,
ip: String(request.ip || '').slice(0, 64), ua: String(request.get('user-agent') || '').slice(0, 1024),
status: spam ? 'spam' : 'waiting', sticky: 0, like: 0, pid: null, rid: null,
inserted_at: timestamp, created_at: timestamp, updated_at: timestamp});
// A target removed or hidden during submission must not retain a newly submitted comment.
try { await this.target(id, true) } catch (error) {
await model().where({id: Number(saved), post_id: item.id}).delete();
throw error;
// Build the target and metadata on the server. Never pass through status,
// user_id, URL, reply IDs, or other client-provided properties.
data.url = commentUrl(item);
data.ua = String(request.get('user-agent') || '').slice(0, 1024);
try {
const post = await host.validateCommentTarget(controller, data.url);
if (Number(post?.id) !== item.id || Number(post?.type) !== SAY_TYPE) {
fail(404, '碎语不存在。');
}
host.validateCommentInput(data, context, runtime.config);
await this.target(id, true);
await runtime.core.comment.create(data, context);
} catch (error) {
// Preserve the legacy HTTP statuses without creating a second policy or
// returning native errors/details that may include private data.
switch (error?.code) {
case 'UNAUTHORIZED': fail(401, '请先登录博客账号再评论。'); break;
case 'FORBIDDEN': fail(403, '评论未通过站点校验,请检查验证码后重试。'); break;
case 'COMMENT_DISABLED': fail(403, '这条碎语的评论已关闭。'); break;
case 'COMMENT_TOO_FAST': fail(429, '评论过于频繁,请稍后再试。'); break;
case 'DUPLICATE_CONTENT': fail(409, '这条评论已提交,请勿重复发送。'); break;
case 'VALIDATION_ERROR': fail(400, '评论不符合站点的字数或必填信息要求。'); break;
case 'INVALID_PATH': fail(404, '碎语不存在。'); break;
default: throw error;
}
}
return {message: '评论已提交,审核通过后会显示。'};
await host.syncCount(controller, item.id);
return {message: '评论已提交。'};
}

async handle(operation, request) {
Expand Down
12 changes: 11 additions & 1 deletion packages/say/lib/urls.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const {SAY_TYPE} = require('./say-service');

const listUrl = '/says';
const detailUrl = id => `${listUrl}/${Number(id)}`;
const tagUrl = tag => `${listUrl}/tag/${encodeURIComponent(tag)}`;
Expand All @@ -8,4 +10,12 @@ const tagUrl = tag => `${listUrl}/tag/${encodeURIComponent(tag)}`;
const pageUrl = (page, tag = '', pathname = listUrl) =>
`${pathname}?page=${page}${tag ? `&tag=${encodeURIComponent(tag)}` : ''}`;

module.exports = {listUrl, detailUrl, tagUrl, pageUrl};
// Both legacy writes and the native Waline UI address the same stored post.
function commentUrl(item) {
if (typeof item.pathname !== 'string' || !item.pathname.trim()) {
throw new TypeError('A stored Say pathname is required for native comments');
}
return `${detailUrl(item.id)}?pathname=${encodeURIComponent(item.pathname)}&type=${SAY_TYPE}`;
}

module.exports = {listUrl, detailUrl, tagUrl, pageUrl, commentUrl};
2 changes: 1 addition & 1 deletion packages/say/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ module.exports = {
service = new SayService({getModel: name => think.model(name), now: () => think.datetime()});
pluginLogger = ctx.logger;
const comments = new SayComments({say: service, getModel: name => think.model(name),
getService: name => think.service(name), now: value => think.datetime(value), logger: ctx.logger});
getService: name => think.service(name), logger: ctx.logger});
ctx.events.on('comment.beforeCreate', data => comments.beforeNativeCreate(data));
const publisher = new FrontendPublish({say: service, getModel: name => think.model(name),
getService: name => think.service(name)});
Expand Down
Loading
Loading