mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-09 04:13:17 +08:00
Add Telegram and Discord IM channels
This commit is contained in:
parent
7123fce47a
commit
cb74e1c4c7
66 changed files with 8579 additions and 1910 deletions
|
|
@ -5,10 +5,17 @@ export const name = 'dsh-dingtalk-host';
|
|||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) return installDingtalkRpc(ctx, config.controller, config.rpcOptions);
|
||||
if (config?.controller) {
|
||||
return installDingtalkRpc(ctx, config.controller, config.rpcOptions, config.rpcAuthority);
|
||||
}
|
||||
|
||||
const production = await createProductionController(ctx, config, config.internals);
|
||||
const disposeRpc = installDingtalkRpc(ctx, production.controller, config.rpcOptions);
|
||||
const disposeRpc = installDingtalkRpc(
|
||||
ctx,
|
||||
production.controller,
|
||||
config.rpcOptions,
|
||||
config.rpcAuthority,
|
||||
);
|
||||
ctx.effect(() => async () => {
|
||||
await production.close();
|
||||
}, 'dsh-dingtalk: close bot connections');
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import QRCode from 'qrcode';
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const DINGTALK_RPC_CHANNEL = '/dingtalk';
|
||||
export const DINGTALK_ENDPOINTS = Object.freeze({
|
||||
|
|
@ -224,13 +225,13 @@ export function createDingtalkRpcHandler(controller, { encodeQr = qrDataUrl } =
|
|||
};
|
||||
}
|
||||
|
||||
export function installDingtalkRpc(ctx, controller, options) {
|
||||
export function installDingtalkRpc(ctx, controller, options, authority) {
|
||||
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
|
||||
throw new TypeError('DSH Host Connection RPC is required');
|
||||
}
|
||||
return ctx.connection.rpc.handle(
|
||||
DINGTALK_RPC_CHANNEL,
|
||||
createDingtalkRpcHandler(controller, options),
|
||||
{ authority: 'loopback' },
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
30
plugin-src/host/channels/discord/index.mjs
Normal file
30
plugin-src/host/channels/discord/index.mjs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { createProductionController } from './production.mjs';
|
||||
import { installDiscordRpc } from './rpc.mjs';
|
||||
|
||||
export const name = 'dsh-im-discord-host';
|
||||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) {
|
||||
return installDiscordRpc(ctx, config.controller, config.rpcAuthority);
|
||||
}
|
||||
const production = await createProductionController(ctx, config, config.internals ?? {});
|
||||
const disposeRpc = installDiscordRpc(ctx, production.controller, config.rpcAuthority);
|
||||
ctx.effect(() => async () => production.close(), 'dsh-im: close Discord bot connections');
|
||||
return disposeRpc;
|
||||
}
|
||||
|
||||
export function createDiscordHostPlugin(config) {
|
||||
return Object.freeze({ name, inject, apply: (ctx) => apply(ctx, config) });
|
||||
}
|
||||
|
||||
export { createProductionController } from './production.mjs';
|
||||
export {
|
||||
DISCORD_ENDPOINTS,
|
||||
DISCORD_RPC_CHANNEL,
|
||||
DISCORD_RPC_ENDPOINTS,
|
||||
createDiscordRpcHandler,
|
||||
installDiscordRpc,
|
||||
} from './rpc.mjs';
|
||||
export { DiscordController } from '../../../../src/channels/discord/discord-controller.mjs';
|
||||
export { DiscordRuntime } from '../../../../src/channels/discord/discord-runtime.mjs';
|
||||
17
plugin-src/host/channels/discord/production.mjs
Normal file
17
plugin-src/host/channels/discord/production.mjs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { DiscordConfigStore } from '../../../../src/channels/discord/config-store.mjs';
|
||||
import { DiscordController } from '../../../../src/channels/discord/discord-controller.mjs';
|
||||
import { DiscordHarnessClient } from '../../../../src/channels/discord/harness-client.mjs';
|
||||
import { DiscordRuntime } from '../../../../src/channels/discord/discord-runtime.mjs';
|
||||
import { DiscordStateStore } from '../../../../src/channels/discord/state-store.mjs';
|
||||
import { createTokenProductionController } from '../shared/production.mjs';
|
||||
|
||||
export function createProductionController(ctx, config = {}, internals = {}) {
|
||||
return createTokenProductionController(ctx, config, internals, {
|
||||
channel: 'discord',
|
||||
ConfigStore: DiscordConfigStore,
|
||||
StateStore: DiscordStateStore,
|
||||
HarnessClient: DiscordHarnessClient,
|
||||
Controller: DiscordController,
|
||||
Runtime: DiscordRuntime,
|
||||
});
|
||||
}
|
||||
21
plugin-src/host/channels/discord/rpc.mjs
Normal file
21
plugin-src/host/channels/discord/rpc.mjs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import {
|
||||
TOKEN_BOT_ENDPOINTS,
|
||||
createTokenBotRpcHandler,
|
||||
installTokenBotRpc,
|
||||
} from '../shared/rpc.mjs';
|
||||
|
||||
export const DISCORD_RPC_CHANNEL = '/discord';
|
||||
export const DISCORD_ENDPOINTS = TOKEN_BOT_ENDPOINTS;
|
||||
export const DISCORD_RPC_ENDPOINTS = Object.freeze(Object.values(DISCORD_ENDPOINTS));
|
||||
|
||||
export function createDiscordRpcHandler(controller) {
|
||||
return createTokenBotRpcHandler(controller, { channel: 'Discord' });
|
||||
}
|
||||
|
||||
export function installDiscordRpc(ctx, controller, authority) {
|
||||
return installTokenBotRpc(ctx, controller, {
|
||||
channel: 'Discord',
|
||||
rpcChannel: DISCORD_RPC_CHANNEL,
|
||||
authority,
|
||||
});
|
||||
}
|
||||
|
|
@ -24,10 +24,17 @@ function controllerFrom(ctx, config) {
|
|||
*/
|
||||
export async function apply(ctx, config = {}) {
|
||||
const controller = controllerFrom(ctx, config);
|
||||
if (controller) return installFeishuRpc(ctx, controller);
|
||||
if (controller) {
|
||||
return installFeishuRpc(ctx, controller, config.rpcOptions, config.rpcAuthority);
|
||||
}
|
||||
|
||||
const production = await createProductionController(ctx, config);
|
||||
const disposeRpc = installFeishuRpc(ctx, production.controller);
|
||||
const disposeRpc = installFeishuRpc(
|
||||
ctx,
|
||||
production.controller,
|
||||
config.rpcOptions,
|
||||
config.rpcAuthority,
|
||||
);
|
||||
ctx.effect(() => async () => {
|
||||
await production.close();
|
||||
}, 'dsh-feishu: close controller and live connection');
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import QRCode from 'qrcode';
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
import {
|
||||
FEISHU_ENDPOINTS,
|
||||
FEISHU_RPC_CHANNEL,
|
||||
|
|
@ -440,14 +441,14 @@ export function createFeishuRpcHandler(controller, { encodeQr = qrCodeDataUrl }
|
|||
};
|
||||
}
|
||||
|
||||
/** Register the loopback-only `/feishu` logical channel. */
|
||||
export function installFeishuRpc(ctx, controller, options) {
|
||||
/** Register the `/feishu` logical channel with its configured browser authority. */
|
||||
export function installFeishuRpc(ctx, controller, options, authority) {
|
||||
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
|
||||
throw new TypeError('DSH Host Connection RPC is required');
|
||||
}
|
||||
return ctx.connection.rpc.handle(
|
||||
FEISHU_RPC_CHANNEL,
|
||||
createFeishuRpcHandler(controller, options),
|
||||
{ authority: 'loopback' },
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,9 +5,16 @@ export const name = 'dsh-im-qq-host';
|
|||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) return installQqRpc(ctx, config.controller, config.rpcOptions);
|
||||
if (config?.controller) {
|
||||
return installQqRpc(ctx, config.controller, config.rpcOptions, config.rpcAuthority);
|
||||
}
|
||||
const production = await createProductionController(ctx, config, config.internals);
|
||||
const disposeRpc = installQqRpc(ctx, production.controller, config.rpcOptions);
|
||||
const disposeRpc = installQqRpc(
|
||||
ctx,
|
||||
production.controller,
|
||||
config.rpcOptions,
|
||||
config.rpcAuthority,
|
||||
);
|
||||
ctx.effect(() => async () => production.close(), 'dsh-im: close QQ bot connections');
|
||||
return disposeRpc;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import QRCode from 'qrcode';
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const QQ_RPC_CHANNEL = '/qq';
|
||||
export const QQ_ENDPOINTS = Object.freeze({
|
||||
|
|
@ -133,9 +134,13 @@ export function createQqRpcHandler(controller, { encodeQr = qrDataUrl } = {}) {
|
|||
};
|
||||
}
|
||||
|
||||
export function installQqRpc(ctx, controller, options) {
|
||||
export function installQqRpc(ctx, controller, options, authority) {
|
||||
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
|
||||
throw new TypeError('DSH Host Connection RPC is required');
|
||||
}
|
||||
return ctx.connection.rpc.handle(QQ_RPC_CHANNEL, createQqRpcHandler(controller, options), { authority: 'loopback' });
|
||||
return ctx.connection.rpc.handle(
|
||||
QQ_RPC_CHANNEL,
|
||||
createQqRpcHandler(controller, options),
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
133
plugin-src/host/channels/shared/connection-supervisor.mjs
Normal file
133
plugin-src/host/channels/shared/connection-supervisor.mjs
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
const DEFAULT_RETRY_DELAYS_MS = Object.freeze([250, 1_000, 3_000, 5_000, 10_000, 30_000]);
|
||||
|
||||
function retryDelays(value) {
|
||||
if (!Array.isArray(value) || value.length === 0) return [...DEFAULT_RETRY_DELAYS_MS];
|
||||
const valid = value.filter((delay) => Number.isFinite(delay) && delay >= 0);
|
||||
return valid.length > 0 ? valid : [...DEFAULT_RETRY_DELAYS_MS];
|
||||
}
|
||||
|
||||
export class TokenConnectionSupervisor {
|
||||
#channel;
|
||||
#controller;
|
||||
#harness;
|
||||
#logger;
|
||||
#retryDelays;
|
||||
#healthyIntervalMs;
|
||||
#setTimeout;
|
||||
#clearTimeout;
|
||||
#timer = null;
|
||||
#running = null;
|
||||
#retryIndex = 0;
|
||||
#closed = false;
|
||||
#started = false;
|
||||
#ready;
|
||||
#resolveReady;
|
||||
|
||||
constructor({
|
||||
channel,
|
||||
controller,
|
||||
harness,
|
||||
logger = console,
|
||||
retryDelaysMs,
|
||||
healthyIntervalMs = 15_000,
|
||||
setTimeoutImpl = setTimeout,
|
||||
clearTimeoutImpl = clearTimeout,
|
||||
}) {
|
||||
if (!channel) throw new TypeError('TokenConnectionSupervisor requires a channel');
|
||||
if (!controller || typeof controller.initialize !== 'function' || typeof controller.status !== 'function') {
|
||||
throw new TypeError('TokenConnectionSupervisor requires a controller');
|
||||
}
|
||||
if (!harness || typeof harness.ensureRunning !== 'function') {
|
||||
throw new TypeError('TokenConnectionSupervisor requires a Harness client');
|
||||
}
|
||||
this.#channel = channel;
|
||||
this.#controller = controller;
|
||||
this.#harness = harness;
|
||||
this.#logger = logger;
|
||||
this.#retryDelays = retryDelays(retryDelaysMs);
|
||||
this.#healthyIntervalMs = Number.isFinite(healthyIntervalMs) && healthyIntervalMs >= 0
|
||||
? healthyIntervalMs : 15_000;
|
||||
this.#setTimeout = setTimeoutImpl;
|
||||
this.#clearTimeout = clearTimeoutImpl;
|
||||
this.#ready = new Promise((resolve) => {
|
||||
this.#resolveReady = resolve;
|
||||
});
|
||||
}
|
||||
|
||||
get ready() {
|
||||
return this.#ready;
|
||||
}
|
||||
|
||||
start() {
|
||||
if (this.#started || this.#closed) return this;
|
||||
this.#started = true;
|
||||
this.#schedule(0);
|
||||
return this;
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.#closed) return;
|
||||
this.#closed = true;
|
||||
if (this.#timer !== null) this.#clearTimeout(this.#timer);
|
||||
this.#timer = null;
|
||||
await this.#running?.catch(() => undefined);
|
||||
this.#resolveReady?.(null);
|
||||
this.#resolveReady = null;
|
||||
}
|
||||
|
||||
#schedule(delayMs) {
|
||||
if (this.#closed) return;
|
||||
this.#timer = this.#setTimeout(() => {
|
||||
this.#timer = null;
|
||||
void this.#run();
|
||||
}, delayMs);
|
||||
this.#timer?.unref?.();
|
||||
}
|
||||
|
||||
async #run() {
|
||||
if (this.#closed || this.#running) return;
|
||||
const operation = this.#reconcile();
|
||||
this.#running = operation;
|
||||
try {
|
||||
await operation;
|
||||
} finally {
|
||||
if (this.#running === operation) this.#running = null;
|
||||
}
|
||||
}
|
||||
|
||||
async #reconcile() {
|
||||
try {
|
||||
await this.#harness.ensureRunning();
|
||||
if (this.#closed) return;
|
||||
const status = await this.#controller.initialize();
|
||||
if (this.#closed) return;
|
||||
this.#resolveReady?.(status);
|
||||
this.#resolveReady = null;
|
||||
const { configured, connected } = status.totals;
|
||||
if (connected < configured) {
|
||||
const delay = this.#retryDelays[Math.min(this.#retryIndex, this.#retryDelays.length - 1)];
|
||||
this.#retryIndex += 1;
|
||||
this.#logger.warn?.(
|
||||
`[dsh-im:${this.#channel}] ${connected}/${configured} bots connected; retrying in ${delay}ms`,
|
||||
);
|
||||
this.#schedule(delay);
|
||||
return;
|
||||
}
|
||||
this.#retryIndex = 0;
|
||||
this.#schedule(this.#healthyIntervalMs);
|
||||
} catch (error) {
|
||||
if (this.#closed) return;
|
||||
const delay = this.#retryDelays[Math.min(this.#retryIndex, this.#retryDelays.length - 1)];
|
||||
this.#retryIndex += 1;
|
||||
this.#logger.warn?.(
|
||||
`[dsh-im:${this.#channel}] connection reconciliation failed; retrying in ${delay}ms`,
|
||||
error,
|
||||
);
|
||||
this.#schedule(delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createTokenConnectionSupervisor(options) {
|
||||
return new TokenConnectionSupervisor(options);
|
||||
}
|
||||
104
plugin-src/host/channels/shared/production.mjs
Normal file
104
plugin-src/host/channels/shared/production.mjs
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
import { unlink } from 'node:fs/promises';
|
||||
import { homedir } from 'node:os';
|
||||
import { join, resolve } from 'node:path';
|
||||
|
||||
import { createTokenConnectionSupervisor } from './connection-supervisor.mjs';
|
||||
|
||||
function harnessOrigin(webServer, configured) {
|
||||
if (configured !== undefined) return new URL(configured);
|
||||
const port = webServer?.port;
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65_535) {
|
||||
throw new Error('dsh-im token channel requires an initialized DSH webServer port');
|
||||
}
|
||||
return new URL(`http://127.0.0.1:${port}`);
|
||||
}
|
||||
|
||||
function pluginPaths(config, channel) {
|
||||
const dshHome = resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
|
||||
const root = resolve(config.dataDir ?? join(dshHome, 'integrations', `dsh-${channel}`));
|
||||
return {
|
||||
config: resolve(config.configPath ?? join(root, 'config.json')),
|
||||
bots: resolve(config.botsDir ?? join(root, 'bots')),
|
||||
};
|
||||
}
|
||||
|
||||
export async function createTokenProductionController(ctx, config, internals, definitions) {
|
||||
const { channel, ConfigStore, StateStore, HarnessClient, Controller, Runtime } = definitions;
|
||||
if (!ctx?.credentials) throw new TypeError(`dsh-im ${channel} requires ctx.credentials`);
|
||||
if (!ctx?.webServer) throw new TypeError(`dsh-im ${channel} requires ctx.webServer`);
|
||||
|
||||
const ResolvedConfigStore = internals.ConfigStore ?? ConfigStore;
|
||||
const ResolvedStateStore = internals.StateStore ?? StateStore;
|
||||
const ResolvedHarness = internals.HarnessClient ?? HarnessClient;
|
||||
const ResolvedController = internals.Controller ?? Controller;
|
||||
const ResolvedRuntime = internals.Runtime ?? Runtime;
|
||||
const createSupervisor = internals.createConnectionSupervisor ?? createTokenConnectionSupervisor;
|
||||
const logger = typeof ctx.logger === 'function'
|
||||
? ctx.logger(`dsh-im:${channel}`) : (ctx.logger ?? console);
|
||||
const paths = pluginPaths(config, channel);
|
||||
const configStore = await new ResolvedConfigStore(paths.config).load();
|
||||
const stateStores = new Map();
|
||||
const statePath = (botId) => resolve(paths.bots, botId, 'state.json');
|
||||
const stateFor = async (botId) => {
|
||||
let state = stateStores.get(botId);
|
||||
if (!state) {
|
||||
state = await new ResolvedStateStore(statePath(botId)).load();
|
||||
stateStores.set(botId, state);
|
||||
}
|
||||
return state;
|
||||
};
|
||||
const harness = new ResolvedHarness({
|
||||
baseUrl: harnessOrigin(ctx.webServer, config.harnessBaseUrl),
|
||||
workspace: resolve(config.workspace ?? process.cwd()),
|
||||
agentPreset: config.agentPreset ?? 'standard',
|
||||
autostart: false,
|
||||
dshBin: config.dshBin ?? 'dsh',
|
||||
});
|
||||
const controller = new ResolvedController({
|
||||
credentials: ctx.credentials,
|
||||
configStore,
|
||||
logger,
|
||||
...(internals.inspectToken ? { inspectToken: internals.inspectToken } : {}),
|
||||
createRuntime: async ({ botId, config: botConfig, token }) => new ResolvedRuntime({
|
||||
config: botConfig,
|
||||
token,
|
||||
harness,
|
||||
state: await stateFor(botId),
|
||||
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
|
||||
connectTimeoutMs: config.connectTimeoutMs ?? 20_000,
|
||||
logger: {
|
||||
error: (...args) => logger.error?.(`[${botId}]`, ...args),
|
||||
warn: (...args) => logger.warn?.(`[${botId}]`, ...args),
|
||||
info: (...args) => logger.info?.(`[${botId}]`, ...args),
|
||||
debug: (...args) => logger.debug?.(`[${botId}]`, ...args),
|
||||
},
|
||||
}),
|
||||
deleteState: async ({ botId }) => {
|
||||
const state = stateStores.get(botId);
|
||||
stateStores.delete(botId);
|
||||
if (state && typeof state.remove === 'function') return state.remove();
|
||||
try {
|
||||
await unlink(statePath(botId));
|
||||
} catch (error) {
|
||||
if (error?.code !== 'ENOENT') throw error;
|
||||
}
|
||||
},
|
||||
});
|
||||
const supervisor = createSupervisor({
|
||||
channel,
|
||||
controller,
|
||||
harness,
|
||||
logger,
|
||||
retryDelaysMs: config.retryDelaysMs,
|
||||
healthyIntervalMs: config.healthyIntervalMs,
|
||||
}).start();
|
||||
return {
|
||||
controller,
|
||||
ready: supervisor.ready,
|
||||
async close() {
|
||||
await supervisor.close();
|
||||
await controller.close();
|
||||
harness.stopManagedProcess();
|
||||
},
|
||||
};
|
||||
}
|
||||
119
plugin-src/host/channels/shared/rpc.mjs
Normal file
119
plugin-src/host/channels/shared/rpc.mjs
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const TOKEN_BOT_ENDPOINTS = Object.freeze({
|
||||
status: 'connection.status',
|
||||
bindCredentials: 'bot.bind-credentials',
|
||||
reconnectBot: 'bot.reconnect',
|
||||
deleteBot: 'bot.delete',
|
||||
});
|
||||
|
||||
const ENDPOINTS = Object.freeze(Object.values(TOKEN_BOT_ENDPOINTS));
|
||||
const FORBIDDEN_PUBLIC_KEYS = new Set([
|
||||
'token', 'botToken', 'tokenRef', 'platformId', 'secret', 'secretRef',
|
||||
]);
|
||||
|
||||
function isRecord(value) {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function exactKeys(value, allowed) {
|
||||
return isRecord(value) && Object.keys(value).every((key) => allowed.includes(key));
|
||||
}
|
||||
|
||||
function validId(value) {
|
||||
return typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value);
|
||||
}
|
||||
|
||||
function validToken(value) {
|
||||
return typeof value === 'string' && value.trim().length >= 20 && value.length <= 4_096;
|
||||
}
|
||||
|
||||
function payloadFailure(endpoint, payload) {
|
||||
if (!isRecord(payload)) return 'Payload must be an object.';
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.status) {
|
||||
return exactKeys(payload, []) ? null : 'connection.status does not accept fields.';
|
||||
}
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.bindCredentials) {
|
||||
return exactKeys(payload, ['token']) && validToken(payload.token)
|
||||
? null : 'bot.bind-credentials requires a Bot Token.';
|
||||
}
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.reconnectBot) {
|
||||
return exactKeys(payload, ['botId']) && validId(payload.botId)
|
||||
? null : 'bot.reconnect requires a botId.';
|
||||
}
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.deleteBot) {
|
||||
return exactKeys(payload, ['botId', 'confirm']) && validId(payload.botId) && payload.confirm === true
|
||||
? null : 'bot.delete requires a botId and confirm=true.';
|
||||
}
|
||||
return 'Unknown bot endpoint.';
|
||||
}
|
||||
|
||||
function sanitizePublic(value) {
|
||||
if (Array.isArray(value)) return value.map(sanitizePublic);
|
||||
if (!isRecord(value)) return value;
|
||||
const safe = {};
|
||||
for (const [key, child] of Object.entries(value)) {
|
||||
if (!FORBIDDEN_PUBLIC_KEYS.has(key)) safe[key] = sanitizePublic(child);
|
||||
}
|
||||
return safe;
|
||||
}
|
||||
|
||||
function operationError(channel, error) {
|
||||
if (error?.code === 'webhook-configured') {
|
||||
return { code: 'webhook-configured', message: error.message };
|
||||
}
|
||||
if (error?.code === 'telegram-401' || error?.code === 'discord-401') {
|
||||
return { code: 'invalid-token', message: `${channel} Bot Token 无效,请重新填写。` };
|
||||
}
|
||||
if (error?.code === 'discord-intents') {
|
||||
return { code: 'discord-intents', message: error.message };
|
||||
}
|
||||
return { code: `${channel.toLowerCase()}-operation-failed`, message: `${channel} 操作失败,请稍后重试。` };
|
||||
}
|
||||
|
||||
export function createTokenBotRpcHandler(controller, { channel }) {
|
||||
for (const method of ['status', 'bindCredentials', 'reconnectBot', 'deleteBot']) {
|
||||
if (typeof controller?.[method] !== 'function') {
|
||||
throw new TypeError(`A complete ${channel} controller is required (${method})`);
|
||||
}
|
||||
}
|
||||
return async (endpoint, payload, signal) => {
|
||||
if (signal?.aborted) {
|
||||
return { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } };
|
||||
}
|
||||
if (!ENDPOINTS.includes(endpoint)) {
|
||||
return { ok: false, error: { code: 'bad-request', message: `Unknown ${channel} endpoint.` } };
|
||||
}
|
||||
const invalid = payloadFailure(endpoint, payload);
|
||||
if (invalid) return { ok: false, error: { code: 'bad-request', message: invalid } };
|
||||
try {
|
||||
let value;
|
||||
if (endpoint === TOKEN_BOT_ENDPOINTS.status) value = await controller.status();
|
||||
else if (endpoint === TOKEN_BOT_ENDPOINTS.bindCredentials) {
|
||||
value = await controller.bindCredentials(payload);
|
||||
} else if (endpoint === TOKEN_BOT_ENDPOINTS.reconnectBot) {
|
||||
value = await controller.reconnectBot(payload.botId);
|
||||
} else {
|
||||
value = await controller.deleteBot(payload.botId);
|
||||
}
|
||||
return signal?.aborted
|
||||
? { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } }
|
||||
: { ok: true, value: sanitizePublic(value) };
|
||||
} catch (error) {
|
||||
return signal?.aborted
|
||||
? { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } }
|
||||
: { ok: false, error: operationError(channel, error) };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function installTokenBotRpc(ctx, controller, { channel, rpcChannel, authority }) {
|
||||
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
|
||||
throw new TypeError('DSH Host Connection RPC is required');
|
||||
}
|
||||
return ctx.connection.rpc.handle(
|
||||
rpcChannel,
|
||||
createTokenBotRpcHandler(controller, { channel }),
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
30
plugin-src/host/channels/telegram/index.mjs
Normal file
30
plugin-src/host/channels/telegram/index.mjs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import { createProductionController } from './production.mjs';
|
||||
import { installTelegramRpc } from './rpc.mjs';
|
||||
|
||||
export const name = 'dsh-im-telegram-host';
|
||||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) {
|
||||
return installTelegramRpc(ctx, config.controller, config.rpcAuthority);
|
||||
}
|
||||
const production = await createProductionController(ctx, config, config.internals ?? {});
|
||||
const disposeRpc = installTelegramRpc(ctx, production.controller, config.rpcAuthority);
|
||||
ctx.effect(() => async () => production.close(), 'dsh-im: close Telegram bot connections');
|
||||
return disposeRpc;
|
||||
}
|
||||
|
||||
export function createTelegramHostPlugin(config) {
|
||||
return Object.freeze({ name, inject, apply: (ctx) => apply(ctx, config) });
|
||||
}
|
||||
|
||||
export { createProductionController } from './production.mjs';
|
||||
export {
|
||||
TELEGRAM_ENDPOINTS,
|
||||
TELEGRAM_RPC_CHANNEL,
|
||||
TELEGRAM_RPC_ENDPOINTS,
|
||||
createTelegramRpcHandler,
|
||||
installTelegramRpc,
|
||||
} from './rpc.mjs';
|
||||
export { TelegramController } from '../../../../src/channels/telegram/telegram-controller.mjs';
|
||||
export { TelegramRuntime } from '../../../../src/channels/telegram/telegram-runtime.mjs';
|
||||
17
plugin-src/host/channels/telegram/production.mjs
Normal file
17
plugin-src/host/channels/telegram/production.mjs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import { TelegramConfigStore } from '../../../../src/channels/telegram/config-store.mjs';
|
||||
import { TelegramHarnessClient } from '../../../../src/channels/telegram/harness-client.mjs';
|
||||
import { TelegramController } from '../../../../src/channels/telegram/telegram-controller.mjs';
|
||||
import { TelegramRuntime } from '../../../../src/channels/telegram/telegram-runtime.mjs';
|
||||
import { TelegramStateStore } from '../../../../src/channels/telegram/state-store.mjs';
|
||||
import { createTokenProductionController } from '../shared/production.mjs';
|
||||
|
||||
export function createProductionController(ctx, config = {}, internals = {}) {
|
||||
return createTokenProductionController(ctx, config, internals, {
|
||||
channel: 'telegram',
|
||||
ConfigStore: TelegramConfigStore,
|
||||
StateStore: TelegramStateStore,
|
||||
HarnessClient: TelegramHarnessClient,
|
||||
Controller: TelegramController,
|
||||
Runtime: TelegramRuntime,
|
||||
});
|
||||
}
|
||||
21
plugin-src/host/channels/telegram/rpc.mjs
Normal file
21
plugin-src/host/channels/telegram/rpc.mjs
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import {
|
||||
TOKEN_BOT_ENDPOINTS,
|
||||
createTokenBotRpcHandler,
|
||||
installTokenBotRpc,
|
||||
} from '../shared/rpc.mjs';
|
||||
|
||||
export const TELEGRAM_RPC_CHANNEL = '/telegram';
|
||||
export const TELEGRAM_ENDPOINTS = TOKEN_BOT_ENDPOINTS;
|
||||
export const TELEGRAM_RPC_ENDPOINTS = Object.freeze(Object.values(TELEGRAM_ENDPOINTS));
|
||||
|
||||
export function createTelegramRpcHandler(controller) {
|
||||
return createTokenBotRpcHandler(controller, { channel: 'Telegram' });
|
||||
}
|
||||
|
||||
export function installTelegramRpc(ctx, controller, authority) {
|
||||
return installTokenBotRpc(ctx, controller, {
|
||||
channel: 'Telegram',
|
||||
rpcChannel: TELEGRAM_RPC_CHANNEL,
|
||||
authority,
|
||||
});
|
||||
}
|
||||
|
|
@ -5,9 +5,16 @@ export const name = 'dsh-im-wecom-host';
|
|||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) return installWecomRpc(ctx, config.controller, config.rpcOptions);
|
||||
if (config?.controller) {
|
||||
return installWecomRpc(ctx, config.controller, config.rpcOptions, config.rpcAuthority);
|
||||
}
|
||||
const production = await createProductionController(ctx, config, config.internals);
|
||||
const disposeRpc = installWecomRpc(ctx, production.controller, config.rpcOptions);
|
||||
const disposeRpc = installWecomRpc(
|
||||
ctx,
|
||||
production.controller,
|
||||
config.rpcOptions,
|
||||
config.rpcAuthority,
|
||||
);
|
||||
ctx.effect(() => async () => production.close(), 'dsh-im: close Enterprise WeChat bot connections');
|
||||
return disposeRpc;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import QRCode from 'qrcode';
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const WECOM_RPC_CHANNEL = '/wecom';
|
||||
export const WECOM_ENDPOINTS = Object.freeze({
|
||||
|
|
@ -138,13 +139,13 @@ export function createWecomRpcHandler(controller, { encodeQr = qrDataUrl } = {})
|
|||
};
|
||||
}
|
||||
|
||||
export function installWecomRpc(ctx, controller, options) {
|
||||
export function installWecomRpc(ctx, controller, options, authority) {
|
||||
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
|
||||
throw new TypeError('DSH Host Connection RPC is required');
|
||||
}
|
||||
return ctx.connection.rpc.handle(
|
||||
WECOM_RPC_CHANNEL,
|
||||
createWecomRpcHandler(controller, options),
|
||||
{ authority: 'loopback' },
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,10 +5,17 @@ export const name = 'dsh-weixin-host';
|
|||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
export async function apply(ctx, config = {}) {
|
||||
if (config?.controller) return installWeixinRpc(ctx, config.controller, config.rpcOptions);
|
||||
if (config?.controller) {
|
||||
return installWeixinRpc(ctx, config.controller, config.rpcOptions, config.rpcAuthority);
|
||||
}
|
||||
|
||||
const production = await createProductionController(ctx, config, config.internals);
|
||||
const disposeRpc = installWeixinRpc(ctx, production.controller, config.rpcOptions);
|
||||
const disposeRpc = installWeixinRpc(
|
||||
ctx,
|
||||
production.controller,
|
||||
config.rpcOptions,
|
||||
config.rpcAuthority,
|
||||
);
|
||||
ctx.effect(() => async () => {
|
||||
await production.close();
|
||||
}, 'dsh-weixin: close account connections');
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import QRCode from 'qrcode';
|
||||
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
||||
|
||||
export const WEIXIN_RPC_CHANNEL = '/weixin';
|
||||
export const WEIXIN_ENDPOINTS = Object.freeze({
|
||||
|
|
@ -165,13 +166,13 @@ export function createWeixinRpcHandler(controller, { encodeQr = qrDataUrl } = {}
|
|||
};
|
||||
}
|
||||
|
||||
export function installWeixinRpc(ctx, controller, options) {
|
||||
export function installWeixinRpc(ctx, controller, options, authority) {
|
||||
if (!ctx?.connection?.rpc || typeof ctx.connection.rpc.handle !== 'function') {
|
||||
throw new TypeError('DSH Host Connection RPC is required');
|
||||
}
|
||||
return ctx.connection.rpc.handle(
|
||||
WEIXIN_RPC_CHANNEL,
|
||||
createWeixinRpcHandler(controller, options),
|
||||
{ authority: 'loopback' },
|
||||
{ authority: resolveRpcAuthority(authority) },
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,27 +1,40 @@
|
|||
import { apply as applyDingtalk } from './channels/dingtalk/index.mjs';
|
||||
import { apply as applyDiscord } from './channels/discord/index.mjs';
|
||||
import { apply as applyFeishu } from './channels/feishu/index.mjs';
|
||||
import { apply as applyQq } from './channels/qq/index.mjs';
|
||||
import { apply as applyTelegram } from './channels/telegram/index.mjs';
|
||||
import { apply as applyWecom } from './channels/wecom/index.mjs';
|
||||
import { apply as applyWeixin } from './channels/weixin/index.mjs';
|
||||
|
||||
export const name = 'dsh-im-host';
|
||||
export const inject = ['connection', 'credentials', 'webServer'];
|
||||
|
||||
function channelConfig(config, name) {
|
||||
const channel = config[name] ?? {};
|
||||
return config.rpcAuthority === undefined
|
||||
? channel
|
||||
: { ...channel, rpcAuthority: config.rpcAuthority };
|
||||
}
|
||||
|
||||
export function createImHostPlugin(internals = {}) {
|
||||
const startFeishu = internals.applyFeishu ?? applyFeishu;
|
||||
const startWeixin = internals.applyWeixin ?? applyWeixin;
|
||||
const startDingtalk = internals.applyDingtalk ?? applyDingtalk;
|
||||
const startWecom = internals.applyWecom ?? applyWecom;
|
||||
const startQq = internals.applyQq ?? applyQq;
|
||||
const startTelegram = internals.applyTelegram ?? applyTelegram;
|
||||
const startDiscord = internals.applyDiscord ?? applyDiscord;
|
||||
return Object.freeze({
|
||||
name,
|
||||
inject,
|
||||
async apply(ctx, config = {}) {
|
||||
await startFeishu(ctx, config.feishu ?? {});
|
||||
await startWeixin(ctx, config.weixin ?? {});
|
||||
await startDingtalk(ctx, config.dingtalk ?? {});
|
||||
await startWecom(ctx, config.wecom ?? {});
|
||||
await startQq(ctx, config.qq ?? {});
|
||||
await startFeishu(ctx, channelConfig(config, 'feishu'));
|
||||
await startWeixin(ctx, channelConfig(config, 'weixin'));
|
||||
await startDingtalk(ctx, channelConfig(config, 'dingtalk'));
|
||||
await startWecom(ctx, channelConfig(config, 'wecom'));
|
||||
await startQq(ctx, channelConfig(config, 'qq'));
|
||||
await startTelegram(ctx, channelConfig(config, 'telegram'));
|
||||
await startDiscord(ctx, channelConfig(config, 'discord'));
|
||||
},
|
||||
});
|
||||
}
|
||||
|
|
|
|||
11
plugin-src/host/rpc-authority.mjs
Normal file
11
plugin-src/host/rpc-authority.mjs
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
const RPC_AUTHORITIES = new Set(['loopback', 'trusted-host']);
|
||||
|
||||
/**
|
||||
* Resolve the browser authority accepted by an IM management RPC channel.
|
||||
* The default keeps credential and bot-management operations on loopback.
|
||||
*/
|
||||
export function resolveRpcAuthority(value) {
|
||||
if (value === undefined) return 'loopback';
|
||||
if (RPC_AUTHORITIES.has(value)) return value;
|
||||
throw new TypeError('dsh-im rpcAuthority must be "loopback" or "trusted-host"');
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue