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
65 changes: 31 additions & 34 deletions packages/say/README.md

Large diffs are not rendered by default.

5 changes: 1 addition & 4 deletions packages/say/lib/qq-publisher.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict';

const {createHash} = require('node:crypto');
const {strings} = require('./say-service');
const feedback = require('./publish-feedback');
const {whoami} = require('./commands');
const HELP = '发送文本、图片、图文或语音可公开发布碎语;纯链接发布为链接。/merge ID1,ID2 合并;/whoami 查看自己的 OpenID。暂不支持群聊、频道、视频、文件、位置和引用消息。';
Expand All @@ -21,7 +20,6 @@ function createQqPublisher({service, mediaClient, logger, isActive = () => true,
['qqAppId', 'qqAppSecret', 'qqSandbox'].some(key => settings[key] !== connection[key])) { diagnostic('IGNORED_CONFIG_CHANGED'); return }
const text = typeof message.content === 'string' ? message.content.trim() : '';
const identity = !message.attachments?.length && whoami('qq', text, openId);
if (!identity && !strings(settings.qqAllowedOpenIds).includes(openId)) { diagnostic('IGNORED_NOT_ALLOWLISTED'); return }
const ext = message.message_scene?.ext;
let index = (Array.isArray(ext) ? ext.find(value => typeof value === 'string' && value.startsWith('msg_idx='))?.slice(8)
: ext?.msg_idx) ?? message.msg_seq ?? '';
Expand All @@ -47,8 +45,7 @@ function createQqPublisher({service, mediaClient, logger, isActive = () => true,
async function authorized() {
const fresh = await service.settings();
if (!isActive() || !fresh.enabled || !fresh.qqEnabled || fresh.authorId !== settings.authorId ||
['qqAppId', 'qqAppSecret', 'qqSandbox'].some(name => fresh[name] !== connection[name]) ||
!strings(fresh.qqAllowedOpenIds).includes(openId)) {
['qqAppId', 'qqAppSecret', 'qqSandbox'].some(name => fresh[name] !== connection[name])) {
throw Object.assign(new Error('QQ publishing stopped'), {code: 'QQ_PUBLISH_DENIED'});
}
}
Expand Down
7 changes: 5 additions & 2 deletions packages/say/lib/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ function media(item, options = {}) {
return '';
}

function renderSayPage(result, {title = '碎语', tag = '', amapKey = '', section = '', composer = ''} = {}) {
function renderSayPage(result, {title = '碎语', tag = '', amapKey = '', section = '', composer = '', navigation = null} = {}) {
const items = result.items.map(item => `<article class="say-item">
<div class="say-text">${escapeHtml(item.text).replaceAll('\n', '<br>')}</div>
${media(item, {amapKey})}
Expand All @@ -43,6 +43,9 @@ function renderSayPage(result, {title = '碎语', tag = '', amapKey = '', sectio
const previous = result.page > 1 ? `<a href="?page=${result.page - 1}${tag ? `&tag=${encodeURIComponent(tag)}` : ''}">上一页</a>` : '';
const next = result.page * result.pageSize < result.total
? `<a href="?page=${result.page + 1}${tag ? `&tag=${encodeURIComponent(tag)}` : ''}">下一页</a>` : '';
const detailNavigation = navigation && (navigation.previous || navigation.next)
? `<nav aria-label="相邻微博">${navigation.previous ? `<a href="/says/${Number(navigation.previous)}" rel="prev">← 上一条</a>` : '<span></span>'}
${navigation.next ? `<a href="/says/${Number(navigation.next)}" rel="next">下一条 →</a>` : '<span></span>'}</nav>` : '';
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>${escapeHtml(tag ? `#${tag} - ${title}` : title)}</title><style>
body{margin:0;background:#f5f5f5;color:#222;font:16px/1.7 system-ui,sans-serif}.say-wrap{max-width:720px;margin:0 auto;padding:32px 20px}
Expand All @@ -51,7 +54,7 @@ function renderSayPage(result, {title = '碎语', tag = '', amapKey = '', sectio
.say-map{display:block;width:100%;max-height:240px;object-fit:cover;border-radius:6px}.say-card{display:flex;gap:12px;align-items:center;margin-top:12px}.say-card img{width:72px;height:72px;object-fit:cover;border-radius:6px}.say-card p{margin:0}.say-card small{display:block;color:#888}
footer{display:flex;gap:8px;flex-wrap:wrap;margin-top:14px;color:#888;font-size:13px}footer time{margin-left:auto}a{color:#1677ff;text-decoration:none}
nav{display:flex;justify-content:space-between;margin-top:24px}.say-empty{color:#888}</style></head><body><main class="say-wrap">
<h1>${escapeHtml(tag ? `#${tag}` : title)}</h1>${composer}${items || '<p class="say-empty">暂无碎语</p>'}<nav>${previous}<span></span>${next}</nav>
<h1>${escapeHtml(tag ? `#${tag}` : title)}</h1>${composer}${items || '<p class="say-empty">暂无碎语</p>'}${navigation ? detailNavigation : `<nav>${previous}<span></span>${next}</nav>`}
${section}</main></body></html>`;
}

Expand Down
27 changes: 14 additions & 13 deletions packages/say/lib/say-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,10 @@ const DEFAULT_SETTINGS = Object.freeze({
feishuAppSecret: '',
feishuVerificationToken: '',
feishuEncryptKey: '',
feishuAllowedOpenIds: '',
qqEnabled: false,
qqSandbox: true,
qqAppId: '',
qqAppSecret: '',
qqAllowedOpenIds: ''
qqAppSecret: ''
});

function parse(value, fallback = {}) {
Expand All @@ -57,20 +55,15 @@ function normalizeSettings(value = {}, previous = {}) {
!/^[A-Za-z0-9+/]{43}$/.test(value.wechatEncodingAESKey)) {
throw Object.assign(new Error('WeChat EncodingAESKey must be 43 characters'), {status: 400});
}
for (const key of ['qqAppId', 'qqAllowedOpenIds']) {
const ids = key === 'qqAppId' ? [value[key]?.trim?.()].filter(Boolean) : strings(value[key]);
if (typeof value[key] === 'string' && ids.some(id => !/^[A-Za-z0-9_-]{1,128}$/.test(id))) {
throw Object.assign(new Error('Invalid QQ AppID or OpenID'), {status: 400});
}
if (typeof value.qqAppId === 'string' && value.qqAppId.trim() && !/^[A-Za-z0-9_-]{1,128}$/.test(value.qqAppId.trim())) {
throw Object.assign(new Error('Invalid QQ AppID'), {status: 400});
}
return {
qqEnabled: typeof value.qqEnabled === 'boolean' ? value.qqEnabled : prior.qqEnabled,
qqSandbox: typeof value.qqSandbox === 'boolean' ? value.qqSandbox : prior.qqSandbox,
qqAppId: typeof value.qqAppId === 'string' ? value.qqAppId.trim().slice(0, 128) : prior.qqAppId,
qqAppSecret: typeof value.qqAppSecret === 'string' && value.qqAppSecret.trim()
? value.qqAppSecret.trim().slice(0, 256) : prior.qqAppSecret,
qqAllowedOpenIds: typeof value.qqAllowedOpenIds === 'string'
? [...new Set(strings(value.qqAllowedOpenIds))].join('\n') : prior.qqAllowedOpenIds,
enabled: typeof value.enabled === 'boolean' ? value.enabled : prior.enabled,
pageSize: integer(value.pageSize, prior.pageSize, 1, 100),
apiKey: typeof value.apiKey === 'string' && value.apiKey ? value.apiKey.slice(0, 256) : prior.apiKey,
Expand Down Expand Up @@ -98,9 +91,7 @@ function normalizeSettings(value = {}, previous = {}) {
feishuVerificationToken: typeof value.feishuVerificationToken === 'string' && value.feishuVerificationToken
? value.feishuVerificationToken.trim().slice(0, 256) : prior.feishuVerificationToken,
feishuEncryptKey: typeof value.feishuEncryptKey === 'string' && value.feishuEncryptKey
? value.feishuEncryptKey.trim().slice(0, 256) : prior.feishuEncryptKey,
feishuAllowedOpenIds: typeof value.feishuAllowedOpenIds === 'string'
? [...new Set(strings(value.feishuAllowedOpenIds))].join('\n') : prior.feishuAllowedOpenIds
? value.feishuEncryptKey.trim().slice(0, 256) : prior.feishuEncryptKey
};
}

Expand Down Expand Up @@ -325,6 +316,16 @@ class SayService {
.order('create_time DESC').select()).map(decode);
}

async publicNeighbors(id) {
const empty = {previous: null, next: null};
if (!(await this.settings()).enabled) return empty;
const items = (await this.all()).filter(item => item.status === 'public')
.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime() || a.id - b.id);
const index = items.findIndex(item => item.id === Number(id));
if (index < 0) return empty;
return {previous: items[index - 1]?.id || null, next: items[index + 1]?.id || null};
}

async list({page = 1, pageSize, tag, status, keyword, publicOnly = false} = {}) {
const settings = await this.settings();
page = integer(page, 1, 1, 100000);
Expand Down
21 changes: 6 additions & 15 deletions packages/say/plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const {decrypt: decryptFeishu, eventToken: feishuEventToken, messageEvent: feish
verify: verifyFeishu} = require('./lib/feishu');
const feishuReply = require('./lib/feishu-reply');
const feedback = require('./lib/publish-feedback');
const {isWhoami, whoami} = require('./lib/commands');
const {whoami} = require('./lib/commands');
const {createQqWebhook} = require('./lib/qq-webhook');
const {renderSayPage} = require('./lib/render');
const {renderWalineComments} = require('./lib/comment-render');
Expand Down Expand Up @@ -251,11 +251,6 @@ function feishuText(message) {
async function fromFeishu(message, settings, mediaClient) {
const identity = whoami('feishu', feishuText(message), message.openId);
if (identity) return identity;
const allowed = new Set(strings(settings.feishuAllowedOpenIds));
if (!allowed.has(message.openId)) {
pluginLogger?.info?.(`say: rejected Feishu publisher OpenID ${message.openId}`);
return;
}
const source = '飞书';
const save = async input => ({item: await feedback.step('save',
() => service.create(input, settings.authorId)), action: 'publish'});
Expand Down Expand Up @@ -328,7 +323,7 @@ async function feishuCallback({ctx: request, body}, mediaClient) {
return request.throw(401, 'Invalid Feishu app ID');
}
const message = feishuMessageEvent(payload);
if (!message || (!isWhoami(feishuText(message)) && !strings(settings.feishuAllowedOpenIds).includes(message.openId))) return {};
if (!message) return {};
if (!/^om_[A-Za-z0-9_-]{1,256}$/.test(message.messageId)) return {};
const eventKey = `${settings.feishuAppId}:${message.eventId || message.messageId}`;
let receipt = feishuEvents.get(eventKey);
Expand Down Expand Up @@ -451,7 +446,7 @@ module.exports = {
request.type = 'text/html';
request.set('Cache-Control', 'no-store');
request.body = renderSayPage({items: [item], page: 1, pageSize: 1, total: 1},
{title: `碎语 #${item.id}`, amapKey: settings.amapKey, section});
{title: `碎语 #${item.id}`, amapKey: settings.amapKey, section, navigation: await service.publicNeighbors(item.id)});
}});

ctx.admin.registerPanel({id: 'say', title: '微博列表', icon: 'comment', order: 74});
Expand Down Expand Up @@ -504,7 +499,7 @@ module.exports = {
{type: 'markdown', title: '消息平台回调设置', content:
'- 企业微信:`/api/plugins/say/wecom`。\n' +
'- 微信公众号:`/api/plugins/say/wechat`,服务器配置必须选择安全模式,并将发布者 OpenID 加入白名单。\n' +
'- 飞书:`/api/plugins/say/feishu`,配置 Encrypt Key,订阅 `im.message.receive_v1`,并将发布者 OpenID 加入白名单。'},
'- 飞书:`/api/plugins/say/feishu`,配置 Encrypt Key,订阅 `im.message.receive_v1`。任何能向机器人发送合规消息的人均可按配置作者发布。'},
{type: 'markdown', title: '公开访问', content:
'公开页面:`/says`;标签页面:`/says/tag/标签`;JSON API:`/api/plugins/say/list`。主题可调用 `say.list` 或 `Widget_Plugin_Say`。'}
]})
Expand Down Expand Up @@ -559,21 +554,17 @@ module.exports = {
{name: 'wechatAllowedOpenIds', type: 'textarea', label: '公众号允许发布的 OpenID',
description: '向公众号发送 /whoami 获取;每行或逗号分隔一个 OpenID,未列出的关注者不能发布碎语。'},
{name: 'qqEnabled', type: 'switch', label: '启用 QQ 私聊发布',
description: '官方机器人 Webhook;回调地址 /api/plugins/say/qq,适用于 Vercel。白名单为空时只可使用 /whoami,不允许发布。'},
description: '官方机器人 Webhook;回调地址 /api/plugins/say/qq,适用于 Vercel。任何能向机器人发送合规私聊消息的人均可按配置作者发布。'},
{name: 'qqSandbox', type: 'switch', label: 'QQ 沙箱环境', description: '测试机器人启用;IP 白名单可选,配置后需匹配实际出口 IP。'},
{name: 'qqAppId', type: 'text', label: 'QQ 机器人 AppID'},
{name: 'qqAppSecret', type: 'password', label: 'QQ 机器人 AppSecret', description: '留空保留原值;关闭 QQ 开关即可停止接收回调。'},
{name: 'qqAllowedOpenIds', type: 'textarea', label: 'QQ 允许发布的 OpenID',
description: '向机器人私聊 /whoami 获取,每行一个;不是数字 QQ 号。仅授权可信发布者,消息会公开发布。'},
{name: 'feishuAppId', type: 'text', label: '飞书 App ID'},
{name: 'feishuAppSecret', type: 'password', label: '飞书 App Secret',
description: '用于获取 tenant_access_token 和下载图片、音频;留空会保留原值。'},
{name: 'feishuVerificationToken', type: 'password', label: '飞书 Verification Token',
description: '在事件与回调的加密策略中获取;留空会保留原值。'},
{name: 'feishuEncryptKey', type: 'password', label: '飞书 Encrypt Key',
description: '用于回调签名校验和事件解密;留空会保留原值。'},
{name: 'feishuAllowedOpenIds', type: 'textarea', label: '飞书允许发布的 OpenID',
description: '向机器人发送 /whoami 获取;每行或逗号分隔一个 ou_ 开头的 OpenID,白名单为空时不能发布。'}
description: '用于回调签名校验和事件解密;留空保留原值。任何能向机器人发送合规消息的人均可按配置作者发布。'}
], load: async() => service.settings(), submit: async values => {
await service.saveSettings(values);
return {message: '全部设置已保存。'};
Expand Down
9 changes: 7 additions & 2 deletions packages/say/test/admin-settings.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ function setup(t) {
wechatEncodingAESKey: 'b'.repeat(43), wechatAllowedOpenIds: 'wx_user',
feishuAppId: 'cli_app', feishuAppSecret: 'private-feishu-secret',
feishuVerificationToken: 'private-feishu-token', feishuEncryptKey: 'private-feishu-key',
feishuAllowedOpenIds: 'ou_user', qqEnabled: false, qqSandbox: true, qqAppId: '', qqAppSecret: '', qqAllowedOpenIds: ''};
qqEnabled: false, qqSandbox: true, qqAppId: '', qqAppSecret: ''};
const load = t.mock.method(SayService.prototype, 'settings', async() => ({...settings}));
plugin.register({logger: {info: noop}, widgets: {Widget: class {}, register: noop},
events: {on: noop}, templates: {registerFunction: noop}, routes: {register: noop}, admin: {
Expand Down Expand Up @@ -89,7 +89,7 @@ test('saves all providers concurrently and preserves existing partial-save behav
const changes = {external: {apiKey: 'new-api-key-at-least-16'},
wecom: {wecomCorpId: 'corp_updated', wecomCorpSecret: ''},
wechat: {wechatAppId: '', wechatAllowedOpenIds: ''},
feishu: {feishuAppId: 'cli_updated', feishuAllowedOpenIds: ''}};
feishu: {feishuAppId: 'cli_updated'}};
for (const values of Object.values(changes)) {
const before = {...stored};
await form.submit({...values, pageSize: 30});
Expand All @@ -110,3 +110,8 @@ test('new post forms allow comments and settings have no global comment switch',
assert.equal((await allForms.find(form => form.id === 'publish-say').load()).allowComments, true);
assert.ok(forms.every(form => form.fields.every(field => field.name !== 'commentsEnabled')));
});

test('Feishu and QQ publisher allowlist controls are removed', t => {
const {forms} = setup(t);
assert.ok(forms.every(form => form.fields.every(field => !['qqAllowedOpenIds', 'feishuAllowedOpenIds'].includes(field.name))));
});
3 changes: 3 additions & 0 deletions packages/say/test/comments.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ test('registered detail and comment routes respect visibility without changing n
const hooks = [];
const noop = () => {};
t.mock.method(SayService.prototype, 'settings', async() => ({enabled: true, commentsEnabled: false}));
t.mock.method(SayService.prototype, 'publicNeighbors', async() => ({previous: 6, next: 8}));
const get = t.mock.method(SayService.prototype, 'get', async() => ({id: 7, status: 'public', text: 'hello', tags: []}));
require('../plugin').register({widgets: {Widget: class {}, register: noop}, events: {on: (name, handler) => hooks.push({name, handler})}, templates: {registerFunction: noop},
routes: {register: route => routes.push(route)}, admin: {registerPanel: noop, registerPage: noop, registerForm: noop, registerAction: noop}});
Expand All @@ -170,6 +171,8 @@ test('registered detail and comment routes respect visibility without changing n
const request = {set() {}, throw(status) {throw Object.assign(new Error(), {status})}};
await detail.handler({ctx: request, params: {id: '7'}, query: {}});
assert.match(request.body, /评论已关闭/);
assert.match(request.body, /href="\/says\/6" rel="prev"/);
assert.match(request.body, /href="\/says\/8" rel="next"/);
t.mock.method(SayService.prototype, 'settings', async() => ({enabled: true, commentsEnabled: false}));
get.mock.mockImplementation(async() => ({id: 7, pathname: 'example', status: 'public', allowComments: true, text: 'hello', tags: []}));
t.mock.method(SayComments.prototype, 'configuration', async() => ({options: {}, public: {}}));
Expand Down
Loading
Loading