Files
SnowLuma/packages/core/tests/web-actions/cookies.test.ts
T
DrSmoothl 069548918b refactor(core): split web-actions.ts into themed modules + barrel
web-actions.ts was a 330-line monolith with 14 exported functions
covering 4 distinct themes: cookie/credential primitives (the 8
functions every web call builds on), group honor leaderboards, group
essence (highlighted messages), and group notices. Same shape problem
the OIDB bridge-actions.ts split fixed three commits back, just smaller.

New layout under packages/core/src/bridge/web-actions/ :

  cookies.ts        (161 lines, 8 fns)
    forceFetchClientKey / getPSkey / getCookies / getSKey /
    getBknFromSKey / getCookiesStr / getCsrfToken / getCredentials
    — the ptlogin2-jump + bkn-derivation primitives.

  group-honor.ts    (45 lines, 1 fn)
    getGroupHonorInfo (talkative / performer / legend / emotion / ALL)

  group-essence.ts  (27 lines, 2 fns)
    getGroupEssence (paged) + getGroupEssenceAll

  group-notice.ts   (118 lines, 3 fns)
    sendGroupNotice (with optional image-from-URL-or-file upload),
    getGroupNotice (OneBot shape flatten), deleteGroupNoticeByFid

  index.ts          (27 lines)
    Barrel re-export. `bridge.ts` keeps its existing
    `from './web-actions'` import — TS resolves the directory's
    index.ts so no caller changes.

