feat(qzone): 添加空友爱看推荐与互动接口 (#2125)
* feat(qzone): 添加空友爱看推荐与互动接口 * fix(qzone): accept nullable public feed identities and preserve error codes * docs(qzone): remove redundant public API readme
This commit is contained in:
28 files changed
+1955
-1
No files matched your search
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<typeof fetch>().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<string, unknown>) {
|
||||
return new Response(JSON.stringify({ retcode: 0, data }));
|
||||
}
|
||||
|
||||
function requestBody (fetchMock: ReturnType<typeof setup>['fetchMock'], index = 0) {
|
||||
return JSON.parse(fetchMock.mock.calls[index]![1]!.body as string) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
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<string, string>;
|
||||
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<string, unknown>)['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);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown>,
|
||||
body: Record<string, unknown> = {},
|
||||
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);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user