feat: add WhatsApp QR channel

This commit is contained in:
xmanrui 2026-08-16 17:30:38 +08:00
parent f8841da76f
commit c54463843f
29 changed files with 4565 additions and 224 deletions

View file

@ -0,0 +1,35 @@
import { createProductionController } from './production.mjs';
import { installWhatsappRpc } from './rpc.mjs';
export const name = 'dsh-im-whatsapp-host';
export const inject = ['connection', 'webServer'];
export async function apply(ctx, config = {}) {
if (config?.controller) {
return installWhatsappRpc(ctx, config.controller, config.rpcOptions, config.rpcAuthority);
}
const production = await createProductionController(ctx, config, config.internals ?? {});
const disposeRpc = installWhatsappRpc(
ctx,
production.controller,
config.rpcOptions,
config.rpcAuthority,
);
ctx.effect(() => async () => production.close(), 'dsh-im: close WhatsApp Web connections');
return disposeRpc;
}
export function createWhatsappHostPlugin(config) {
return Object.freeze({ name, inject, apply: (ctx) => apply(ctx, config) });
}
export { createProductionController } from './production.mjs';
export {
WHATSAPP_ENDPOINTS,
WHATSAPP_RPC_CHANNEL,
WHATSAPP_RPC_ENDPOINTS,
createWhatsappRpcHandler,
installWhatsappRpc,
} from './rpc.mjs';
export { WhatsappController } from '../../../../src/channels/whatsapp/whatsapp-controller.mjs';
export { WhatsappRuntime } from '../../../../src/channels/whatsapp/whatsapp-runtime.mjs';

View file

@ -0,0 +1,121 @@
import { rm, unlink } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
import { WhatsappConfigStore } from '../../../../src/channels/whatsapp/config-store.mjs';
import { WhatsappHarnessClient } from '../../../../src/channels/whatsapp/harness-client.mjs';
import { WhatsappStateStore } from '../../../../src/channels/whatsapp/state-store.mjs';
import { WhatsappController } from '../../../../src/channels/whatsapp/whatsapp-controller.mjs';
import { WhatsappRuntime } from '../../../../src/channels/whatsapp/whatsapp-runtime.mjs';
import { createWhatsappWebSession } from '../../../../src/channels/whatsapp/whatsapp-web-session.mjs';
import { createTokenConnectionSupervisor } from '../shared/connection-supervisor.mjs';
const AUTH_DIRECTORY_PATTERN = /^[a-f0-9-]{36}$/;
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 WhatsApp requires an initialized DSH webServer port');
}
return new URL(`http://127.0.0.1:${port}`);
}
function pluginPaths(config) {
const dshHome = resolve(config.dshHome ?? process.env.DSH_HOME ?? join(homedir(), '.dsh'));
const root = resolve(config.dataDir ?? join(dshHome, 'integrations', 'dsh-whatsapp'));
const authRoot = resolve(config.authDir ?? join(root, 'auth'));
const authPath = (name) => {
if (!AUTH_DIRECTORY_PATTERN.test(name ?? '')) throw new TypeError('Invalid WhatsApp auth directory');
return resolve(authRoot, name);
};
return {
config: resolve(config.configPath ?? join(root, 'config.json')),
bots: resolve(config.botsDir ?? join(root, 'bots')),
authPath,
};
}
export async function createProductionController(ctx, config = {}, internals = {}) {
if (!ctx?.webServer) throw new TypeError('dsh-im WhatsApp requires ctx.webServer');
const logger = typeof ctx.logger === 'function'
? ctx.logger('dsh-im:whatsapp') : (ctx.logger ?? console);
const ConfigStore = internals.ConfigStore ?? WhatsappConfigStore;
const StateStore = internals.StateStore ?? WhatsappStateStore;
const Harness = internals.HarnessClient ?? WhatsappHarnessClient;
const Controller = internals.Controller ?? WhatsappController;
const Runtime = internals.Runtime ?? WhatsappRuntime;
const createSession = internals.createSession ?? createWhatsappWebSession;
const createSupervisor = internals.createConnectionSupervisor ?? createTokenConnectionSupervisor;
const paths = pluginPaths(config);
const configStore = await new ConfigStore(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 StateStore(statePath(botId)).load();
stateStores.set(botId, state);
}
return state;
};
const harness = new Harness({
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 Controller({
configStore,
authPath: paths.authPath,
createSession,
logger,
createRuntime: async ({ botId, config: botConfig, authDir }) => new Runtime({
config: botConfig,
authDir,
harness,
state: await stateFor(botId),
replyTimeoutMs: config.replyTimeoutMs ?? 600_000,
connectTimeoutMs: config.connectTimeoutMs ?? 30_000,
createSession,
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),
},
}),
deleteAuth: (authDirectory) => rm(paths.authPath(authDirectory), {
recursive: true,
force: true,
}),
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: 'whatsapp',
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();
},
};
}

View file

