@dsh-prism/dsh-im-gateway 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
1
+ <div align="center">
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <img src="icon.svg" width="256" height="256" alt="dsh-im-gateway icon">
4
+
5
+ # dsh-im-gateway
6
+
7
+ **Send requests to Prism in a private chat and receive updates there as delegated tasks progress.**
8
+
9
+ English | [简体中文](README.zh_CN.md)
10
+
11
+ </div>
12
+
13
+ ## Set up Prism
14
+
15
+ Use Node.js 24.9 or later, npm, Git and credentials with read access to the five private plugin repositories. The checkout script places matching plugins and launcher files in a local `runtime/` directory. Run subsequent installation, configuration and launch commands there. The public guide is available without signing in. To use the example models, configure your DeepSeek credentials in DSH or set the `DEEPSEEK_API_KEY` environment variable. [Installation guide](https://prism.dsh-plug.in/)
16
+
17
+ ```sh
18
+ git clone https://github.com/dsh-plugins/dsh-prism.git
19
+ cd dsh-prism
20
+ node scripts/checkout.mjs
21
+ cd runtime
22
+ npm ci
23
+ npm run build
24
+ npm start
25
+ ```
26
+
27
+ ## Connect your chat app
28
+
29
+ Before connecting a service, copy the sample configuration in your local `runtime/` directory. Each transport verifies the platform identity before handing a message to the conversation agent.
30
+
31
+ ```sh
32
+ cp prism.example.json prism.config.json
33
+ ```
34
+
35
+ | Chat service | Configuration key |
36
+ | --- | --- |
37
+ | Telegram | `im.telegram` |
38
+ | WeChat | `im.wechat` |
39
+ | Feishu / Lark | `im.feishu` |
40
+ | WeCom | `im.wecom` |
41
+ | QQ Bot | `im.qq` |
42
+ | OneBot | `im.onebot` |
43
+ | Discord | `im.discord` |
44
+
45
+ ## Link a private chat
46
+
47
+ For WeChat or Feishu, run the appropriate login command on the Prism host and follow the QR login instructions. Using the same `--config` file for setup and startup stores the registration in the configured gateway database and enables that channel.
48
+
49
+ ```sh
50
+ npm run im -- login wechat --config prism.config.json
51
+ ```
52
+
53
+ Use `feishu` instead of `wechat` to set up Feishu. To authorize a user with a one-time code, run the pairing command for their channel and have them send the printed `/pair` command in a private chat before the code expires. Their channel, bot, private chat and sender determine which conversation they return to.
54
+
55
+ ```sh
56
+ npm run im -- pair telegram --config prism.config.json
57
+ ```
58
+
59
+ ## Try a Telegram conversation
60
+
61
+ Create a bot with BotFather and store its token in the environment variable `TELEGRAM_BOT_TOKEN` on the Prism host. Run the setup command below. For WeCom, QQ Bot, OneBot or Discord, replace `telegram` with the channel key in the table. Setup asks for the public identifiers that channel needs and prints the credential environment variables and a private pairing command.
62
+
63
+ ```sh
64
+ npm run im -- setup telegram --config prism.config.json
65
+ ```
66
+
67
+ Start or restart Prism with the updated configuration. Open the bot’s private chat and send the printed `/pair` command within ten minutes. An operator can also explicitly allow known Telegram numeric user IDs under `im.telegram.allowedUserIds`.
68
+
69
+ ```sh
70
+ npm start -- prism.config.json --host 127.0.0.1 --port 3080 --no-open
71
+ ```
72
+
73
+ Send a request such as “Find the files that implement the login screen.” Use `/models` to read model descriptions and `/model 2` to choose the second entry. Use `/tasks` to see your tasks. Tap the task’s read-only session button or use `/inspect` with its task ID to see the underlying messages. Use `/language en` to change the language of gateway commands and status text. The supported codes are `de`, `en`, `es`, `fr`, `ja`, `pt`, `ru` and `zh`.
74
+
75
+ [Prism documentation](https://prism.dsh-plug.in/) · [Technical reference](docs/TECH.md)
@@ -0,0 +1,75 @@
1
+ <div align="center">
2
+
3
+ <img src="icon.svg" width="256" height="256" alt="dsh-im-gateway 图标">
4
+
5
+ # dsh-im-gateway
6
+
7
+ **在私聊中向棱镜提出请求,并在任务推进时收到主动更新。**
8
+
9
+ [English](README.md) | 简体中文
10
+
11
+ </div>
12
+
13
+ ## 接入棱镜
14
+
15
+ 需要 Node.js 24.9 或更高版本、npm、Git,以及对五个私有插件仓库的 Git 读取权限。检出脚本把匹配的插件和启动文件放入本机的 `runtime/` 目录,后续安装、配置和运行命令均在该目录执行。公开使用指南可直接阅读。需要调用示例模型时,请先在 DSH 凭据存储中配置 DeepSeek 凭据,或设置环境变量 `DEEPSEEK_API_KEY`。[安装指南](https://prism.dsh-plug.in/zh/)
16
+
17
+ ```sh
18
+ git clone https://github.com/dsh-plugins/dsh-prism.git
19
+ cd dsh-prism
20
+ node scripts/checkout.mjs
21
+ cd runtime
22
+ npm ci
23
+ npm run build
24
+ npm start
25
+ ```
26
+
27
+ ## 连接聊天应用
28
+
29
+ 接入通道前,先在本机的 `runtime/` 中复制示例配置。各适配器会先认证平台上的用户身份,再将消息交给对话代理。
30
+
31
+ ```sh
32
+ cp prism.example.json prism.config.json
33
+ ```
34
+
35
+ | 聊天服务 | 配置键 |
36
+ | --- | --- |
37
+ | Telegram | `im.telegram` |
38
+ | 微信 | `im.wechat` |
39
+ | 飞书 / Lark | `im.feishu` |
40
+ | 企业微信 | `im.wecom` |
41
+ | QQ 机器人 | `im.qq` |
42
+ | OneBot | `im.onebot` |
43
+ | Discord | `im.discord` |
44
+
45
+ ## 绑定私聊
46
+
47
+ 使用微信或飞书时,请在棱镜宿主上运行对应登录命令,并按提示扫码。使用同一个 `--config` 文件配置和启动网关后,注册信息会写入所配置的网关数据库,相应通道会启用。
48
+
49
+ ```sh
50
+ npm run im -- login wechat --config prism.config.json
51
+ ```
52
+
53
+ 如需接入飞书,将 `wechat` 换为 `feishu`。如需用一次性配对码授权用户,在宿主上为该通道运行配对命令,请用户在有效期内将终端打印的 `/pair` 命令发到私聊中。通道、机器人、私聊和发送者共同决定用户返回哪段对话。
54
+
55
+ ```sh
56
+ npm run im -- pair telegram --config prism.config.json
57
+ ```
58
+
59
+ ## 在 Telegram 中试用
60
+
61
+ 通过 BotFather 创建机器人,在棱镜宿主的环境变量 `TELEGRAM_BOT_TOKEN` 中保存令牌,然后运行以下设置命令。如需接入企业微信、QQ 机器人、OneBot 或 Discord,把 `telegram` 换为表中的通道键。配置向导会询问该平台所需的公开标识,列出凭据环境变量并打印私聊配对命令。
62
+
63
+ ```sh
64
+ npm run im -- setup telegram --config prism.config.json
65
+ ```
66
+
67
+ 使用更新后的配置启动或重启棱镜。打开机器人私聊,在十分钟内发送终端打印的 `/pair` 命令。管理员也可直接在 `im.telegram.allowedUserIds` 中允许已知的 Telegram 数字用户 ID。
68
+
69
+ ```sh
70
+ npm start -- prism.config.json --host 127.0.0.1 --port 3080 --no-open
71
+ ```
72
+
73
+ 发送一条请求,例如「找出实现登录页的文件」。使用 `/models` 阅读模型介绍,使用 `/model 2` 选择第 2 项。通过 `/tasks` 查看自己的任务,点击任务的只读会话按钮,或在 `/inspect` 后填写任务 ID,即可阅读底层消息。使用 `/language zh` 可以切换网关命令和状态文字的语言。可选语言代码为 `de`、`en`、`es`、`fr`、`ja`、`pt`、`ru` 和 `zh`。
74
+
75
+ [棱镜使用指南](https://prism.dsh-plug.in/zh/) · [技术参考](docs/TECH.md)
@@ -0,0 +1,29 @@
1
+ import { ActionRowBuilder, ButtonBuilder, ChannelType } from 'discord.js';
2
+ import type { ChannelRuntime } from '../runtime.js';
3
+ import type { Incoming, Reply } from '../transport.js';
4
+ export interface DiscordConfig {
5
+ tokenEnv?: string;
6
+ allowedUserIds?: string[];
7
+ }
8
+ export declare function discordMessage(message: {
9
+ channel: {
10
+ type: ChannelType;
11
+ recipientId?: string | null;
12
+ };
13
+ channelId: string;
14
+ author: {
15
+ id: string;
16
+ bot: boolean;
17
+ };
18
+ id: string;
19
+ content: string;
20
+ webhookId: string | null;
21
+ }): Incoming | undefined;
22
+ export declare function discordPayload(reply: Reply): {
23
+ content: string;
24
+ allowedMentions: {
25
+ parse: never[];
26
+ };
27
+ components: ActionRowBuilder<ButtonBuilder>[];
28
+ };
29
+ export declare function startDiscord(config: DiscordConfig, runtime: ChannelRuntime): Promise<void>;
@@ -0,0 +1,100 @@
1
+ import { ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, Client, DefaultRestOptions, DiscordAPIError, Events, GatewayIntentBits, Partials, RESTJSONErrorCodes, } from 'discord.js';
2
+ const inspectPrefix = 'prism:inspect:';
3
+ export function discordMessage(message) {
4
+ if (message.channel.type !== ChannelType.DM || message.author.bot || message.webhookId ||
5
+ message.channel.recipientId !== message.author.id || !message.content.trim())
6
+ return;
7
+ return { chat: message.channelId, user: message.author.id, text: message.content, id: message.id };
8
+ }
9
+ export function discordPayload(reply) {
10
+ const button = reply.inspectTask && new ButtonBuilder().setStyle(ButtonStyle.Secondary)
11
+ .setCustomId(inspectPrefix + reply.inspectTask).setLabel(reply.inspectLabel || '/inspect');
12
+ return {
13
+ content: reply.text,
14
+ allowedMentions: { parse: [] },
15
+ components: button ? [new ActionRowBuilder().addComponents(button)] : [],
16
+ };
17
+ }
18
+ export async function startDiscord(config, runtime) {
19
+ if (runtime.signal.aborted)
20
+ return;
21
+ const token = process.env[config.tokenEnv ?? 'DISCORD_BOT_TOKEN'];
22
+ if (!token)
23
+ throw new Error('Discord bot token environment variable is empty');
24
+ // Discord delivers DM contents without the privileged guild message-content intent.
25
+ const client = new Client({
26
+ intents: [GatewayIntentBits.DirectMessages], partials: [Partials.Channel],
27
+ rest: { makeRequest(url, init) {
28
+ runtime.signal.throwIfAborted();
29
+ const signal = init.signal ? AbortSignal.any([runtime.signal, init.signal]) : runtime.signal;
30
+ return DefaultRestOptions.makeRequest(url, { ...init, signal });
31
+ } },
32
+ });
33
+ const stopped = Promise.withResolvers();
34
+ const stop = () => stopped.resolve();
35
+ runtime.signal.addEventListener('abort', stop, { once: true });
36
+ const privateChannel = async (target) => {
37
+ const channel = await client.channels.fetch(target.chat);
38
+ if (channel?.type !== ChannelType.DM || channel.recipientId !== target.user)
39
+ throw new Error('Discord direct message recipient does not match');
40
+ return channel;
41
+ };
42
+ const send = async (target, reply) => {
43
+ const channel = await privateChannel(target);
44
+ const nonce = reply.deliveryId?.slice(0, 24);
45
+ const message = await channel.send({ ...discordPayload(reply), ...(nonce ? { nonce, enforceNonce: true } : {}) });
46
+ return message.id;
47
+ };
48
+ client.once(Events.ClientReady, ready => {
49
+ if (runtime.signal.aborted)
50
+ return;
51
+ const id = 'discord/' + ready.user.id;
52
+ const gateway = runtime.mount({
53
+ id, maxTextLength: 2000, permits: runtime.access(id, config.allowedUserIds),
54
+ send,
55
+ async edit(target, messageId, reply) {
56
+ const channel = await privateChannel(target);
57
+ try {
58
+ return (await channel.messages.edit(messageId, discordPayload(reply))).id;
59
+ }
60
+ catch (error) {
61
+ if (error instanceof DiscordAPIError && error.code === RESTJSONErrorCodes.UnknownMessage)
62
+ return send(target, reply);
63
+ throw error;
64
+ }
65
+ },
66
+ });
67
+ client.on(Events.MessageCreate, message => {
68
+ const input = discordMessage(message);
69
+ if (input)
70
+ void gateway.receive(input).catch(() => runtime.warn('Discord message processing failed'));
71
+ });
72
+ client.on(Events.InteractionCreate, async (interaction) => {
73
+ if (!interaction.isButton() || !interaction.customId.startsWith(inspectPrefix) ||
74
+ interaction.channel?.type !== ChannelType.DM || interaction.channel.recipientId !== interaction.user.id ||
75
+ interaction.message.author.id !== ready.user.id)
76
+ return;
77
+ try {
78
+ await interaction.deferUpdate();
79
+ await gateway.receive({ chat: interaction.channelId, user: interaction.user.id, id: interaction.id,
80
+ locale: interaction.locale, text: '/inspect ' + interaction.customId.slice(inspectPrefix.length) });
81
+ }
82
+ catch {
83
+ runtime.warn('Discord task inspection failed');
84
+ }
85
+ });
86
+ });
87
+ client.on(Events.Error, () => runtime.warn('Discord connection error'));
88
+ try {
89
+ // Login can wait indefinitely for a shard's first ready event, even after destroy().
90
+ await Promise.race([client.login(token).then(() => stopped.promise), stopped.promise]);
91
+ }
92
+ catch (error) {
93
+ if (!runtime.signal.aborted)
94
+ throw error;
95
+ }
96
+ finally {
97
+ runtime.signal.removeEventListener('abort', stop);
98
+ await client.destroy();
99
+ }
100
+ }
@@ -0,0 +1,9 @@
1
+ import type { ChannelRuntime } from '../runtime.js';
2
+ export interface OneBotConfig {
3
+ selfId: string;
4
+ apiBase: string;
5
+ accessTokenEnv?: string;
6
+ eventSecretEnv?: string;
7
+ allowedUserIds?: string[];
8
+ }
9
+ export declare function startOneBot(config: OneBotConfig, runtime: ChannelRuntime): void;
@@ -0,0 +1,90 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ import { CallbackError, credential, messageText, signedEvents } from './signed-events.js';
3
+ function qqNumber(value) {
4
+ if (!/^[1-9]\d*$/.test(String(value)) || !Number.isSafeInteger(Number(value)))
5
+ return;
6
+ return String(value);
7
+ }
8
+ function textOnly(message) {
9
+ if (typeof message === 'string') {
10
+ // CQ escaping is applied to text segments in the string-form wire representation.
11
+ return message.replace(/\[CQ:[^\]]*\]/g, '').replace(/&#91;/g, '[').replace(/&#93;/g, ']').replace(/&amp;/g, '&');
12
+ }
13
+ if (Array.isArray(message))
14
+ return message.map(part => part?.type === 'text' && typeof part.data?.text === 'string' ? part.data.text : '').join('');
15
+ return '';
16
+ }
17
+ export function startOneBot(config, runtime) {
18
+ const selfId = qqNumber(config.selfId);
19
+ if (!selfId)
20
+ throw new Error('OneBot selfId must be a numeric bot account');
21
+ const base = new URL(config.apiBase);
22
+ if (base.username || base.password || base.search || base.hash ||
23
+ !['https:', 'http:'].includes(base.protocol)) {
24
+ throw new Error('OneBot apiBase must be an HTTP(S) action URL');
25
+ }
26
+ if (!base.pathname.endsWith('/'))
27
+ base.pathname += '/';
28
+ const token = credential(config.accessTokenEnv ?? 'ONEBOT_ACCESS_TOKEN');
29
+ const secret = credential(config.eventSecretEnv ?? 'ONEBOT_EVENT_SECRET');
30
+ const id = 'onebot/' + selfId;
31
+ const access = runtime.access(id, config.allowedUserIds);
32
+ const permits = (target) => target.chat === target.user && !!qqNumber(target.user) && target.user !== selfId && access(target);
33
+ async function action(name, data) {
34
+ const response = await fetch(new URL(name, base), {
35
+ method: 'POST', redirect: 'error', signal: AbortSignal.any([runtime.signal, AbortSignal.timeout(15000)]),
36
+ headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' }, body: JSON.stringify(data),
37
+ });
38
+ if (!response.ok)
39
+ throw new Error('OneBot action unavailable (' + response.status + ')');
40
+ const result = await response.json();
41
+ if (result?.status !== 'ok' || result.retcode !== 0)
42
+ throw new Error('OneBot action failed');
43
+ return result.data;
44
+ }
45
+ let identity;
46
+ async function checkIdentity() {
47
+ if (!identity)
48
+ identity = action('get_login_info', {}).then(data => {
49
+ if (qqNumber(data?.user_id) !== selfId)
50
+ throw new Error('OneBot outbound account mismatch');
51
+ }).catch(error => { identity = undefined; throw error; });
52
+ return identity;
53
+ }
54
+ async function send(target, reply) {
55
+ if (!permits(target))
56
+ throw new Error('OneBot private recipient unavailable');
57
+ await checkIdentity();
58
+ const result = await action('send_private_msg', {
59
+ user_id: Number(target.user), message: [{ type: 'text', data: { text: messageText(reply) } }],
60
+ });
61
+ if (!Number.isSafeInteger(result?.message_id))
62
+ throw new Error('Missing OneBot message receipt');
63
+ return String(result.message_id);
64
+ }
65
+ const gateway = runtime.mount({
66
+ id, permits, send, edit: (target, _previous, reply) => send(target, reply),
67
+ });
68
+ runtime.webhook('/prism/im/onebot', signedEvents((headers, raw) => {
69
+ const sig = headers['x-signature'];
70
+ if (headers['x-self-id'] !== selfId || typeof sig !== 'string' || !/^sha1=[0-9a-f]{40}$/i.test(sig))
71
+ return false;
72
+ return timingSafeEqual(Buffer.from(sig.slice(5), 'hex'), createHmac('sha1', secret).update(raw).digest());
73
+ }, async (event) => {
74
+ if (qqNumber(event.self_id) !== selfId)
75
+ throw new CallbackError(403);
76
+ if (event.post_type !== 'message' || event.message_type !== 'private' || event.sub_type !== 'friend')
77
+ return {};
78
+ const user = qqNumber(event.user_id);
79
+ const sender = event.sender;
80
+ if (!user || user === selfId || (sender?.user_id !== undefined && qqNumber(sender.user_id) !== user) ||
81
+ !Number.isSafeInteger(event.message_id))
82
+ return {};
83
+ const text = textOnly(event.message);
84
+ if (text.trim()) {
85
+ const input = { chat: user, user, id: String(event.message_id), text };
86
+ await gateway.receive(input);
87
+ }
88
+ return {};
89
+ }));
90
+ }
@@ -0,0 +1,7 @@
1
+ import type { ChannelRuntime } from '../runtime.js';
2
+ export interface QQConfig {
3
+ appId: string;
4
+ appSecretEnv?: string;
5
+ allowedUserIds?: string[];
6
+ }
7
+ export declare function startQQ(options: QQConfig, runtime: ChannelRuntime): void;
@@ -0,0 +1,149 @@
1
+ import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
2
+ import { CallbackError, credential, messageText, signedEvents } from './signed-events.js';
3
+ /** Tencent signs timestamp || rawBody with the Ed25519 key derived from the app secret. */
4
+ function signingKey(secret) {
5
+ let seed = Buffer.from(secret);
6
+ while (seed.length < 32)
7
+ seed = Buffer.concat([seed, seed]);
8
+ const prefix = Buffer.from('302e020100300506032b657004220420', 'hex');
9
+ return createPrivateKey({ format: 'der', type: 'pkcs8', key: Buffer.concat([prefix, seed.subarray(0, 32)]) });
10
+ }
11
+ const api = 'https://api.bot.qq.com';
12
+ const passiveWindow = 5 * 60_000;
13
+ const openId = (id) => typeof id === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(id);
14
+ export function startQQ(options, runtime) {
15
+ if (!/^\d+$/.test(options.appId) || typeof options.appId !== 'string')
16
+ throw new Error('Invalid QQ appId');
17
+ const secret = credential(options.appSecretEnv ?? 'QQ_BOT_SECRET');
18
+ const privateKey = signingKey(secret);
19
+ const publicKey = createPublicKey(privateKey);
20
+ const id = 'qq/' + options.appId;
21
+ const access = runtime.access(id, options.allowedUserIds);
22
+ const permits = (target) => target.chat === target.user && openId(target.user) && access(target);
23
+ const key = (part, user) => [id, part, user].join('/');
24
+ let token;
25
+ let refresh;
26
+ const signal = () => AbortSignal.any([runtime.signal, AbortSignal.timeout(15_000)]);
27
+ async function accessToken() {
28
+ if (token && token.expires > Date.now() + 60_000)
29
+ return token.value;
30
+ if (!refresh)
31
+ refresh = (async () => {
32
+ const response = await fetch(api + '/app/getAppAccessToken', {
33
+ method: 'POST', redirect: 'error', signal: signal(), headers: { 'content-type': 'application/json' },
34
+ body: JSON.stringify({ appId: options.appId, clientSecret: secret }),
35
+ });
36
+ if (!response.ok)
37
+ throw new Error('QQ token request failed (' + response.status + ')');
38
+ const result = await response.json();
39
+ const expires = Number(result?.expires_in);
40
+ if (typeof result.access_token !== 'string' || !result.access_token || !Number.isFinite(expires) || expires <= 0) {
41
+ throw new Error('QQ token unavailable');
42
+ }
43
+ token = { value: result.access_token, expires: Date.now() + expires * 1000 };
44
+ return token.value;
45
+ })().finally(() => { refresh = undefined; });
46
+ return refresh;
47
+ }
48
+ function remember(user, message, at) {
49
+ const name = key('window', user);
50
+ const current = JSON.parse(runtime.state.get(name) ?? 'null');
51
+ if (current && (current.id === message || current.at > at))
52
+ return;
53
+ runtime.state.set(name, JSON.stringify({ id: message, at, used: 0 }));
54
+ }
55
+ // Persist the reply slot before posting. A transport retry reuses msg_id + msg_seq.
56
+ function frame(user, receipt) {
57
+ const slotKey = receipt && key('slot/' + user, receipt);
58
+ const saved = slotKey && runtime.state.get(slotKey);
59
+ if (saved) {
60
+ const previous = JSON.parse(saved);
61
+ return previous && previous.expires > Date.now() ? previous : undefined;
62
+ }
63
+ const windowKey = key('window', user);
64
+ const current = JSON.parse(runtime.state.get(windowKey) ?? 'null');
65
+ let result;
66
+ if (current && current.at + passiveWindow > Date.now() && current.used < 4) {
67
+ result = { msg_id: current.id, msg_seq: ++current.used, expires: current.at + passiveWindow };
68
+ runtime.state.set(windowKey, JSON.stringify(current));
69
+ }
70
+ if (slotKey)
71
+ runtime.state.set(slotKey, JSON.stringify(result ?? null));
72
+ return result;
73
+ }
74
+ async function send(target, reply) {
75
+ if (!permits(target))
76
+ throw new Error('QQ private recipient unavailable');
77
+ const slot = frame(target.user, reply.deliveryId);
78
+ if (!slot && runtime.state.get(key('blocked', target.user)) === 'yes')
79
+ throw new Error('QQ proactive messages disabled');
80
+ const authorization = await accessToken();
81
+ const response = await fetch(api + '/v2/users/' + encodeURIComponent(target.user) + '/messages', {
82
+ method: 'POST', redirect: 'error', signal: signal(),
83
+ headers: { authorization: 'QQBot ' + authorization, 'content-type': 'application/json' },
84
+ body: JSON.stringify({ msg_type: 0, content: messageText(reply), ...(slot && { msg_id: slot.msg_id, msg_seq: slot.msg_seq }) }),
85
+ });
86
+ const result = await response.json();
87
+ if (response.status === 401 && token?.value === authorization)
88
+ token = undefined;
89
+ const code = Number(result?.code ?? 0);
90
+ if (slot && code === 40054005)
91
+ return 'reply:' + slot.msg_id + ':' + slot.msg_seq;
92
+ if (!response.ok || code !== 0)
93
+ throw new Error('QQ C2C delivery failed (' + response.status + '/' + code + ')');
94
+ if (typeof result.id !== 'string' || !result.id)
95
+ throw new Error('Missing QQ C2C message receipt');
96
+ return result.id;
97
+ }
98
+ const gateway = runtime.mount({ id, permits, maxTextBytes: 3500, send, edit: (target, _prev, reply) => send(target, reply) });
99
+ runtime.webhook('/prism/im/qq', signedEvents((headers, raw) => {
100
+ const ts = headers['x-signature-timestamp'], signature = headers['x-signature-ed25519'];
101
+ // The open platform's URL-registration example sends only X-Bot-Appid.
102
+ // An unsigned challenge may sign a plain token, never arbitrary event bytes.
103
+ if (ts === undefined && signature === undefined && headers['x-bot-appid'] === options.appId) {
104
+ try {
105
+ const challenge = JSON.parse(raw.toString('utf8'));
106
+ return challenge?.op === 13 && typeof challenge.d?.plain_token === 'string' &&
107
+ /^[a-zA-Z0-9_-]{1,256}$/.test(challenge.d.plain_token) && /^\d{1,15}$/.test(challenge.d.event_ts) &&
108
+ typeof challenge.d.event_ts === 'string';
109
+ }
110
+ catch {
111
+ return false;
112
+ }
113
+ }
114
+ if (typeof ts !== 'string' || !/^\d{1,15}$/.test(ts) || typeof signature !== 'string' || !/^[\da-f]{128}$/i.test(signature))
115
+ return false;
116
+ return verify(null, Buffer.concat([Buffer.from(ts), raw]), publicKey, Buffer.from(signature, 'hex'));
117
+ }, async (event) => {
118
+ const data = event.d;
119
+ if (event.op === 13) {
120
+ if (typeof data?.plain_token !== 'string' || typeof data.event_ts !== 'string')
121
+ throw new CallbackError(400);
122
+ return { plain_token: data.plain_token, signature: sign(null, Buffer.from(data.event_ts + data.plain_token), privateKey).toString('hex') };
123
+ }
124
+ if (event.op === 1)
125
+ return { op: 11, d: data };
126
+ if (event.op === 0 && data) {
127
+ if (event.t === 'C2C_MESSAGE_CREATE') {
128
+ const author = data.author;
129
+ const user = author?.user_openid ?? author?.id;
130
+ if (openId(user) && !author?.bot && typeof data.id === 'string' && data.id && typeof data.content === 'string' && data.content.trim()) {
131
+ const target = { user, chat: user };
132
+ if (permits(target) || /^\/pair\s+[a-f\d]{20}$/i.test(data.content.trim())) {
133
+ const timestamp = typeof data.timestamp === 'string' ? Date.parse(data.timestamp) : NaN;
134
+ if (Number.isFinite(timestamp))
135
+ remember(user, data.id, Math.min(timestamp, Date.now()));
136
+ }
137
+ await gateway.receive({ ...target, id: data.id, text: data.content });
138
+ }
139
+ }
140
+ else if (openId(data.openid)) {
141
+ if (event.t === 'C2C_MSG_REJECT' || event.t === 'FRIEND_DEL')
142
+ runtime.state.set(key('blocked', data.openid), 'yes');
143
+ if (event.t === 'C2C_MSG_RECEIVE' || event.t === 'FRIEND_ADD')
144
+ runtime.state.set(key('blocked', data.openid), 'no');
145
+ }
146
+ }
147
+ return { op: 12, d: 0 };
148
+ }));
149
+ }
@@ -0,0 +1,12 @@
1
+ import type { IncomingHttpHeaders, IncomingMessage, ServerResponse } from 'node:http';
2
+ export declare class CallbackError extends Error {
3
+ readonly status: number;
4
+ constructor(status: number);
5
+ }
6
+ /** Authentication always consumes the original bytes, including JSON whitespace. */
7
+ export declare function signedEvents(authenticate: (headers: IncomingHttpHeaders, raw: Buffer) => boolean, handle: (event: Record<string, unknown>) => Promise<unknown>): (req: IncomingMessage, res: ServerResponse) => Promise<void>;
8
+ export declare function credential(envName: string): string;
9
+ export declare function messageText(reply: {
10
+ text: string;
11
+ inspectTask?: string;
12
+ }): string;
@@ -0,0 +1,55 @@
1
+ export class CallbackError extends Error {
2
+ status;
3
+ constructor(status) {
4
+ super('Invalid channel callback');
5
+ this.status = status;
6
+ }
7
+ }
8
+ /** Authentication always consumes the original bytes, including JSON whitespace. */
9
+ export function signedEvents(authenticate, handle) {
10
+ return async (req, res) => {
11
+ try {
12
+ if (req.method !== 'POST')
13
+ throw new CallbackError(405);
14
+ const buffers = [];
15
+ let bytes = 0;
16
+ for await (const chunk of req.iterator({ destroyOnReturn: false })) {
17
+ const value = Buffer.from(chunk);
18
+ bytes += value.length;
19
+ if (bytes > 1_048_576) {
20
+ req.resume();
21
+ throw new CallbackError(413);
22
+ }
23
+ buffers.push(value);
24
+ }
25
+ const raw = Buffer.concat(buffers);
26
+ if (!authenticate(req.headers, raw))
27
+ throw new CallbackError(401);
28
+ let event;
29
+ try {
30
+ event = JSON.parse(raw.toString('utf8'));
31
+ }
32
+ catch {
33
+ throw new CallbackError(400);
34
+ }
35
+ if (!event || typeof event !== 'object' || Array.isArray(event))
36
+ throw new CallbackError(400);
37
+ const result = await handle(event);
38
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
39
+ res.end(JSON.stringify(result ?? {}));
40
+ }
41
+ catch (error) {
42
+ res.writeHead(error instanceof CallbackError ? error.status : 503, { 'cache-control': 'no-store' });
43
+ res.end();
44
+ }
45
+ };
46
+ }
47
+ export function credential(envName) {
48
+ const value = process.env[envName];
49
+ if (!value?.trim())
50
+ throw new Error('Channel credential missing from ' + envName);
51
+ return value;
52
+ }
53
+ export function messageText(reply) {
54
+ return reply.text + (reply.inspectTask ? '\n/inspect ' + reply.inspectTask : '');
55
+ }
@@ -0,0 +1,9 @@
1
+ import type { ChannelRuntime } from '../runtime.js';
2
+ import type { GatewayState } from '../state.js';
3
+ export interface WechatConfig {
4
+ allowedUserIds?: string[];
5
+ }
6
+ export declare function loginWechat(state: GatewayState, onQr: (url: string) => void, verify: () => Promise<string>, signal: AbortSignal, request?: typeof fetch): Promise<{
7
+ botId: string;
8
+ }>;
9
+ export declare function startWechat(options: WechatConfig, runtime: ChannelRuntime, request?: typeof fetch): Promise<void>;