@dsh-prism/dsh-im-gateway 0.1.0 → 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 CHANGED
@@ -10,7 +10,13 @@ English | [简体中文](README.zh_CN.md)
10
10
 
11
11
  </div>
12
12
 
13
- ## Set up Prism
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
14
20
 
15
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/)
16
22
 
@@ -24,7 +30,7 @@ npm run build
24
30
  npm start
25
31
  ```
26
32
 
27
- ## Connect your chat app
33
+ ## Configure a chat app on the standalone host
28
34
 
29
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.
30
36
 
@@ -42,7 +48,7 @@ cp prism.example.json prism.config.json
42
48
  | OneBot | `im.onebot` |
43
49
  | Discord | `im.discord` |
44
50
 
45
- ## Link a private chat
51
+ ## Link a private chat on the standalone host
46
52
 
47
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.
48
54
 
package/README.zh_CN.md CHANGED
@@ -10,7 +10,13 @@
10
10
 
11
11
  </div>
12
12
 
13
- ## 接入棱镜
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
+ ## 从源码运行独立宿主
14
20
 
15
21
  需要 Node.js 24.9 或更高版本、npm、Git,以及对五个私有插件仓库的 Git 读取权限。检出脚本把匹配的插件和启动文件放入本机的 `runtime/` 目录,后续安装、配置和运行命令均在该目录执行。公开使用指南可直接阅读。需要调用示例模型时,请先在 DSH 凭据存储中配置 DeepSeek 凭据,或设置环境变量 `DEEPSEEK_API_KEY`。[安装指南](https://prism.dsh-plug.in/zh/)
16
22
 
@@ -24,7 +30,7 @@ npm run build
24
30
  npm start
25
31
  ```
26
32
 
27
- ## 连接聊天应用
33
+ ## 在独立宿主中配置聊天应用
28
34
 
29
35
  接入通道前,先在本机的 `runtime/` 中复制示例配置。各适配器会先认证平台上的用户身份,再将消息交给对话代理。
30
36
 
@@ -42,7 +48,7 @@ cp prism.example.json prism.config.json
42
48
  | OneBot | `im.onebot` |
43
49
  | Discord | `im.discord` |
44
50
 
45
- ## 绑定私聊
51
+ ## 在独立宿主中绑定私聊
46
52
 
47
53
  使用微信或飞书时,请在棱镜宿主上运行对应登录命令,并按提示扫码。使用同一个 `--config` 文件配置和启动网关后,注册信息会写入所配置的网关数据库,相应通道会启用。
48
54
 
@@ -0,0 +1,5 @@
1
+ - insert:
2
+ - id: dsh-im-gateway
3
+ name: '@dsh-prism/dsh-im-gateway'
4
+ config:
5
+ managed: true
@@ -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
+ }
@@ -1,5 +1,5 @@
1
1
  import { ActionRowBuilder, ButtonBuilder, ChannelType } from 'discord.js';
2
- import type { ChannelRuntime } from '../runtime.js';
2
+ import { type ChannelRuntime } from '../runtime.js';
3
3
  import type { Incoming, Reply } from '../transport.js';
