@dsh-prism/dsh-im-gateway 0.0.0-stage → 0.1.1
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 +80 -2
- package/README.zh_CN.md +81 -0
- package/cordis.patch.yml +5 -0
- package/dist/admin-config.d.ts +45 -0
- package/dist/admin-config.js +172 -0
- package/dist/admin-route.d.ts +14 -0
- package/dist/admin-route.js +75 -0
- package/dist/channels/discord.d.ts +29 -0
- package/dist/channels/discord.js +101 -0
- package/dist/channels/onebot.d.ts +9 -0
- package/dist/channels/onebot.js +91 -0
- package/dist/channels/qq.d.ts +7 -0
- package/dist/channels/qq.js +150 -0
- package/dist/channels/signed-events.d.ts +11 -0
- package/dist/channels/signed-events.js +49 -0
- package/dist/channels/wechat.d.ts +9 -0
- package/dist/channels/wechat.js +166 -0
- package/dist/feishu.d.ts +46 -0
- package/dist/feishu.js +136 -0
- package/dist/gateway.d.ts +38 -0
- package/dist/gateway.js +209 -0
- package/dist/i18n.d.ts +28 -0
- package/dist/i18n.js +15 -0
- package/dist/index.d.ts +30 -0
- package/dist/index.js +47 -0
- package/dist/login-admin.d.ts +37 -0
- package/dist/login-admin.js +163 -0
- package/dist/runtime.d.ts +16 -0
- package/dist/runtime.js +9 -0
- package/dist/state.d.ts +26 -0
- package/dist/state.js +129 -0
- package/dist/supervisor.d.ts +30 -0
- package/dist/supervisor.js +129 -0
- package/dist/telegram.d.ts +52 -0
- package/dist/telegram.js +133 -0
- package/dist/transport.d.ts +27 -0
- package/dist/transport.js +23 -0
- package/dist/wecom.d.ts +21 -0
- package/dist/wecom.js +56 -0
- package/icon.svg +12 -0
- package/locale/de.json +51 -0
- package/locale/en.json +52 -0
- package/locale/es.json +51 -0
- package/locale/fr.json +51 -0
- package/locale/ja.json +51 -0
- package/locale/pt.json +51 -0
- package/locale/ru.json +51 -0
- package/locale/zh.json +52 -0
- package/package.json +65 -4
- package/scripts/prism-im.mjs +137 -0
package/README.md
CHANGED
|
@@ -1,3 +1,81 @@
|
|
|
1
|
-
|
|
1
|
+
<div align="center">
|
|
2
2
|
|
|
3
|
-
|
|
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
|
+
## Install in the DSH web app
|
|
14
|
+
|
|
15
|
+
Open **Plugins → Add plugin** and install and enable the five `@dsh-prism` packages in the order shown in the guide. To install this package, enter `@dsh-prism/dsh-im-gateway@0.1.1`. [Illustrated installation guide](https://prism.dsh-plug.in/guide/start)
|
|
16
|
+
|
|
17
|
+
Open **Settings → Prism** and choose a messaging channel. Telegram, WeChat, Feishu / Lark, WeCom, QQ Bot, OneBot and Discord each have settings for credentials or account registration and direct-message access. For Feishu, you can generate a registration QR code or enter an existing app’s credentials. Save your settings, then enable the channel when you are ready. [Messaging channel walkthrough](https://prism.dsh-plug.in/guide/im)
|
|
18
|
+
|
|
19
|
+
## Run the standalone host from source
|
|
20
|
+
|
|
21
|
+
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/)
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
git clone https://github.com/dsh-plugins/dsh-prism.git
|
|
25
|
+
cd dsh-prism
|
|
26
|
+
node scripts/checkout.mjs
|
|
27
|
+
cd runtime
|
|
28
|
+
npm ci
|
|
29
|
+
npm run build
|
|
30
|
+
npm start
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Configure a chat app on the standalone host
|
|
34
|
+
|
|
35
|
+
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.
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
cp prism.example.json prism.config.json
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
| Chat service | Configuration key |
|
|
42
|
+
| --- | --- |
|
|
43
|
+
| Telegram | `im.telegram` |
|
|
44
|
+
| WeChat | `im.wechat` |
|
|
45
|
+
| Feishu / Lark | `im.feishu` |
|
|
46
|
+
| WeCom | `im.wecom` |
|
|
47
|
+
| QQ Bot | `im.qq` |
|
|
48
|
+
| OneBot | `im.onebot` |
|
|
49
|
+
| Discord | `im.discord` |
|
|
50
|
+
|
|
51
|
+
## Link a private chat on the standalone host
|
|
52
|
+
|
|
53
|
+
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.
|
|
54
|
+
|
|
55
|
+
```sh
|
|
56
|
+
npm run im -- login wechat --config prism.config.json
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
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.
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
npm run im -- pair telegram --config prism.config.json
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Try a Telegram conversation
|
|
66
|
+
|
|
67
|
+
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.
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
npm run im -- setup telegram --config prism.config.json
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
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`.
|
|
74
|
+
|
|
75
|
+
```sh
|
|
76
|
+
npm start -- prism.config.json --host 127.0.0.1 --port 3080 --no-open
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
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`.
|
|
80
|
+
|
|
81
|
+
[Prism documentation](https://prism.dsh-plug.in/) · [Technical reference](docs/TECH.md)
|
package/README.zh_CN.md
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
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
|
+
## 在 DSH 网页端安装
|
|
14
|
+
|
|
15
|
+
在 DSH 的 **插件 → 添加插件** 中按安装指南列出的顺序安装并启用五个 `@dsh-prism` 包。此包可按完整包名 `@dsh-prism/dsh-im-gateway@0.1.1` 安装。[前端安装图解](https://prism.dsh-plug.in/zh/guide/start)
|
|
16
|
+
|
|
17
|
+
进入 **设置 → 棱镜**,打开消息渠道并选择 Telegram、微信、飞书 / Lark、企业微信、QQ 机器人、OneBot 或 Discord。可以先查看各渠道的凭据和私聊授权设置。飞书支持生成二维码注册应用,也可填写已有应用的凭据。保存设置后,可单独启用该渠道。[各渠道配置图解](https://prism.dsh-plug.in/zh/guide/im)
|
|
18
|
+
|
|
19
|
+
## 从源码运行独立宿主
|
|
20
|
+
|
|
21
|
+
需要 Node.js 24.9 或更高版本、npm、Git,以及对五个私有插件仓库的 Git 读取权限。检出脚本把匹配的插件和启动文件放入本机的 `runtime/` 目录,后续安装、配置和运行命令均在该目录执行。公开使用指南可直接阅读。需要调用示例模型时,请先在 DSH 凭据存储中配置 DeepSeek 凭据,或设置环境变量 `DEEPSEEK_API_KEY`。[安装指南](https://prism.dsh-plug.in/zh/)
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
git clone https://github.com/dsh-plugins/dsh-prism.git
|
|
25
|
+
cd dsh-prism
|
|
26
|
+
node scripts/checkout.mjs
|
|
27
|
+
cd runtime
|
|
28
|
+
npm ci
|
|
29
|
+
npm run build
|
|
30
|
+
npm start
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## 在独立宿主中配置聊天应用
|
|
34
|
+
|
|
35
|
+
接入通道前,先在本机的 `runtime/` 中复制示例配置。各适配器会先认证平台上的用户身份,再将消息交给对话代理。
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
cp prism.example.json prism.config.json
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
| 聊天服务 | 配置键 |
|
|
42
|
+
| --- | --- |
|
|
43
|
+
| Telegram | `im.telegram` |
|
|
44
|
+
| 微信 | `im.wechat` |
|
|
45
|
+
| 飞书 / Lark | `im.feishu` |
|
|
46
|
+
| 企业微信 | `im.wecom` |
|
|
47
|
+
| QQ 机器人 | `im.qq` |
|
|
48
|
+
| OneBot | `im.onebot` |
|
|
49
|
+
| Discord | `im.discord` |
|
|
50
|
+
|
|
51
|
+
## 在独立宿主中绑定私聊
|
|
52
|
+
|
|
53
|
+
使用微信或飞书时,请在棱镜宿主上运行对应登录命令,并按提示扫码。使用同一个 `--config` 文件配置和启动网关后,注册信息会写入所配置的网关数据库,相应通道会启用。
|
|
54
|
+
|
|
55
|
+
```sh
|
|
56
|
+
npm run im -- login wechat --config prism.config.json
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
如需接入飞书,将 `wechat` 换为 `feishu`。如需用一次性配对码授权用户,在宿主上为该通道运行配对命令,请用户在有效期内将终端打印的 `/pair` 命令发到私聊中。通道、机器人、私聊和发送者共同决定用户返回哪段对话。
|
|
60
|
+
|
|
61
|
+
```sh
|
|
62
|
+
npm run im -- pair telegram --config prism.config.json
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## 在 Telegram 中试用
|
|
66
|
+
|
|
67
|
+
通过 BotFather 创建机器人,在棱镜宿主的环境变量 `TELEGRAM_BOT_TOKEN` 中保存令牌,然后运行以下设置命令。如需接入企业微信、QQ 机器人、OneBot 或 Discord,把 `telegram` 换为表中的通道键。配置向导会询问该平台所需的公开标识,列出凭据环境变量并打印私聊配对命令。
|
|
68
|
+
|
|
69
|
+
```sh
|
|
70
|
+
npm run im -- setup telegram --config prism.config.json
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
使用更新后的配置启动或重启棱镜。打开机器人私聊,在十分钟内发送终端打印的 `/pair` 命令。管理员也可直接在 `im.telegram.allowedUserIds` 中允许已知的 Telegram 数字用户 ID。
|
|
74
|
+
|
|
75
|
+
```sh
|
|
76
|
+
npm start -- prism.config.json --host 127.0.0.1 --port 3080 --no-open
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
发送一条请求,例如「找出实现登录页的文件」。使用 `/models` 阅读模型介绍,使用 `/model 2` 选择第 2 项。通过 `/tasks` 查看自己的任务,点击任务的只读会话按钮,或在 `/inspect` 后填写任务 ID,即可阅读底层消息。使用 `/language zh` 可以切换网关命令和状态文字的语言。可选语言代码为 `de`、`en`、`es`、`fr`、`ja`、`pt`、`ru` 和 `zh`。
|
|
80
|
+
|
|
81
|
+
[棱镜使用指南](https://prism.dsh-plug.in/zh/) · [技术参考](docs/TECH.md)
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { Config } from './index.js';
|
|
2
|
+
import type { GatewayState } from './state.js';
|
|
3
|
+
export declare const channels: readonly ["telegram", "wechat", "feishu", "wecom", "qq", "onebot", "discord"];
|
|
4
|
+
export type Channel = typeof channels[number];
|
|
5
|
+
export type ChannelStatus = 'disabled' | 'starting' | 'running' | 'error';
|
|
6
|
+
type Fields = {
|
|
7
|
+
allowedUserIds: string[];
|
|
8
|
+
appId?: string;
|
|
9
|
+
domain?: string;
|
|
10
|
+
botId?: string;
|
|
11
|
+
selfId?: string;
|
|
12
|
+
apiBase?: string;
|
|
13
|
+
};
|
|
14
|
+
type SecretValues = Record<string, string | null>;
|
|
15
|
+
type Document = {
|
|
16
|
+
revision: number;
|
|
17
|
+
enabled: boolean;
|
|
18
|
+
fields: Fields;
|
|
19
|
+
secrets: SecretValues;
|
|
20
|
+
};
|
|
21
|
+
export type ChannelView = Omit<Document, 'secrets'> & {
|
|
22
|
+
channel: Channel;
|
|
23
|
+
status: ChannelStatus;
|
|
24
|
+
registered: boolean;
|
|
25
|
+
secrets: Record<string, boolean>;
|
|
26
|
+
};
|
|
27
|
+
export declare class AdminError extends Error {
|
|
28
|
+
readonly code: 'invalid' | 'conflict' | 'not_found' | 'unavailable' | 'forbidden';
|
|
29
|
+
constructor(code: 'invalid' | 'conflict' | 'not_found' | 'unavailable' | 'forbidden');
|
|
30
|
+
}
|
|
31
|
+
export declare function isChannel(value: unknown): value is Channel;
|
|
32
|
+
export declare function object(input: unknown): Record<string, unknown>;
|
|
33
|
+
export declare class ChannelConfiguration {
|
|
34
|
+
private readonly state;
|
|
35
|
+
private readonly initial;
|
|
36
|
+
constructor(state: GatewayState, initial: Config);
|
|
37
|
+
private key;
|
|
38
|
+
private read;
|
|
39
|
+
secret(channel: Channel, field: string, secrets?: SecretValues): string | undefined;
|
|
40
|
+
view(channel: Channel, status: ChannelStatus): ChannelView;
|
|
41
|
+
save(channel: Channel, payload: Record<string, unknown>): void;
|
|
42
|
+
registered(channel: 'wechat' | 'feishu'): void;
|
|
43
|
+
options(channel: Channel): Config[Channel];
|
|
44
|
+
}
|
|
45
|
+
export {};
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
export const channels = ['telegram', 'wechat', 'feishu', 'wecom', 'qq', 'onebot', 'discord'];
|
|
2
|
+
export class AdminError extends Error {
|
|
3
|
+
code;
|
|
4
|
+
constructor(code) {
|
|
5
|
+
super(code);
|
|
6
|
+
this.code = code;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export function isChannel(value) {
|
|
10
|
+
return typeof value === 'string' && channels.some(channel => channel === value);
|
|
11
|
+
}
|
|
12
|
+
const fieldsByChannel = {
|
|
13
|
+
telegram: [], wechat: [], feishu: ['domain', 'appId'], wecom: ['botId'], qq: ['appId'],
|
|
14
|
+
onebot: ['selfId', 'apiBase'], discord: [],
|
|
15
|
+
};
|
|
16
|
+
// Browser clients can replace values but cannot choose an arbitrary process environment key.
|
|
17
|
+
const credentialFields = {
|
|
18
|
+
telegram: { token: ['tokenEnv', 'TELEGRAM_BOT_TOKEN'] }, wechat: {},
|
|
19
|
+
feishu: { appSecret: ['appSecretEnv', 'FEISHU_APP_SECRET'] },
|
|
20
|
+
wecom: { secret: ['secretEnv', 'WECOM_BOT_SECRET'] }, qq: { appSecret: ['appSecretEnv', 'QQ_BOT_SECRET'] },
|
|
21
|
+
onebot: { accessToken: ['accessTokenEnv', 'ONEBOT_ACCESS_TOKEN'], eventSecret: ['eventSecretEnv', 'ONEBOT_EVENT_SECRET'] },
|
|
22
|
+
discord: { token: ['tokenEnv', 'DISCORD_BOT_TOKEN'] },
|
|
23
|
+
};
|
|
24
|
+
export function object(input) {
|
|
25
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
26
|
+
throw new AdminError('invalid');
|
|
27
|
+
return input;
|
|
28
|
+
}
|
|
29
|
+
function clean(value, max) {
|
|
30
|
+
if (typeof value !== 'string' || value.length > max || /[\x00-\x1f\x7f]/.test(value))
|
|
31
|
+
throw new AdminError('invalid');
|
|
32
|
+
return value.trim();
|
|
33
|
+
}
|
|
34
|
+
function updateFields(channel, before, input) {
|
|
35
|
+
const fields = { ...before };
|
|
36
|
+
for (const [name, value] of Object.entries(object(input))) {
|
|
37
|
+
if (name === 'allowedUserIds') {
|
|
38
|
+
if (!Array.isArray(value) || value.length > 1024)
|
|
39
|
+
throw new AdminError('invalid');
|
|
40
|
+
fields.allowedUserIds = [...new Set(value.map(v => clean(v, 256)))];
|
|
41
|
+
if (fields.allowedUserIds.some(user => !user))
|
|
42
|
+
throw new AdminError('invalid');
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const key = fieldsByChannel[channel].find(key => key === name);
|
|
46
|
+
if (!key)
|
|
47
|
+
throw new AdminError('invalid');
|
|
48
|
+
const text = clean(value, key === 'apiBase' ? 2048 : 256);
|
|
49
|
+
if (key === 'domain' && text && !['feishu', 'lark'].includes(text))
|
|
50
|
+
throw new AdminError('invalid');
|
|
51
|
+
if (key === 'selfId' && text && (!/^[1-9]\d*$/.test(text) || !Number.isSafeInteger(Number(text))))
|
|
52
|
+
throw new AdminError('invalid');
|
|
53
|
+
if (channel === 'qq' && key === 'appId' && text && !/^\d+$/.test(text))
|
|
54
|
+
throw new AdminError('invalid');
|
|
55
|
+
if (key === 'apiBase' && text) {
|
|
56
|
+
const url = URL.parse(text);
|
|
57
|
+
if (!url || !['https:', 'http:'].includes(url.protocol) || url.username || url.password || url.search || url.hash)
|
|
58
|
+
throw new AdminError('invalid');
|
|
59
|
+
}
|
|
60
|
+
fields[key] = text;
|
|
61
|
+
}
|
|
62
|
+
return fields;
|
|
63
|
+
}
|
|
64
|
+
export class ChannelConfiguration {
|
|
65
|
+
state;
|
|
66
|
+
initial;
|
|
67
|
+
constructor(state, initial) {
|
|
68
|
+
this.state = state;
|
|
69
|
+
this.initial = initial;
|
|
70
|
+
}
|
|
71
|
+
key(channel) { return 'admin/channel/' + channel; }
|
|
72
|
+
read(channel, raw = this.state.get(this.key(channel))) {
|
|
73
|
+
if (raw !== undefined)
|
|
74
|
+
return JSON.parse(raw);
|
|
75
|
+
const original = (this.initial[channel] ?? {});
|
|
76
|
+
const fields = { allowedUserIds: (original.allowedUserIds ?? original.allowedUsers ?? []) };
|
|
77
|
+
for (const name of fieldsByChannel[channel])
|
|
78
|
+
fields[name] = String(original[name] ?? '');
|
|
79
|
+
return { revision: 0, enabled: Boolean(this.initial[channel]), fields, secrets: {} };
|
|
80
|
+
}
|
|
81
|
+
secret(channel, field, secrets = this.read(channel).secrets) {
|
|
82
|
+
if (!Object.hasOwn(credentialFields[channel], field))
|
|
83
|
+
return;
|
|
84
|
+
if (Object.hasOwn(secrets, field))
|
|
85
|
+
return secrets[field] || undefined;
|
|
86
|
+
const old = this.initial[channel];
|
|
87
|
+
if (old) {
|
|
88
|
+
const [ref, fallback] = credentialFields[channel][field];
|
|
89
|
+
const inherited = process.env[String(old[ref] ?? fallback)];
|
|
90
|
+
if (inherited)
|
|
91
|
+
return inherited;
|
|
92
|
+
}
|
|
93
|
+
if (channel === 'telegram')
|
|
94
|
+
return this.state.get('telegram/token');
|
|
95
|
+
}
|
|
96
|
+
view(channel, status) {
|
|
97
|
+
const { enabled, revision, fields, secrets } = this.read(channel);
|
|
98
|
+
const registered = (channel === 'feishu' || channel === 'wechat') && !!this.state.get(channel + '/registration');
|
|
99
|
+
return { channel, enabled, revision, fields, status, registered, secrets: Object.fromEntries(Object.keys(credentialFields[channel]).map(name => [name, !!this.secret(channel, name, secrets)])) };
|
|
100
|
+
}
|
|
101
|
+
save(channel, payload) {
|
|
102
|
+
const key = this.key(channel);
|
|
103
|
+
const raw = this.state.get(key);
|
|
104
|
+
const current = this.read(channel, raw);
|
|
105
|
+
if (typeof payload.enabled !== 'boolean' || !Number.isSafeInteger(payload.revision))
|
|
106
|
+
throw new AdminError('invalid');
|
|
107
|
+
if (payload.revision !== current.revision)
|
|
108
|
+
throw new AdminError('conflict');
|
|
109
|
+
const fields = updateFields(channel, current.fields, payload.fields);
|
|
110
|
+
const updates = object(payload.secrets ?? {});
|
|
111
|
+
const secrets = { ...current.secrets };
|
|
112
|
+
for (const [name, value] of Object.entries(updates)) {
|
|
113
|
+
if (!Object.hasOwn(credentialFields[channel], name))
|
|
114
|
+
throw new AdminError('invalid');
|
|
115
|
+
if (value === null)
|
|
116
|
+
secrets[name] = null;
|
|
117
|
+
else {
|
|
118
|
+
if (typeof value !== 'string' || !value || !value.trim() || value.length > 8192 || /[\x00-\x1f\x7f]/.test(value))
|
|
119
|
+
throw new AdminError('invalid');
|
|
120
|
+
secrets[name] = value;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
// An existing outgoing token belongs to the endpoint it was entered for.
|
|
124
|
+
if (channel === 'onebot' && current.fields.apiBase && fields.apiBase !== current.fields.apiBase
|
|
125
|
+
&& this.secret(channel, 'accessToken', current.secrets) && !Object.hasOwn(updates, 'accessToken'))
|
|
126
|
+
throw new AdminError('invalid');
|
|
127
|
+
if (payload.enabled) {
|
|
128
|
+
if (channel === 'wechat' && !this.state.get('wechat/registration'))
|
|
129
|
+
throw new AdminError('invalid');
|
|
130
|
+
if (channel === 'wecom' && !fields.botId || channel === 'qq' && !fields.appId
|
|
131
|
+
|| channel === 'onebot' && (!fields.selfId || !fields.apiBase))
|
|
132
|
+
throw new AdminError('invalid');
|
|
133
|
+
const useRegistration = channel === 'feishu' && !fields.appId;
|
|
134
|
+
if (useRegistration) {
|
|
135
|
+
const registered = this.state.get('feishu/registration');
|
|
136
|
+
if (!registered || fields.domain && JSON.parse(registered).domain !== fields.domain)
|
|
137
|
+
throw new AdminError('invalid');
|
|
138
|
+
}
|
|
139
|
+
else if (Object.keys(credentialFields[channel]).some(name => !this.secret(channel, name, secrets)))
|
|
140
|
+
throw new AdminError('invalid');
|
|
141
|
+
}
|
|
142
|
+
const next = { revision: current.revision + 1, enabled: payload.enabled, fields, secrets };
|
|
143
|
+
if (!this.state.compareAndSet(key, raw, JSON.stringify(next)))
|
|
144
|
+
throw new AdminError('conflict');
|
|
145
|
+
}
|
|
146
|
+
registered(channel) {
|
|
147
|
+
const key = this.key(channel);
|
|
148
|
+
const raw = this.state.get(key);
|
|
149
|
+
const doc = this.read(channel, raw);
|
|
150
|
+
if (channel === 'feishu') {
|
|
151
|
+
const saved = this.state.get('feishu/registration');
|
|
152
|
+
if (!saved)
|
|
153
|
+
throw new AdminError('unavailable');
|
|
154
|
+
const domain = JSON.parse(saved).domain;
|
|
155
|
+
if (domain !== 'feishu' && domain !== 'lark')
|
|
156
|
+
throw new AdminError('unavailable');
|
|
157
|
+
doc.fields = { ...doc.fields, appId: '', domain: '' };
|
|
158
|
+
doc.secrets = { ...doc.secrets, appSecret: null };
|
|
159
|
+
}
|
|
160
|
+
doc.revision++;
|
|
161
|
+
if (!this.state.compareAndSet(key, raw, JSON.stringify(doc)))
|
|
162
|
+
throw new AdminError('conflict');
|
|
163
|
+
}
|
|
164
|
+
options(channel) {
|
|
165
|
+
const doc = this.read(channel);
|
|
166
|
+
if (!doc.enabled)
|
|
167
|
+
return;
|
|
168
|
+
if (doc.revision === 0)
|
|
169
|
+
return this.initial[channel];
|
|
170
|
+
return Object.fromEntries(Object.entries(doc.fields).filter(([, value]) => value !== ''));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { WebRoute } from '@deepseek-ai/dsh-host-webserver';
|
|
2
|
+
import { type Channel, type ChannelView } from './admin-config.js';
|
|
3
|
+
import type { LoginAdmin } from './login-admin.js';
|
|
4
|
+
interface Administration {
|
|
5
|
+
list(): ChannelView[];
|
|
6
|
+
save(channel: Channel, request: Record<string, unknown>): Promise<ChannelView>;
|
|
7
|
+
pair(channel: Channel): {
|
|
8
|
+
code: string;
|
|
9
|
+
expiresAt: number;
|
|
10
|
+
};
|
|
11
|
+
login: Pick<LoginAdmin, 'execute'>;
|
|
12
|
+
}
|
|
13
|
+
export declare function adminRoute(admin: Administration): WebRoute;
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { AdminError, isChannel, object } from './admin-config.js';
|
|
2
|
+
const statusCodes = { invalid: 400, forbidden: 403, not_found: 404, conflict: 409, unavailable: 503 };
|
|
3
|
+
async function body(req) {
|
|
4
|
+
const parts = [];
|
|
5
|
+
let size = 0;
|
|
6
|
+
for await (const data of req.iterator({ destroyOnReturn: false })) {
|
|
7
|
+
const chunk = Buffer.isBuffer(data) ? data : Buffer.from(data);
|
|
8
|
+
size += chunk.length;
|
|
9
|
+
if (size > 64 * 1024) {
|
|
10
|
+
req.resume();
|
|
11
|
+
throw new AdminError('invalid');
|
|
12
|
+
}
|
|
13
|
+
parts.push(chunk);
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
16
|
+
return object(JSON.parse(Buffer.concat(parts).toString('utf8')));
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
throw new AdminError('invalid');
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
export function adminRoute(admin) {
|
|
23
|
+
return { kind: 'exact', path: '/prism/im/admin', auth: 'required', async handler(req, res, peer) {
|
|
24
|
+
res.setHeader('Cache-Control', 'private, no-store');
|
|
25
|
+
res.setHeader('Content-Type', 'application/json; charset=utf-8');
|
|
26
|
+
res.setHeader('X-Content-Type-Options', 'nosniff');
|
|
27
|
+
res.setHeader('Referrer-Policy', 'no-referrer');
|
|
28
|
+
try {
|
|
29
|
+
if (!peer || peer.signal.aborted || peer.principal.kind !== 'owner')
|
|
30
|
+
throw new AdminError('forbidden');
|
|
31
|
+
if (req.headers['sec-fetch-site'] === 'cross-site')
|
|
32
|
+
throw new AdminError('forbidden');
|
|
33
|
+
if (req.method === 'GET') {
|
|
34
|
+
res.end(JSON.stringify({ channels: admin.list() }));
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
if (req.method !== 'POST') {
|
|
38
|
+
res.writeHead(405, { Allow: 'GET, POST' });
|
|
39
|
+
res.end();
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
const origin = typeof req.headers.origin === 'string' ? URL.parse(req.headers.origin) : null;
|
|
43
|
+
if (!origin || !['http:', 'https:'].includes(origin.protocol) || origin.host !== req.headers.host
|
|
44
|
+
|| req.headers['x-prism-request'] !== '1')
|
|
45
|
+
throw new AdminError('forbidden');
|
|
46
|
+
if (req.headers['content-type']?.split(';')[0].trim().toLowerCase() !== 'application/json')
|
|
47
|
+
throw new AdminError('invalid');
|
|
48
|
+
const input = await body(req);
|
|
49
|
+
if (peer.signal.aborted || !isChannel(input.channel) || typeof input.op !== 'string')
|
|
50
|
+
throw new AdminError('invalid');
|
|
51
|
+
if (input.op === 'pair') {
|
|
52
|
+
res.end(JSON.stringify(admin.pair(input.channel)));
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (input.op === 'save') {
|
|
56
|
+
res.end(JSON.stringify(await admin.save(input.channel, input)));
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
if (!['loginStart', 'loginStatus', 'loginCancel', 'loginCode'].includes(input.op)
|
|
60
|
+
|| (input.channel !== 'wechat' && input.channel !== 'feishu'))
|
|
61
|
+
throw new AdminError('invalid');
|
|
62
|
+
if (input.loginId !== undefined && typeof input.loginId !== 'string'
|
|
63
|
+
|| input.code !== undefined && typeof input.code !== 'string')
|
|
64
|
+
throw new AdminError('invalid');
|
|
65
|
+
res.end(JSON.stringify(await admin.login.execute({
|
|
66
|
+
channel: input.channel, op: input.op, loginId: input.loginId, code: input.code,
|
|
67
|
+
})));
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
const code = error instanceof AdminError ? error.code : 'unavailable';
|
|
71
|
+
res.statusCode = statusCodes[code];
|
|
72
|
+
res.end(JSON.stringify({ error: code }));
|
|
73
|
+
}
|
|
74
|
+
} };
|
|
75
|
+
}
|
|
@@ -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,101 @@
|
|
|
1
|
+
import { ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, Client, DefaultRestOptions, DiscordAPIError, Events, GatewayIntentBits, Partials, RESTJSONErrorCodes, } from 'discord.js';
|
|
2
|
+
import { channelSecret } from '../runtime.js';
|
|
3
|
+
const inspectPrefix = 'prism:inspect:';
|
|
4
|
+
export function discordMessage(message) {
|
|
5
|
+
if (message.channel.type !== ChannelType.DM || message.author.bot || message.webhookId ||
|
|
6
|
+
message.channel.recipientId !== message.author.id || !message.content.trim())
|
|
7
|
+
return;
|
|
8
|
+
return { chat: message.channelId, user: message.author.id, text: message.content, id: message.id };
|
|
9
|
+
}
|
|
10
|
+
export function discordPayload(reply) {
|
|
11
|
+
const button = reply.inspectTask && new ButtonBuilder().setStyle(ButtonStyle.Secondary)
|
|
12
|
+
.setCustomId(inspectPrefix + reply.inspectTask).setLabel(reply.inspectLabel || '/inspect');
|
|
13
|
+
return {
|
|
14
|
+
content: reply.text,
|
|
15
|
+
allowedMentions: { parse: [] },
|
|
16
|
+
components: button ? [new ActionRowBuilder().addComponents(button)] : [],
|
|
17
|
+
};
|
|
18
|
+
}
|
|
19
|
+
export async function startDiscord(config, runtime) {
|
|
20
|
+
if (runtime.signal.aborted)
|
|
21
|
+
return;
|
|
22
|
+
const token = channelSecret(runtime, 'token', config.tokenEnv ?? 'DISCORD_BOT_TOKEN');
|
|
23
|
+
if (!token)
|
|
24
|
+
throw new Error('Discord bot token environment variable is empty');
|
|
25
|
+
// Discord delivers DM contents without the privileged guild message-content intent.
|
|
26
|
+
const client = new Client({
|
|
27
|
+
intents: [GatewayIntentBits.DirectMessages], partials: [Partials.Channel],
|
|
28
|
+
rest: { makeRequest(url, init) {
|
|
29
|
+
runtime.signal.throwIfAborted();
|
|
30
|
+
const signal = init.signal ? AbortSignal.any([runtime.signal, init.signal]) : runtime.signal;
|
|
31
|
+
return DefaultRestOptions.makeRequest(url, { ...init, signal });
|
|
32
|
+
} },
|
|
33
|
+
});
|
|
34
|
+
const stopped = Promise.withResolvers();
|
|
35
|
+
const stop = () => stopped.resolve();
|
|
36
|
+
runtime.signal.addEventListener('abort', stop, { once: true });
|
|
37
|
+
const privateChannel = async (target) => {
|
|
38
|
+
const channel = await client.channels.fetch(target.chat);
|
|
39
|
+
if (channel?.type !== ChannelType.DM || channel.recipientId !== target.user)
|
|
40
|
+
throw new Error('Discord direct message recipient does not match');
|
|
41
|
+
return channel;
|
|
42
|
+
};
|
|
43
|
+
const send = async (target, reply) => {
|
|
44
|
+
const channel = await privateChannel(target);
|
|
45
|
+
const nonce = reply.deliveryId?.slice(0, 24);
|
|
46
|
+
const message = await channel.send({ ...discordPayload(reply), ...(nonce ? { nonce, enforceNonce: true } : {}) });
|
|
47
|
+
return message.id;
|
|
48
|
+
};
|
|
49
|
+
client.once(Events.ClientReady, ready => {
|
|
50
|
+
if (runtime.signal.aborted)
|
|
51
|
+
return;
|
|
52
|
+
const id = 'discord/' + ready.user.id;
|
|
53
|
+
const gateway = runtime.mount({
|
|
54
|
+
id, maxTextLength: 2000, permits: runtime.access(id, config.allowedUserIds),
|
|
55
|
+
send,
|
|
56
|
+
async edit(target, messageId, reply) {
|
|
57
|
+
const channel = await privateChannel(target);
|
|
58
|
+
try {
|
|
59
|
+
return (await channel.messages.edit(messageId, discordPayload(reply))).id;
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error instanceof DiscordAPIError && error.code === RESTJSONErrorCodes.UnknownMessage)
|
|
63
|
+
return send(target, reply);
|
|
64
|
+
throw error;
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
client.on(Events.MessageCreate, message => {
|
|
69
|
+
const input = discordMessage(message);
|
|
70
|
+
if (input)
|
|
71
|
+
void gateway.receive(input).catch(() => runtime.warn('Discord message processing failed'));
|
|
72
|
+
});
|
|
73
|
+
client.on(Events.InteractionCreate, async (interaction) => {
|
|
74
|
+
if (!interaction.isButton() || !interaction.customId.startsWith(inspectPrefix) ||
|
|
75
|
+
interaction.channel?.type !== ChannelType.DM || interaction.channel.recipientId !== interaction.user.id ||
|
|
76
|
+
interaction.message.author.id !== ready.user.id)
|
|
77
|
+
return;
|
|
78
|
+
try {
|
|
79
|
+
await interaction.deferUpdate();
|
|
80
|
+
await gateway.receive({ chat: interaction.channelId, user: interaction.user.id, id: interaction.id,
|
|
81
|
+
locale: interaction.locale, text: '/inspect ' + interaction.customId.slice(inspectPrefix.length) });
|
|
82
|
+
}
|
|
83
|
+
catch {
|
|
84
|
+
runtime.warn('Discord task inspection failed');
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
client.on(Events.Error, () => runtime.warn('Discord connection error'));
|
|
89
|
+
try {
|
|
90
|
+
// Login can wait indefinitely for a shard's first ready event, even after destroy().
|
|
91
|
+
await Promise.race([client.login(token).then(() => stopped.promise), stopped.promise]);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
if (!runtime.signal.aborted)
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
runtime.signal.removeEventListener('abort', stop);
|
|
99
|
+
await client.destroy();
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -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;
|