From fd10b3b93bb9633e244a83bef5c080c3961da860 Mon Sep 17 00:00:00 2001 From: Austin Lee Date: Sat, 21 Nov 2026 11:32:25 +0800 Subject: [PATCH] fix(say): delegate comment moderation to core --- packages/say/README.md | 20 +- packages/say/lib/comment-render.js | 10 +- packages/say/lib/comments.js | 90 ++++---- packages/say/lib/urls.js | 12 +- packages/say/plugin.js | 2 +- packages/say/test/comments.test.js | 341 +++++++++++++++++++---------- 6 files changed, 303 insertions(+), 172 deletions(-) diff --git a/packages/say/README.md b/packages/say/README.md index 6c0fb70..31d23e7 100644 --- a/packages/say/README.md +++ b/packages/say/README.md @@ -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 diff --git a/packages/say/lib/comment-render.js b/packages/say/lib/comment-render.js index 048bbe8..1720e2d 100644 --- a/packages/say/lib/comment-render.js +++ b/packages/say/lib/comment-render.js @@ -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; @@ -14,7 +14,7 @@ function renderComments(id, result, config) { ${result.items.map(item => `
${esc(item.nick)}

${esc(item.comment)}

`).join('')} -

评论审核通过后显示。${config.forceLogin ? '本站要求登录后评论。' : ''}登录博客

+

评论是否立即公开取决于站点的审核设置。${config.forceLogin ? '本站要求登录后评论。' : ''}登录博客

@@ -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, diff --git a/packages/say/lib/comments.js b/packages/say/lib/comments.js index 492ab55..ecf97d8 100644 --- a/packages/say/lib/comments.js +++ b/packages/say/lib/comments.js @@ -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) { @@ -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(); } @@ -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() { @@ -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, '评论字段格式不正确。'); @@ -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) { diff --git a/packages/say/lib/urls.js b/packages/say/lib/urls.js index b8e91cd..bfd04f0 100644 --- a/packages/say/lib/urls.js +++ b/packages/say/lib/urls.js @@ -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)}`; @@ -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}; diff --git a/packages/say/plugin.js b/packages/say/plugin.js index a195dd2..ad7aaf8 100644 --- a/packages/say/plugin.js +++ b/packages/say/plugin.js @@ -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)}); diff --git a/packages/say/test/comments.test.js b/packages/say/test/comments.test.js index 1c4c6f7..69f8efb 100644 --- a/packages/say/test/comments.test.js +++ b/packages/say/test/comments.test.js @@ -7,86 +7,142 @@ const {renderComments} = require('../lib/comment-render'); function fixture() { const rows = []; const settings = {enabled: true, commentsEnabled: false}; // Obsolete stored option must have no effect. - const item = {id: 7, status: 'public', allowComments: true}; + const item = {id: 7, pathname: 'a&b%2F中文', status: 'public', allowComments: true}; const options = {comment: {}}; let user; const captcha = {settings: () => ({}), enabled: () => false, publicSettings: () => ({}), verify: async() => true}; - const host = {create: async() => ({}), context: async() => ({state: {userInfo: user}}), validateCommentInput() {}}; - const getModel = name => name === 'options' ? {getOptions: async() => options} : { - where(where) { this.condition = where; return this }, order() { return this }, - limit(offset, size) { this.offset = offset; this.size = size; return this }, - filtered() { return rows.filter(row => Object.entries(this.condition || {}).every(([key, value]) => - Array.isArray(value) ? row[key] > value[1] : row[key] === value)) }, - async count() { return this.filtered().length }, - async select() { return this.filtered().slice(this.offset || 0, (this.offset || 0) + (this.size || 20)) }, - async add(row) { rows.push({...row, id: rows.length + 1}); return rows.length }, - async delete() { for (const row of this.filtered()) rows.splice(rows.indexOf(row), 1) } + const calls = []; + const runtime = {options, config: options.comment, core: {comment: { + async create(input, context) { + calls.push(['create', input, context]); + return {objectId: '88', status: 'spam', mail: 'never-forward@example.test'}; + } + }}}; + const host = { + create: async() => runtime, + context: async controller => ({state: {userInfo: user}, ip: controller.ctx.ip, headers: controller.ctx.headers}), + async validateCommentTarget(controller, url) { + calls.push(['target', controller, url]); + return {id: item.id, type: 3}; + }, + validateCommentInput(input, context, config) { + calls.push(['input', input, context, config]); + }, + async syncCount(controller, id) { calls.push(['count', controller, id]) } + }; + const getModel = name => { + if (name === 'options') return {getOptions: async() => options}; + const source = name === 'post' ? [{id: item.id, pathname: item.pathname, type: 3, + status: item.status === 'hidden' ? 0 : 3, is_public: item.status === 'public' ? 1 : 0, + allow_comment: Number(item.allowComments)}] : rows; + return { + where(where) { this.condition = where; return this }, + order() { return this }, + field() { return this }, + limit(offset, size) { this.offset = size ? offset : 0; this.size = size || offset; return this }, + filtered() { + return source.filter(row => Object.entries(this.condition || {}).every(([key, value]) => { + if (!Array.isArray(value)) return (row[key] ?? null) === (value ?? null); + if (value[0] === '>') return row[key] > value[1]; + if (value[0] === 'NOT IN') return !value[1].includes(row[key]); + throw new Error(`Unexpected fixture operator: ${value[0]}`); + })); + }, + async count() { return this.filtered().length }, + async select() { return this.filtered().slice(this.offset || 0, (this.offset || 0) + (this.size || 20)) }, + async find() { return this.filtered()[0] || {} }, + async add(row) { rows.push({...row, id: rows.length + 1}); return rows.length }, + async update(patch) { if (name === 'post') item.commentCount = patch.comment_num } + }; }; - const request = {state: {}, query: {}, ip: '127.0.0.1', protocol: 'https', host: 'blog.test', - is: type => type === 'application/json', get: name => name === 'origin' ? 'https://blog.test' : ''}; + const request = {state: {}, query: {}, ip: '127.0.0.1', protocol: 'https', host: 'blog.test', headers: {}, + referrer: () => 'https://blog.test/says/7', cookie: () => '', + is: type => type === 'application/json', get: name => ({origin: 'https://blog.test', 'user-agent': 'test-agent'})[name] || ''}; const comments = new SayComments({say: {settings: async() => settings, get: async() => item}, getModel, - getService: name => name === 'captcha' ? captcha : host, now: date => (date || new Date()).toISOString()}); - return {rows, item, options, settings, request, comments, captcha, host, getModel, setUser: value => { user = value }}; + getService: name => name === 'captcha' ? captcha : host}); + return {rows, item, options, settings, request, comments, captcha, host, runtime, calls, getModel, + setUser: value => { user = value }}; } const body = {comment: 'hello', nick: 'Visitor', mail: 'v@example.test'}; -test('stores pending comments with canonical target and ignores forged identity/status', async() => { +test('legacy POST delegates trusted fields and canonical target to core without exposing the result', async() => { const f = fixture(); - await f.comments.submit(7, {...body, status: 'approved', user_id: '1', post_id: 99, url: '/fake'}, f.request); - assert.equal(f.rows[0].status, 'waiting'); - assert.equal(f.rows[0].post_id, 7); - assert.equal(f.rows[0].url, '/says/7'); - assert.equal(f.rows[0].user_id, null); - assert.deepEqual((await f.comments.list(7)).items, []); - f.rows[0].status = 'approved'; - const listed = await f.comments.list(7); - assert.equal(listed.total, 1); - assert.deepEqual(Object.keys(listed.items[0]), ['id', 'nick', 'comment', 'createdAt']); - await assert.rejects(f.comments.submit(7, body, f.request), {status: 429}); + const result = await f.comments.handle(() => f.comments.submit(7, {...body, captcha: 'proof', status: 'approved', + user_id: '1', post_id: 99, url: '/fake', ua: 'forged'}, f.request), {...f.request, + set: (name, value) => assert.deepEqual([name, value], ['Cache-Control', 'no-store'])}); + assert.deepEqual(result, {success: true, data: {message: '评论已提交。'}}); + assert.deepEqual(f.calls.map(call => call[0]), ['target', 'input', 'create', 'count']); + const [target, input, write, count] = f.calls; + const url = '/says/7?pathname=a%26b%252F%E4%B8%AD%E6%96%87&type=3'; + assert.equal(target[2], url); + assert.deepEqual(write[1], {...body, link: '', captcha: 'proof', url, ua: 'test-agent'}); + assert.equal(write[1], input[1]); + assert.equal(write[2], input[2]); + assert.equal(input[3], f.runtime.config); + assert.deepEqual(count, ['count', target[1], 7]); }); test('requires public, enabled, commentable targets for reads and writes', async() => { for (const change of [f => { f.item.status = 'private' }, f => { f.item.status = 'hidden' }, f => { f.settings.enabled = false }, f => { f.item.allowComments = false }]) { - const f = fixture(); change(f); + const f = fixture(); + change(f); await assert.rejects(f.comments.list(7)); await assert.rejects(f.comments.submit(7, body, f.request)); - assert.equal(f.rows.length, 0); + assert.deepEqual(f.calls, []); } await assert.rejects(fixture().comments.list('7oops'), {status: 404}); }); -test('checks origin, JSON, login, captcha and validated account identity', async() => { +test('requires same-origin JSON and uses the native authenticated account metadata', async() => { const f = fixture(); await assert.rejects(f.comments.submit(7, body, {...f.request, get: () => 'https://evil.test'}), {status: 403}); + await assert.rejects(f.comments.submit(7, body, {...f.request, get: () => ''}), {status: 403}); await assert.rejects(f.comments.submit(7, body, {...f.request, is: () => false}), {status: 415}); - f.options.comment.forceLogin = true; - await assert.rejects(f.comments.submit(7, body, f.request), {status: 401}); - f.options.comment.forceLogin = false; - f.captcha.verify = async() => false; - await assert.rejects(f.comments.submit(7, body, f.request), {status: 403}); - f.setUser({objectId: '9', display_name: 'Authenticated', email: 'real@example.test'}); + f.runtime.config.forceLogin = true; + await assert.rejects(f.comments.submit(7, {comment: 'hello'}, f.request), {status: 401}); + const user = {objectId: '9', display_name: 'Authenticated', email: 'real@example.test'}; + f.setUser(user); + f.runtime.options.jwt_secret = 'fixture'; await f.comments.submit(7, body, f.request); - assert.equal(f.rows[0].nick, 'Authenticated'); - assert.equal(f.rows[0].user_id, '9'); - assert.equal(f.rows[0].status, 'waiting'); + const [, input, context] = f.calls.find(call => call[0] === 'create'); + assert.equal(input.nick, 'Authenticated'); + assert.equal(input.mail, 'real@example.test'); + assert.equal(input.user_id, undefined); + assert.equal(context.state.userInfo, user); + assert.equal(f.request.state.jwtSecret, 'fixture'); }); -test('validates input and host requirements, rejects duplicates and marks spam', async() => { +test('validates legacy fields, rejects mismatched targets and fails closed on incompatible core', async() => { for (const value of [{comment: ''}, {comment: 'x'.repeat(5001)}, {nick: ''}, {mail: 'invalid'}, {link: 'javascript:alert(1)'}, {pid: 3}, {comment: {text: 'x'}}]) { const f = fixture(); await assert.rejects(f.comments.submit(7, {...body, ...value}, f.request), {status: 400}); + assert.deepEqual(f.calls, []); + } + for (const post of [{id: 8, type: 3}, {id: 7, type: 0}]) { + const f = fixture(); + f.host.validateCommentTarget = async() => post; + await assert.rejects(f.comments.submit(7, body, f.request), {status: 404}); + assert.deepEqual(f.calls, []); } const f = fixture(); - f.host.validateCommentInput = () => { throw new Error('required meta') }; - await assert.rejects(f.comments.submit(7, body, f.request), {status: 400}); - f.host.validateCommentInput = () => {}; - f.options.comment.forbiddenWords = ['hello']; - await f.comments.submit(7, body, f.request); - assert.equal(f.rows[0].status, 'spam'); - f.rows[0].inserted_at = '2000-01-01'; - await assert.rejects(f.comments.submit(7, body, f.request), {status: 409}); + delete f.runtime.core.comment.create; + await assert.rejects(f.comments.submit(7, body, f.request), {status: 503}); + assert.deepEqual(f.calls, []); +}); + +test('maps native validation and filtering failures to safe legacy HTTP errors', async() => { + for (const [code, status] of Object.entries({VALIDATION_ERROR: 400, UNAUTHORIZED: 401, FORBIDDEN: 403, + COMMENT_DISABLED: 403, INVALID_PATH: 404, DUPLICATE_CONTENT: 409, COMMENT_TOO_FAST: 429, unexpected: 503})) { + const f = fixture(); + f.runtime.core.comment.create = async() => { throw Object.assign(new Error('private detail'), {code}) }; + const result = await f.comments.handle(() => f.comments.submit(7, body, f.request), f.request); + assert.equal(f.request.status, status); + assert.equal(result.success, false); + assert.doesNotMatch(JSON.stringify(result), /private detail/); + assert.deepEqual(f.calls.map(call => call[0]), ['target', 'input']); + } }); test('safe errors hide infrastructure details; rendered comments cannot inject HTML', async() => { @@ -105,51 +161,109 @@ test('safe errors hide infrastructure details; rendered comments cannot inject H }); -test('real host identity, input validation and moderation interoperate with Say', +test('real core owns guest and admin approval, required metadata, spam, rate limits and count updates', {skip: !process.env.FIREKYLIN_CORE_PATH}, async t => { const path = require('node:path'); const crypto = require('node:crypto'); + const Module = require('node:module'); const root = process.env.FIREKYLIN_CORE_PATH; - const previousThink = global.think, previousFirekylin = global.firekylin; - global.think = {Service: class {}, logger: {error() {}}, isEmpty: value => !value || !Object.keys(value).length, - md5: value => crypto.createHash('md5').update(value).digest('hex')}; - global.firekylin = {USER_ADMIN: 1, USER_EDITOR: 2, USER_COMMENTER: 4}; - t.after(() => { global.think = previousThink; global.firekylin = previousFirekylin }); + const previousThink = global.think; + const previousFirekylin = global.firekylin; + global.think = {Service: class {}, logger: {}, isEmpty: value => !value || !Object.keys(value).length, + md5: value => crypto.createHash('md5').update(value).digest('hex'), + datetime: (value = new Date()) => new Date(value).toISOString(), cache: async() => {}}; + global.firekylin = {POST_PUBLISH: 3, POST_PUBLIC: 1, POST_ALLOW_COMMENT: 1, USER_ADMIN: 1}; + t.after(() => { + global.think = previousThink; + global.firekylin = previousFirekylin; + }); const Host = require(path.join(root, 'src/service/comment')); const auth = require(path.join(root, 'src/service/admin-auth')); const Moderation = require(path.join(root, 'src/service/comment-moderation')); - const f = fixture(); + const EventBus = require(path.join(root, 'src/plugin/events')); + const load = Module._load; + t.mock.method(Module, '_load', function(name, ...args) { + if (name === 'firekylin/src/service/comment') return Host; + return load.call(this, name, ...args); + }); const host = new Host(); - f.options.jwt_secret = 'a'.repeat(64); - f.options.comment.requiredMeta = ['mail']; - f.request.cookie = () => ''; - f.request.referrer = () => 'https://blog.test/says/7'; - f.request.headers = {}; - f.comments.getService = name => name === 'comment' ? host : require(path.join(root, 'src/service/captcha')); - await assert.rejects(f.comments.submit(7, {...body, mail: ''}, f.request), {status: 400}); - await f.comments.submit(7, body, f.request); - assert.equal(f.rows[0].status, 'waiting'); - f.rows[0].inserted_at = '2000-01-01'; - const jwt = auth.sign({id: 9, type: 1, name: 'Admin'}, f.options.jwt_secret); - f.request.cookie = () => jwt; - const originalModel = f.comments.getModel; - f.comments.getModel = name => name === 'user' ? {where() {return this}, - select: async() => [{id: 9, name: 'Admin', type: 1, status: 1, email: 'admin@example.test'}]} : originalModel(name); - await f.comments.submit(7, {...body, comment: 'admin message', user_id: '1'}, f.request); - assert.equal(f.rows[1].user_id, '9'); - assert.equal(f.rows[1].nick, 'Admin'); - const counts = []; - const moderation = new Moderation({getModel: () => { - let id; - return {where(where) {id = where.id; return this}, setRelation() {return this}, - find: async() => ({...f.rows.find(row => row.id === id)}), - update: async patch => Object.assign(f.rows.find(row => row.id === id), patch)}; - }, now: () => new Date().toISOString(), syncCount: async id => { counts.push(id) }}); - await moderation.moderate({id: 1, operation: 'approved'}, {id: 9, type: 1}); - assert.equal((await f.comments.list(7)).items.length, 1); - assert.deepEqual(counts, [7]); - await moderation.moderate({id: 1, operation: 'spam'}, {id: 9, type: 1}); - assert.equal((await f.comments.list(7)).items.length, 0); + const captcha = require(path.join(root, 'src/service/captcha')); + const verifications = []; + t.mock.method(captcha, 'verify', async(_config, token, ip, area) => { + verifications.push([token, ip, area]); + return token === 'valid-proof'; + }); + for (const [audit, user, message, expected, ai] of [ + [false, false, 'guest message', 'approved'], + [true, false, 'guest message', 'waiting'], + [true, true, 'admin message', 'approved'], + [false, false, 'blocked terms', 'spam'], + [false, false, 'marked by native AI', 'spam', 'spam'], + [false, false, 'AI failure goes to review', 'waiting', 'error'] + ]) { + const f = fixture(); + f.options.jwt_secret = 'a'.repeat(64); + Object.assign(f.options.comment, {audit, requiredMeta: ['mail'], forbiddenWords: ['blocked']}); + f.options.captcha = {provider: 'turnstile', areas: ['comment']}; + f.comments.getService = name => name === 'comment' ? host : captcha; + verifications.length = 0; + const events = new EventBus(); + let aiCalls = 0; + f.options.ai_content_features = {commentModeration: Boolean(ai)}; + global.firekylin.plugins = {events, ai: {generate: async(_input, context) => { + assert.equal(context.scenario, 'comment.moderation'); + aiCalls++; + if (ai === 'error') throw new Error('Fixture AI unavailable'); + return {text: JSON.stringify({spam: true})}; + }}}; + events.on('comment.beforeCreate', data => f.comments.beforeNativeCreate(data)); + let created = 0; + events.on('comment.created', () => { created++ }); + if (user) { + f.request.cookie = () => auth.sign({id: 9, type: 1, name: 'Admin'}, f.options.jwt_secret); + f.comments.getModel = name => name === 'user' ? {where() { return this }, + select: async() => [{id: 9, name: 'Admin', type: 1, status: 1, email: 'admin@example.test'}]} : f.getModel(name); + } else { + await assert.rejects(f.comments.submit(7, {...body, mail: ''}, f.request), {status: 400}); + f.options.comment.forceLogin = true; + await assert.rejects(f.comments.submit(7, body, f.request), {status: 401}); + f.options.comment.forceLogin = false; + await assert.rejects(f.comments.submit(7, body, f.request), {status: 403}); + f.options.comment.disallowIPList = [f.request.ip]; + await assert.rejects(f.comments.submit(7, {...body, captcha: 'valid-proof'}, f.request), {status: 403}); + f.options.comment.disallowIPList = []; + } + const input = {...body, comment: message, status: 'approved', user_id: '1', captcha: 'valid-proof'}; + assert.deepEqual(await f.comments.submit(7, input, f.request), {message: '评论已提交。'}); + assert.equal(f.rows[0].status, expected); + assert.equal(f.rows[0].post_id, 7); + assert.equal(f.rows[0].user_id, user ? '9' : undefined); + assert.equal(f.rows[0].nick, user ? 'Admin' : 'Visitor'); + assert.equal(f.item.commentCount, Number(expected === 'approved')); + assert.equal((await f.comments.list(7)).total, f.item.commentCount); + assert.equal(created, 1); + assert.equal(aiCalls, Number(Boolean(ai))); + assert.deepEqual(verifications, user ? [] : ['', 'valid-proof', 'valid-proof'] + .map(token => [token, f.request.ip, 'comment'])); + if (!user) { + await assert.rejects(f.comments.submit(7, {...input, comment: 'another'}, f.request), {status: 429}); + await assert.rejects(f.comments.submit(7, input, f.request), {status: 409}); + } + if (expected === 'waiting') { + const counts = []; + const moderation = new Moderation({getModel: () => { + let id; + return {where(where) { id = where.id; return this }, setRelation() { return this }, + find: async() => ({...f.rows.find(row => row.id === id)}), + update: async patch => Object.assign(f.rows.find(row => row.id === id), patch)}; + }, now: () => new Date().toISOString(), syncCount: async id => { counts.push(id) }}); + await moderation.moderate({id: 1, operation: 'approved'}, {id: 9, type: 1}); + assert.equal((await f.comments.list(7)).items.length, 1); + assert.deepEqual(counts, [7]); + await moderation.moderate({id: 1, operation: 'spam'}, {id: 9, type: 1}); + assert.equal((await f.comments.list(7)).items.length, 0); + } + } }); test('registered detail and comment routes respect visibility without changing native routes', async t => { @@ -183,27 +297,19 @@ test('registered detail and comment routes respect visibility without changing n await assert.rejects(detail.handler({ctx: request, params: {id: '7'}, query: {}}), {status: 404}); }); -test('rejects simultaneous submissions and removes a comment when target closes during save', async() => { +test('keeps the in-flight lock and rechecks a target that closes before native save', async() => { const f = fixture(); let release; - f.captcha.verify = () => new Promise(resolve => { release = resolve }); + f.runtime.core.comment.create = () => new Promise(resolve => { release = resolve }); const first = f.comments.submit(7, body, f.request); while (!release) await new Promise(resolve => setImmediate(resolve)); await assert.rejects(f.comments.submit(7, body, f.request), {status: 429}); - release(true); + release({objectId: '88'}); await first; const other = fixture(); - const originalModel = other.comments.getModel; - other.comments.getModel = name => { - const model = originalModel(name); - if (name === 'comment') { - const add = model.add.bind(model); - model.add = async row => { const id = await add(row); other.item.status = 'private'; return id }; - } - return model; - }; + other.host.validateCommentInput = () => { other.item.status = 'private' }; await assert.rejects(other.comments.submit(7, body, other.request), {status: 404}); - assert.equal(other.rows.length, 0); + assert.deepEqual(other.calls.map(call => call[0]), ['target']); }); test('legacy lists include native and historical URLs by post ID without exposing pending comments', async() => { @@ -219,24 +325,35 @@ test('legacy lists include native and historical URLs by post ID without exposin assert.deepEqual(result.items.map(item => item.comment), ['old', 'native']); }); -test('native comment filter retains Say switches and moderation without adding a public API', async() => { +test('native comment filter gates Say availability without rewriting the input or status', async t => { const Module = require('node:module'); const original = Module._load; const f = fixture(); let type = 3; + let resolvedId = 7; f.comments.getModel = name => name === 'post' ? {where: () => ({field: () => ({find: async() => ({id: 7, type})})})} : f.getModel(name); - try { - Module._load = function(name, ...args) { - if (name === 'firekylin/src/service/comment') return {resolveCommentPostId: async() => 7}; - return original.call(this, name, ...args); - }; - const data = {url: '/says?pathname=example&type=3', status: 'approved'}; - assert.equal((await f.comments.beforeNativeCreate(data)).status, 'waiting'); - assert.equal((await f.comments.beforeNativeCreate({...data, status: 'spam'})).status, 'spam'); - f.item.allowComments = false; - await assert.rejects(f.comments.beforeNativeCreate(data), {status: 403}); - type = 0; - assert.equal(await f.comments.beforeNativeCreate(data), data); - } finally { Module._load = original; } + t.mock.method(Module, '_load', function(name, ...args) { + if (name === 'firekylin/src/service/comment') return {resolveCommentPostId: async() => resolvedId}; + return original.call(this, name, ...args); + }); + const data = {url: '/says?pathname=example&type=3', comment: 'test'}; + for (const status of ['approved', 'waiting', 'spam', undefined]) { + const input = Object.freeze({...data, status}); + assert.equal(await f.comments.beforeNativeCreate(input), input); + } + f.item.allowComments = false; + await assert.rejects(f.comments.beforeNativeCreate(data), {status: 403}); + f.item.allowComments = true; + for (const change of [() => { f.item.status = 'private' }, () => { f.item.status = 'hidden' }, () => { + f.item.status = 'public'; + f.settings.enabled = false; + }]) { + change(); + await assert.rejects(f.comments.beforeNativeCreate(data), {status: 404}); + } + type = 0; + assert.equal(await f.comments.beforeNativeCreate(data), data); + resolvedId = null; + assert.equal(await f.comments.beforeNativeCreate(data), data); });