@ -0,0 +1,140 @@
import QRCode from 'qrcode';
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
export const WHATSAPP_RPC_CHANNEL = '/whatsapp';
export const WHATSAPP_ENDPOINTS = Object.freeze({
status: 'connection.status',
beginProvisioning: 'provision.begin',
pollProvisioning: 'provision.poll',
cancelProvisioning: 'provision.cancel',
reconnectBot: 'bot.reconnect',
deleteBot: 'bot.delete',
});
export const WHATSAPP_RPC_ENDPOINTS = Object.freeze(Object.values(WHATSAPP_ENDPOINTS));
const FORBIDDEN_PUBLIC_KEYS = new Set(['qrValue', 'accountJid', 'authDirectory']);
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 payloadFailure(endpoint, payload) {
if (!isRecord(payload)) return 'Payload must be an object.';
if ([WHATSAPP_ENDPOINTS.status, WHATSAPP_ENDPOINTS.beginProvisioning].includes(endpoint)) {
return exactKeys(payload, []) ? null : `${endpoint} does not accept fields.`;
}
if ([WHATSAPP_ENDPOINTS.pollProvisioning, WHATSAPP_ENDPOINTS.cancelProvisioning].includes(endpoint)) {
return exactKeys(payload, ['attemptId']) && validId(payload.attemptId)
? null : `${endpoint} requires an attemptId.`;
}
if (endpoint === WHATSAPP_ENDPOINTS.reconnectBot) {
return exactKeys(payload, ['botId']) && validId(payload.botId)
? null : 'bot.reconnect requires a botId.';
}
if (endpoint === WHATSAPP_ENDPOINTS.deleteBot) {
return exactKeys(payload, ['botId', 'confirm']) && validId(payload.botId)
&& payload.confirm === true ? null : 'bot.delete requires a botId and confirm=true.';
}
return 'Unknown WhatsApp 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;
}
async function qrDataUrl(value) {
return QRCode.toDataURL(value, {
type: 'image/png',
errorCorrectionLevel: 'M',
margin: 2,
width: 320,
});
}
async function encodeAttempt(value, encodeQr) {
if (!value || typeof value.qrValue !== 'string') return sanitizePublic(value);
return sanitizePublic({ ...value, qrCodeDataUrl: await encodeQr(value.qrValue) });
}
async function publicStatus(value, encodeQr) {
const snapshot = structuredClone(value);
if (snapshot?.provisioning) snapshot.provisioning = await encodeAttempt(snapshot.provisioning, encodeQr);
return sanitizePublic(snapshot);
}
export function createWhatsappRpcHandler(controller, { encodeQr = qrDataUrl } = {}) {
for (const method of ['status', 'startProvisioning', 'registrationStatus', 'cancelProvisioning', 'reconnectBot', 'deleteBot']) {
if (typeof controller?.[method] !== 'function') {
throw new TypeError(`A complete WhatsApp controller is required (${method})`);
}
}
const qrCache = new Map();
const cachedEncode = (value) => {
let encoded = qrCache.get(value);
if (!encoded) {
if (qrCache.size >= 16) qrCache.delete(qrCache.keys().next().value);
encoded = Promise.resolve().then(() => encodeQr(value));
qrCache.set(value, encoded);
}
return encoded;
};
return async (endpoint, payload, signal) => {
if (signal?.aborted) return { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } };
if (!WHATSAPP_RPC_ENDPOINTS.includes(endpoint)) {
return { ok: false, error: { code: 'bad-request', message: 'Unknown WhatsApp endpoint.' } };
}
const invalid = payloadFailure(endpoint, payload);
if (invalid) return { ok: false, error: { code: 'bad-request', message: invalid } };
try {
let value;
if (endpoint === WHATSAPP_ENDPOINTS.status) {
value = await publicStatus(await controller.status(), cachedEncode);
} else if (endpoint === WHATSAPP_ENDPOINTS.beginProvisioning) {
value = await encodeAttempt(await controller.startProvisioning(), cachedEncode);
} else if (endpoint === WHATSAPP_ENDPOINTS.pollProvisioning) {
const attempt = await controller.registrationStatus(payload.attemptId);
if (!attempt) return { ok: false, error: { code: 'bad-request', message: 'The provisioning attempt no longer exists.' } };
value = await encodeAttempt(attempt, cachedEncode);
} else if (endpoint === WHATSAPP_ENDPOINTS.cancelProvisioning) {
value = sanitizePublic(await controller.cancelProvisioning(payload.attemptId));
} else if (endpoint === WHATSAPP_ENDPOINTS.reconnectBot) {
value = await publicStatus(await controller.reconnectBot(payload.botId), cachedEncode);
} else {
value = await publicStatus(await controller.deleteBot(payload.botId), cachedEncode);
}
return signal?.aborted
? { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } }
: { ok: true, value };
} catch {
return signal?.aborted
? { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } }
: { ok: false, error: { code: 'whatsapp-operation-failed', message: 'WhatsApp 操作失败,请稍后重试。' } };
}
};
}
export function installWhatsappRpc(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(
WHATSAPP_RPC_CHANNEL,
createWhatsappRpcHandler(controller, options),
{ authority: resolveRpcAuthority(authority) },
);
}

View file

@ -5,6 +5,7 @@ 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';
import { apply as applyWhatsapp } from './channels/whatsapp/index.mjs';
export const name = 'dsh-im-host';
export const inject = ['connection', 'credentials', 'webServer'];
@ -24,6 +25,7 @@ export function createImHostPlugin(internals = {}) {
const startQq = internals.applyQq ?? applyQq;
const startTelegram = internals.applyTelegram ?? applyTelegram;
const startDiscord = internals.applyDiscord ?? applyDiscord;
const startWhatsapp = internals.applyWhatsapp ?? applyWhatsapp;
return Object.freeze({
name,
inject,
@ -35,6 +37,7 @@ export function createImHostPlugin(internals = {}) {
await startQq(ctx, channelConfig(config, 'qq'));
await startTelegram(ctx, channelConfig(config, 'telegram'));
await startDiscord(ctx, channelConfig(config, 'discord'));
await startWhatsapp(ctx, channelConfig(config, 'whatsapp'));
},
});
}