The lower-level web/* helpers (request-util, group-essence,
group-honor, group-notice) stay where they were — they're the
direct HTTP/cookie wrappers, distinct from these Bridge-level
orchestrators.

Behavior preserved end-to-end. Same ptlogin2 URL construction,
same fall-back-to-getPSkey-when-p_skey-missing path in getCookies,
same default keyIndex='19' / expireTime='1800', same djb2 bkn hash,
same NapCat-derived default 540x300 notice image dimensions, same
chinese error messages ('设置群公告失败', '获取公告失败').

Adds 35 happy-path tests across 4 new files in tests/web-actions/ :

  cookies         (13)  forceFetchClientKey response shape + defaults,
                        getPSkey pskeyItems folding, getCookies ptlogin2
                        URL params, p_skey fallback path (both success
                        and throwing), getSKey success / no-clientKey /
                        no-skey throws, getBknFromSKey determinism +
                        range, getCookiesStr formatting, getCsrfToken
                        composition, getCredentials full + empty paths.
  group-honor      (7)  TALKATIVE list vs empty list behaviour,
                        PERFORMER / LEGEND / EMOTION per-type dispatch,
                        ALL fetches all four types, groupId stringification.
  group-essence    (4)  pageStart/pageLimit forwarding, defaults,
                        null-result fallback envelope, getAll delegation.
  group-notice    (11)  text-only dispatch + defaults, options override,
                        http image fetch + upload + thread, fetch failure,
                        ec≠0 surfaces em, generic error fallback,
                        getGroupNotice feed flattening + pics mapping,
                        null-result throw, empty-feeds case,
                        deleteGroupNoticeByFid argument forwarding.

Tests use vi.mock on bridge-oidb / web/request-util / web/group-*
to isolate each theme from real HTTP, mirroring the pattern from
the bridge-actions split.

369 tests pass (was 334); 3 stability runs, same pre-existing
macOS-arm64 websocket addon failure, unrelated.
2026-05-12 20:49:36 +08:00

187 lines
7.3 KiB
TypeScript

import { describe, it, expect, vi, beforeEach } from 'vitest';
// Mock the OIDB shim so we can control what `forceFetchClientKey` and
// `getPSkey` see without standing up a Bridge.
vi.mock('../../src/bridge/bridge-oidb', () => ({
sendOidbAndDecode: vi.fn(async () => ({})),
sendOidbAndCheck: vi.fn(async () => undefined),
resolveUserUid: vi.fn(async () => 'uid'),
makeOidbRequest: vi.fn(() => new Uint8Array(0)),
}));
// Mock the actual HTTP cookie fetch.
vi.mock('../../src/bridge/web/request-util', () => ({
RequestUtil: {
HttpsGetCookies: vi.fn(async () => ({}) as Record<string, string>),
},
}));
import * as oidb from '../../src/bridge/bridge-oidb';
import { RequestUtil } from '../../src/bridge/web/request-util';
import {
forceFetchClientKey,
getPSkey,
getCookies,
getSKey,
getBknFromSKey,
getCookiesStr,
getCsrfToken,
getCredentials,
} from '../../src/bridge/web-actions/cookies';
const bridge = { qqInfo: { uin: '10001' } } as any;
describe('cookies — forceFetchClientKey', () => {
beforeEach(() => { vi.mocked(oidb.sendOidbAndDecode).mockReset(); });
it('returns clientKey + keyIndex + expireTime from the OIDB response', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
clientKey: 'ck-xyz', keyIndex: 42, expireTime: 3600,
});
const out = await forceFetchClientKey(bridge);
expect(out).toEqual({ clientKey: 'ck-xyz', keyIndex: '42', expireTime: '3600' });
});
it('falls back to default keyIndex/expireTime when the response omits them', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck' });
const out = await forceFetchClientKey(bridge);
expect(out).toEqual({ clientKey: 'ck', keyIndex: '19', expireTime: '1800' });
});
});
describe('cookies — getPSkey', () => {
beforeEach(() => { vi.mocked(oidb.sendOidbAndDecode).mockReset(); });
it('folds pskeyItems into a domain → pskey Map', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({
pskeyItems: [
{ domain: 'qun.qq.com', pskey: 'psk-a' },
{ domain: 'qzone.qq.com', pskey: 'psk-b' },
{ domain: 'corrupt', pskey: '' },
],
});
const { domainPskeyMap } = await getPSkey(bridge, ['qun.qq.com', 'qzone.qq.com']);
expect(domainPskeyMap.get('qun.qq.com')).toBe('psk-a');
expect(domainPskeyMap.get('qzone.qq.com')).toBe('psk-b');
expect(domainPskeyMap.has('corrupt')).toBe(false); // empty pskey skipped
});
});
describe('cookies — getCookies', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockReset();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
});
it('builds the ptlogin2 jump URL with the right query params', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({
p_skey: 'psk',
skey: 'sk',
});
const out = await getCookies(bridge, 'qun.qq.com');
expect(out).toEqual({ p_skey: 'psk', skey: 'sk' });
const url = vi.mocked(RequestUtil.HttpsGetCookies).mock.calls[0]![0];
expect(url).toContain('ssl.ptlogin2.qq.com/jump');
expect(url).toContain('clientuin=10001');
expect(url).toContain('clientkey=ck');
expect(url).toContain('keyindex=19');
});
it('falls back to getPSkey when p_skey is missing in the cookie response', async () => {
vi.mocked(oidb.sendOidbAndDecode)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 }) // forceFetchClientKey
.mockResolvedValueOnce({ // getPSkey
pskeyItems: [{ domain: 'qun.qq.com', pskey: 'psk-from-oidb' }],
});
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
const out = await getCookies(bridge, 'qun.qq.com');
expect(out['p_skey']).toBe('psk-from-oidb');
});
it('returns whatever cookies it got if getPSkey fallback throws', async () => {
vi.mocked(oidb.sendOidbAndDecode)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockRejectedValueOnce(new Error('pskey unavailable'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'sk' });
const out = await getCookies(bridge, 'qun.qq.com');
expect(out).toEqual({ skey: 'sk' }); // no p_skey, but no throw
});
});
describe('cookies — getSKey', () => {
beforeEach(() => {
vi.mocked(oidb.sendOidbAndDecode).mockReset();
vi.mocked(RequestUtil.HttpsGetCookies).mockReset();
});
it('returns skey from the qzone-targeted ptlogin2 jump', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'the-skey' });
expect(await getSKey(bridge)).toBe('the-skey');
});
it('throws when clientKey comes back empty', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: '' });
await expect(getSKey(bridge)).rejects.toThrow(/clientKey is empty/);
});
it('throws when the jump response omits skey', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
await expect(getSKey(bridge)).rejects.toThrow(/SKey is Empty/);
});
});
describe('cookies — pure helpers', () => {
it('getBknFromSKey: deterministic djb2 truncated to 31 bits', () => {
// Two calls on the same input → same number; different input → different.
const a = getBknFromSKey('hello');
const b = getBknFromSKey('hello');
const c = getBknFromSKey('world');
expect(a).toBe(b);
expect(a).not.toBe(c);
expect(a).toBeGreaterThanOrEqual(0);
expect(a).toBeLessThanOrEqual(2147483647);
});
it('getCookiesStr: joins cookies with "; "', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCookiesStr(bridge, 'qun.qq.com');
expect(out).toBe('p_skey=p; skey=s');
});
it('getCsrfToken: combines getSKey + getBknFromSKey', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ skey: 'abc' });
const csrf = await getCsrfToken(bridge);
expect(csrf).toBe(getBknFromSKey('abc'));
});
it('getCredentials: returns { cookies, token, csrf_token } with bkn(p_skey)', async () => {
vi.mocked(oidb.sendOidbAndDecode).mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 });
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({ p_skey: 'p', skey: 's' });
const out = await getCredentials(bridge, 'qun.qq.com');
expect(out.cookies).toBe('p_skey=p; skey=s');
expect(out.token).toBe(getBknFromSKey('p'));
expect(out.csrf_token).toBe(out.token);
});
it('getCredentials: token is 0 when no skey/p_skey available', async () => {
vi.mocked(oidb.sendOidbAndDecode)
.mockResolvedValueOnce({ clientKey: 'ck', keyIndex: 19 })
.mockRejectedValueOnce(new Error('no pskey'));
vi.mocked(RequestUtil.HttpsGetCookies).mockResolvedValueOnce({});
const out = await getCredentials(bridge, 'qun.qq.com');
expect(out.token).toBe(0);
expect(out.cookies).toBe('');
});
});