Skip to content

Commit 4170e11

Browse files
authored
fix(qqbot): keep channel API calls on the active account [AI] (#118575)
* fix(qqbot): bind channel API tool to active account * fix(qqbot): scope active account binding to QQ turns * fix(qqbot): reject disabled channel API accounts
1 parent 6d88ec5 commit 4170e11

2 files changed

Lines changed: 225 additions & 45 deletions

File tree

Lines changed: 168 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,168 @@
1+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
2+
import type {
3+
AnyAgentTool,
4+
OpenClawPluginApi,
5+
OpenClawPluginToolContext,
6+
} from "openclaw/plugin-sdk/core";
7+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
8+
9+
const { fetchWithSsrFGuardMock, getAccessTokenMock } = vi.hoisted(() => ({
10+
fetchWithSsrFGuardMock: vi.fn(),
11+
getAccessTokenMock: vi.fn(),
12+
}));
13+
14+
vi.mock("openclaw/plugin-sdk/ssrf-runtime", async (importOriginal) => {
15+
const actual = await importOriginal<typeof import("openclaw/plugin-sdk/ssrf-runtime")>();
16+
return { ...actual, fetchWithSsrFGuard: fetchWithSsrFGuardMock };
17+
});
18+
19+
vi.mock("../../engine/messaging/sender.js", async (importOriginal) => {
20+
const actual = await importOriginal<typeof import("../../engine/messaging/sender.js")>();
21+
return { ...actual, getAccessToken: getAccessTokenMock };
22+
});
23+
24+
import { ensurePlatformAdapter } from "../bootstrap.js";
25+
import { registerChannelTool } from "./channel.js";
26+
27+
const cfg = {
28+
channels: {
29+
qqbot: {
30+
appId: "app-a",
31+
clientSecret: "secret-a",
32+
accounts: {
33+
bot2: {
34+
appId: "app-b",
35+
clientSecret: "secret-b",
36+
},
37+
},
38+
},
39+
},
40+
} as OpenClawConfig;
41+
42+
function registerToolFactory(
43+
config: OpenClawConfig = cfg,
44+
): (context: OpenClawPluginToolContext) => AnyAgentTool | null {
45+
let factory: ((context: OpenClawPluginToolContext) => AnyAgentTool | null) | undefined;
46+
const api = {
47+
config,
48+
registerTool(
49+
tool: AnyAgentTool | ((context: OpenClawPluginToolContext) => AnyAgentTool | null),
50+
) {
51+
if (typeof tool === "function") {
52+
factory = tool;
53+
}
54+
},
55+
} as unknown as OpenClawPluginApi;
56+
registerChannelTool(api);
57+
if (!factory) {
58+
throw new Error("Expected QQBot channel API tool factory");
59+
}
60+
return factory;
61+
}
62+
63+
describe("bridge/tools/channel", () => {
64+
beforeEach(() => {
65+
ensurePlatformAdapter();
66+
getAccessTokenMock.mockImplementation(
67+
async (appId: string, secret: string) => `token-for-${appId}-${secret}`,
68+
);
69+
fetchWithSsrFGuardMock.mockResolvedValue({
70+
response: new Response(JSON.stringify([{ id: "guild-1" }]), { status: 200 }),
71+
release: vi.fn(async () => {}),
72+
});
73+
});
74+
75+
afterEach(() => {
76+
getAccessTokenMock.mockReset();
77+
fetchWithSsrFGuardMock.mockReset();
78+
});
79+
80+
it("uses the active QQBot account for token acquisition and API authorization", async () => {
81+
const tool = registerToolFactory()({ messageChannel: "qqbot", agentAccountId: "bot2" });
82+
expect(tool).not.toBeNull();
83+
84+
await tool?.execute("call-b", { method: "GET", path: "/users/@me/guilds" });
85+
86+
expect(getAccessTokenMock).toHaveBeenCalledWith("app-b", "secret-b");
87+
expect(getAccessTokenMock).not.toHaveBeenCalledWith("app-a", "secret-a");
88+
expect(fetchWithSsrFGuardMock).toHaveBeenCalledWith(
89+
expect.objectContaining({
90+
init: expect.objectContaining({
91+
headers: expect.objectContaining({
92+
Authorization: "QQBot token-for-app-b-secret-b",
93+
}),
94+
}),
95+
}),
96+
);
97+
});
98+
99+
it("uses the configured default account without an active account", async () => {
100+
const configuredDefault = {
101+
...cfg,
102+
channels: {
103+
qqbot: {
104+
...cfg.channels?.qqbot,
105+
defaultAccount: "bot2",
106+
},
107+
},
108+
} as OpenClawConfig;
109+
const tool = registerToolFactory(configuredDefault)({});
110+
expect(tool).not.toBeNull();
111+
112+
await tool?.execute("call-default", { method: "GET", path: "/users/@me/guilds" });
113+
114+
expect(getAccessTokenMock).toHaveBeenCalledWith("app-b", "secret-b");
115+
expect(fetchWithSsrFGuardMock).toHaveBeenCalledWith(
116+
expect.objectContaining({
117+
init: expect.objectContaining({
118+
headers: expect.objectContaining({
119+
Authorization: "QQBot token-for-app-b-secret-b",
120+
}),
121+
}),
122+
}),
123+
);
124+
});
125+
126+
it("does not expose the tool when the active account has no credentials", () => {
127+
expect(
128+
registerToolFactory()({ messageChannel: "qqbot", agentAccountId: "missing" }),
129+
).toBeNull();
130+
expect(getAccessTokenMock).not.toHaveBeenCalled();
131+
});
132+
133+
it("does not expose the tool when the active account is disabled", () => {
134+
const disabledAccount = {
135+
...cfg,
136+
channels: {
137+
qqbot: {
138+
...cfg.channels?.qqbot,
139+
accounts: {
140+
bot2: {
141+
...cfg.channels?.qqbot?.accounts?.bot2,
142+
enabled: false,
143+
},
144+
},
145+
},
146+
},
147+
} as OpenClawConfig;
148+
149+
expect(
150+
registerToolFactory(disabledAccount)({
151+
messageChannel: "qqbot",
152+
agentAccountId: "bot2",
153+
}),
154+
).toBeNull();
155+
expect(getAccessTokenMock).not.toHaveBeenCalled();
156+
expect(fetchWithSsrFGuardMock).not.toHaveBeenCalled();
157+
});
158+
159+
it("does not treat another channel's account ID as a QQBot account", async () => {
160+
const tool = registerToolFactory()({ messageChannel: "discord", agentAccountId: "bot2" });
161+
expect(tool).not.toBeNull();
162+
163+
await tool?.execute("call-discord", { method: "GET", path: "/users/@me/guilds" });
164+
165+
expect(getAccessTokenMock).toHaveBeenCalledWith("app-a", "secret-a");
166+
expect(getAccessTokenMock).not.toHaveBeenCalledWith("app-b", "secret-b");
167+
});
168+
});
Lines changed: 57 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
// Qqbot plugin module implements channel behavior.
2-
import type { OpenClawPluginApi } from "openclaw/plugin-sdk/core";
2+
import type {
3+
AnyAgentTool,
4+
OpenClawPluginApi,
5+
OpenClawPluginToolContext,
6+
} from "openclaw/plugin-sdk/core";
37
import { ChannelApiSchema, executeChannelApi } from "../../engine/tools/channel-api.js";
48
import type { ChannelApiParams } from "../../engine/tools/channel-api.js";
59
import { listQQBotAccountIds, resolveQQBotAccount } from "../config.js";
@@ -11,54 +15,62 @@ import { listQQBotAccountIds, resolveQQBotAccount } from "../config.js";
1115
* channel APIs. Agents learn endpoint details from the skill docs and
1216
* send requests through this proxy.
1317
*/
14-
export function registerChannelTool(api: OpenClawPluginApi): void {
15-
const cfg = api.config;
16-
if (!cfg) {
17-
return;
18-
}
19-
20-
const accountIds = listQQBotAccountIds(cfg);
21-
if (accountIds.length === 0) {
22-
return;
18+
function createChannelTool(
19+
cfg: NonNullable<OpenClawPluginApi["config"]>,
20+
context: OpenClawPluginToolContext,
21+
): AnyAgentTool | null {
22+
// Bind credentials when the per-run tool is built; a process-wide account
23+
// selection would let one QQBot ingress account exercise another account's API authority.
24+
const activeConfig = context.runtimeConfig ?? cfg;
25+
const activeChannel = context.messageChannel ?? context.deliveryContext?.channel;
26+
const account = resolveQQBotAccount(
27+
activeConfig,
28+
activeChannel === "qqbot"
29+
? (context.agentAccountId ?? context.deliveryContext?.accountId)
30+
: undefined,
31+
);
32+
if (!account.enabled || !account.appId || !account.clientSecret) {
33+
return null;
2334
}
2435

25-
const firstAccountId = accountIds[0];
26-
const account = resolveQQBotAccount(cfg, firstAccountId);
36+
return {
37+
name: "qqbot_channel_api",
38+
label: "QQBot Channel API",
39+
description:
40+
"Authenticated HTTP proxy for QQ Open Platform channel APIs. " +
41+
"Use write and delete endpoints only after explicit user intent; DELETE requires confirmed=true, and bulk deletes require bulkConfirmed=true after confirming the exact target. " +
42+
"Common endpoints: " +
43+
"list guilds GET /users/@me/guilds | " +
44+
"list channels GET /guilds/{guild_id}/channels | " +
45+
"get channel GET /channels/{channel_id} | " +
46+
"create channel POST /guilds/{guild_id}/channels | " +
47+
"list members GET /guilds/{guild_id}/members?after=0&limit=100 | " +
48+
"get member GET /guilds/{guild_id}/members/{user_id} | " +
49+
"list threads GET /channels/{channel_id}/threads | " +
50+
"create thread PUT /channels/{channel_id}/threads | " +
51+
"create announce POST /guilds/{guild_id}/announces | " +
52+
"create schedule POST /channels/{channel_id}/schedules. " +
53+
"See the qqbot-channel skill for full endpoint details.",
54+
parameters: ChannelApiSchema,
55+
async execute(_toolCallId, params) {
56+
const { getAccessToken } = await import("../../engine/messaging/sender.js");
57+
const accessToken = await getAccessToken(account.appId, account.clientSecret);
58+
return executeChannelApi(params as ChannelApiParams, {
59+
accessToken,
60+
cfg: activeConfig,
61+
accountId: account.accountId,
62+
});
63+
},
64+
};
65+
}
2766

28-
if (!account.appId || !account.clientSecret) {
67+
export function registerChannelTool(api: OpenClawPluginApi): void {
68+
const cfg = api.config;
69+
if (!cfg || listQQBotAccountIds(cfg).length === 0) {
2970
return;
3071
}
3172

32-
api.registerTool(
33-
{
34-
name: "qqbot_channel_api",
35-
label: "QQBot Channel API",
36-
description:
37-
"Authenticated HTTP proxy for QQ Open Platform channel APIs. " +
38-
"Use write and delete endpoints only after explicit user intent; DELETE requires confirmed=true, and bulk deletes require bulkConfirmed=true after confirming the exact target. " +
39-
"Common endpoints: " +
40-
"list guilds GET /users/@me/guilds | " +
41-
"list channels GET /guilds/{guild_id}/channels | " +
42-
"get channel GET /channels/{channel_id} | " +
43-
"create channel POST /guilds/{guild_id}/channels | " +
44-
"list members GET /guilds/{guild_id}/members?after=0&limit=100 | " +
45-
"get member GET /guilds/{guild_id}/members/{user_id} | " +
46-
"list threads GET /channels/{channel_id}/threads | " +
47-
"create thread PUT /channels/{channel_id}/threads | " +
48-
"create announce POST /guilds/{guild_id}/announces | " +
49-
"create schedule POST /channels/{channel_id}/schedules. " +
50-
"See the qqbot-channel skill for full endpoint details.",
51-
parameters: ChannelApiSchema,
52-
async execute(_toolCallId, params) {
53-
const { getAccessToken } = await import("../../engine/messaging/sender.js");
54-
const accessToken = await getAccessToken(account.appId, account.clientSecret);
55-
return executeChannelApi(params as ChannelApiParams, {
56-
accessToken,
57-
cfg,
58-
accountId: firstAccountId,
59-
});
60-
},
61-
},
62-
{ name: "qqbot_channel_api" },
63-
);
73+
api.registerTool((context) => createChannelTool(cfg, context), {
74+
name: "qqbot_channel_api",
75+
});
6476
}

0 commit comments

Comments
 (0)