fix(onebot): TierB ① — propagate signed-list errors instead of fail-soft []

Adversarial review: swallowing transport/auth errors to [] made an expired
cookie indistinguishable from a group with zero sign-ins, and left the
onebot action's try/catch as dead code. Now getDaySignedListWebAPI
propagates transport errors and throws on a page-less response (matches
NapCat, which throws on missing page) — so auth failure becomes a proper
'failed' OneBot response; a genuinely empty group still maps to [].

Also: cover the previously-untested HTTP layer (exact URL + g_tk + json
body + error propagation), harden the rank de-skew with Number(), and
document the deliberate local-date (vs NapCat UTC) choice for dayYmd.
This commit is contained in:
DrSmoothl
2026-06-18 19:28:52 +08:00
parent 36d557e5ea
commit 9b787dfdc1
2 changed files with 79 additions and 30 deletions
+39 -28
View File
@@ -45,20 +45,32 @@ export function mapDaySignedList(data: DaySignedListResponse): SignedListMember[
user_id: Number(info.uid),
nick: info.uidGroupNick,
time: Number(info.signedTimeStamp),
rank: (info.signInRank - 1) / 2 + 1,
// signInRank arrives on a doubled/offset scale (1,3,5,…); de-skew to a
// human 1-based rank. Number() guards against the server sending it as
// a string, which trpc endpoints occasionally do.
rank: (Number(info.signInRank) - 1) / 2 + 1,
}));
}
/** YYYYMMDD for the given Date (defaults to today), the form the endpoint wants. */
function yyyymmdd(d: Date = new Date()): string {
// Local date (not UTC) on purpose: "today's 打卡" is a CN-clock concept,
// so the local calendar day is the right one near the UTC midnight seam.
// (NapCat uses UTC here; this is a deliberate divergence.)
return `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, '0')}${String(d.getDate()).padStart(2, '0')}`;
}
/**
* Fetch today's group sign-in (打卡) list via the qun.qq.com web API.
* Mirrors NapCat's `getDaySignedList`: POST JSON to the signin trpc
* endpoint with `g_tk` derived from p_skey and a minimal cookie jar.
* Returns the mapped list, or [] on any transport / shape failure.
* endpoint with `g_tk` derived from p_skey and the cookie jar.
*
* Errors PROPAGATE (transport failure, or a page-less response — which the
* endpoint returns when auth/cookie is bad): we do NOT swallow them to [],
* because that would make an expired cookie indistinguishable from a group
* with zero sign-ins. A genuinely empty group returns page→empty infos,
* which maps to []. The caller (onebot action) turns a throw into a failed
* response. Matches NapCat, which throws on a missing page.
*/
export async function getDaySignedListWebAPI(
cookieObject: Record<string, string>,
@@ -66,30 +78,29 @@ export async function getDaySignedListWebAPI(
selfUin: string,
day?: Date,
): Promise<SignedListMember[]> {
try {
const gtk = getBknFromCookie(cookieObject);
const url = `https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${gtk}`;
const body = {
dayYmd: yyyymmdd(day),
offset: 0,
limit: 100,
uid: selfUin,
groupId: groupCode,
};
const data = await RequestUtil.HttpGetJson<DaySignedListResponse>(
url,
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/json',
},
true,
true,
);
return mapDaySignedList(data);
} catch (e) {
log.warn('getDaySignedList failed (group=%s): %s', groupCode, e instanceof Error ? (e.stack ?? e.message) : String(e));
return [];
const gtk = getBknFromCookie(cookieObject);
const url = `https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${gtk}`;
const body = {
dayYmd: yyyymmdd(day),
offset: 0,
limit: 100,
uid: selfUin,
groupId: groupCode,
};
const data = await RequestUtil.HttpGetJson<DaySignedListResponse>(
url,
'POST',
body,
{
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/json',
},
true,
true,
);
if (!data.response?.page) {
log.warn('getDaySignedList: no page in response (group=%s) — likely auth/cookie failure', groupCode);
throw new Error('无法获取该群组打卡列表');
}
return mapDaySignedList(data);
}
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest';
import { mapDaySignedList, type DaySignedInfo, type DaySignedListResponse } from '@snowluma/protocol/web/group-signin';
import { describe, it, expect, vi, afterEach } from 'vitest';
import { getDaySignedListWebAPI, mapDaySignedList, type DaySignedInfo, type DaySignedListResponse } from '@snowluma/protocol/web/group-signin';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
// The signed-in list comes back from qun.qq.com's GetDaySignedList trpc
// endpoint nested under response.page[0].infos. We pin the field renames
@@ -33,3 +34,40 @@ describe('group-signin / mapDaySignedList', () => {
expect(mapDaySignedList({ retCode: 0, response: {}, funcCode: 0 })).toEqual([]);
});
});
describe('group-signin / getDaySignedListWebAPI (HTTP layer)', () => {
afterEach(() => vi.restoreAllMocks());
const cookies = { p_skey: 'PSK', skey: 'SK', uin: 'o10000', p_uin: 'o10000' };
// g_tk = djb2-31bit over p_skey 'PSK'
const expectedGtk = (() => { let h = 5381; for (const c of 'PSK') h += (h << 5) + c.charCodeAt(0); return (h & 0x7FFFFFFF).toString(); })();
it('POSTs the exact url + json body and maps the result', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({
retCode: 0, funcCode: 0,
response: { page: [{ infos: [{ uid: '777', uidGroupNick: 'Z', signedTimeStamp: '1700000000', signInRank: 3 }], offset: 0, total: 1 }] },
} satisfies DaySignedListResponse as never);
const out = await getDaySignedListWebAPI(cookies, '54321', '10000', new Date(2026, 0, 2));
expect(out).toEqual([{ user_id: 777, nick: 'Z', time: 1700000000, rank: 2 }]);
const [url, method, body, headers, isJsonRet, isArgJson] = spy.mock.calls[0]!;
expect(url).toBe(`https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${expectedGtk}`);
expect(method).toBe('POST');
expect(body).toEqual({ dayYmd: '20260102', offset: 0, limit: 100, uid: '10000', groupId: '54321' });
expect((headers as Record<string, string>)['Content-Type']).toBe('application/json');
expect((headers as Record<string, string>).Cookie).toContain('p_skey=PSK');
expect(isJsonRet).toBe(true);
expect(isArgJson).toBe(true);
});
it('propagates a transport error instead of swallowing it to []', async () => {
vi.spyOn(RequestUtil, 'HttpGetJson').mockRejectedValue(new Error('Unexpected status code: 403'));
await expect(getDaySignedListWebAPI(cookies, '1', '1')).rejects.toThrow('403');
});
it('throws when the response has no page (auth/cookie failure), not []', async () => {
vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ retCode: 0, funcCode: 0, response: {} } satisfies DaySignedListResponse as never);
await expect(getDaySignedListWebAPI(cookies, '1', '1')).rejects.toThrow('无法获取该群组打卡列表');
});
});