4
4
  export interface DiscordConfig {
5
5
  tokenEnv?: string;
@@ -1,4 +1,5 @@
1
1
  import { ActionRowBuilder, ButtonBuilder, ButtonStyle, ChannelType, Client, DefaultRestOptions, DiscordAPIError, Events, GatewayIntentBits, Partials, RESTJSONErrorCodes, } from 'discord.js';
2
+ import { channelSecret } from '../runtime.js';
2
3
  const inspectPrefix = 'prism:inspect:';
3
4
  export function discordMessage(message) {
4
5
  if (message.channel.type !== ChannelType.DM || message.author.bot || message.webhookId ||
@@ -18,7 +19,7 @@ export function discordPayload(reply) {
18
19
  export async function startDiscord(config, runtime) {
19
20
  if (runtime.signal.aborted)
20
21
  return;
21
- const token = process.env[config.tokenEnv ?? 'DISCORD_BOT_TOKEN'];
22
+ const token = channelSecret(runtime, 'token', config.tokenEnv ?? 'DISCORD_BOT_TOKEN');
22
23
  if (!token)
23
24
  throw new Error('Discord bot token environment variable is empty');
24
25
  // Discord delivers DM contents without the privileged guild message-content intent.
@@ -1,4 +1,4 @@
1
- import type { ChannelRuntime } from '../runtime.js';
1
+ import { type ChannelRuntime } from '../runtime.js';
2
2
  export interface OneBotConfig {
3
3
  selfId: string;
4
4
  apiBase: string;
@@ -1,5 +1,6 @@
1
1
  import { createHmac, timingSafeEqual } from 'node:crypto';
2
- import { CallbackError, credential, messageText, signedEvents } from './signed-events.js';
2
+ import { requiredSecret } from '../runtime.js';
3
+ import { CallbackError, messageText, signedEvents } from './signed-events.js';
3
4
  function qqNumber(value) {
4
5
  if (!/^[1-9]\d*$/.test(String(value)) || !Number.isSafeInteger(Number(value)))
5
6
  return;
@@ -25,8 +26,8 @@ export function startOneBot(config, runtime) {
25
26
  }
26
27
  if (!base.pathname.endsWith('/'))
27
28
  base.pathname += '/';
28
- const token = credential(config.accessTokenEnv ?? 'ONEBOT_ACCESS_TOKEN');
29
- const secret = credential(config.eventSecretEnv ?? 'ONEBOT_EVENT_SECRET');
29
+ const token = requiredSecret(runtime, 'accessToken', config.accessTokenEnv ?? 'ONEBOT_ACCESS_TOKEN');
30
+ const secret = requiredSecret(runtime, 'eventSecret', config.eventSecretEnv ?? 'ONEBOT_EVENT_SECRET');
30
31
  const id = 'onebot/' + selfId;
31
32
  const access = runtime.access(id, config.allowedUserIds);
32
33
  const permits = (target) => target.chat === target.user && !!qqNumber(target.user) && target.user !== selfId && access(target);
@@ -1,4 +1,4 @@
1
- import type { ChannelRuntime } from '../runtime.js';
1
+ import { type ChannelRuntime } from '../runtime.js';
2
2
  export interface QQConfig {
3
3
  appId: string;
4
4
  appSecretEnv?: string;
@@ -1,5 +1,6 @@
1
1
  import { createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
2
- import { CallbackError, credential, messageText, signedEvents } from './signed-events.js';
2
+ import { requiredSecret } from '../runtime.js';
3
+ import { CallbackError, messageText, signedEvents } from './signed-events.js';
3
4
  /** Tencent signs timestamp || rawBody with the Ed25519 key derived from the app secret. */
4
5
  function signingKey(secret) {
5
6
  let seed = Buffer.from(secret);
@@ -14,7 +15,7 @@ const openId = (id) => typeof id === 'string' && /^[a-zA-Z0-9_-]{1,128}$/.test(i
14
15
  export function startQQ(options, runtime) {
15
16
  if (!/^\d+$/.test(options.appId) || typeof options.appId !== 'string')
16
17
  throw new Error('Invalid QQ appId');
17
- const secret = credential(options.appSecretEnv ?? 'QQ_BOT_SECRET');
18
+ const secret = requiredSecret(runtime, 'appSecret', options.appSecretEnv ?? 'QQ_BOT_SECRET');
18
19
  const privateKey = signingKey(secret);
19
20
  const publicKey = createPublicKey(privateKey);
20
21
  const id = 'qq/' + options.appId;
@@ -5,7 +5,6 @@ export declare class CallbackError extends Error {
5
5
  }
6
6
  /** Authentication always consumes the original bytes, including JSON whitespace. */
7
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
8
  export declare function messageText(reply: {
10
9
  text: string;
11
10
  inspectTask?: string;
@@ -44,12 +44,6 @@ export function signedEvents(authenticate, handle) {
44
44
  }
45
45
  };
46
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
47
  export function messageText(reply) {
54
48
  return reply.text + (reply.inspectTask ? '\n/inspect ' + reply.inspectTask : '');
55
49
  }
package/dist/feishu.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as Lark from '@larksuiteoapi/node-sdk';
2
- import type { ChannelRuntime } from './runtime.js';
2
+ import { type ChannelRuntime } from './runtime.js';
3
3
  import type { GatewayState } from './state.js';
4
4
  import type { Destination, ImTransport, Incoming, Reply } from './transport.js';
5
5
  export interface FeishuConfig {
@@ -16,7 +16,7 @@ type Registration = {
16
16
  openId?: string;
17
17
  };
18
18
  /** The SDK polls Feishu's app registration endpoint and switches domains for Lark tenants. */
19
- export declare function loginFeishu(state: Pick<GatewayState, 'set'>, onCode: (url: string) => void, signal?: AbortSignal, register?: typeof Lark.registerApp): Promise<Omit<Registration, 'appSecret'>>;
19
+ export declare function loginFeishu(state: Pick<GatewayState, 'set'>, onCode: (url: string, expireIn?: number) => void, signal?: AbortSignal, register?: typeof Lark.registerApp): Promise<Omit<Registration, 'appSecret'>>;
20
20
  type ChatEvent = {
21
21
  app_id?: string;
22
22
  sender?: {
package/dist/feishu.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import * as Lark from '@larksuiteoapi/node-sdk';
2
+ import { channelSecret } from './runtime.js';
2
3
  const registrationKey = 'feishu/registration';
3
4
  /** The SDK polls Feishu's app registration endpoint and switches domains for Lark tenants. */
4
5
  export async function loginFeishu(state, onCode, signal, register = Lark.registerApp) {
@@ -12,7 +13,7 @@ export async function loginFeishu(state, onCode, signal, register = Lark.registe
12
13
  scopes: { tenant: ['im:message.p2p_msg:readonly', 'im:message:send_as_bot', 'im:message:update'] },
13
14
  events: { items: { tenant: ['im.message.receive_v1'] } },
14
15
  },
15
- onQRCodeReady: ({ url }) => onCode(url),
16
+ onQRCodeReady: ({ url, expireIn }) => onCode(url, expireIn),
16
17
  onStatusChange: event => { if (event.status === 'domain_switched')
17
18
  domain = 'lark'; },
18
19
  });
@@ -23,14 +24,14 @@ export async function loginFeishu(state, onCode, signal, register = Lark.registe
23
24
  state.set(registrationKey, JSON.stringify({ ...info, appSecret: result.client_secret }));
24
25
  return info;
25
26
  }
26
- function credentials(config, state) {
27
+ function credentials(config, runtime) {
27
28
  if (config.appId || config.appSecretEnv) {
28
- const secret = process.env[config.appSecretEnv ?? 'FEISHU_APP_SECRET'];
29
+ const secret = channelSecret(runtime, 'appSecret', config.appSecretEnv ?? 'FEISHU_APP_SECRET');
29
30
  if (!config.appId || !secret)
30
31
  throw new Error('Feishu needs an appId and an app secret');
31
32
  return { appId: config.appId, appSecret: secret, domain: config.domain ?? 'feishu' };
32
33
  }
33
- const stored = state.get(registrationKey);
34
+ const stored = runtime.state.get(registrationKey);
34
35
  if (!stored)
35
36
  throw new Error('Feishu requires app credentials or prism-im login feishu');
36
37
  const saved = JSON.parse(stored);
@@ -106,7 +107,7 @@ export class FeishuTransport {
106
107
  }
107
108
  export async function startFeishu(config, runtime) {
108
109
  runtime.signal.throwIfAborted();
109
- const auth = credentials(config, runtime.state);
110
+ const auth = credentials(config, runtime);
110
111
  const id = 'feishu/' + auth.domain + '/' + auth.appId;
111
112
  const users = [...config.allowedUserIds ?? config.allowedUsers ?? [], ...auth.openId ? [auth.openId] : []];
112
113
  // Some SDK clients fall back to info at the fatal level. Keep credential-bearing HTTP objects off host logs.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Context } from '@deepseek-ai/cordis';
2
- import { type Locale } from './i18n.js';
2
+ import type { Locale } from './i18n.js';
3
3
  import type { TelegramConfig } from './telegram.js';
4
4
  import type { WechatConfig } from './channels/wechat.js';
5
5
  import type { FeishuConfig } from './feishu.js';
@@ -23,6 +23,7 @@ export interface Config {
23
23
  qq?: QQConfig;
24
24
  onebot?: OneBotConfig;
25
25
  discord?: DiscordConfig;
26
+ managed?: boolean;
26
27
  statePath?: string;
27
28
  locale?: Locale;
28
29
  }
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
- import { dirname } from 'node:path';
2
1
  import { dshPath } from '@deepseek-ai/dsh-home-paths';
3
- import { ImGateway } from './gateway.js';
4
2
  import { GatewayState } from './state.js';
5
- import { localeOf } from './i18n.js';
3
+ import { channels } from './admin-config.js';
4
+ import { adminRoute } from './admin-route.js';
5
+ import { ChannelSupervisor } from './supervisor.js';
6
+ import { LoginAdmin } from './login-admin.js';
6
7
  export { ImGateway } from './gateway.js';
7
8
  export { GatewayState, principal } from './state.js';
8
9
  export { TelegramTransport } from './telegram.js';
@@ -10,60 +11,37 @@ export { loginWechat } from './channels/wechat.js';
10
11
  export const name = 'dsh-im-gateway';
11
12
  export const inject = ['prism'];
12
13
  export function apply(ctx, config = {}) {
13
- if (![config.telegram, config.wechat, config.feishu, config.wecom, config.qq, config.onebot, config.discord].some(Boolean))
14
+ if (!config.managed && !channels.some(channel => config[channel]))
14
15
  return;
15
- const stop = new AbortController();
16
16
  const file = config.statePath ?? dshPath('data', 'prism', 'im.sqlite');
17
17
  const state = new GatewayState(file);
18
- const log = ctx.logger(name);
19
- const gateways = new Map();
20
- const workers = [];
21
- const disposers = [];
22
- const runtime = {
23
- directory: dirname(file), signal: stop.signal, state, warn: text => log.warn(text),
24
- access(channel, allowedUsers) {
25
- const configured = new Set(allowedUsers);
26
- return target => configured.has(target.user) || state.paired(channel, target);
27
- },
28
- mount(transport) {
29
- stop.signal.throwIfAborted();
30
- if (gateways.has(transport.id))
31
- throw new Error('Duplicate IM channel');
32
- const gateway = new ImGateway(ctx.get('prism', true), state, transport, () => log.warn('IM delivery pending: ' + transport.id.split('/')[0]), localeOf(config.locale) ?? 'zh');
33
- gateways.set(transport.id, gateway);
34
- gateway.start();
35
- return gateway;
36
- },
37
- webhook(path, handler) {
38
- if (!['/prism/im/qq', '/prism/im/onebot'].includes(path))
39
- throw new Error('Invalid IM callback route');
18
+ const runner = new ChannelSupervisor(ctx, config, state, file);
19
+ let login;
20
+ let unmount;
21
+ try {
22
+ if (config.managed) {
40
23
  const server = ctx.get('webServer', true);
41
24
  if (!server)
42
- throw new Error('A DSH Web host is required for IM callbacks');
43
- disposers.push(server.register({ kind: 'exact', path, auth: 'anonymous', handler }));
44
- },
45
- };
46
- function launch(name, value, start) {
47
- if (!value)
48
- return;
49
- workers.push(start(value).catch(error => {
50
- if (!stop.signal.aborted)
51
- log.error('IM channel %s stopped (%s); check its credentials and configuration.', name, error instanceof Error ? error.name : 'error');
52
- }));
25
+ throw new Error('DSH Web host required for IM settings');
26
+ login = new LoginAdmin(state, channel => runner.registered(channel));
27
+ unmount = server.register(adminRoute({
28
+ list: () => runner.list(), save: (channel, body) => runner.save(channel, body),
29
+ pair: channel => ({ code: state.issuePairingCode(channel), expiresAt: Date.now() + 600_000 }),
30
+ login,
31
+ }));
32
+ }
33
+ for (const channel of channels)
34
+ runner.start(channel);
35
+ }
36
+ catch (error) {
37
+ unmount?.();
38
+ void runner.close().finally(() => state.close());
39
+ throw error;
53
40
  }
54
- launch('telegram', config.telegram, async (opt) => (await import('./telegram.js')).startTelegram(opt, runtime));
55
- launch('wechat', config.wechat, async (opt) => (await import('./channels/wechat.js')).startWechat(opt, runtime));
56
- launch('feishu', config.feishu, async (opt) => (await import('./feishu.js')).startFeishu(opt, runtime));
57
- launch('wecom', config.wecom, async (opt) => (await import('./wecom.js')).startWecom(opt, runtime));
58
- launch('qq', config.qq, async (opt) => (await import('./channels/qq.js')).startQQ(opt, runtime));
59
- launch('onebot', config.onebot, async (opt) => (await import('./channels/onebot.js')).startOneBot(opt, runtime));
60
- launch('discord', config.discord, async (opt) => (await import('./channels/discord.js')).startDiscord(opt, runtime));
61
41
  return async () => {
62
- for (const dispose of disposers)
63
- dispose();
64
- stop.abort();
65
- await Promise.allSettled(workers);
66
- await Promise.all([...gateways.values()].map(gateway => gateway.close()));
42
+ unmount?.();
43
+ await login?.close();
44
+ await runner.close();
67
45
  state.close();
68
46
  };
69
47
  }
@@ -0,0 +1,37 @@
1
+ import { GatewayState } from './state.js';
2
+ type Channel = 'wechat' | 'feishu';
3
+ type Status = 'starting' | 'waiting' | 'code' | 'complete' | 'cancelled' | 'expired' | 'error';
4
+ export interface LoginView {
5
+ loginId: string;
6
+ channel: Channel;
7
+ status: Status;
8
+ url?: string;
9
+ expiresAt: number;
10
+ }
11
+ type Driver = (staging: GatewayState, showQr: (url: string, expireIn?: number) => void, askCode: () => Promise<string>, signal: AbortSignal) => Promise<unknown>;
12
+ interface Options {
13
+ drivers?: Partial<Record<Channel, Driver>>;
14
+ timeoutMs?: number;
15
+ }
16
+ /** The host owns provider polling. The settings UI sees only the QR challenge and a short-lived handle. */
17
+ export declare class LoginAdmin {
18
+ private readonly state;
19
+ private readonly onComplete;
20
+ private readonly options;
21
+ private readonly sessions;
22
+ private readonly workers;
23
+ private closed;
24
+ constructor(state: GatewayState, onComplete: (channel: Channel) => Promise<void> | void, options?: Options);
25
+ private finish;
26
+ private checkDeadline;
27
+ private armDeadline;
28
+ private poll;
29
+ execute(body: {
30
+ op: string;
31
+ channel: string;
32
+ loginId?: string;
33
+ code?: string;
34
+ }): Promise<LoginView>;
35
+ close(): Promise<void>;
36
+ }
37
+ export {};
@@ -0,0 +1,163 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { AdminError } from './admin-config.js';
3
+ import { loginWechat } from './channels/wechat.js';
4
+ import { GatewayState } from './state.js';
5
+ const defaults = {
6
+ wechat: loginWechat,
7
+ feishu: async (staging, showQr, _askCode, signal) => (await import('./feishu.js')).loginFeishu(staging, showQr, signal),
8
+ };
9
+ const trustedQrHosts = {
10
+ wechat: /(^|\.)(weixin\.qq\.com|wechat\.com)$/,
11
+ feishu: /(^|\.)(feishu\.cn|larksuite\.com)$/,
12
+ };
13
+ function pending(status) { return status === 'starting' || status === 'waiting' || status === 'code'; }
14
+ function expired(error) {
15
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === 'expired_token'
16
+ || error instanceof Error && (error.name === 'TimeoutError' || error.message === 'iLink login QR expired');
17
+ }
18
+ /** The host owns provider polling. The settings UI sees only the QR challenge and a short-lived handle. */
19
+ export class LoginAdmin {
20
+ state;
21
+ onComplete;
22
+ options;
23
+ sessions = new Map();
24
+ workers = new Set();
25
+ closed = false;
26
+ constructor(state, onComplete, options = {}) {
27
+ this.state = state;
28
+ this.onComplete = onComplete;
29
+ this.options = options;
30
+ }
31
+ finish(session, status) {
32
+ if (!pending(session.view.status))
33
+ return;
34
+ session.view.status = status;
35
+ delete session.view.url;
36
+ clearTimeout(session.timer);
37
+ if (status !== 'complete') {
38
+ session.controller.abort();
39
+ session.code?.reject(session.controller.signal.reason);
40
+ }
41
+ delete session.code;
42
+ }
43
+ checkDeadline(session) {
44
+ if (Date.now() >= session.view.expiresAt)
45
+ this.finish(session, 'expired');
46
+ }
47
+ armDeadline(session, expiresAt) {
48
+ clearTimeout(session.timer);
49
+ session.view.expiresAt = expiresAt;
50
+ this.checkDeadline(session);
51
+ if (!pending(session.view.status))
52
+ return;
53
+ session.timer = setTimeout(() => this.finish(session, 'expired'), expiresAt - Date.now());
54
+ session.timer.unref();
55
+ }
56
+ async poll(session) {
57
+ const { channel } = session.view;
58
+ const key = channel + '/registration';
59
+ // The CLI drivers persist before resolving. Keep late successes from a cancelled
60
+ // attempt out of the live store, including when the provider ignores cancellation.
61
+ const staging = new GatewayState(':memory:');
62
+ const signal = session.controller.signal;
63
+ try {
64
+ const previous = this.state.get(key);
65
+ if (previous !== undefined)
66
+ staging.set(key, previous);
67
+ const driver = this.options.drivers?.[channel] ?? defaults[channel];
68
+ await driver(staging, (raw, expireIn) => {
69
+ signal.throwIfAborted();
70
+ if (typeof expireIn === 'number' && Number.isFinite(expireIn)) {
71
+ this.armDeadline(session, Math.min(session.view.expiresAt, Date.now() + Math.max(0, expireIn) * 1000));
72
+ }
73
+ this.checkDeadline(session);
74
+ signal.throwIfAborted();
75
+ const url = new URL(raw);
76
+ if (url.protocol !== 'https:' || url.username || url.password || url.port || !trustedQrHosts[channel].test(url.hostname)) {
77
+ throw new Error('Unexpected provider QR address');
78
+ }
79
+ session.view.status = 'waiting';
80
+ session.view.url = url.href;
81
+ }, () => {
82
+ this.checkDeadline(session);
83
+ signal.throwIfAborted();
84
+ if (channel !== 'wechat' || session.code)
85
+ throw new Error('Unexpected verification prompt');
86
+ session.view.status = 'code';
87
+ session.code = Promise.withResolvers();
88
+ return session.code.promise;
89
+ }, signal);
90
+ this.checkDeadline(session);
91
+ signal.throwIfAborted();
92
+ const registration = staging.get(key);
93
+ if (!registration || this.state.get(key) !== previous)
94
+ throw new Error('Registration was missing or changed');
95
+ this.state.set(key, registration);
96
+ this.finish(session, 'complete');
97
+ await this.onComplete(channel);
98
+ }
99
+ catch (error) {
100
+ if (session.view.status === 'complete')
101
+ session.view.status = 'error';
102
+ else
103
+ this.finish(session, expired(error) ? 'expired' : 'error');
104
+ }
105
+ finally {
106
+ staging.close();
107
+ }
108
+ }
109
+ async execute(body) {
110
+ if (this.closed)
111
+ throw new AdminError('unavailable');
112
+ const channel = body.channel;
113
+ if (channel !== 'wechat' && channel !== 'feishu')
114
+ throw new AdminError('invalid');
115
+ let session = this.sessions.get(channel);
116
+ if (session)
117
+ this.checkDeadline(session);
118
+ if (body.op === 'loginStart') {
119
+ // Repeated clicks and a retry after a lost response share the active challenge.
120
+ if (session && pending(session.view.status))
121
+ return { ...session.view };
122
+ const timeout = this.options.timeoutMs ?? (channel === 'wechat' ? 300_000 : 600_000);
123
+ const next = {
124
+ view: { loginId: randomUUID(), channel, status: 'starting', expiresAt: Date.now() + timeout },
125
+ controller: new AbortController(),
126
+ };
127
+ this.sessions.set(channel, next);
128
+ this.armDeadline(next, next.view.expiresAt);
129
+ const worker = this.poll(next);
130
+ this.workers.add(worker);
131
+ void worker.then(() => this.workers.delete(worker), () => this.workers.delete(worker));
132
+ return { ...next.view };
133
+ }
134
+ if (!['loginStatus', 'loginCode', 'loginCancel'].includes(body.op))
135
+ throw new AdminError('invalid');
136
+ if (!session || body.loginId !== session.view.loginId)
137
+ throw new AdminError('not_found');
138
+ if (body.op === 'loginStatus')
139
+ return { ...session.view };
140
+ if (session.view.status === 'expired')
141
+ throw new AdminError('not_found');
142
+ if (body.op === 'loginCancel') {
143
+ this.finish(session, 'cancelled');
144
+ }
145
+ else {
146
+ if (channel !== 'wechat' || typeof body.code !== 'string' || !/^\d{1,16}$/.test(body.code))
147
+ throw new AdminError('invalid');
148
+ if (session.view.status !== 'code' || !session.code)
149
+ throw new AdminError('conflict');
150
+ session.code.resolve(body.code);
151
+ delete session.code;
152
+ session.view.status = 'waiting';
153
+ }
154
+ return { ...session.view };
155
+ }
156
+ async close() {
157
+ this.closed = true;
158
+ for (const session of this.sessions.values())
159
+ this.finish(session, 'cancelled');
160
+ await Promise.all(this.workers);
161
+ this.sessions.clear();
162
+ }
163
+ }
package/dist/runtime.d.ts CHANGED
@@ -6,8 +6,11 @@ export interface ChannelRuntime {
6
6
  readonly signal: AbortSignal;
7
7
  readonly state: GatewayState;
8
8
  readonly directory: string;
9
+ readSecret?(field: string): string | undefined;
9
10
  mount(transport: ImTransport): ImGateway;
10
11
  access(channel: string, allowedUsers?: readonly string[]): (target: Destination) => boolean;
11
12
  warn(message: string): void;
12
13
  webhook(path: string, handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>): void;
13
14
  }
15
+ export declare function channelSecret(runtime: ChannelRuntime, field: string, env: string, fallback?: () => string | undefined): string | undefined;
16
+ export declare function requiredSecret(runtime: ChannelRuntime, field: string, env: string): string;
package/dist/runtime.js CHANGED
@@ -1 +1,9 @@
1
- export {};
1
+ export function channelSecret(runtime, field, env, fallback) {
2
+ return runtime.readSecret ? runtime.readSecret(field) : process.env[env] ?? fallback?.();
3
+ }
4
+ export function requiredSecret(runtime, field, env) {
5
+ const value = channelSecret(runtime, field, env);
6
+ if (!value?.trim())
7
+ throw new Error('Channel credential missing');
8
+ return value;
9
+ }
package/dist/state.d.ts CHANGED
@@ -18,6 +18,7 @@ export declare class GatewayState {
18
18
  advance(channel: string, next: number): void;
19
19
  get(key: string): string | undefined;
20
20
  set(key: string, value: string): void;
21
+ compareAndSet(key: string, previous: string | undefined, value: string): boolean;
21
22
  paired(channel: string, target: Destination): boolean;
22
23
  issuePairingCode(channel: string): string;
23
24
  claim(channel: string, target: Destination, code: string): boolean;
package/dist/state.js CHANGED
@@ -91,6 +91,12 @@ export class GatewayState {
91
91
  set(key, value) {
92
92
  this.db.prepare('INSERT OR REPLACE INTO gateway_values VALUES (?,?)').run(key, value);
93
93
  }
94
+ compareAndSet(key, previous, value) {
95
+ const result = previous === undefined
96
+ ? this.db.prepare('INSERT OR IGNORE INTO gateway_values VALUES (?, ?)').run(key, value)
97
+ : this.db.prepare('UPDATE gateway_values SET value=? WHERE key=? AND value=?').run(value, key, previous);
98
+ return Number(result.changes) === 1;
99
+ }
94
100
  paired(channel, target) {
95
101
  return !!this.db.prepare('SELECT 1 FROM authorized_chats WHERE owner=?').get(principal(channel, target));
96
102
  }
@@ -0,0 +1,30 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import type { Config } from './index.js';
3
+ import type { GatewayState } from './state.js';
4
+ import type { ChannelRuntime } from './runtime.js';
5
+ import { ChannelConfiguration, type Channel } from './admin-config.js';
6
+ type Starters = {
7
+ [K in Channel]: (options: NonNullable<Config[K]>, runtime: ChannelRuntime) => Promise<void>;
8
+ };
9
+ export declare class ChannelSupervisor {
10
+ private readonly ctx;
11
+ private readonly config;
12
+ private readonly state;
13
+ private readonly file;
14
+ private readonly starters;
15
+ readonly configuration: ChannelConfiguration;
16
+ private active;
17
+ private pending;
18
+ private closed;
19
+ constructor(ctx: Context, config: Config, state: GatewayState, file: string, starters?: Starters);
20
+ view(channel: Channel): import("./admin-config.js").ChannelView;
21
+ list(): import("./admin-config.js").ChannelView[];
22
+ save(channel: Channel, request: Record<string, unknown>): Promise<import("./admin-config.js").ChannelView>;
23
+ registered(channel: 'wechat' | 'feishu'): Promise<void>;
24
+ reload(channel: Channel): Promise<void>;
25
+ start<K extends Channel>(channel: K): void;
26
+ private release;
27
+ private stop;
28
+ close(): Promise<void>;
29
+ }
30
+ export {};
@@ -0,0 +1,129 @@
1
+ import { dirname } from 'node:path';
2
+ import { ImGateway } from './gateway.js';
3
+ import { localeOf } from './i18n.js';
4
+ import { channels, ChannelConfiguration } from './admin-config.js';
5
+ const adapters = {
6
+ telegram: async (config, rt) => (await import('./telegram.js')).startTelegram(config, rt),
7
+ wechat: async (config, rt) => (await import('./channels/wechat.js')).startWechat(config, rt),
8
+ feishu: async (config, rt) => (await import('./feishu.js')).startFeishu(config, rt),
9
+ wecom: async (config, rt) => (await import('./wecom.js')).startWecom(config, rt),
10
+ qq: async (config, rt) => (await import('./channels/qq.js')).startQQ(config, rt),
11
+ onebot: async (config, rt) => (await import('./channels/onebot.js')).startOneBot(config, rt),
12
+ discord: async (config, rt) => (await import('./channels/discord.js')).startDiscord(config, rt),
13
+ };
14
+ export class ChannelSupervisor {
15
+ ctx;
16
+ config;
17
+ state;
18
+ file;
19
+ starters;
20
+ configuration;
21
+ active = new Map();
22
+ pending = new Map();
23
+ closed = false;
24
+ constructor(ctx, config, state, file, starters = adapters) {
25
+ this.ctx = ctx;
26
+ this.config = config;
27
+ this.state = state;
28
+ this.file = file;
29
+ this.starters = starters;
30
+ this.configuration = new ChannelConfiguration(state, config);
31
+ }
32
+ view(channel) {
33
+ return this.configuration.view(channel, this.active.get(channel)?.status ?? 'disabled');
34
+ }
35
+ list() { return channels.map(channel => this.view(channel)); }
36
+ async save(channel, request) {
37
+ this.configuration.save(channel, request);
38
+ await this.reload(channel);
39
+ return this.view(channel);
40
+ }
41
+ async registered(channel) {
42
+ this.configuration.registered(channel);
43
+ await this.reload(channel);
44
+ }
45
+ reload(channel) {
46
+ const previous = this.pending.get(channel) ?? Promise.resolve();
47
+ const next = previous.catch(() => { }).then(async () => {
48
+ await this.stop(channel);
49
+ if (!this.closed)
50
+ this.start(channel);
51
+ });
52
+ this.pending.set(channel, next);
53
+ const clear = () => { if (this.pending.get(channel) === next)
54
+ this.pending.delete(channel); };
55
+ void next.then(clear, clear);
56
+ return next;
57
+ }
58
+ start(channel) {
59
+ const options = (this.config.managed ? this.configuration.options(channel) : this.config[channel]);
60
+ if (!options || this.closed)
61
+ return;
62
+ const task = { status: 'starting', stop: new AbortController(), gateways: new Map(), routes: [], worker: Promise.resolve() };
63
+ this.active.set(channel, task);
64
+ const signal = task.stop.signal;
65
+ const log = this.ctx.logger('dsh-im-gateway');
66
+ const runtime = {
67
+ state: this.state, directory: dirname(this.file), signal,
68
+ ...(this.config.managed && { readSecret: field => this.configuration.secret(channel, field) }),
69
+ warn: message => log.warn(message),
70
+ access: (id, users) => {
71
+ const allowed = new Set(users);
72
+ return target => !signal.aborted && (allowed.has(target.user) || this.state.paired(id, target));
73
+ },
74
+ mount: transport => {
75
+ signal.throwIfAborted();
76
+ if (task.gateways.has(transport.id))
77
+ throw new Error('Duplicate IM transport');
78
+ const gateway = new ImGateway(this.ctx.get('prism', true), this.state, transport, () => log.warn('IM delivery pending: ' + channel), localeOf(this.config.locale) ?? 'zh');
79
+ task.gateways.set(transport.id, gateway);
80
+ gateway.start();
81
+ task.status = 'running';
82
+ return gateway;
83
+ },
84
+ webhook: (path, handler) => {
85
+ signal.throwIfAborted();
86
+ if (!['/prism/im/qq', '/prism/im/onebot'].includes(path))
87
+ throw new Error('Invalid IM callback route');
88
+ const server = this.ctx.get('webServer', true);
89
+ if (!server)
90
+ throw new Error('DSH Web host required');
91
+ task.routes.push(server.register({ kind: 'exact', path, auth: 'anonymous', handler }));
92
+ },
93
+ };
94
+ task.worker = Promise.resolve().then(() => {
95
+ signal.throwIfAborted();
96
+ return this.starters[channel](options, runtime);
97
+ }).then(() => {
98
+ if (channel === 'wechat' && !signal.aborted)
99
+ throw new Error('WeChat polling ended');
100
+ }).catch(async () => {
101
+ if (signal.aborted)
102
+ return;
103
+ task.status = 'error';
104
+ log.error('IM channel %s stopped; check its credentials and configuration.', channel);
105
+ await this.release(task);
106
+ });
107
+ }
108
+ async release(task) {
109
+ task.stop.abort();
110
+ for (const dispose of task.routes.splice(0))
111
+ dispose();
112
+ const gateways = [...task.gateways.values()];
113
+ task.gateways.clear();
114
+ await Promise.allSettled(gateways.map(gateway => gateway.close()));
115
+ }
116
+ async stop(channel) {
117
+ const task = this.active.get(channel);
118
+ if (!task)
119
+ return;
120
+ await this.release(task);
121
+ await task.worker;
122
+ this.active.delete(channel);
123
+ }
124
+ async close() {
125
+ this.closed = true;
126
+ await Promise.allSettled([...this.pending.values()]);
127
+ await Promise.allSettled(channels.map(channel => this.stop(channel)));
128
+ }
129
+ }
@@ -1,7 +1,7 @@
1
1
  import type { ImGateway } from './gateway.js';
2
2
  import type { GatewayState } from './state.js';
3
3
  import type { Destination, ImTransport, Incoming, Reply } from './transport.js';
4
- import type { ChannelRuntime } from './runtime.js';
4
+ import { type ChannelRuntime } from './runtime.js';
5
5
  export interface TelegramConfig {
6
6
  tokenEnv?: string;
7
7
  allowedUserIds?: string[];
package/dist/telegram.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
+ import { channelSecret } from './runtime.js';
2
3
  class ApiError extends Error {
3
4
  httpStatus;
4
5
  detail;
@@ -123,7 +124,7 @@ export class TelegramTransport {
123
124
  }
124
125
  }
125
126
  export function startTelegram(options, runtime) {
126
- const token = process.env[options.tokenEnv ?? 'TELEGRAM_BOT_TOKEN'] ?? runtime.state.get('telegram/token');
127
+ const token = channelSecret(runtime, 'token', options.tokenEnv ?? 'TELEGRAM_BOT_TOKEN', () => runtime.state.get('telegram/token'));
127
128
  if (!token)
128
129
  throw new Error('Missing Telegram bot token');
129
130
  const channel = 'telegram/' + token.split(':')[0];
package/dist/wecom.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { WSClient, type TextMessage } from '@wecom/aibot-node-sdk';
2
- import type { ChannelRuntime } from './runtime.js';
2
+ import { type ChannelRuntime } from './runtime.js';
3
3
  import type { Destination, ImTransport, Incoming, Reply } from './transport.js';
4
4
  export interface WecomConfig {
5
5
  botId: string;
package/dist/wecom.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { WSClient } from '@wecom/aibot-node-sdk';
2
+ import { channelSecret } from './runtime.js';
2
3
  export function decodeWecom(message, botId) {
3
4
  const user = message?.from?.userid;
4
5
  const text = message?.text?.content;
@@ -32,7 +33,7 @@ export class WecomTransport {
32
33
  }
33
34
  export function startWecom(config, runtime) {
34
35
  runtime.signal.throwIfAborted();
35
- const secret = process.env[config.secretEnv ?? 'WECOM_BOT_SECRET'];
36
+ const secret = channelSecret(runtime, 'secret', config.secretEnv ?? 'WECOM_BOT_SECRET');
36
37
  if (!config.botId || !secret)
37
38
  throw new Error('WeCom needs a botId and a bot secret');
38
39
  const id = 'wecom/' + config.botId;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dsh-prism/dsh-im-gateway",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -10,7 +10,8 @@
10
10
  "import": "./dist/index.js"
11
11
  },
12
12
  "./locale/*.json": "./locale/*.json",
13
- "./package.json": "./package.json"
13
+ "./package.json": "./package.json",
14
+ "./cordis.patch.yml": "./cordis.patch.yml"
14
15
  },
15
16
  "files": [
16
17
  "dist/",
@@ -20,7 +21,8 @@
20
21
  "locale/*.json",
21
22
  "icon.svg",
22
23
  "scripts/prism-im.mjs",
23
- "README.zh_CN.md"
24
+ "README.zh_CN.md",
25
+ "cordis.patch.yml"
24
26
  ],
25
27
  "engines": {
26
28
  "node": ">=24.0.0",
@@ -32,7 +34,7 @@
32
34
  "peerDependencies": {
33
35
  "@deepseek-ai/cordis": "4.2.0-alpha.1",
34
36
  "@deepseek-ai/dsh-home-paths": "0.2.3-alpha.2",
35
- "@dsh-prism/dsh-orchestrator": "0.1.0",
37
+ "@dsh-prism/dsh-orchestrator": "^0.1.0",
36
38
  "@deepseek-ai/dsh-host-webserver": "0.2.3-alpha.2"
37
39
  },
38
40
  "scripts": {
@@ -56,5 +58,10 @@
56
58
  "repository": {
57
59
  "type": "git",
58
60
  "url": "git+https://github.com/dsh-plugins/dsh-im-gateway.git"
61
+ },
62
+ "dsh": {
63
+ "bundle": {
64
+ "patch": "./cordis.patch.yml"
65
+ }
59
66
  }
60
67
  }