diff --git a/packages/napcat-core/apis/index.ts b/packages/napcat-core/apis/index.ts index 8dba6ac37..b6102bfc4 100644 --- a/packages/napcat-core/apis/index.ts +++ b/packages/napcat-core/apis/index.ts @@ -10,3 +10,4 @@ export * from './file'; export * from './online'; export * from './flash'; export * from './database'; +export * from './qzone-public'; diff --git a/packages/napcat-core/apis/qzone-public.ts b/packages/napcat-core/apis/qzone-public.ts new file mode 100644 index 000000000..722789b7b --- /dev/null +++ b/packages/napcat-core/apis/qzone-public.ts @@ -0,0 +1,274 @@ +import type { InstanceContext, NapCatCore } from '@/napcat-core'; +import { randomUUID } from 'node:crypto'; +import { + buildQzonePublicRequest, + parseQzonePublicResponse, + QZONE_PUBLIC_ROUTES, + type QzonePublicContent, + type QzonePublicFeedsPage, + type QzonePublicObject, + type QzonePublicOperation, +} from '../data/qzone-public'; + +const RPC_ROOT = 'https://h5.qzone.qq.com/http2rpc/gotrpc/v1/'; +const TIMEOUT_MS = 15000; +const MAX_RESPONSE_BYTES = 8 * 1024 * 1024; +const MAX_CURSOR_COUNT = 128; +const CURSOR_TTL_MS = 10 * 60 * 1000; +const READ_OPERATIONS = new Set(['capabilities', 'feeds', 'detail', 'comments', 'replies']); + +interface CurrentUser extends QzonePublicObject { uin: string; uid: string; nick: string; } +interface PublicCursor { + account: string; + issuedAt: number; + refreshId: string; + attachInfo: string; + lastUnionId?: QzonePublicObject; +} + +function object (value: unknown): value is QzonePublicObject { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +async function withTimeout (work: () => Promise): Promise { + let timer: ReturnType | undefined; + try { + return await Promise.race([ + Promise.resolve().then(work), + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error('空间登录态读取超时')), TIMEOUT_MS); + }), + ]); + } finally { + if (timer !== undefined) clearTimeout(timer); + } +} + +/** Public recommendation uses its own feed identities, interaction routes and cursor chain. */ +export class NTQQQzonePublicApi { + private readonly cursors = new Map(); + + constructor (readonly context: InstanceContext, readonly core: NapCatCore) {} + + private currentUser (): CurrentUser { + const info = this.core.selfInfo; + if (!info || !/^[1-9]\d{0,19}$/.test(info.uin) || typeof info.uid !== 'string' || !info.uid.trim()) { + throw new Error('空友爱看需要已登录的当前账号'); + } + return { uin: info.uin, uid: info.uid, nick: info.nick ?? '' }; + } + + private assertAccount (user: CurrentUser): void { + const current = this.currentUser(); + if (current.uin !== user.uin || current.uid !== user.uid) throw new Error('QQ账号已切换,请重新获取空友动态'); + } + + private async auth (user: CurrentUser): Promise<{ cookie: string; gtk: number; }> { + this.assertAccount(user); + const [skey, pskey] = await withTimeout(() => Promise.allSettled([ + this.core.apis.UserApi.getSKey(), + this.core.apis.UserApi.getPSkey(['qzone.qq.com']), + ])); + this.assertAccount(user); + const sk = skey.status === 'fulfilled' && typeof skey.value === 'string' ? skey.value : ''; + const pk = pskey.status === 'fulfilled' ? pskey.value.domainPskeyMap.get('qzone.qq.com') ?? '' : ''; + if (!sk && !pk) throw new Error('无法取得当前账号的空间登录态'); + let hash = 5381; + const key = pk || sk; + for (let index = 0; index < key.length; index++) hash += (hash << 5) + key.charCodeAt(index); + const cookies = [`uin=o${user.uin}`, `p_uin=o${user.uin}`]; + if (sk) cookies.push(`skey=${sk}`); + if (pk) cookies.push(`p_skey=${pk}`); + return { cookie: cookies.join('; '), gtk: hash & 0x7fffffff }; + } + + private async rpc ( + operation: QzonePublicOperation, + options: Parameters[1] = {}, + user = this.currentUser() + ): Promise { + // Validate complete caller data before acquiring tickets or starting any request. + const body = buildQzonePublicRequest(operation, { ...options, selfUin: user.uin, user }); + const encoded = JSON.stringify(body); + if (Buffer.byteLength(encoded) > MAX_RESPONSE_BYTES) throw new Error('空友爱看请求超过大小限制'); + const auth = await this.auth(user); + const route = QZONE_PUBLIC_ROUTES[operation]; + const [command, serviceType] = route.oidb.split('_'); + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), TIMEOUT_MS); + let text: string; + try { + this.assertAccount(user); + const response = await fetch(`${RPC_ROOT}${route.service}/${route.method}?g_tk=${auth.gtk}`, { + method: 'POST', + redirect: 'error', + signal: controller.signal, + headers: { + Cookie: auth.cookie, + 'Content-Type': 'application/json', + Accept: 'application/json', + Origin: 'https://h5.qzone.qq.com', + Referer: 'https://h5.qzone.qq.com/pc-qzone/index.html', + 'x-web-qua': 'V1_HT5_QZ_9.9.32_001_IDC_B', + 'x-oidb': JSON.stringify({ uint32_command: command, uint32_service_type: serviceType }), + }, + body: encoded, + }); + if (!response.ok) { + await response.body?.cancel(); + throw new Error('HTTP请求失败'); + } + const reader = response.body?.getReader(); + if (!reader) throw new Error('响应为空'); + const chunks: Uint8Array[] = []; + let bytes = 0; + try { + for (;;) { + const chunk = await reader.read(); + if (chunk.done) break; + bytes += chunk.value.byteLength; + if (bytes > MAX_RESPONSE_BYTES) { + await reader.cancel(); + throw new Error('响应超过大小限制'); + } + chunks.push(chunk.value); + } + } finally { + reader.releaseLock(); + } + text = Buffer.concat(chunks, bytes).toString('utf8'); + } catch { + throw new Error(READ_OPERATIONS.has(operation) + ? '空友爱看请求失败或超时' + : '空友爱看写入结果未确认,请查询状态,勿自动重试'); + } finally { + clearTimeout(timer); + } + this.assertAccount(user); + let value: unknown; + try { + value = JSON.parse(text); + } catch { + throw new Error(READ_OPERATIONS.has(operation) + ? '空友爱看响应不是有效JSON' + : '空友爱看写入回执无效,请查询状态,勿自动重试'); + } + return parseQzonePublicResponse(value, operation); + } + + private readCursor (token: string | undefined, user: CurrentUser): PublicCursor | undefined { + if (token === undefined) return undefined; + const state = typeof token === 'string' && token.length <= 128 ? this.cursors.get(token) : undefined; + if (!state || state.account !== `${user.uin}:${user.uid}` || Date.now() - state.issuedAt > CURSOR_TTL_MS) { + throw new Error('空友爱看游标无效或已过期,请重新获取第一页'); + } + return state; + } + + private issueCursor (state: PublicCursor): string { + const now = Date.now(); + for (const [key, value] of this.cursors) { + if (now - value.issuedAt > CURSOR_TTL_MS) this.cursors.delete(key); + } + while (this.cursors.size >= MAX_CURSOR_COUNT) this.cursors.delete(this.cursors.keys().next().value!); + const token = `qzone-public:${randomUUID()}`; + this.cursors.set(token, state); + return token; + } + + getCapabilities (): Promise { + return this.rpc('capabilities'); + } + + async getFeeds (cursor?: string): Promise { + const user = this.currentUser(); + const state = this.readCursor(cursor, user); + const refreshId = state?.refreshId ?? `${user.uin}_${Date.now()}`; + const page = await this.rpc('feeds', { + refreshId, + cursor: state?.attachInfo, + lastUnionId: state?.lastUnionId, + }, user); + if (!Array.isArray(page['feeds']) || typeof page['has_more'] !== 'boolean') throw new Error('空友动态分页响应不完整'); + const feeds: QzonePublicObject[] = page['feeds'].map((entry: unknown) => { + if (!object(entry)) throw new Error('空友动态条目格式无效'); + const feed = Object.prototype.hasOwnProperty.call(entry, 'feed') ? entry['feed'] : entry; + if (!object(feed)) throw new Error('空友动态条目缺少完整内容'); + return feed; + }); + let lastUnionId = state?.lastUnionId; + for (let index = feeds.length - 1; index >= 0; index--) { + const common = feeds[index]!['cell_common']; + if (object(common) && common['feed_type'] !== 3 && object(common['union_id'])) { + lastUnionId = common['union_id']; + break; + } + } + const hasMore = page['has_more']; + let nextCursor: string | null = null; + if (hasMore) { + const attachInfo = page['attach_info']; + if (typeof attachInfo !== 'string' || !attachInfo || attachInfo.length > 65536) throw new Error('空友动态缺少有效续页信息'); + nextCursor = this.issueCursor({ + account: `${user.uin}:${user.uid}`, + issuedAt: Date.now(), + refreshId, + attachInfo, + lastUnionId: lastUnionId === undefined ? undefined : structuredClone(lastUnionId), + }); + } + return { ...page, feeds, has_more: hasMore, next_cursor: nextCursor }; + } + + getFeedDetail (feed: QzonePublicObject): Promise { + return this.rpc('detail', { feed }); + } + + getComments (feed: QzonePublicObject, cursor: string): Promise { + return this.rpc('comments', { feed, cursor }); + } + + getReplies (feed: QzonePublicObject, comment: QzonePublicObject, cursor?: string, pageSize = 20): Promise { + return this.rpc('replies', { feed, comment, cursor, pageSize }); + } + + setUpvote (feed: QzonePublicObject, enable = true): Promise { + if (typeof enable !== 'boolean') throw new Error('enable必须为布尔值'); + return this.rpc(enable ? 'upvote' : 'downvote', { feed }); + } + + setLike (feed: QzonePublicObject, enable = true): Promise { + if (typeof enable !== 'boolean') throw new Error('enable必须为布尔值'); + return this.rpc(enable ? 'like' : 'unlike', { feed }); + } + + setFollow (feed: QzonePublicObject, enable = true): Promise { + if (typeof enable !== 'boolean') throw new Error('enable必须为布尔值'); + return this.rpc(enable ? 'follow' : 'unfollow', { feed }); + } + + setCommentLike (feed: QzonePublicObject, comment: QzonePublicObject, enable = true, reply?: QzonePublicObject): Promise { + if (typeof enable !== 'boolean') throw new Error('enable必须为布尔值'); + return this.rpc(enable ? 'commentLike' : 'commentUnlike', { feed, comment, reply }); + } + + addComment (feed: QzonePublicObject, content: QzonePublicContent): Promise { + return this.rpc('addComment', { feed, content }); + } + + addReply (feed: QzonePublicObject, comment: QzonePublicObject, content: QzonePublicContent, reply?: QzonePublicObject): Promise { + return this.rpc('addReply', { feed, comment, content, reply }); + } + + deleteComment (feed: QzonePublicObject, comment: QzonePublicObject): Promise { + return this.rpc('deleteComment', { feed, comment }); + } + + deleteReply (feed: QzonePublicObject, comment: QzonePublicObject, reply: QzonePublicObject): Promise { + return this.rpc('deleteReply', { feed, comment, reply }); + } + + forwardFeed (feed: QzonePublicObject, reason = ''): Promise { + return this.rpc('forward', { feed, reason }); + } +} diff --git a/packages/napcat-core/data/qzone-public.ts b/packages/napcat-core/data/qzone-public.ts new file mode 100644 index 000000000..083eedf23 --- /dev/null +++ b/packages/napcat-core/data/qzone-public.ts @@ -0,0 +1,282 @@ +export type QzonePublicObject = Record; +export type QzonePublicContent = string | QzonePublicObject[]; +export type QzonePublicOperation = + | 'capabilities' | 'feeds' | 'detail' | 'comments' | 'replies' + | 'upvote' | 'downvote' | 'like' | 'unlike' | 'follow' | 'unfollow' + | 'commentLike' | 'commentUnlike' | 'addComment' | 'addReply' + | 'deleteComment' | 'deleteReply' | 'forward'; + +export interface QzonePublicFeedsPage extends QzonePublicObject { + feeds: QzonePublicObject[]; + has_more: boolean; + next_cursor: string | null; +} + +export interface QzonePublicRequestOptions extends QzonePublicObject { + feed?: QzonePublicObject; + comment?: QzonePublicObject; + reply?: QzonePublicObject; + content?: QzonePublicContent; + cursor?: string; + pageSize?: number; + reason?: string; + selfUin?: string; + user?: QzonePublicObject; + refreshId?: string; + lastUnionId?: QzonePublicObject; +} + +export interface QzonePublicRoute { + service: string; + method: string; + oidb: string; +} + +const READER = 'trpc.qzone.feeds_reader.FeedsReader'; +const WRITER = 'trpc.qzone.feeds_writer.FeedsWriter'; +const INTERACTION = 'trpc.qzone.interaction_writer.InteractionWriter'; +const RELATION = 'trpc.public_qzone.relation.RelationService'; +const UPVOTE = 'trpc.public_qzone.interaction.UFOComment'; +const MAX_OBJECT_BYTES = 8 * 1024 * 1024; +const MAX_RESPONSE_BYTES = 8 * 1024 * 1024; +const MAX_IDENTITY_LENGTH = 8192; + +function route (service: string, method: string, oidb: string): QzonePublicRoute { + return Object.freeze({ service, method, oidb }); +} + +export const QZONE_PUBLIC_ROUTES: Record = Object.freeze({ + capabilities: route('trpc.public_qzone.entrance_ctrl.EntranceCtrl', 'BatchEntranceWhitelist', '0x9741_0'), + feeds: route(READER, 'GetPublicRecomFeeds', '0x9a38_0'), + detail: route(READER, 'GetFeedDetail', '0x97b1_1'), + comments: route(READER, 'GetComment', '0x9bfd_1'), + replies: route(READER, 'GetReplies', '0x9bfe_1'), + upvote: route(UPVOTE, 'Upvote', '0x9d18_1'), + downvote: route(UPVOTE, 'Downvote', '0x9d19_1'), + like: route(INTERACTION, 'DoLike', '0x9699_1'), + unlike: route(INTERACTION, 'UnLike', '0x969c_1'), + follow: route(RELATION, 'Follow', '0x9d1a_1'), + unfollow: route(RELATION, 'Unfollow', '0x9d1b_1'), + commentLike: route(INTERACTION, 'DoLike', '0x9699_1'), + commentUnlike: route(INTERACTION, 'UnLike', '0x969c_1'), + addComment: route(INTERACTION, 'AddComment', '0x9676_1'), + addReply: route(INTERACTION, 'AddReply', '0x9677_1'), + deleteComment: route(INTERACTION, 'DeleteComment', '0x9989_0'), + deleteReply: route(INTERACTION, 'DeleteReply', '0x998a_0'), + forward: route(WRITER, 'ForwardFeed', '0x969a_1'), +}); + +function object (value: unknown): value is QzonePublicObject { + if (!value || typeof value !== 'object' || Array.isArray(value)) return false; + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +function assertOperation (operation: QzonePublicOperation): void { + if (!Object.prototype.hasOwnProperty.call(QZONE_PUBLIC_ROUTES, operation)) throw new Error('QQ空间公开接口操作无效'); +} + +/** Clone JSON without calling toJSON or assigning prototype setters. */ +function snapshot (value: T, name: string, maxBytes = MAX_OBJECT_BYTES): T { + const seen = new Set(); + let nodes = 0; + const maxNodes = 200000; + const maxDepth = 64; + function copy (input: unknown, depth: number): unknown { + if (++nodes > maxNodes || depth > maxDepth) throw new Error(`${name}结构超出限制`); + if (input === null || typeof input === 'boolean') return input; + if (typeof input === 'string') { + if (Buffer.byteLength(input, 'utf8') > maxBytes) throw new Error(`${name}超过大小限制`); + return input; + } + if (typeof input === 'number' && Number.isFinite(input)) return input; + if (!Array.isArray(input) && !object(input)) throw new Error(`${name}必须为JSON数据`); + if (seen.has(input)) throw new Error(`${name}不能包含循环引用`); + seen.add(input); + let output: unknown; + if (Array.isArray(input)) { + const items: unknown[] = []; + for (let index = 0; index < input.length; index++) items.push(copy(input[index], depth + 1)); + output = items; + } else { + const result: QzonePublicObject = {}; + for (const key of Object.keys(input)) { + const item = input[key]; + if (item === undefined) continue; + Object.defineProperty(result, key, { value: copy(item, depth + 1), enumerable: true, configurable: true, writable: true }); + } + output = result; + } + seen.delete(input); + return output; + } + const result = copy(value, 0) as T; + if (Buffer.byteLength(JSON.stringify(result), 'utf8') > maxBytes) throw new Error(`${name}超过大小限制`); + return result; +} + +function jsonObject (value: unknown, name: string): QzonePublicObject { + if (!object(value)) throw new Error(`${name}必须为JSON对象`); + return snapshot(value, name); +} + +function identity (value: unknown, name: string, allowEmpty = false): string { + if (typeof value !== 'string' || value.length > MAX_IDENTITY_LENGTH || (!allowEmpty && !value.trim())) { + throw new Error(`${name}无效`); + } + for (const character of value) { + const code = character.charCodeAt(0); + if (code < 32 || code === 127) throw new Error(`${name}无效`); + } + return value; +} + +function uin (value: unknown, name: string): string { + if (typeof value !== 'string' || !/^[1-9]\d{0,19}$/.test(value)) throw new Error(`${name}无效`); + return value; +} + +function pageToken (value: unknown, name: string, allowEmpty = false, maxLength = MAX_OBJECT_BYTES): string { + if (typeof value !== 'string' || value.length > maxLength || (!allowEmpty && value.length === 0)) throw new Error(`${name}无效`); + return value; +} + +function unionId (value: unknown): QzonePublicObject { + const union = jsonObject(value, 'QQ空间完整动态标识'); + let identified = false; + for (const key of ['uf_key', 'ugc_id', 'feed_id', 'serialized_data']) { + if (union[key] === undefined || union[key] === null) continue; + const field = identity(union[key], 'QQ空间动态身份字段', true); + if (field.trim()) identified = true; + } + if (!identified) throw new Error('QQ空间动态缺少完整有效身份'); + if (union['ext_ids'] !== undefined && union['ext_ids'] !== null && (!Array.isArray(union['ext_ids']) || union['ext_ids'].some(item => !object(item)))) { + throw new Error('QQ空间动态扩展身份无效'); + } + return union; +} + +function readComment (value: unknown, name: string): QzonePublicObject { + const comment = jsonObject(value, name); + const id = comment['id']; + if (typeof id === 'string') identity(id, `${name}标识`); + else if (typeof id !== 'number' || !Number.isSafeInteger(id) || id < 0) throw new Error(`${name}标识无效`); + if (comment['user'] !== undefined && !object(comment['user'])) throw new Error(`${name}用户必须为JSON对象`); + return comment; +} + +function user (value: unknown, name: string): QzonePublicObject { + const result = jsonObject(value, name); + const userUin = result['uin']; + const userUid = result['uid']; + const absentUin = userUin === undefined || userUin === null || userUin === '' || userUin === '0' || userUin === 0; + if (!absentUin) uin(userUin, `${name}QQ号`); + if (userUid !== undefined && userUid !== null && userUid !== '') identity(userUid, `${name}UID`); + if (absentUin && !userUid) throw new Error(`${name}缺少QQ号或UID`); + return result; +} + +function content (value: unknown): QzonePublicObject[] { + if (typeof value === 'string') { + if (!value.length) throw new Error('QQ空间评论正文不能为空'); + return snapshot([{ type: 0, content: value }], 'QQ空间评论正文'); + } + if (!Array.isArray(value) || !value.length) throw new Error('QQ空间评论正文必须为非空文本或RichMsg数组'); + const items = snapshot(value, 'QQ空间评论正文'); + for (const item of items) { + if (!object(item)) throw new Error('QQ空间RichMsg条目必须为JSON对象'); + } + return items as QzonePublicObject[]; +} + +export function buildQzonePublicRequest (operation: QzonePublicOperation, options: QzonePublicRequestOptions): QzonePublicObject { + assertOperation(operation); + if (!object(options)) throw new Error('QQ空间公开接口参数必须为对象'); + if (operation === 'capabilities') return { uins: [uin(options.selfUin, '当前QQ号')], entrance_types: [1, 15] }; + if (operation === 'feeds') { + const body: QzonePublicObject = { refresh_id: identity(options.refreshId, 'QQ空间刷新标识') }; + if (options.cursor !== undefined) body['attach_info'] = pageToken(options.cursor, 'QQ空间分页标识', true, 65536); + if (options.lastUnionId !== undefined) body['last_client_feed_union_id'] = unionId(options.lastUnionId); + return body; + } + + const feed = jsonObject(options.feed, 'QQ空间原始Feed'); + const common = feed['cell_common']; + if (!object(common)) throw new Error('QQ空间原始Feed缺少cell_common'); + const union = unionId(common['union_id']); + const body: QzonePublicObject = { union_id: union }; + if (feed['cell_feed_transfer'] !== undefined) body['cell_feed_transfer'] = snapshot(feed['cell_feed_transfer'], 'QQ空间动态上下文'); + + if (operation === 'detail') return { ...body, feed_action_domain_type: 3, from_page: 1 }; + if (operation === 'comments') return { ...body, attach_info: pageToken(options.cursor, 'QQ空间评论分页标识') }; + if (operation === 'replies') { + const parent = readComment(options.comment, 'QQ空间父评论'); + const size = options.pageSize === undefined ? 20 : options.pageSize; + if (typeof size !== 'number' || !Number.isFinite(size) || size < 1) throw new Error('QQ空间回复page_size必须为不小于1的有限数值'); + const pointer = options.cursor || parent['reply_attach_info'] || ''; + return { ...body, cur_comment: parent, comment_attach_info: '', reply_attach_info: pageToken(pointer, 'QQ空间回复分页标识', true), page_size: Math.trunc(size) }; + } + if (operation === 'upvote' || operation === 'downvote') return body; + if (operation === 'like' || operation === 'unlike') { + return { ...body, like_key: identity(common['cur_like_key'], 'QQ空间动态点赞标识'), like_type: 1 }; + } + if (operation === 'follow' || operation === 'unfollow') { + const userInfo = feed['cell_user_info']; + const author = user(object(userInfo) ? userInfo['user'] : undefined, 'QQ空间动态作者'); + const authorUin = typeof author['uin'] === 'string' && /^[1-9]\d{0,19}$/.test(author['uin']) ? author['uin'] : ''; + const authorUid = typeof author['uid'] === 'string' ? author['uid'].trim() : ''; + const useUid = (common['domain_type'] === 3 && !!authorUid) || !authorUin; + const request: QzonePublicObject = { follow_from_type: 1, ...(useUid ? { target_uid: authorUid } : { target_uin: authorUin }) }; + if ((useUid && !authorUid) || (!useUid && !authorUin)) throw new Error('QQ空间动态缺少可蹲的作者身份'); + if (typeof union['uf_key'] === 'string' && union['uf_key']) request['follow_feed_id'] = union['uf_key']; + if (feed['cell_feed_transfer']) request['cell_feed_transfer'] = body['cell_feed_transfer']; + return request; + } + if (operation === 'commentLike' || operation === 'commentUnlike') { + const parent = readComment(options.comment, 'QQ空间父评论'); + const target = options.reply === undefined ? parent : readComment(options.reply, 'QQ空间回复'); + const like = target['like']; + return { ...body, like_key: identity(object(like) ? like['id'] : undefined, 'QQ空间评论点赞标识'), like_type: options.reply === undefined ? 2 : 3 }; + } + if (operation === 'addComment') return { ...body, comment: { user: user(options.user, '当前用户'), content: content(options.content) } }; + if (operation === 'addReply') { + const parent = readComment(options.comment, 'QQ空间父评论'); + const target = options.reply === undefined ? parent : readComment(options.reply, 'QQ空间回复'); + return { ...body, comment: parent, reply: { content: content(options.content), target_user: user(target['user'], 'QQ空间回复目标'), user: user(options.user, '当前用户') } }; + } + if (operation === 'deleteComment') return { ...body, comment: readComment(options.comment, 'QQ空间父评论') }; + if (operation === 'deleteReply') return { ...body, comment: readComment(options.comment, 'QQ空间父评论'), reply: readComment(options.reply, 'QQ空间回复') }; + if (operation === 'forward') { + const reason = options.reason ?? ''; + if (typeof reason !== 'string') throw new Error('QQ空间转发理由必须为文本'); + return { ...body, reason: snapshot(reason, 'QQ空间转发理由') }; + } + throw new Error('QQ空间公开接口操作无效'); +} + +/** Return the business data, preserving unknown fields while checking the observed acknowledgements. */ +export function parseQzonePublicResponse (value: unknown, operation: QzonePublicOperation): QzonePublicObject { + assertOperation(operation); + if (object(value) && typeof value['retcode'] === 'number' && Number.isSafeInteger(value['retcode']) && value['retcode'] !== 0) { + throw new Error(`QQ空间公开接口拒绝请求 (retcode=${value['retcode']})`); + } + if (!object(value) || value['retcode'] !== 0 || !object(value['data'])) throw new Error('QQ空间公开接口未返回明确成功响应'); + const data = snapshot(value['data'], 'QQ空间公开接口响应', MAX_RESPONSE_BYTES); + if (operation === 'follow' || operation === 'unfollow') { + const code = data['ret_code']; + if (code !== undefined && code !== null && code !== 0 && code !== '0') throw new Error('QQ空间蹲操作未确认成功'); + } + const resultFields: Partial> = { + upvote: 'upvote', + downvote: 'upvote', + like: 'like', + unlike: 'like', + commentLike: 'like', + commentUnlike: 'like', + addComment: 'comment', + addReply: 'reply', + }; + const field = resultFields[operation]; + if (field && !data[field]) throw new Error('QQ空间公开互动未返回业务成功结果'); + return data; +} diff --git a/packages/napcat-core/index.ts b/packages/napcat-core/index.ts index d5fd604e2..67de48dc4 100644 --- a/packages/napcat-core/index.ts +++ b/packages/napcat-core/index.ts @@ -9,6 +9,7 @@ import { NTQQFlashApi, NTQQOnlineApi, NTQQDatabaseApi, + NTQQQzonePublicApi, } from '@/napcat-core/apis'; import { NTQQCollectionApi } from '@/napcat-core/apis/collection'; import { @@ -171,6 +172,7 @@ export class NapCatCore { FlashApi: new NTQQFlashApi(this.context, this), OnlineApi: new NTQQOnlineApi(this.context, this), DatabaseApi: new NTQQDatabaseApi(this.context, this), + QzonePublicApi: new NTQQQzonePublicApi(this.context, this), }; container.bind(NapCatCore).toConstantValue(this); container.bind(TypedEventEmitter).toConstantValue(this.event); @@ -382,4 +384,5 @@ export interface StableNTApiWrapper { FlashApi: NTQQFlashApi, OnlineApi: NTQQOnlineApi, DatabaseApi: NTQQDatabaseApi, + QzonePublicApi: NTQQQzonePublicApi, } diff --git a/packages/napcat-onebot/action/extends/qzone-public/CommentQzonePublicFeed.ts b/packages/napcat-onebot/action/extends/qzone-public/CommentQzonePublicFeed.ts new file mode 100644 index 000000000..d46d5bbb3 --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/CommentQzonePublicFeed.ts @@ -0,0 +1,18 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { QzonePublicAction, QzonePublicContentSchema, QzonePublicFeedExample, QzonePublicFeedSchema } from './common'; + +const PayloadSchema = Type.Object({ feed: QzonePublicFeedSchema, content: QzonePublicContentSchema }); +type PayloadType = Static; + +export class CommentQzonePublicFeed extends QzonePublicAction { + override actionName = ActionName.CommentQzonePublicFeed; + override actionSummary = '评论空友爱看动态'; + override actionDescription = '对完整 feed 发表评论;content 接受非空文本或富文本对象数组,富文本字段原样保留'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample, content: '很有意思' }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.addComment(payload.feed, payload.content); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/DeleteQzonePublicComment.ts b/packages/napcat-onebot/action/extends/qzone-public/DeleteQzonePublicComment.ts new file mode 100644 index 000000000..b4830be8c --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/DeleteQzonePublicComment.ts @@ -0,0 +1,18 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { QzonePublicAction, QzonePublicCommentExample, QzonePublicCommentSchema, QzonePublicFeedExample, QzonePublicFeedSchema } from './common'; + +const PayloadSchema = Type.Object({ feed: QzonePublicFeedSchema, comment: QzonePublicCommentSchema }); +type PayloadType = Static; + +export class DeleteQzonePublicComment extends QzonePublicAction { + override actionName = ActionName.DeleteQzonePublicComment; + override actionSummary = '删除空友爱看评论'; + override actionDescription = '传入完整 feed 及 comment 删除评论,操作权限由上游校验'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample, comment: QzonePublicCommentExample }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.deleteComment(payload.feed, payload.comment); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/DeleteQzonePublicReply.ts b/packages/napcat-onebot/action/extends/qzone-public/DeleteQzonePublicReply.ts new file mode 100644 index 000000000..5efbc0227 --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/DeleteQzonePublicReply.ts @@ -0,0 +1,26 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { + QzonePublicAction, + QzonePublicCommentExample, + QzonePublicCommentSchema, + QzonePublicFeedExample, + QzonePublicFeedSchema, + QzonePublicReplyExample, + QzonePublicReplySchema, +} from './common'; + +const PayloadSchema = Type.Object({ feed: QzonePublicFeedSchema, comment: QzonePublicCommentSchema, reply: QzonePublicReplySchema }); +type PayloadType = Static; + +export class DeleteQzonePublicReply extends QzonePublicAction { + override actionName = ActionName.DeleteQzonePublicReply; + override actionSummary = '删除空友爱看回复'; + override actionDescription = '传入完整 feed、父 comment 和目标 reply 删除回复,操作权限由上游校验'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample, comment: QzonePublicCommentExample, reply: QzonePublicReplyExample }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.deleteReply(payload.feed, payload.comment, payload.reply); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/ForwardQzonePublicFeed.ts b/packages/napcat-onebot/action/extends/qzone-public/ForwardQzonePublicFeed.ts new file mode 100644 index 000000000..66313133b --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/ForwardQzonePublicFeed.ts @@ -0,0 +1,21 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { QzonePublicAction, QzonePublicFeedExample, QzonePublicFeedSchema } from './common'; + +const PayloadSchema = Type.Object({ + feed: QzonePublicFeedSchema, + reason: Type.Optional(Type.String({ default: '', description: '转发附言,默认空字符串;数字或布尔值会转为文本' })), +}); +type PayloadType = Static; + +export class ForwardQzonePublicFeed extends QzonePublicAction { + override actionName = ActionName.ForwardQzonePublicFeed; + override actionSummary = '转发空友爱看动态'; + override actionDescription = '将完整 feed 转发到自己的空间,可通过 reason 添加转发附言'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample, reason: '分享一条动态' }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.forwardFeed(payload.feed, payload.reason ?? ''); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicCapabilities.ts b/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicCapabilities.ts new file mode 100644 index 000000000..af622f024 --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicCapabilities.ts @@ -0,0 +1,18 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { QzonePublicAction } from './common'; + +const PayloadSchema = Type.Object({}); +type PayloadType = Static; + +export class GetQzonePublicCapabilities extends QzonePublicAction { + override actionName = ActionName.GetQzonePublicCapabilities; + override actionSummary = '获取空友爱看接口能力'; + override actionDescription = '获取当前 QQ 版本和账号可用的空友爱看接口能力,不会执行写操作'; + override payloadSchema = PayloadSchema; + override payloadExample = {}; + + async _handle () { + return this.core.apis.QzonePublicApi.getCapabilities(); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicComments.ts b/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicComments.ts new file mode 100644 index 000000000..e5ecbed4e --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicComments.ts @@ -0,0 +1,21 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { QzonePublicAction, QzonePublicFeedExample, QzonePublicFeedSchema } from './common'; + +const PayloadSchema = Type.Object({ + feed: QzonePublicFeedSchema, + cursor: Type.String({ minLength: 1, description: '动态详情或上一评论页返回的非空 attach_info;数字或布尔值会转为文本' }), +}); +type PayloadType = Static; + +export class GetQzonePublicComments extends QzonePublicAction { + override actionName = ActionName.GetQzonePublicComments; + override actionSummary = '获取空友爱看评论'; + override actionDescription = '读取动态的后续评论;cursor 为必填非空字符串,使用动态详情或上一评论页的 attach_info,原始评论对象应完整保留'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample, cursor: 'detail-attach-info' }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.getComments(payload.feed, payload.cursor); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicFeedDetail.ts b/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicFeedDetail.ts new file mode 100644 index 000000000..776b0c0cd --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicFeedDetail.ts @@ -0,0 +1,18 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { QzonePublicAction, QzonePublicFeedExample, QzonePublicFeedSchema } from './common'; + +const PayloadSchema = Type.Object({ feed: QzonePublicFeedSchema }); +type PayloadType = Static; + +export class GetQzonePublicFeedDetail extends QzonePublicAction { + override actionName = ActionName.GetQzonePublicFeedDetail; + override actionSummary = '获取空友爱看动态详情'; + override actionDescription = '传入列表中的完整 feed 对象获取详情;继续读取评论时,将详情返回的 attach_info 作为 cursor'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.getFeedDetail(payload.feed); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicFeeds.ts b/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicFeeds.ts new file mode 100644 index 000000000..cbfe89d50 --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicFeeds.ts @@ -0,0 +1,29 @@ +import { Static, Type } from '@sinclair/typebox'; +import type { QzonePublicFeedsPage } from '@/napcat-core/data/qzone-public'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { QzonePublicAction, QzonePublicFeedExample, QzonePublicObjectSchema } from './common'; + +const PayloadSchema = Type.Object({ + cursor: Type.Optional(Type.String({ minLength: 1, maxLength: 65536, description: '上一页返回的非空 next_cursor,首次请求可省略;数字或布尔值会转为文本' })), +}); +type PayloadType = Static; + +const ReturnSchema = Type.Object({ + feeds: Type.Array(QzonePublicObjectSchema, { description: '完整动态对象,可直接传给详情和互动接口' }), + has_more: Type.Boolean({ description: '是否还有下一页' }), + next_cursor: Type.Union([Type.String(), Type.Null()], { description: '下一页游标,没有下一页时为 null' }), +}, { additionalProperties: true, description: '动态列表分页结果,保留上游返回的额外字段' }); + +export class GetQzonePublicFeeds extends QzonePublicAction { + override actionName = ActionName.GetQzonePublicFeeds; + override actionSummary = '获取空友爱看动态'; + override actionDescription = '获取空友爱看动态列表;后续操作应直接传入 feeds 中的完整对象,翻页使用 next_cursor'; + override payloadSchema = PayloadSchema; + override returnSchema = ReturnSchema; + override payloadExample = {}; + override returnExample = { feeds: [QzonePublicFeedExample], has_more: false, next_cursor: null }; + + async _handle (payload: PayloadType): Promise { + return this.core.apis.QzonePublicApi.getFeeds(payload.cursor); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicReplies.ts b/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicReplies.ts new file mode 100644 index 000000000..9e0d0651e --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/GetQzonePublicReplies.ts @@ -0,0 +1,32 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { + parseQzonePublicPageSize, + QzonePublicAction, + QzonePublicCommentExample, + QzonePublicCommentSchema, + QzonePublicFeedExample, + QzonePublicFeedSchema, +} from './common'; + +const PayloadSchema = Type.Object({ + feed: QzonePublicFeedSchema, + comment: QzonePublicCommentSchema, + cursor: Type.Optional(Type.String({ default: '', description: '回复分页游标,默认为空字符串;空字符串时使用 comment.reply_attach_info;数字或布尔值会转为文本' })), + page_size: Type.Optional(Type.Union([ + Type.Number({ minimum: 1 }), Type.String(), + ], { default: 20, description: '每页回复数量,默认 20;有限数字或非空数值字符串,向零截断后应大于等于 1' })), +}); +type PayloadType = Static; + +export class GetQzonePublicReplies extends QzonePublicAction { + override actionName = ActionName.GetQzonePublicReplies; + override actionSummary = '获取空友爱看评论回复'; + override actionDescription = '传入完整动态及父评论读取回复分页;省略 cursor 时使用父评论中的 reply_attach_info'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample, comment: QzonePublicCommentExample, page_size: 20 }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.getReplies(payload.feed, payload.comment, payload.cursor ?? '', parseQzonePublicPageSize(payload.page_size)); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/ReplyQzonePublicFeed.ts b/packages/napcat-onebot/action/extends/qzone-public/ReplyQzonePublicFeed.ts new file mode 100644 index 000000000..491186aee --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/ReplyQzonePublicFeed.ts @@ -0,0 +1,31 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { + QzonePublicAction, + QzonePublicCommentExample, + QzonePublicCommentSchema, + QzonePublicContentSchema, + QzonePublicFeedExample, + QzonePublicFeedSchema, + QzonePublicReplySchema, +} from './common'; + +const PayloadSchema = Type.Object({ + feed: QzonePublicFeedSchema, + comment: QzonePublicCommentSchema, + content: QzonePublicContentSchema, + reply: Type.Optional(QzonePublicReplySchema), +}); +type PayloadType = Static; + +export class ReplyQzonePublicFeed extends QzonePublicAction { + override actionName = ActionName.ReplyQzonePublicFeed; + override actionSummary = '回复空友爱看评论'; + override actionDescription = '传入完整 feed、父 comment 及非空 content 发表回复;需要回复已有回复时一并传入完整 reply'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample, comment: QzonePublicCommentExample, content: '谢谢分享' }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.addReply(payload.feed, payload.comment, payload.content, payload.reply); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicCommentLike.ts b/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicCommentLike.ts new file mode 100644 index 000000000..78d8679a0 --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicCommentLike.ts @@ -0,0 +1,32 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { + parseQzonePublicEnable, + QzonePublicAction, + QzonePublicCommentExample, + QzonePublicCommentSchema, + QzonePublicEnableSchema, + QzonePublicFeedExample, + QzonePublicFeedSchema, + QzonePublicReplySchema, +} from './common'; + +const PayloadSchema = Type.Object({ + feed: QzonePublicFeedSchema, + comment: QzonePublicCommentSchema, + reply: Type.Optional(QzonePublicReplySchema), + enable: QzonePublicEnableSchema, +}); +type PayloadType = Static; + +export class SetQzonePublicCommentLike extends QzonePublicAction { + override actionName = ActionName.SetQzonePublicCommentLike; + override actionSummary = '设置空友爱看评论或回复赞'; + override actionDescription = '对完整 comment 点赞或取消点赞;传入完整 reply 时操作该回复,保留 comment/reply 的 like.id 等字段'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample, comment: QzonePublicCommentExample, enable: true }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.setCommentLike(payload.feed, payload.comment, parseQzonePublicEnable(payload.enable), payload.reply); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicFollow.ts b/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicFollow.ts new file mode 100644 index 000000000..9311afb9f --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicFollow.ts @@ -0,0 +1,18 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { parseQzonePublicEnable, QzonePublicAction, QzonePublicEnableSchema, QzonePublicFeedExample, QzonePublicFeedSchema } from './common'; + +const PayloadSchema = Type.Object({ feed: QzonePublicFeedSchema, enable: QzonePublicEnableSchema }); +type PayloadType = Static; + +export class SetQzonePublicFollow extends QzonePublicAction { + override actionName = ActionName.SetQzonePublicFollow; + override actionSummary = '蹲或取消蹲空友爱看作者'; + override actionDescription = '根据完整 feed 蹲或取消蹲动态作者;enable 默认 true,返回上游操作结果'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample, enable: true }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.setFollow(payload.feed, parseQzonePublicEnable(payload.enable)); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicLike.ts b/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicLike.ts new file mode 100644 index 000000000..75b026150 --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicLike.ts @@ -0,0 +1,18 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { parseQzonePublicEnable, QzonePublicAction, QzonePublicEnableSchema, QzonePublicFeedExample, QzonePublicFeedSchema } from './common'; + +const PayloadSchema = Type.Object({ feed: QzonePublicFeedSchema, enable: QzonePublicEnableSchema }); +type PayloadType = Static; + +export class SetQzonePublicLike extends QzonePublicAction { + override actionName = ActionName.SetQzonePublicLike; + override actionSummary = '设置空友爱看普通赞'; + override actionDescription = '对完整 feed 设置或取消普通点赞(like);enable 默认 true,此操作与推分别处理'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample, enable: true }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.setLike(payload.feed, parseQzonePublicEnable(payload.enable)); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicUpvote.ts b/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicUpvote.ts new file mode 100644 index 000000000..824d45b0a --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/SetQzonePublicUpvote.ts @@ -0,0 +1,18 @@ +import { Static, Type } from '@sinclair/typebox'; +import { ActionName } from '@/napcat-onebot/action/router'; +import { parseQzonePublicEnable, QzonePublicAction, QzonePublicEnableSchema, QzonePublicFeedExample, QzonePublicFeedSchema } from './common'; + +const PayloadSchema = Type.Object({ feed: QzonePublicFeedSchema, enable: QzonePublicEnableSchema }); +type PayloadType = Static; + +export class SetQzonePublicUpvote extends QzonePublicAction { + override actionName = ActionName.SetQzonePublicUpvote; + override actionSummary = '推或取消推空友爱看动态'; + override actionDescription = '对完整 feed 设置推或取消推(upvote);enable 默认 true,此操作与普通点赞分别处理'; + override payloadSchema = PayloadSchema; + override payloadExample = { feed: QzonePublicFeedExample, enable: true }; + + async _handle (payload: PayloadType) { + return this.core.apis.QzonePublicApi.setUpvote(payload.feed, parseQzonePublicEnable(payload.enable)); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/common.ts b/packages/napcat-onebot/action/extends/qzone-public/common.ts new file mode 100644 index 000000000..d4b8f26fe --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/common.ts @@ -0,0 +1,125 @@ +import { Type } from '@sinclair/typebox'; +import { OneBotAction } from '@/napcat-onebot/action/OneBotAction'; +import type { BaseCheckResult } from '@/napcat-onebot/action/router'; +import type { QzonePublicObject } from '@/napcat-core/data/qzone-public'; + +export const QzonePublicObjectSchema = Type.Object({}, { additionalProperties: Type.Unknown() }); +export const QzonePublicFeedSchema = Type.Object({}, { + additionalProperties: Type.Unknown(), + description: 'get_qzone_public_feeds 返回的完整 feed 对象,请保留全部字段', +}); +export const QzonePublicCommentSchema = Type.Object({}, { + additionalProperties: Type.Unknown(), + description: '详情或评论列表返回的完整 comment 对象,请保留 like.id 等全部字段', +}); +export const QzonePublicReplySchema = Type.Object({}, { + additionalProperties: Type.Unknown(), + description: '回复列表返回的完整 reply 对象,请保留全部字段', +}); +export const QzonePublicResultSchema = Type.Object({}, { + additionalProperties: Type.Unknown(), + description: '上游返回的原始 JSON 对象,字段随内容类型和服务端版本变化', +}); +export const QzonePublicEnableSchema = Type.Optional(Type.Union([ + Type.Boolean(), Type.Number(), Type.String(), +], { default: true, description: '是否启用,默认 true;数字非 0 为 true,文本支持 true/false、1/0、yes/no、on/off' })); +export const QzonePublicContentSchema = Type.Union([ + Type.String({ minLength: 1 }), + Type.Array(QzonePublicObjectSchema, { minItems: 1 }), +], { description: '非空文本或非空富文本对象数组,保留每个对象的全部字段' }); + +// 示例仅说明对象传递方式;实际调用应直接使用上游返回的完整对象。 +export const QzonePublicFeedExample = { + cell_common: { + union_id: { uf_key: 'example-uf-key', ugc_id: 'example-ugc-id', feed_id: 'example-feed-id', ext_ids: [] }, + cur_like_key: 'example-like-key', + domain_type: 3, + }, + cell_user_info: { user: { uin: '10001' } }, + cell_feed_transfer: {}, +}; +export const QzonePublicCommentExample = { id: 'example-comment', like: { id: 'example-comment-like' }, reply_attach_info: '' }; +export const QzonePublicReplyExample = { id: 'example-reply', like: { id: 'example-reply-like' } }; + +export function parseQzonePublicEnable (value: boolean | number | string | undefined): boolean { + if (value === undefined) return true; + if (typeof value === 'boolean') return value; + if (typeof value === 'number') return value !== 0; + if (typeof value === 'string') { + const text = value.trim().toLowerCase(); + if (['true', '1', 'yes', 'on'].includes(text)) return true; + if (['false', '0', 'no', 'off'].includes(text)) return false; + } + throw new Error('enable 必须为布尔值、数字或 true/false、1/0、yes/no、on/off 文本'); +} + +export function parseQzonePublicPageSize (value: number | string | undefined): number { + if (value === undefined) return 20; + if (typeof value !== 'number' && typeof value !== 'string') { + throw new Error('page_size 必须为数字或数值字符串,截断后应大于等于 1'); + } + if (typeof value === 'string' && !value.trim()) { + throw new Error('page_size 必须为数字或数值字符串,截断后应大于等于 1'); + } + const numericValue = Number(value); + const pageSize = Math.trunc(numericValue); + if (!Number.isFinite(numericValue) || pageSize < 1) { + throw new Error('page_size 必须为数字或数值字符串,截断后应大于等于 1'); + } + return pageSize; +} + +function isObject (value: unknown): value is QzonePublicObject { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +export abstract class QzonePublicAction extends OneBotAction { + override actionTags = ['QQ空间扩展']; + override returnSchema = QzonePublicResultSchema; + override returnExample = {}; + + protected override async check (payload: PayloadType): Promise { + // OneBot 的通用解析会转换原始类型。先校验这些透传参数,避免数字被当作文本或对象。 + if (!isObject(payload)) return { valid: false, message: '请求参数必须为 JSON 对象' }; + const parameters: QzonePublicObject = payload; + for (const key of ['feed', 'comment', 'reply']) { + if (parameters[key] !== undefined && !isObject(parameters[key])) { + return { valid: false, message: `${key} 必须为上游返回的完整 JSON 对象` }; + } + } + for (const key of ['cursor', 'reason']) { + const value = parameters[key]; + if (value !== undefined) { + if (!['string', 'number', 'boolean'].includes(typeof value)) { + return { valid: false, message: `${key} 必须为字符串、数字或布尔值` }; + } + parameters[key] = String(value); + } + } + if ('content' in parameters) { + let content = parameters['content']; + if (typeof content === 'string') { + const text = content.trim(); + if (text.startsWith('[') && text.endsWith(']')) { + try { + const decoded: unknown = JSON.parse(text); + if (Array.isArray(decoded)) content = decoded; + } catch { + // 无效 JSON 仍按原始文本处理。 + } + } + } + if (typeof content === 'string' ? content.length === 0 : !Array.isArray(content) || content.length === 0 || !content.every(isObject)) { + return { valid: false, message: 'content 必须为非空文本或非空富文本对象数组' }; + } + parameters['content'] = content; + } + try { + if ('enable' in parameters) parameters['enable'] = parseQzonePublicEnable(parameters['enable'] as boolean | number | string | undefined); + if ('page_size' in parameters) parameters['page_size'] = parseQzonePublicPageSize(parameters['page_size'] as number | string | undefined); + } catch (error) { + return { valid: false, message: (error as Error).message }; + } + return super.check(payload as PayloadType); + } +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/http-params.ts b/packages/napcat-onebot/action/extends/qzone-public/http-params.ts new file mode 100644 index 000000000..eda934e7a --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/http-params.ts @@ -0,0 +1,12 @@ +/** Decode individual GET / form values before applying the public Qzone action contract. */ +export function decodeQzonePublicHttpParameters (parameters: unknown): Record { + if (parameters === null || typeof parameters !== 'object' || Array.isArray(parameters)) return {}; + return Object.fromEntries(Object.entries(parameters).map(([key, value]) => { + if (typeof value !== 'string') return [key, value]; + try { + return [key, JSON.parse(value) as unknown]; + } catch { + return [key, value]; + } + })); +} diff --git a/packages/napcat-onebot/action/extends/qzone-public/index.ts b/packages/napcat-onebot/action/extends/qzone-public/index.ts new file mode 100644 index 000000000..2a27be09a --- /dev/null +++ b/packages/napcat-onebot/action/extends/qzone-public/index.ts @@ -0,0 +1,14 @@ +export { GetQzonePublicCapabilities } from './GetQzonePublicCapabilities'; +export { GetQzonePublicFeeds } from './GetQzonePublicFeeds'; +export { GetQzonePublicFeedDetail } from './GetQzonePublicFeedDetail'; +export { GetQzonePublicComments } from './GetQzonePublicComments'; +export { GetQzonePublicReplies } from './GetQzonePublicReplies'; +export { SetQzonePublicUpvote } from './SetQzonePublicUpvote'; +export { SetQzonePublicLike } from './SetQzonePublicLike'; +export { SetQzonePublicFollow } from './SetQzonePublicFollow'; +export { SetQzonePublicCommentLike } from './SetQzonePublicCommentLike'; +export { CommentQzonePublicFeed } from './CommentQzonePublicFeed'; +export { ReplyQzonePublicFeed } from './ReplyQzonePublicFeed'; +export { DeleteQzonePublicComment } from './DeleteQzonePublicComment'; +export { DeleteQzonePublicReply } from './DeleteQzonePublicReply'; +export { ForwardQzonePublicFeed } from './ForwardQzonePublicFeed'; diff --git a/packages/napcat-onebot/action/index.ts b/packages/napcat-onebot/action/index.ts index b515402d5..fad49fb86 100644 --- a/packages/napcat-onebot/action/index.ts +++ b/packages/napcat-onebot/action/index.ts @@ -165,6 +165,22 @@ import { FetchPttText } from '@/napcat-onebot/action/msg/FetchPttText'; import { GetGroupSignedList } from './extends/GetGroupSignedList'; import { SendQzoneMsg } from './extends/SendQzoneMsg'; import { DeleteQzoneMsg } from './extends/DeleteQzoneMsg'; +import { + GetQzonePublicCapabilities, + GetQzonePublicFeeds, + GetQzonePublicFeedDetail, + GetQzonePublicComments, + GetQzonePublicReplies, + SetQzonePublicUpvote, + SetQzonePublicLike, + SetQzonePublicFollow, + SetQzonePublicCommentLike, + CommentQzonePublicFeed, + ReplyQzonePublicFeed, + DeleteQzonePublicComment, + DeleteQzonePublicReply, + ForwardQzonePublicFeed, +} from './extends/qzone-public'; import SetGroupMemberInvitePolicy from './group/SetGroupMemberInvitePolicy'; import SetGroupMemberPermissions from './group/SetGroupMemberPermissions'; import SetGroupNewMemberHistoryVisibility from './group/SetGroupNewMemberHistoryVisibility'; @@ -229,6 +245,20 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo new GetGroupSignedList(obContext, core), new SendQzoneMsg(obContext, core), new DeleteQzoneMsg(obContext, core), + new GetQzonePublicCapabilities(obContext, core), + new GetQzonePublicFeeds(obContext, core), + new GetQzonePublicFeedDetail(obContext, core), + new GetQzonePublicComments(obContext, core), + new GetQzonePublicReplies(obContext, core), + new SetQzonePublicUpvote(obContext, core), + new SetQzonePublicLike(obContext, core), + new SetQzonePublicFollow(obContext, core), + new SetQzonePublicCommentLike(obContext, core), + new CommentQzonePublicFeed(obContext, core), + new ReplyQzonePublicFeed(obContext, core), + new DeleteQzonePublicComment(obContext, core), + new DeleteQzonePublicReply(obContext, core), + new ForwardQzonePublicFeed(obContext, core), new SetGroupMemberInvitePolicy(obContext, core), new SetGroupMemberPermissions(obContext, core), new SetGroupNewMemberHistoryVisibility(obContext, core), diff --git a/packages/napcat-onebot/action/router.ts b/packages/napcat-onebot/action/router.ts index 893a7af68..4c5ae64ae 100644 --- a/packages/napcat-onebot/action/router.ts +++ b/packages/napcat-onebot/action/router.ts @@ -224,4 +224,18 @@ export const ActionName = { // QQ 空间扩展 SendQzoneMsg: 'send_qzone_msg', DeleteQzoneMsg: 'delete_qzone_msg', + GetQzonePublicCapabilities: 'get_qzone_public_capabilities', + GetQzonePublicFeeds: 'get_qzone_public_feeds', + GetQzonePublicFeedDetail: 'get_qzone_public_feed_detail', + GetQzonePublicComments: 'get_qzone_public_comments', + GetQzonePublicReplies: 'get_qzone_public_replies', + SetQzonePublicUpvote: 'set_qzone_public_upvote', + SetQzonePublicLike: 'set_qzone_public_like', + SetQzonePublicFollow: 'set_qzone_public_follow', + SetQzonePublicCommentLike: 'set_qzone_public_comment_like', + CommentQzonePublicFeed: 'comment_qzone_public_feed', + ReplyQzonePublicFeed: 'reply_qzone_public_feed', + DeleteQzonePublicComment: 'delete_qzone_public_comment', + DeleteQzonePublicReply: 'delete_qzone_public_reply', + ForwardQzonePublicFeed: 'forward_qzone_public_feed', } as const; diff --git a/packages/napcat-onebot/network/http-server.ts b/packages/napcat-onebot/network/http-server.ts index a8277eabf..370ef1120 100644 --- a/packages/napcat-onebot/network/http-server.ts +++ b/packages/napcat-onebot/network/http-server.ts @@ -13,6 +13,8 @@ import { URL } from 'url'; import { ActionName } from '@/napcat-onebot/action/router'; import { OB11HeartbeatEvent } from '@/napcat-onebot/event/meta/OB11HeartbeatEvent'; import { OB11LifeCycleEvent, LifeCycleSubType } from '@/napcat-onebot/event/meta/OB11LifeCycleEvent'; +import { QzonePublicAction } from '@/napcat-onebot/action/extends/qzone-public/common'; +import { decodeQzonePublicHttpParameters } from '@/napcat-onebot/action/extends/qzone-public/http-params'; export class OB11HttpServerAdapter extends IOB11NetworkAdapter { private app: Express | undefined; @@ -261,10 +263,15 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter return res.json(hello); } const actionName = req.path.split('/')[1]; + const action = this.actions.get(actionName as any); + if (action instanceof QzonePublicAction) { + const query = decodeQzonePublicHttpParameters(req.query); + const body = req.is('application/x-www-form-urlencoded') ? decodeQzonePublicHttpParameters(req.body) : req.body; + payload = req.method === 'GET' ? query : { ...body, ...query }; + } const payload_echo = payload['echo']; const real_echo = payload_echo ?? Math.random().toString(36).substring(2, 15); - const action = this.actions.get(actionName as any); if (action) { const useStream = action.useStream; try { diff --git a/packages/napcat-test/qzonePublicActions.test.ts b/packages/napcat-test/qzonePublicActions.test.ts new file mode 100644 index 000000000..402f6e848 --- /dev/null +++ b/packages/napcat-test/qzonePublicActions.test.ts @@ -0,0 +1,305 @@ +// StreamBasic must be evaluated before OneBotAction because they import each other. +import '../napcat-onebot/action/stream/StreamBasic'; +import { describe, expect, test, vi } from 'vitest'; +import { TypeCompiler } from '@sinclair/typebox/compiler'; +import { + CommentQzonePublicFeed, + DeleteQzonePublicComment, + DeleteQzonePublicReply, + ForwardQzonePublicFeed, + GetQzonePublicCapabilities, + GetQzonePublicComments, + GetQzonePublicFeedDetail, + GetQzonePublicFeeds, + GetQzonePublicReplies, + ReplyQzonePublicFeed, + SetQzonePublicCommentLike, + SetQzonePublicFollow, + SetQzonePublicLike, + SetQzonePublicUpvote, +} from '../napcat-onebot/action/extends/qzone-public'; + +const FEED = { + cell_id: { id: 'feed-id', extra_id: 'raw-id' }, + cell_feed_transfer: { transfer: 'raw-transfer' }, + extra_feed: { nested: [1, true, null, { opaque: '001' }] }, +}; +const COMMENT = { + id: 'comment-id', + like: { id: 'comment-like-id', extra_like: true }, + reply_attach_info: 'reply-cursor', + extra_comment: { opaque: '002' }, +}; +const REPLY = { id: 'reply-id', like: { id: 'reply-like-id' }, extra_reply: [false, 3] }; +const CONTENT = '保留评论正文'; + +const ACTION_CASES = [ + { Action: GetQzonePublicCapabilities, name: 'get_qzone_public_capabilities', method: 'getCapabilities', payload: {}, args: [] }, + { Action: GetQzonePublicFeeds, name: 'get_qzone_public_feeds', method: 'getFeeds', payload: { cursor: 'feeds-cursor' }, args: ['feeds-cursor'] }, + { Action: GetQzonePublicFeedDetail, name: 'get_qzone_public_feed_detail', method: 'getFeedDetail', payload: { feed: FEED }, args: [FEED] }, + { Action: GetQzonePublicComments, name: 'get_qzone_public_comments', method: 'getComments', payload: { feed: FEED, cursor: 'detail-cursor' }, args: [FEED, 'detail-cursor'] }, + { Action: GetQzonePublicReplies, name: 'get_qzone_public_replies', method: 'getReplies', payload: { feed: FEED, comment: COMMENT, cursor: 'next-replies', page_size: '7' }, args: [FEED, COMMENT, 'next-replies', 7] }, + { Action: SetQzonePublicUpvote, name: 'set_qzone_public_upvote', method: 'setUpvote', payload: { feed: FEED, enable: false }, args: [FEED, false] }, + { Action: SetQzonePublicLike, name: 'set_qzone_public_like', method: 'setLike', payload: { feed: FEED, enable: false }, args: [FEED, false] }, + { Action: SetQzonePublicFollow, name: 'set_qzone_public_follow', method: 'setFollow', payload: { feed: FEED, enable: false }, args: [FEED, false] }, + { Action: SetQzonePublicCommentLike, name: 'set_qzone_public_comment_like', method: 'setCommentLike', payload: { feed: FEED, comment: COMMENT, reply: REPLY, enable: false }, args: [FEED, COMMENT, false, REPLY] }, + { Action: CommentQzonePublicFeed, name: 'comment_qzone_public_feed', method: 'addComment', payload: { feed: FEED, content: CONTENT }, args: [FEED, CONTENT] }, + { Action: ReplyQzonePublicFeed, name: 'reply_qzone_public_feed', method: 'addReply', payload: { feed: FEED, comment: COMMENT, content: CONTENT, reply: REPLY }, args: [FEED, COMMENT, CONTENT, REPLY] }, + { Action: DeleteQzonePublicComment, name: 'delete_qzone_public_comment', method: 'deleteComment', payload: { feed: FEED, comment: COMMENT }, args: [FEED, COMMENT] }, + { Action: DeleteQzonePublicReply, name: 'delete_qzone_public_reply', method: 'deleteReply', payload: { feed: FEED, comment: COMMENT, reply: REPLY }, args: [FEED, COMMENT, REPLY] }, + { Action: ForwardQzonePublicFeed, name: 'forward_qzone_public_feed', method: 'forwardFeed', payload: { feed: FEED, reason: '转发理由' }, args: [FEED, '转发理由'] }, +] as const; + +type ActionConstructor = typeof ACTION_CASES[number]['Action']; + +function createAction (Action: ActionConstructor) { + const nativeResult = { + feeds: [FEED], + has_more: true, + next_cursor: 'next-feeds', + extra_result: { untouched: [null, 1, false, '001'] }, + }; + const methods = Object.fromEntries(ACTION_CASES.map(({ method }) => [method, vi.fn().mockResolvedValue(nativeResult)])); + const action = new Action(undefined as never, { + context: { logger: { logError: vi.fn() } }, + apis: { QzonePublicApi: methods }, + } as never); + return { action, methods, nativeResult }; +} + +describe('Qzone public OneBot actions', () => { + test.each(ACTION_CASES)('$name delegates complete raw objects and returns the original JSON object', async ({ Action, name, method, payload, args }) => { + const { action, methods, nativeResult } = createAction(Action); + const response = await action.handle(structuredClone(payload) as never, 'test', {} as never); + + expect(action.actionName).toBe(name); + expect(response.status).toBe('ok'); + expect(response.data).toBe(nativeResult); + expect(methods[method]).toHaveBeenCalledExactlyOnceWith(...args); + for (const [otherMethod, mock] of Object.entries(methods)) { + if (otherMethod !== method) expect(mock).not.toHaveBeenCalled(); + } + }); + + test.each(ACTION_CASES)('$name provides compilable OpenAPI schemas and examples', ({ Action }) => { + const { action, nativeResult } = createAction(Action); + + expect(action.actionSummary).not.toBe(''); + expect(action.actionDescription).not.toBe(''); + expect(action.actionTags.length).toBeGreaterThan(0); + expect(action.payloadSchema).toBeDefined(); + expect(action.returnSchema).toBeDefined(); + expect(action.payloadExample).toBeDefined(); + expect(action.returnExample).toBeDefined(); + expect(TypeCompiler.Compile(action.payloadSchema!).Check(action.payloadExample)).toBe(true); + const checkResult = TypeCompiler.Compile(action.returnSchema!); + expect(checkResult.Check(action.returnExample)).toBe(true); + expect(checkResult.Check(nativeResult)).toBe(true); + }); + + test('reply pagination uses the SL empty cursor default for parent-cursor fallback', async () => { + const { action, methods } = createAction(GetQzonePublicReplies); + + await action.handle({ feed: FEED, comment: COMMENT } as never, 'test', {} as never); + await action.handle({ feed: FEED, comment: COMMENT, cursor: '' } as never, 'test', {} as never); + + expect(methods['getReplies']).toHaveBeenNthCalledWith(1, FEED, COMMENT, '', 20); + expect(methods['getReplies']).toHaveBeenNthCalledWith(2, FEED, COMMENT, '', 20); + }); + + test('comment pagination requires a non-empty detail cursor', async () => { + const { action, methods } = createAction(GetQzonePublicComments); + + const missing = await action.handle({ feed: FEED } as never, 'test', {} as never); + expect(missing).toMatchObject({ status: 'failed', retcode: 400 }); + expect(methods['getComments']).not.toHaveBeenCalled(); + + const empty = await action.handle({ feed: FEED, cursor: '' } as never, 'test', {} as never); + expect(empty).toMatchObject({ status: 'failed', retcode: 400 }); + expect(methods['getComments']).not.toHaveBeenCalled(); + }); + + test.each([ + { value: true, expected: true }, + { value: false, expected: false }, + { value: 1, expected: true }, + { value: 0, expected: false }, + { value: 'true', expected: true }, + { value: 'false', expected: false }, + { value: '1', expected: true }, + { value: '0', expected: false }, + { value: ' TRUE ', expected: true }, + { value: ' FALSE ', expected: false }, + { value: 'yes', expected: true }, + { value: 'no', expected: false }, + { value: ' ON ', expected: true }, + { value: ' OFF ', expected: false }, + { value: 2, expected: true }, + { value: -1, expected: true }, + { value: 0.1, expected: true }, + ])('normalizes enable=$value without merging upvote, like and follow', async ({ value, expected }) => { + for (const { Action, method } of ACTION_CASES.filter(({ method }) => ['setUpvote', 'setLike', 'setFollow', 'setCommentLike'].includes(method))) { + const { action, methods } = createAction(Action); + const response = await action.handle({ feed: FEED, comment: COMMENT, enable: value } as never, 'test', {} as never); + + expect(response.status).toBe('ok'); + expect(methods[method]).toHaveBeenCalledExactlyOnceWith(...(method === 'setCommentLike' ? [FEED, COMMENT, expected, undefined] : [FEED, expected])); + } + }); + + test('uses documented defaults for optional mutation parameters', async () => { + for (const { Action, method } of ACTION_CASES.filter(({ method }) => ['setUpvote', 'setLike', 'setFollow', 'setCommentLike'].includes(method))) { + const { action, methods } = createAction(Action); + await action.handle({ feed: FEED, comment: COMMENT } as never, 'test', {} as never); + expect(methods[method]).toHaveBeenCalledExactlyOnceWith(...(method === 'setCommentLike' ? [FEED, COMMENT, true, undefined] : [FEED, true])); + } + + const forward = createAction(ForwardQzonePublicFeed); + await forward.action.handle({ feed: FEED } as never, 'test', {} as never); + expect(forward.methods['forwardFeed']).toHaveBeenCalledExactlyOnceWith(FEED, ''); + + const reply = createAction(ReplyQzonePublicFeed); + await reply.action.handle({ feed: FEED, comment: COMMENT, content: CONTENT } as never, 'test', {} as never); + expect(reply.methods['addReply']).toHaveBeenCalledExactlyOnceWith(FEED, COMMENT, CONTENT, undefined); + }); + + test.each(['maybe', '', '2', null, {}, []].map(enable => ({ enable })))('rejects unsupported enable=$enable', async ({ enable }) => { + const { action, methods } = createAction(SetQzonePublicLike); + const response = await action.handle({ feed: FEED, enable } as never, 'test', {} as never); + + expect(response).toMatchObject({ status: 'failed', retcode: 400 }); + expect(methods['setLike']).not.toHaveBeenCalled(); + }); + + test.each([ + { pageSize: 1, expected: 1 }, + { pageSize: '1', expected: 1 }, + { pageSize: 20, expected: 20 }, + { pageSize: '37', expected: 37 }, + { pageSize: 1.5, expected: 1 }, + { pageSize: '1.9', expected: 1 }, + { pageSize: ' 2e1 ', expected: 20 }, + { pageSize: '0x10', expected: 16 }, + { pageSize: Number.MAX_SAFE_INTEGER + 1, expected: Number.MAX_SAFE_INTEGER + 1 }, + ])('normalizes SL-compatible page_size=$pageSize to $expected', async ({ pageSize, expected }) => { + const { action, methods } = createAction(GetQzonePublicReplies); + const response = await action.handle({ feed: FEED, comment: COMMENT, page_size: pageSize } as never, 'test', {} as never); + + expect(response.status).toBe('ok'); + expect(methods['getReplies']).toHaveBeenCalledExactlyOnceWith(FEED, COMMENT, '', expected); + }); + + test.each([0, -1, 0.9, '', ' ', '0', '-1', 'abc', true, null, Infinity, 'Infinity'])('rejects invalid page_size=%j', async (pageSize) => { + const { action, methods } = createAction(GetQzonePublicReplies); + const response = await action.handle({ feed: FEED, comment: COMMENT, page_size: pageSize } as never, 'test', {} as never); + + expect(response).toMatchObject({ status: 'failed', retcode: 400 }); + expect(methods['getReplies']).not.toHaveBeenCalled(); + }); + + test.each([CommentQzonePublicFeed, ReplyQzonePublicFeed])('preserves arbitrary rich content objects', async (Action) => { + const { action, methods } = createAction(Action); + const content = [{ type: 0, content: '正文', unknown: { id: '001', list: [null, false] } }, { type: 1, uid: '123', extra: ['a'] }]; + const response = await action.handle({ feed: FEED, comment: COMMENT, content } as never, 'test', {} as never); + + expect(response.status).toBe('ok'); + const method = Action === CommentQzonePublicFeed ? 'addComment' : 'addReply'; + expect(methods[method]).toHaveBeenCalledExactlyOnceWith(...(method === 'addComment' ? [FEED, content] : [FEED, COMMENT, content, undefined])); + }); + + test.each(['', '[]', '[1]', 123, false, null, {}, [], ['text'], [1], [null], [[]]].map(content => ({ content })))('rejects invalid rich content=$content before conversion', async ({ content }) => { + const { action, methods } = createAction(CommentQzonePublicFeed); + const response = await action.handle({ feed: FEED, content } as never, 'test', {} as never); + + expect(response).toMatchObject({ status: 'failed', retcode: 400 }); + expect(methods['addComment']).not.toHaveBeenCalled(); + }); + + test.each([CommentQzonePublicFeed, ReplyQzonePublicFeed])('normalizes JSON-array content strings using the SL consumer contract', async (Action) => { + const { action, methods } = createAction(Action); + const content = [{ type: 0, content: '正文', future: { opaque: '001' } }]; + const method = Action === CommentQzonePublicFeed ? 'addComment' : 'addReply'; + const response = await action.handle({ feed: FEED, comment: COMMENT, content: ` ${JSON.stringify(content)} ` } as never, 'test', {} as never); + + expect(response.status).toBe('ok'); + expect(methods[method]).toHaveBeenCalledExactlyOnceWith(...(method === 'addComment' ? [FEED, content] : [FEED, COMMENT, content, undefined])); + }); + + test.each([' ', '[invalid]'])('preserves non-empty SL text content %j', async (content) => { + const { action, methods } = createAction(CommentQzonePublicFeed); + const response = await action.handle({ feed: FEED, content } as never, 'test', {} as never); + + expect(response.status).toBe('ok'); + expect(methods['addComment']).toHaveBeenCalledExactlyOnceWith(FEED, content); + }); + + test('feed cursors are optional, non-empty and limited to 65536 characters', async () => { + const { action, methods } = createAction(GetQzonePublicFeeds); + const first = await action.handle({} as never, 'test', {} as never); + expect(first.status).toBe('ok'); + expect(methods['getFeeds']).toHaveBeenCalledExactlyOnceWith(undefined); + methods['getFeeds']!.mockClear(); + + for (const cursor of ['', 'a'.repeat(65537)]) { + const response = await action.handle({ cursor } as never, 'test', {} as never); + expect(response).toMatchObject({ status: 'failed', retcode: 400 }); + } + expect(methods['getFeeds']).not.toHaveBeenCalled(); + const cursor = 'a'.repeat(65536); + expect((await action.handle({ cursor } as never, 'test', {} as never)).status).toBe('ok'); + expect(methods['getFeeds']).toHaveBeenCalledExactlyOnceWith(cursor); + }); + + test.each([ + { Action: GetQzonePublicFeeds, method: 'getFeeds', field: 'cursor', payload: {}, args: [] }, + { Action: GetQzonePublicComments, method: 'getComments', field: 'cursor', payload: { feed: FEED }, args: [FEED] }, + { Action: GetQzonePublicReplies, method: 'getReplies', field: 'cursor', payload: { feed: FEED, comment: COMMENT }, args: [FEED, COMMENT] }, + { Action: ForwardQzonePublicFeed, method: 'forwardFeed', field: 'reason', payload: { feed: FEED }, args: [FEED] }, + ])('$method uses SL string coercion for $field', async ({ Action, method, field, payload, args }) => { + for (const value of [42, false]) { + const { action, methods } = createAction(Action); + const response = await action.handle({ ...payload, [field]: value } as never, 'test', {} as never); + expect(response.status).toBe('ok'); + expect(methods[method]).toHaveBeenCalledExactlyOnceWith(...args, String(value), ...(method === 'getReplies' ? [20] : [])); + } + for (const value of [null, {}, []]) { + const { action, methods } = createAction(Action); + const response = await action.handle({ ...payload, [field]: value } as never, 'test', {} as never); + expect(response).toMatchObject({ status: 'failed', retcode: 400 }); + expect(methods[method]).not.toHaveBeenCalled(); + } + }); + + test.each([ + { feed: null, comment: COMMENT, reply: REPLY }, + { feed: [], comment: COMMENT, reply: REPLY }, + { feed: 'feed-id', comment: COMMENT, reply: REPLY }, + { feed: FEED, comment: null, reply: REPLY }, + { feed: FEED, comment: 'comment-id', reply: REPLY }, + { feed: FEED, comment: COMMENT, reply: [] }, + { feed: FEED, comment: COMMENT, reply: 'reply-id' }, + ])('requires raw objects for feed, comment and reply: %j', async (payload) => { + const { action, methods } = createAction(DeleteQzonePublicReply); + const response = await action.handle(payload as never, 'test', {} as never); + + expect(response).toMatchObject({ status: 'failed', retcode: 400 }); + expect(methods['deleteReply']).not.toHaveBeenCalled(); + }); + + test('WebSocket validation preserves echo and prevents writes', async () => { + const { action, methods } = createAction(DeleteQzonePublicReply); + const response = await action.websocketHandle({ feed: FEED, comment: COMMENT } as never, 'public-echo', 'test', {} as never); + + expect(response).toMatchObject({ status: 'failed', retcode: 1400, echo: 'public-echo' }); + expect(methods['deleteReply']).not.toHaveBeenCalled(); + }); + + test('reports core failures through the existing OneBot error response', async () => { + const { action, methods } = createAction(SetQzonePublicUpvote); + methods['setUpvote']!.mockRejectedValue(new Error('public interaction rejected')); + const response = await action.handle({ feed: FEED } as never, 'test', {} as never); + + expect(response).toMatchObject({ status: 'failed', message: 'public interaction rejected' }); + expect(methods['setUpvote']).toHaveBeenCalledExactlyOnceWith(FEED, true); + }); +}); diff --git a/packages/napcat-test/qzonePublicApi.test.ts b/packages/napcat-test/qzonePublicApi.test.ts new file mode 100644 index 000000000..5b9f4369d --- /dev/null +++ b/packages/napcat-test/qzonePublicApi.test.ts @@ -0,0 +1,182 @@ +import { afterEach, describe, expect, test, vi } from 'vitest'; +import type { InstanceContext, NapCatCore } from '@/napcat-core'; +import { NTQQQzonePublicApi } from '@/napcat-core/apis/qzone-public'; + +const feed = { + cell_common: { union_id: { uf_key: 'synthetic-public-feed', opaque: { preserve: true } }, domain_type: 3, feed_type: 1, cur_like_key: 'synthetic-feed-like' }, + cell_feed_transfer: { opaque: 'synthetic-transfer' }, + cell_user_info: { user: { uin: '20002', uid: 'u_author', nick: 'Synthetic author' } }, + cell_summary: { summary: [{ type: 0, content: 'Synthetic public feed' }] }, +}; +const comment = { id: 'synthetic-comment', user: { uin: '10001', uid: null, nick: 'Synthetic' }, like: { id: 'synthetic-comment-like' }, reply_attach_info: 'parent-reply-cursor' }; +const reply = { id: 'synthetic-reply', user: { uin: '10001', uid: 'u_self', nick: 'Synthetic' }, like: { id: 'synthetic-reply-like' } }; + +function setup () { + const user = { uin: '10001', uid: 'u_self', nick: 'Synthetic' }; + const userApi = { + getSKey: vi.fn().mockResolvedValue('synthetic-skey'), + getPSkey: vi.fn().mockResolvedValue({ domainPskeyMap: new Map([['qzone.qq.com', 'synthetic-pskey']]) }), + }; + const core = { selfInfo: user, apis: { UserApi: userApi } } as unknown as NapCatCore; + const fetchMock = vi.fn().mockImplementation(async () => new Response(JSON.stringify({ + retcode: 0, data: { like: true, upvote: true, comment: { id: 'new' }, reply: { id: 'new-reply' }, ret_code: 0 }, + }))); + vi.stubGlobal('fetch', fetchMock); + return { api: new NTQQQzonePublicApi({} as InstanceContext, core), core, user, userApi, fetchMock }; +} + +function response (data: Record) { + return new Response(JSON.stringify({ retcode: 0, data })); +} + +function requestBody (fetchMock: ReturnType['fetchMock'], index = 0) { + return JSON.parse(fetchMock.mock.calls[index]![1]!.body as string) as Record; +} + +afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.useRealTimers(); }); + +describe('public Qzone HTTP integration', () => { + test('uses scoped native tickets and the fixed JSON gateway and metadata', async () => { + const { api, userApi, fetchMock } = setup(); + await api.getCapabilities(); + expect(userApi.getPSkey).toHaveBeenCalledWith(['qzone.qq.com']); + const [url, options] = fetchMock.mock.calls[0]!; + expect(String(url)).toMatch(/^https:\/\/h5\.qzone\.qq\.com\/http2rpc\/gotrpc\/v1\/trpc\.public_qzone\.entrance_ctrl\.EntranceCtrl\/BatchEntranceWhitelist\?g_tk=\d+$/); + expect(options).toMatchObject({ method: 'POST', redirect: 'error', signal: expect.any(AbortSignal) }); + const headers = options!.headers as Record; + expect(headers['x-web-qua']).toBe('V1_HT5_QZ_9.9.32_001_IDC_B'); + expect(JSON.parse(headers['x-oidb']!)).toEqual({ uint32_command: '0x9741', uint32_service_type: '0' }); + expect(headers['Cookie']).toContain('p_skey=synthetic-pskey'); + expect(requestBody(fetchMock)).toEqual({ uins: ['10001'], entrance_types: [1, 15] }); + }); + + test('keeps page metadata and full identities and terminates only on has_more', async () => { + const { api, fetchMock } = setup(); + fetchMock.mockResolvedValueOnce(response({ feeds: [{ feed }], has_more: true, attach_info: 'attach-one', bottom_title: { title: 'More' } })); + const first = await api.getFeeds(); + expect(first).toMatchObject({ feeds: [feed], has_more: true, bottom_title: { title: 'More' } }); + expect(first.next_cursor).toBeTypeOf('string'); + const initial = requestBody(fetchMock); + expect(initial['refresh_id']).toMatch(/^10001_\d+$/); + expect(initial).not.toHaveProperty('attach_info'); + fetchMock.mockResolvedValueOnce(response({ feeds: [], has_more: false, attach_info: '', extra: true })); + expect(await api.getFeeds(first.next_cursor!)).toEqual({ feeds: [], has_more: false, attach_info: '', extra: true, next_cursor: null }); + expect(requestBody(fetchMock, 1)).toEqual({ refresh_id: initial['refresh_id'], attach_info: 'attach-one', last_client_feed_union_id: feed.cell_common.union_id }); + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + test('an ad-only page retains the last non-ad full union object', async () => { + const { api, fetchMock } = setup(); + fetchMock.mockResolvedValueOnce(response({ feeds: [{ feed }], has_more: true, attach_info: 'one' })); + const first = await api.getFeeds(); + const ad = { cell_common: { feed_type: 3, union_id: { uf_key: 'ad' } } }; + fetchMock.mockResolvedValueOnce(response({ feeds: [{ feed: ad }], has_more: true, attach_info: 'two' })); + const second = await api.getFeeds(first.next_cursor!); + fetchMock.mockResolvedValueOnce(response({ feeds: [], has_more: false })); + await api.getFeeds(second.next_cursor!); + expect(requestBody(fetchMock, 2)['last_client_feed_union_id']).toEqual(feed.cell_common.union_id); + }); + + test.each([8193, 65536])('continues an issued cursor with %s characters of upstream attach_info', async (length) => { + const { api, fetchMock } = setup(); + const attach = 'x'.repeat(length); + fetchMock.mockResolvedValueOnce(response({ feeds: [{ feed }], has_more: true, attach_info: attach })); + const first = await api.getFeeds(); + fetchMock.mockResolvedValueOnce(response({ feeds: [], has_more: false })); + await api.getFeeds(first.next_cursor!); + expect(requestBody(fetchMock, 1)['attach_info']).toBe(attach); + }); + + test('returned feed mutation cannot alter a stored continuation identity', async () => { + const { api, fetchMock } = setup(); + fetchMock.mockResolvedValueOnce(response({ feeds: [{ feed: structuredClone(feed) }], has_more: true, attach_info: 'one' })); + const first = await api.getFeeds(); + (first.feeds[0]!['cell_common'] as Record)['union_id'] = { uf_key: 'changed-by-caller' }; + fetchMock.mockResolvedValueOnce(response({ feeds: [], has_more: false })); + await api.getFeeds(first.next_cursor!); + expect(requestBody(fetchMock, 1)['last_client_feed_union_id']).toEqual(feed.cell_common.union_id); + }); + + test('rejects cross-account and expired cursors before fetching', async () => { + const { api, user, fetchMock } = setup(); + let now = 1700000000000; + vi.spyOn(Date, 'now').mockImplementation(() => now); + fetchMock.mockResolvedValueOnce(response({ feeds: [{ feed }], has_more: true, attach_info: 'one' })); + const first = await api.getFeeds(); + user.uid = 'other-session'; + await expect(api.getFeeds(first.next_cursor!)).rejects.toThrow('游标'); + user.uid = 'u_self'; + now += 10 * 60 * 1000 + 1; + await expect(api.getFeeds(first.next_cursor!)).rejects.toThrow('游标'); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + test('aborts before effects when the account switches while tickets are being read', async () => { + const { api, user, userApi, fetchMock } = setup(); + userApi.getPSkey.mockImplementationOnce(async () => { + user.uin = '30003'; + return { domainPskeyMap: new Map([['qzone.qq.com', 'synthetic-pskey']]) }; + }); + await expect(api.setUpvote(feed)).rejects.toThrow('切换'); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + test('rejects malformed write input before ticket or network activity', async () => { + const { api, userApi, fetchMock } = setup(); + await expect(api.addComment({}, 'text')).rejects.toThrow(); + expect(userApi.getSKey).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + test.each([ + ['upvote', (api: NTQQQzonePublicApi) => api.setUpvote(feed), 'UFOComment/Upvote'], + ['downvote', (api: NTQQQzonePublicApi) => api.setUpvote(feed, false), 'UFOComment/Downvote'], + ['like', (api: NTQQQzonePublicApi) => api.setLike(feed), 'InteractionWriter/DoLike'], + ['unlike', (api: NTQQQzonePublicApi) => api.setLike(feed, false), 'InteractionWriter/UnLike'], + ['follow', (api: NTQQQzonePublicApi) => api.setFollow(feed), 'RelationService/Follow'], + ['unfollow', (api: NTQQQzonePublicApi) => api.setFollow(feed, false), 'RelationService/Unfollow'], + ['comment like', (api: NTQQQzonePublicApi) => api.setCommentLike(feed, comment), 'InteractionWriter/DoLike'], + ['reply unlike', (api: NTQQQzonePublicApi) => api.setCommentLike(feed, comment, false, reply), 'InteractionWriter/UnLike'], + ['comment', (api: NTQQQzonePublicApi) => api.addComment(feed, 'Comment'), 'InteractionWriter/AddComment'], + ['reply', (api: NTQQQzonePublicApi) => api.addReply(feed, comment, 'Reply', reply), 'InteractionWriter/AddReply'], + ['delete comment', (api: NTQQQzonePublicApi) => api.deleteComment(feed, comment), 'InteractionWriter/DeleteComment'], + ['delete reply', (api: NTQQQzonePublicApi) => api.deleteReply(feed, comment, reply), 'InteractionWriter/DeleteReply'], + ['forward', (api: NTQQQzonePublicApi) => api.forwardFeed(feed, 'Reason'), 'FeedsWriter/ForwardFeed'], + ])('dispatches %s once using its own business route', async (_label, invoke, suffix) => { + const { api, fetchMock } = setup(); + await invoke(api); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(String(fetchMock.mock.calls[0]![0])).toContain(`.${suffix}?`); + }); + + test('keeps reply cursor defaults and explicit page_size and raw null-UID parent', async () => { + const { api, fetchMock } = setup(); + await api.getReplies(feed, comment, undefined, 7); + expect(requestBody(fetchMock)).toMatchObject({ cur_comment: comment, reply_attach_info: 'parent-reply-cursor', page_size: 7 }); + await api.getReplies(feed, comment, '', 20); + expect(requestBody(fetchMock, 1)).toMatchObject({ cur_comment: comment, reply_attach_info: 'parent-reply-cursor', page_size: 20 }); + expect(comment.user.uid).toBeNull(); + }); + + test('does not retry or expose ticket values on HTTP, JSON or business failure', async () => { + const { api, fetchMock } = setup(); + fetchMock.mockResolvedValueOnce(new Response('private ticket=synthetic-pskey', { status: 403 })); + await expect(api.setLike(feed)).rejects.toThrow('勿自动重试'); + fetchMock.mockResolvedValueOnce(new Response('synthetic-pskey')); + await expect(api.addComment(feed, 'Text')).rejects.toThrow('勿自动重试'); + fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ retcode: -1, message: 'synthetic-pskey' }))); + await expect(api.setFollow(feed)).rejects.not.toThrow('synthetic-pskey'); + expect(fetchMock).toHaveBeenCalledTimes(3); + }); + + test('bounds response streams and cancels oversized bodies', async () => { + const { api, fetchMock } = setup(); + const cancel = vi.fn(); + fetchMock.mockResolvedValueOnce(new Response(new ReadableStream({ + start (controller) { controller.enqueue(new Uint8Array(8 * 1024 * 1024 + 1)); }, + cancel, + }))); + await expect(api.getCapabilities()).rejects.toThrow('请求失败'); + expect(cancel).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/napcat-test/qzonePublicData.test.ts b/packages/napcat-test/qzonePublicData.test.ts new file mode 100644 index 000000000..79049a671 --- /dev/null +++ b/packages/napcat-test/qzonePublicData.test.ts @@ -0,0 +1,283 @@ +import { describe, expect, test } from 'vitest'; +import { + buildQzonePublicRequest, + parseQzonePublicResponse, + QZONE_PUBLIC_ROUTES, + type QzonePublicObject, + type QzonePublicOperation, +} from '@/napcat-core/data/qzone-public'; + +function feed (): QzonePublicObject { + return { + cell_common: { + union_id: { uf_key: 'synthetic-feed', ugc_id: 'synthetic-ugc', auxiliary: { keep: 0 } }, + cur_like_key: 'feed-like', + domain_type: 3, + }, + cell_user_info: { user: { uin: '10002', uid: 'u_author', nick: 'Synthetic author' } }, + cell_feed_transfer: { opaque: { token: 'synthetic-context', flags: [false, 0, null] } }, + cell_summary: { summary: [{ type: 0, content: 'Synthetic content' }] }, + }; +} + +function parent (): QzonePublicObject { + return { + id: 0, + user: { uin: '10003', uid: null, nick: 'Synthetic parent' }, + content: [{ type: 0, content: 'Original parent' }], + like: { id: 'parent-like', count: 4, status: 0 }, + reply_attach_info: 'parent-replies', + has_more_reply: true, + future: { zero: 0, nullable: null, flags: [true, false] }, + }; +} + +function reply (): QzonePublicObject { + return { id: 'reply-0', user: { uid: 'u_recipient', uin: '', nick: 'Synthetic recipient' }, like: { id: 'reply-like' }, future: { retain: true } }; +} + +const currentUser = { uin: '10001', uid: 'u_current', nick: 'Synthetic current' }; + +describe('QQ public Qzone fixed protocol routes', () => { + test('binds all operations to known service methods and OIDB hints', () => { + expect(Object.keys(QZONE_PUBLIC_ROUTES)).toHaveLength(18); + expect(QZONE_PUBLIC_ROUTES.capabilities).toEqual({ service: 'trpc.public_qzone.entrance_ctrl.EntranceCtrl', method: 'BatchEntranceWhitelist', oidb: '0x9741_0' }); + expect(QZONE_PUBLIC_ROUTES.feeds).toEqual({ service: 'trpc.qzone.feeds_reader.FeedsReader', method: 'GetPublicRecomFeeds', oidb: '0x9a38_0' }); + expect(QZONE_PUBLIC_ROUTES.follow).toEqual({ service: 'trpc.public_qzone.relation.RelationService', method: 'Follow', oidb: '0x9d1a_1' }); + expect(QZONE_PUBLIC_ROUTES.unfollow).toEqual({ service: 'trpc.public_qzone.relation.RelationService', method: 'Unfollow', oidb: '0x9d1b_1' }); + expect(QZONE_PUBLIC_ROUTES.commentLike).toEqual(QZONE_PUBLIC_ROUTES.like); + expect(QZONE_PUBLIC_ROUTES.commentUnlike).toEqual(QZONE_PUBLIC_ROUTES.unlike); + expect(QZONE_PUBLIC_ROUTES.deleteComment).toMatchObject({ method: 'DeleteComment', oidb: '0x9989_0' }); + expect(QZONE_PUBLIC_ROUTES.deleteReply).toMatchObject({ method: 'DeleteReply', oidb: '0x998a_0' }); + expect(QZONE_PUBLIC_ROUTES.forward).toEqual({ service: 'trpc.qzone.feeds_writer.FeedsWriter', method: 'ForwardFeed', oidb: '0x969a_1' }); + expect(Object.isFrozen(QZONE_PUBLIC_ROUTES)).toBe(true); + expect(Object.values(QZONE_PUBLIC_ROUTES).every(Object.isFrozen)).toBe(true); + expect(() => buildQzonePublicRequest('__proto__' as QzonePublicOperation, {})).toThrow(); + }); + + test('builds entrance and recommendation requests without a tid-derived union', () => { + expect(buildQzonePublicRequest('capabilities', { selfUin: '10001' })).toEqual({ uins: ['10001'], entrance_types: [1, 15] }); + expect(buildQzonePublicRequest('feeds', { refreshId: '10001_1700000000' })).toEqual({ refresh_id: '10001_1700000000' }); + const last = { uf_key: 'last-real-feed', future: { preserve: true } }; + expect(buildQzonePublicRequest('feeds', { refreshId: 'r', cursor: 'opaque-attach', lastUnionId: last })) + .toEqual({ refresh_id: 'r', attach_info: 'opaque-attach', last_client_feed_union_id: last }); + expect(() => buildQzonePublicRequest('feeds', { refreshId: 'r', lastUnionId: { tid: 'legacy-tid' } })).toThrow('身份'); + expect(() => buildQzonePublicRequest('capabilities', { selfUin: 10001 as never })).toThrow(); + }); +}); + +describe('QQ public Qzone request business data', () => { + test('builds public detail and comment continuation with full context', () => { + const source = feed(); + const common = source['cell_common'] as QzonePublicObject; + expect(buildQzonePublicRequest('detail', { feed: source })).toEqual({ + union_id: common['union_id'], cell_feed_transfer: source['cell_feed_transfer'], feed_action_domain_type: 3, from_page: 1, + }); + expect(buildQzonePublicRequest('comments', { feed: source, cursor: 'next-comments' })).toEqual({ + union_id: common['union_id'], cell_feed_transfer: source['cell_feed_transfer'], attach_info: 'next-comments', + }); + for (const cursor of [undefined, '']) expect(() => buildQzonePublicRequest('comments', { feed: source, cursor })).toThrow(); + expect(() => buildQzonePublicRequest('detail', { feed: { union_id: { uf_key: 'reference-only' } } })).toThrow('cell_common'); + }); + + test('replies retain the whole parent and honor fallback cursor and page size compatibility', () => { + const source = feed(); + const comment = parent(); + const first = buildQzonePublicRequest('replies', { feed: source, comment }); + expect(first).toMatchObject({ cur_comment: comment, comment_attach_info: '', reply_attach_info: 'parent-replies', page_size: 20 }); + expect(first['cur_comment']).not.toBe(comment); + expect((first['cur_comment'] as QzonePublicObject)['id']).toBe(0); + expect(((first['cur_comment'] as QzonePublicObject)['user'] as QzonePublicObject)['uid']).toBeNull(); + expect(buildQzonePublicRequest('replies', { feed: source, comment, cursor: '', pageSize: 7.9 })) + .toMatchObject({ reply_attach_info: 'parent-replies', page_size: 7 }); + expect(buildQzonePublicRequest('replies', { feed: source, comment, cursor: 'next-replies', pageSize: Number.MAX_SAFE_INTEGER + 1 })) + .toMatchObject({ reply_attach_info: 'next-replies', page_size: Number.MAX_SAFE_INTEGER + 1 }); + expect(buildQzonePublicRequest('replies', { feed: source, comment: { id: 'parent-without-user' } })) + .toMatchObject({ cur_comment: { id: 'parent-without-user' }, reply_attach_info: '' }); + for (const pageSize of [0, -1, NaN, Infinity, true, null]) { + expect(() => buildQzonePublicRequest('replies', { feed: source, comment, pageSize: pageSize as number })).toThrow(); + } + }); + + test('distinguishes feed, parent-comment and reply like contexts', () => { + for (const operation of ['like', 'unlike'] as const) { + expect(buildQzonePublicRequest(operation, { feed: feed() })).toMatchObject({ like_key: 'feed-like', like_type: 1 }); + } + for (const operation of ['commentLike', 'commentUnlike'] as const) { + expect(buildQzonePublicRequest(operation, { feed: feed(), comment: parent() })).toMatchObject({ like_key: 'parent-like', like_type: 2 }); + const body = buildQzonePublicRequest(operation, { feed: feed(), comment: parent(), reply: reply() }); + expect(body).toMatchObject({ like_key: 'reply-like', like_type: 3 }); + expect(body).not.toHaveProperty('comment'); + expect(body).not.toHaveProperty('reply'); + } + }); + + test.each([ + { domain: 3, author: { uin: '10002', uid: 'u_author' }, identity: { target_uid: 'u_author' } }, + { domain: 3, author: { uin: '10002', uid: null }, identity: { target_uin: '10002' } }, + { domain: 1, author: { uin: '10002', uid: 'u_author' }, identity: { target_uin: '10002' } }, + { domain: 1, author: { uin: '', uid: 'u_author' }, identity: { target_uid: 'u_author' } }, + { domain: 3, author: { uin: '0', uid: 'u_author' }, identity: { target_uid: 'u_author' } }, + { domain: 3, author: { uin: 0, uid: 'u_author' }, identity: { target_uid: 'u_author' } }, + ])('uses the observed feed follow identity rule ($domain/$author)', ({ domain, author, identity }) => { + const source = feed(); + (source['cell_common'] as QzonePublicObject)['domain_type'] = domain; + source['cell_user_info'] = { user: author }; + for (const operation of ['follow', 'unfollow'] as const) { + expect(buildQzonePublicRequest(operation, { feed: source })).toEqual({ + follow_from_type: 1, ...identity, follow_feed_id: 'synthetic-feed', cell_feed_transfer: source['cell_feed_transfer'], + }); + } + }); + + test('rejects missing follow authors and does not substitute the ugc ID for follow_feed_id', () => { + const source = feed(); + (source['cell_common'] as QzonePublicObject)['union_id'] = { ugc_id: 'ugc-only' }; + expect(buildQzonePublicRequest('follow', { feed: source })).not.toHaveProperty('follow_feed_id'); + source['cell_user_info'] = { user: { uin: '', uid: null } }; + expect(() => buildQzonePublicRequest('follow', { feed: source })).toThrow(); + }); + + test('builds comments from text or raw rich items and snapshots every preserved field', () => { + const source = feed(); + const rich = [{ type: 0, content: ' text ', future: { color: 'blue' } }, { type: 1, uin: '10004', name: 'Mention', opaque: [0, false] }]; + const actor = { ...currentUser }; + const body = buildQzonePublicRequest('addComment', { feed: source, content: rich, user: actor }); + expect(body['comment']).toEqual({ user: currentUser, content: rich }); + (rich[0]!.future as QzonePublicObject)['color'] = 'changed'; + (source['cell_feed_transfer'] as QzonePublicObject)['opaque'] = 'changed'; + actor.nick = 'Changed after request'; + expect(((body['comment'] as QzonePublicObject)['content'] as QzonePublicObject[])[0]).toHaveProperty('future.color', 'blue'); + expect(body['cell_feed_transfer']).toHaveProperty('opaque.token', 'synthetic-context'); + expect(body['comment']).toHaveProperty('user.nick', 'Synthetic current'); + expect(buildQzonePublicRequest('addComment', { feed: feed(), content: ' \n ', user: currentUser })) + .toHaveProperty('comment.content', [{ type: 0, content: ' \n ' }]); + const unknownRich = [{}, { type: 'unknown', content: 42, future: { preserve: true } }]; + expect(buildQzonePublicRequest('addComment', { feed: feed(), content: unknownRich, user: currentUser })) + .toHaveProperty('comment.content', unknownRich); + }); + + test('targets the parent or selected reply author while preserving nullable UID and raw ID zero', () => { + const comment = parent(); + const parentReply = buildQzonePublicRequest('addReply', { feed: feed(), comment, content: 'reply', user: currentUser }); + expect(parentReply).toHaveProperty('comment.id', 0); + expect(parentReply).toHaveProperty('reply.target_user', comment['user']); + expect(parentReply).toHaveProperty('reply.target_user.uid', null); + const selected = reply(); + expect(buildQzonePublicRequest('addReply', { feed: feed(), comment, reply: selected, content: [{ type: 0, content: 'reply' }], user: currentUser })) + .toHaveProperty('reply.target_user', selected['user']); + expect(comment).not.toHaveProperty('reply'); + }); + + test('deletes using full original parent and reply snapshots', () => { + const comment = parent(); + const selected = reply(); + expect(buildQzonePublicRequest('deleteComment', { feed: feed(), comment })).toHaveProperty('comment', comment); + const body = buildQzonePublicRequest('deleteReply', { feed: feed(), comment, reply: selected }); + expect(body).toHaveProperty('comment', comment); + expect(body).toHaveProperty('reply', selected); + expect(body['comment']).not.toBe(comment); + expect(body['reply']).not.toBe(selected); + }); + + test('forwards with an empty or exact text reason and no implicit second write', () => { + expect(buildQzonePublicRequest('forward', { feed: feed() })).toHaveProperty('reason', ''); + expect(buildQzonePublicRequest('forward', { feed: feed(), reason: ' @{uin:10002,nick:Synthetic} \n' })).toHaveProperty('reason', ' @{uin:10002,nick:Synthetic} \n'); + expect(buildQzonePublicRequest('forward', { feed: feed() })).not.toHaveProperty('comment'); + }); +}); + +describe('QQ public Qzone JSON and identity boundaries', () => { + test.each([null, [{ key: 'synthetic-extension', future: null }]])('preserves nullable protobuf defaults in full feed identity (%j)', (extIds) => { + const union = { uf_key: 'synthetic-public', ugc_id: 'synthetic-ugc', feed_id: 'synthetic-feed', serialized_data: null, ext_ids: extIds }; + const source = feed(); + (source['cell_common'] as QzonePublicObject)['union_id'] = union; + expect(buildQzonePublicRequest('detail', { feed: source })).toHaveProperty('union_id', union); + expect(buildQzonePublicRequest('feeds', { refreshId: 'synthetic-refresh', cursor: 'next', lastUnionId: union })) + .toHaveProperty('last_client_feed_union_id', union); + expect(union.serialized_data).toBeNull(); + }); + + test.each([null, true, -1, Number.MAX_SAFE_INTEGER + 1, '', 'bad\nidentity'])('rejects invalid parent identities without changing their types (%j)', (id) => { + expect(() => buildQzonePublicRequest('deleteComment', { feed: feed(), comment: { id } })).toThrow(); + }); + + test('rejects non-JSON, circular, oversized and excessively nested raw context', () => { + const circular: QzonePublicObject = {}; + circular['self'] = circular; + const nested: QzonePublicObject = {}; + let cursor = nested; + for (let index = 0; index < 80; index++) { cursor['nested'] = {}; cursor = cursor['nested'] as QzonePublicObject; } + for (const context of [circular, { value: () => 0 }, { value: new Date() }, { value: Infinity }, { value: 'x'.repeat(8 * 1024 * 1024 + 1) }, nested]) { + const source = feed(); + source['cell_feed_transfer'] = context; + expect(() => buildQzonePublicRequest('detail', { feed: source })).toThrow(); + } + const sparse: unknown[] = []; + sparse.length = 1; + const source = feed(); + source['cell_feed_transfer'] = sparse; + expect(() => buildQzonePublicRequest('detail', { feed: source })).toThrow(); + }); + + test.each(['', [], [null], [1], [false], ['text'], [[{}]]].map(value => ({ value })))('rejects malformed comment content ($value)', ({ value }) => { + expect(() => buildQzonePublicRequest('addComment', { feed: feed(), content: value as never, user: currentUser })).toThrow(); + }); + + test('preserves unknown JSON keys without triggering prototype setters', () => { + const source = feed(); + source['cell_feed_transfer'] = JSON.parse('{"__proto__":{"synthetic":true},"constructor":{"opaque":0}}'); + const transfer = buildQzonePublicRequest('detail', { feed: source })['cell_feed_transfer'] as QzonePublicObject; + expect(Object.prototype.hasOwnProperty.call(transfer, '__proto__')).toBe(true); + expect(Object.getPrototypeOf(transfer)).toBe(Object.prototype); + expect(Object.getOwnPropertyDescriptor(transfer, '__proto__')?.value).toEqual({ synthetic: true }); + }); + + test('accepts a full returned feed larger than an old reference-handle limit', () => { + const source = feed(); + source['cell_comment'] = { comments: [{ id: 'large-comment', content: [{ type: 0, content: 'x'.repeat(70000) }] }] }; + expect(buildQzonePublicRequest('detail', { feed: source })).toHaveProperty('union_id.uf_key', 'synthetic-feed'); + }); +}); + +describe('QQ public Qzone response acknowledgements', () => { + test('requires numeric gateway retcode zero and object data without exposing server text', () => { + for (const response of [null, {}, { retcode: '0', data: {} }, { retcode: -1, data: {}, message: 'synthetic-private' }, { retcode: 0, data: [] }, { retcode: 0, data: null }]) { + expect(() => parseQzonePublicResponse(response, 'feeds')).toThrow(); + } + try { parseQzonePublicResponse({ retcode: -1, data: {}, message: 'synthetic-private' }, 'feeds'); } catch (error) { + expect((error as Error).message).not.toContain('synthetic-private'); + } + }); + + test('exposes a numeric upstream rejection code while keeping its private text out of errors', () => { + expect(() => parseQzonePublicResponse({ retcode: 10120, message: 'synthetic-private', data: null }, 'addReply')) + .toThrow('QQ空间公开接口拒绝请求 (retcode=10120)'); + }); + + test.each([ + ['upvote', 'upvote'], ['downvote', 'upvote'], ['like', 'like'], ['unlike', 'like'], + ['commentLike', 'like'], ['commentUnlike', 'like'], ['addComment', 'comment'], ['addReply', 'reply'], + ] as const)('checks the %s business result beyond gateway success', (operation, field) => { + for (const result of [undefined, null, false, 0, '']) expect(() => parseQzonePublicResponse({ retcode: 0, data: { [field]: result } }, operation)).toThrow(); + expect(parseQzonePublicResponse({ retcode: 0, data: { [field]: { status: false, count: 0 }, future: { keep: true } } }, operation)) + .toEqual({ [field]: { status: false, count: 0 }, future: { keep: true } }); + }); + + test.each(['follow', 'unfollow'] as const)('checks optional %s business ret_code and tolerates protobuf zero defaults', (operation) => { + for (const code of [undefined, null, 0, '0']) expect(parseQzonePublicResponse({ retcode: 0, data: { ret_code: code, future: true } }, operation)).toHaveProperty('future', true); + for (const code of [-1, 1, '1', false, '', {}, []]) expect(() => parseQzonePublicResponse({ retcode: 0, data: { ret_code: code, ret_msg: 'synthetic-private' } }, operation)).toThrow(); + }); + + test.each(['deleteComment', 'deleteReply', 'forward'] as const)('does not invent an undocumented success field for %s', (operation) => { + expect(parseQzonePublicResponse({ retcode: 0, data: {} }, operation)).toEqual({}); + }); + + test('returns preserved business data snapshots and permits a whole response above an old handle limit', () => { + const data = { feeds: [{ feed: feed() }], has_more: false, future: { retained: true }, text: 'x'.repeat(70000) }; + const parsed = parseQzonePublicResponse({ retcode: 0, data }, 'feeds'); + expect(parsed).toEqual(data); + data.future.retained = false; + expect(parsed).toHaveProperty('future.retained', true); + }); +}); diff --git a/packages/napcat-test/qzonePublicHttp.test.ts b/packages/napcat-test/qzonePublicHttp.test.ts new file mode 100644 index 000000000..94323fa85 --- /dev/null +++ b/packages/napcat-test/qzonePublicHttp.test.ts @@ -0,0 +1,104 @@ +// StreamBasic must be evaluated before OneBotAction because they import each other. +import '../napcat-onebot/action/stream/StreamBasic'; +import { describe, expect, test, vi } from 'vitest'; +import { OB11HttpServerAdapter } from '../napcat-onebot/network/http-server'; +import { CommentQzonePublicFeed, DeleteQzonePublicReply } from '../napcat-onebot/action/extends/qzone-public'; + +const FEED = { cell_common: { union_id: { feed_id: 'opaque' } }, future_feed: [1, false] }; +const COMMENT = { id: 'comment-id', like: { id: 'comment-like-id' }, future_comment: true }; +const REPLY = { id: 'reply-id', user: { uid: 'recipient' }, future_reply: { keep: true } }; + +function fixture (Action = DeleteQzonePublicReply as typeof DeleteQzonePublicReply | typeof CommentQzonePublicFeed) { + const result = { upstream_result: { unknown: 'preserved' } }; + const methods = { deleteReply: vi.fn().mockResolvedValue(result), addComment: vi.fn().mockResolvedValue(result) }; + const action = new Action(undefined as never, { + context: { logger: { logError: vi.fn() } }, + apis: { QzonePublicApi: methods }, + } as never); + // Exercise the adapter handler without opening a listener or constructing native QQ services. + const adapter = Object.assign(Object.create(OB11HttpServerAdapter.prototype), { + name: 'test-http', config: {}, actions: new Map([[action.actionName, action]]), + }) as OB11HttpServerAdapter; + return { adapter, action, methods, result }; +} + +async function request ( + adapter: OB11HttpServerAdapter, + actionName: string, + method: string, + query: Record, + body: Record = {}, + contentType = 'application/json' +) { + const json = vi.fn(); + await adapter.httpApiRequest({ + method, + path: `/${actionName}`, + query, + body, + is: (type: string) => type === contentType, + } as never, { json } as never); + return json.mock.calls[0]?.[0]; +} + +describe('Qzone public HTTP parameter compatibility', () => { + test.each(['GET', 'FORM'])('%s decodes feed, comment and reply JSON values before action validation', async (transport) => { + const { adapter, action, methods, result } = fixture(); + const parameters = { feed: JSON.stringify(FEED), comment: JSON.stringify(COMMENT), reply: JSON.stringify(REPLY) }; + const response = transport === 'GET' + ? await request(adapter, action.actionName, 'GET', parameters) + : await request(adapter, action.actionName, 'POST', {}, parameters, 'application/x-www-form-urlencoded'); + + expect(response).toMatchObject({ status: 'ok', data: result }); + expect(methods.deleteReply).toHaveBeenCalledExactlyOnceWith(FEED, COMMENT, REPLY); + }); + + test('POST query parameters receive the same decoding and override body parameters', async () => { + const { adapter, action, methods } = fixture(); + const response = await request(adapter, action.actionName, 'POST', { + feed: JSON.stringify(FEED), comment: JSON.stringify(COMMENT), reply: JSON.stringify(REPLY), + }, { feed: {}, comment: {}, reply: {} }); + + expect(response.status).toBe('ok'); + expect(methods.deleteReply).toHaveBeenCalledExactlyOnceWith(FEED, COMMENT, REPLY); + }); + + test('JSON request bodies and WebSocket parameters retain strict object validation', async () => { + const { adapter, action, methods } = fixture(); + const parameters = { feed: JSON.stringify(FEED), comment: JSON.stringify(COMMENT), reply: JSON.stringify(REPLY) }; + const http = await request(adapter, action.actionName, 'POST', {}, { ...parameters }); + const websocket = await action.websocketHandle({ ...parameters } as never, 'strict-echo', 'test', {} as never); + + expect(http).toMatchObject({ status: 'failed', retcode: 400 }); + expect(websocket).toMatchObject({ status: 'failed', retcode: 1400, echo: 'strict-echo' }); + expect(methods.deleteReply).not.toHaveBeenCalled(); + }); + + test('query content is decoded before rich content validation, including quoted strings', async () => { + const { adapter, action, methods } = fixture(CommentQzonePublicFeed); + const query = { feed: JSON.stringify(FEED) }; + const invalid = await request(adapter, action.actionName, 'GET', { ...query, content: '123' }); + expect(invalid).toMatchObject({ status: 'failed', retcode: 400 }); + expect(methods.addComment).not.toHaveBeenCalled(); + + const quoted = await request(adapter, action.actionName, 'GET', { ...query, content: '"123"' }); + expect(quoted.status).toBe('ok'); + expect(methods.addComment).toHaveBeenCalledExactlyOnceWith(FEED, '123'); + methods.addComment.mockClear(); + + const content = [{ type: 0, content: '正文', future: { keep: true } }]; + expect((await request(adapter, action.actionName, 'GET', { ...query, content: JSON.stringify(content) })).status).toBe('ok'); + expect(methods.addComment).toHaveBeenCalledExactlyOnceWith(FEED, content); + }); + + test('other OneBot actions retain their existing undecoded HTTP parameters', async () => { + const { adapter } = fixture(); + const handle = vi.fn().mockResolvedValue({ status: 'ok', retcode: 0, data: {} }); + Object.assign(adapter, { actions: new Map([['other_action', { handle, useStream: false }]]) }); + const parameters = { feed: JSON.stringify(FEED), content: '123' }; + + await request(adapter, 'other_action', 'GET', parameters); + + expect(handle.mock.calls[0]?.[0]).toEqual(parameters); + }); +});