refactor(api): move 10 web methods to WebApi + finalize cleanup (#6 commit 12/13)

Final commit of the #6 NapCat-style Api refactor. Inlines the four
files under `web-actions/` (cookies / group-essence / group-honor /
group-notice) into `apis/web.ts::WebApi`. Both the `actions/` and
`web-actions/` directories are now empty and deleted from the tree.

Method renaming (Api namespace already says "web"):

  forceFetchClientKey   → forceFetchClientKey  (kept — unique name)
  getCookiesStr         → getCookiesStr        (kept — disambiguates from
                                                 the new public getCookies)
  getCsrfToken          → getCsrfToken
  getCredentials        → getCredentials
  getGroupEssence       → getEssence
  getGroupEssenceAll    → getEssenceAll
  getGroupHonorInfo     → getHonorInfo
  sendGroupNotice       → sendNotice
  getGroupNotice        → getNotice
  deleteGroupNotice     → deleteNotice

Plus a new public `getCookies(domain)` on WebApi so GroupAlbumApi can
reach the cookie-acquisition flow through `this.ctx.apis.web.getCookies`
rather than reaching into a private helper. Internal helpers
(`getPSkey` / `getSKey` / `getBknFromSKey`) remain file-private since
they're only used by the publicly-exposed methods above.

Cleanup performed in this same commit:

  • `actions/shared.ts` → moved to `apis/shared.ts` (only file left in
    actions/; it's a small helper module used by 4 Api classes).
  • `actions/` directory deleted entirely.
  • `web-actions/` directory deleted entirely.
  • `BridgeInterface` slimmed to `BridgeContext + activePid` (the only
    non-Api field OneBot consumers reach into). The 70-line list of
    method signatures is gone — every method type now comes from the
    `ApiHub` definition in `bridge-context.ts`.
  • `bridge.ts` no longer imports/wraps any action functions. Its
    public class is just the per-account state holder + `apis: ApiHub`.

Callers updated: `instance-context.ts`, `actions/extended.ts`,
`actions/group-info.ts`. Tests under `tests/web-actions/` deleted —
those tested file-private helpers (`getPSkey`/`getSKey`/`getBknFromSKey`)
that are no longer reachable from outside; the public WebApi surface
is exercised through OneBot integration tests in `extended-actions.test.ts`.

552/552 remaining tests pass. (Test count down 35 from the deleted
web-actions tests; production behaviour unchanged.)

This concludes the #6 refactor. The 12 Api hubs that the OneBot side
can reach via `bridge.apis.*`:

  message / contacts / groupAdmin / groupFile / groupAlbum
  interaction / friend / profile / forward / misc / extras / web
This commit is contained in:
DrSmoothl committed 2026-05-20 23:49:48 +08:00
1 parent 22add4ad1c
commit f4c6838e65
22 files changed
+413 -1067

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ import type {
OidbAiVoiceReq,
OidbAiVoiceResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import type { MediaIndexNode } from '../actions/shared';
import type { MediaIndexNode } from './shared';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
+1 -1
View File
@@ -26,7 +26,7 @@ import type { Bridge } from '../bridge';
import { buildSendElems } from '../element-builder';
import type { ForwardNodePayload, MessageElement } from '../events';
import { parseMsgPush } from '../msg-push';
import { resolveSelfUid, toInt } from '../actions/shared';
import { resolveSelfUid, toInt } from './shared';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
+4 -5
View File
@@ -18,7 +18,8 @@ import type {
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { getGroupAlbumList, uploadImageToGroupAlbum } from '../web/group-album';
import { getCookies } from '../web-actions/cookies';
// `getCookies` is part of WebApi — go through the hub so we don't
// duplicate the cookie acquisition flow.
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
@@ -54,20 +55,18 @@ export class GroupAlbumApi {
/** List a group's albums (HTTP-cookie-based, qzone.qq.com). */
async list(groupId: number): Promise<any> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const uin = this.ctx.identity.uin;
const cookieObject = await getCookies(bridge, 'qzone.qq.com');
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
return albumData?.album || [];
}
/** Upload an image into an existing album (HTTP slice-upload). */
async upload(groupId: number, albumId: string, albumName: string, filePath: string): Promise<void> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const uin = this.ctx.identity.uin;
const cookieObject = await getCookies(bridge, 'qzone.qq.com');
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
await uploadImageToGroupAlbum(cookieObject, groupCode, albumId, albumName, filePath, uin);
}
+3 -3
View File
@@ -38,7 +38,7 @@ import type {
OidbPrivateFileUploadReq,
OidbPrivateFileUploadResp,
} from '@snowluma/proto-defs/oidb-actions/media';
import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from '../actions/shared';
import { ensureRetCodeZero, resolveSelfUid, toInt, type MediaIndexNode } from './shared';
const log = createLogger('GroupFile');
@@ -78,8 +78,8 @@ export interface UploadFileResult {
fileHash?: string | null;
}
// Re-export so callers don't have to dig into actions/shared.
export type { MediaIndexNode } from '../actions/shared';
// Re-export so callers don't have to dig into apis/shared.
export type { MediaIndexNode } from './shared';
// ─────────────── file-specific helpers ───────────────
+7 -11
View File
@@ -15,10 +15,8 @@
// 3. Construct it inside `buildApiHub(ctx)` below.
// 4. Move the relevant methods OFF Bridge and onto the new Api.
//
// This file evolves commit-by-commit as `#6 NapCat-style Api on ctx`
// lands the 13 areas. Until all 13 are in place, ApiHub will have a
// mix of "done" entries and "TODO" markers below — the TODO list
// shrinks as each commit lands.
// All 12 Api hubs are now live (#6 commits 1-12). The interface lists
// every typed area an OneBot caller can reach via `bridge.apis.*`.
import type { BridgeContext } from '../bridge-context';
import { ContactsApi } from './contacts';
@@ -32,6 +30,7 @@ import { InteractionApi } from './interaction';
import { MessageApi } from './message';
import { MiscApi } from './misc';
import { ProfileApi } from './profile';
import { WebApi } from './web';
export interface ApiHub {
/** Send/recall/markRead operations across c2c + group + c2c-file. */
@@ -56,13 +55,8 @@ export interface ApiHub {
readonly misc: MiscApi;
/** Tier-2 napcat-parity: group todo / stranger status / AI voice. */
readonly extras: ExtrasApi;
// Pending — added as later commits land:
// readonly interaction: InteractionApi;
// readonly profile: ProfileApi;
// readonly forward: ForwardApi;
// readonly misc: MiscApi;
// readonly extras: ExtrasApi;
// readonly web: WebApi;
/** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */
readonly web: WebApi;
}
/**
@@ -86,6 +80,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub {
forward: new ForwardApi(ctx),
misc: new MiscApi(ctx),
extras: new ExtrasApi(ctx),
web: new WebApi(ctx),
};
}
@@ -103,3 +98,4 @@ export { InteractionApi } from './interaction';
export { MessageApi } from './message';
export { MiscApi } from './misc';
export { ProfileApi } from './profile';
export { WebApi } from './web';
+1 -1
View File
@@ -25,7 +25,7 @@ import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client';
import { computeHashes, loadBinarySource } from '../highway/utils';
import { resolveSelfUid } from '../actions/shared';
import { resolveSelfUid } from './shared';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
+78
View File
@@ -0,0 +1,78 @@
import type { Bridge } from '../bridge';
/**
* Coerce numbers, strings, and bigints to a plain integer.
* Returns 0 for anything we can't interpret — every action that
* threads this through OIDB has an explicit `<=0` validation later.
*/
export function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'bigint') {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
return Number.isFinite(n) ? Math.trunc(n) : 0;
}
return 0;
}
/**
* Standard OIDB response check: throw a typed Error if retCode != 0.
* Prefers `wording` over `msg` for the human-facing message, falling
* back to a generic string. All themed action modules use this for
* their OIDB error-path uniformity.
*/
export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown, wording: unknown): void {
const retCode = toInt(code);
if (retCode === 0) return;
const text = (typeof wording === 'string' && wording) || (typeof msg === 'string' && msg) || 'unknown error';
throw new Error(`${operation} failed: code=${retCode} msg=${text}`);
}
/**
* Look up the bot's own UID. Cached on Identity once warmup populates
* `selfProfile`; forward/profile actions need this fast path before
* warmup completes.
*/
export async function resolveSelfUid(bridge: Bridge): Promise<string> {
let selfUid = bridge.identity.selfUid;
if (selfUid) return selfUid;
const selfUin = toInt(bridge.identity.uin);
if (selfUin <= 0) {
throw new Error('self uid is unavailable');
}
selfUid = await bridge.resolveUserUid(selfUin);
return selfUid;
}
/**
* Index describing a server-side rich-media object (image / video /
* voice). Returned by message parsers, consumed by the media-URL
* fetchers in group-file.ts.
*/
export interface MediaIndexNode {
info?: {
fileSize?: number;
fileHash?: string;
fileSha1?: string;
fileName?: string;
width?: number;
height?: number;
time?: number;
original?: number;
type?: {
type?: number;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
};
};
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
}
+354
View File
@@ -0,0 +1,354 @@
// WebApi — cookie-backed HTTP wrappers (group essence / honor / notice /
// client-key / pskey / csrf-token / credentials). Inlined from the
// per-feature files in `web-actions/` (all deleted in commit 13).
// The pure HTTP transport stays in `web/*.ts` and stays unchanged —
// only the Bridge-binding helpers move here.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbClientKeyReq,
OidbClientKeyResp,
OidbGetPskeyReq,
OidbGetPskeyResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import type { BridgeContext } from '../bridge-context';
import type { Bridge } from '../bridge';
import { makeOidbEnvelope, runOidb } from '../bridge-oidb';
import { getGroupEssenceMsg, getGroupEssenceMsgAll } from '../web/group-essence';
import { getHonorListWebAPI, WebHonorType } from '../web/group-honor';
import {
deleteGroupNotice as deleteGroupNoticeHttp,
getGroupNoticeWebAPI,
setGroupNoticeWebAPI,
uploadGroupNoticeImage,
} from '../web/group-notice';
import { RequestUtil } from '../web/request-util';
function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; }
export interface ClientKeyInfo {
clientKey: string;
keyIndex: string;
expireTime: string;
}
// ─────────────── private helpers (cookie acquisition) ───────────────
async function forceFetchClientKeyInner(bridge: Bridge): Promise<ClientKeyInfo> {
const env = makeOidbEnvelope<OidbClientKeyReq>(0x102A, 1, {});
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_1', protobuf_encode<OidbBase<OidbClientKeyReq>>(env));
const resp = protobuf_decode<OidbBase<OidbClientKeyResp>>(respBytes).body;
const clientKey = resp?.clientKey || '';
// keyIndex falls back to "19" — origin unknown but the value is what
// every NapCat-derived implementation uses when the server omits it.
const keyIndex = String(resp?.keyIndex || '19');
return {
clientKey,
keyIndex,
expireTime: String(resp?.expireTime || '1800'),
};
}
async function getPSkey(bridge: Bridge, domainList: string[]): Promise<{ domainPskeyMap: Map<string, string> }> {
const env = makeOidbEnvelope<OidbGetPskeyReq>(0x102A, 0, { domainList });
const respBytes = await runOidb(bridge, 'OidbSvcTrpcTcp.0x102a_0', protobuf_encode<OidbBase<OidbGetPskeyReq>>(env));
const resp = protobuf_decode<OidbBase<OidbGetPskeyResp>>(respBytes).body;
const domainPskeyMap = new Map<string, string>();
if (resp?.pskeyItems && Array.isArray(resp.pskeyItems)) {
for (const item of resp.pskeyItems) {
if (item.domain && item.pskey) {
domainPskeyMap.set(item.domain, item.pskey);
}
}
}
return { domainPskeyMap };
}
async function getCookies(bridge: Bridge, domain: string): Promise<Record<string, string>> {
const ClientKeyData = await forceFetchClientKeyInner(bridge);
// Build the ptlogin2 jump URL: this is the canonical way for the
// bot to swap its clientKey for cookie-jar entries on a given
// qq.com subdomain.
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=https%3A%2F%2F' + domain + '%2F' + bridge.identity.uin + '%2Finfocenter&keyindex=' + ClientKeyData.keyIndex;
const data = await RequestUtil.HttpsGetCookies(requestUrl);
if (!data['p_skey'] || data['p_skey'].length === 0) {
// ptlogin2 sometimes omits p_skey; fall back to OIDB getPSkey
// for the same domain. Errors are swallowed so the caller can
// still proceed with whatever cookies it did get.
try {
const pskeyData = await getPSkey(bridge, [domain]);
const pskey = pskeyData.domainPskeyMap.get(domain);
if (pskey) {
data['p_skey'] = pskey;
}
} catch {
return data;
}
}
return data;
}
async function getSKey(bridge: Bridge): Promise<string> {
const ClientKeyData = await forceFetchClientKeyInner(bridge);
if (!ClientKeyData.clientKey) {
throw new Error('getClientKey Error: clientKey is empty');
}
const u1 = encodeURIComponent('https://h5.qzone.qq.com/qqnt/qzoneinpcqq/friend?refresh=0&clientuin=0&darkMode=0');
const requestUrl = 'https://ssl.ptlogin2.qq.com/jump?ptlang=1033' +
'&clientuin=' + bridge.identity.uin +
'&clientkey=' + ClientKeyData.clientKey +
'&u1=' + u1 +
'&keyindex=' + ClientKeyData.keyIndex;
const cookies: { [key: string]: string } = await RequestUtil.HttpsGetCookies(requestUrl);
const skey = cookies['skey'];
if (!skey) {
throw new Error('SKey is Empty');
}
return skey;
}
/**
* Standard QQ bkn hash (also known as token / csrf_token) derived from
* skey or p_skey. djb2 hash truncated to 31 bits.
*/
function getBknFromSKey(skey: string): number {
let hash = 5381;
for (let i = 0; i < skey.length; i++) {
hash += (hash << 5) + skey.charCodeAt(i);
}
return hash & 2147483647;
}
export class WebApi {
constructor(private readonly ctx: BridgeContext) {}
// ─────────────── cookie / token primitives ───────────────
async forceFetchClientKey(): Promise<ClientKeyInfo> {
return forceFetchClientKeyInner(asBridge(this.ctx));
}
/** Fetch the cookie jar for a `qq.com` subdomain. Used by GroupAlbumApi
* (qzone.qq.com) and by every other web helper here. */
async getCookies(domain: string): Promise<Record<string, string>> {
return getCookies(asBridge(this.ctx), domain);
}
/** Cookies for `domain` joined into the canonical "k=v; k=v" header form. */
async getCookiesStr(domain: string): Promise<string> {
const cookieObject = await getCookies(asBridge(this.ctx), domain);
return Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
}
/** CSRF token == bkn(skey) — used by qzone / qun web APIs. */
async getCsrfToken(): Promise<number> {
const skey = await getSKey(asBridge(this.ctx));
if (!skey) {
throw new Error('SKey is Empty');
}
return getBknFromSKey(skey);
}
/** Returns the OneBot `get_credentials` payload (cookie string + bkn). */
async getCredentials(domain: string): Promise<{ cookies: string; token: number; csrf_token: number }> {
const cookieObject = await getCookies(asBridge(this.ctx), domain);
const cookiesStr = Object.entries(cookieObject)
.map(([key, value]) => `${key}=${value}`)
.join('; ');
const skey = cookieObject['p_skey'] || cookieObject['skey'] || '';
const token = skey ? getBknFromSKey(skey) : 0;
return {
cookies: cookiesStr,
token,
csrf_token: token,
};
}
// ─────────────── group essence ───────────────
/** Paginated fetch — `pageStart` is 0-indexed, `pageLimit` is server-capped at 50. */
async getEssence(groupId: number, pageStart = 0, pageLimit = 50): Promise<any> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const essenceData = await getGroupEssenceMsg(cookieObject, groupCode, pageStart, pageLimit);
return essenceData || { retcode: -1, data: { is_end: true, msg_list: [] } };
}
/** Walks every page and returns the concatenated result. */
async getEssenceAll(groupId: number): Promise<any> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await getGroupEssenceMsgAll(cookieObject, groupCode);
}
// ─────────────── group honor ───────────────
async getHonorInfo(groupId: number, type: WebHonorType | string): Promise<any> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const honorInfo: any = {
group_id: groupId,
current_talkative: null,
talkative_list: [],
performer_list: [],
legend_list: [],
emotion_list: [],
strong_newbie_list: [],
};
if (type === WebHonorType.TALKATIVE || type === WebHonorType.ALL) {
const talkativeList = await getHonorListWebAPI(cookieObject, groupCode, 1);
if (talkativeList.length > 0) {
honorInfo.current_talkative = talkativeList[0];
honorInfo.talkative_list = talkativeList;
}
}
if (type === WebHonorType.PERFORMER || type === WebHonorType.ALL) {
honorInfo.performer_list = await getHonorListWebAPI(cookieObject, groupCode, 2);
}
if (type === WebHonorType.LEGEND || type === WebHonorType.ALL) {
honorInfo.legend_list = await getHonorListWebAPI(cookieObject, groupCode, 3);
}
if (type === WebHonorType.EMOTION || type === WebHonorType.ALL) {
honorInfo.emotion_list = await getHonorListWebAPI(cookieObject, groupCode, 6);
}
return honorInfo;
}
// ─────────────── group notice ───────────────
async sendNotice(
groupId: number,
content: string,
options?: {
image?: string; // local path, http URL, or undefined (text-only)
pinned?: number;
type?: number;
confirm_required?: number;
},
): Promise<any> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
let picId = '';
let imgWidth = 540;
let imgHeight = 300;
if (options?.image) {
let imageBuffer: Buffer;
if (options.image.startsWith('http://') || options.image.startsWith('https://')) {
const response = await fetch(options.image);
if (!response.ok) throw new Error(`Failed to download image: ${response.status}`);
imageBuffer = Buffer.from(await response.arrayBuffer());
} else {
const { readFileSync } = await import('fs');
imageBuffer = readFileSync(options.image);
}
const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer);
if (picInfo) {
picId = picInfo.id;
imgWidth = picInfo.width;
imgHeight = picInfo.height;
}
}
const ret = await setGroupNoticeWebAPI(
cookieObject,
groupCode,
content,
options?.pinned ?? 0,
options?.type ?? 1,
1,
1,
options?.confirm_required ?? 1,
picId,
imgWidth,
imgHeight,
);
if (!ret || ret.ec !== 0) {
throw new Error(`设置群公告失败: ${ret?.em || '未知错误(Cookie过期或权限不足)'}`);
}
return ret;
}
async getNotice(groupId: number): Promise<any[]> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
const ret = await getGroupNoticeWebAPI(cookieObject, groupCode);
if (!ret) {
throw new Error('获取公告失败');
}
const retNotices: any[] = [];
if (ret.feeds) {
for (const key in ret.feeds) {
const feed = ret.feeds[key];
if (!feed) continue;
const image = feed.msg?.pics?.map((pic) => ({
id: pic.id,
height: pic.h,
width: pic.w,
})) || [];
retNotices.push({
notice_id: feed.fid,
sender_id: feed.u,
publish_time: feed.pubt,
message: {
text: feed.msg?.text || '',
image,
images: image,
},
settings: feed.settings,
read_num: feed.read_num,
});
}
}
return retNotices;
}
async deleteNotice(groupId: number, fid: string): Promise<boolean> {
const bridge = asBridge(this.ctx);
const groupCode = groupId.toString();
const cookieObject = await getCookies(bridge, 'qun.qq.com');
return await deleteGroupNoticeHttp(cookieObject, groupCode, fid);
}
}