mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-12 17:50:45 +08:00
Add WeCom QR bot channel
This commit is contained in:
parent
601271a7f8
commit
4874d3e354
33 changed files with 5200 additions and 440 deletions
137
plugin-src/host/channels/wecom/rpc.mjs
Normal file
137
plugin-src/host/channels/wecom/rpc.mjs
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
import QRCode from 'qrcode';
|
||||
|
||||
export const WECOM_RPC_CHANNEL = '/wecom';
|
||||
export const WECOM_ENDPOINTS = Object.freeze({
|
||||
status: 'connection.status',
|
||||
beginProvisioning: 'provision.begin',
|
||||
pollProvisioning: 'provision.poll',
|
||||
cancelProvisioning: 'provision.cancel',
|
||||
reconnectBot: 'bot.reconnect',
|
||||
deleteBot: 'bot.delete',
|
||||
});
|
||||
export const WECOM_RPC_ENDPOINTS = Object.freeze(Object.values(WECOM_ENDPOINTS));
|
||||
|
||||
const FORBIDDEN_PUBLIC_KEYS = new Set([
|
||||
'secret', 'secretRef', 'scode', 'remoteBotId', 'verificationUrl', 'bot_info', 'botid',
|
||||
]);
|
||||
|
||||
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 (endpoint === WECOM_ENDPOINTS.status) return exactKeys(payload, []) ? null : 'connection.status does not accept fields.';
|
||||
if (endpoint === WECOM_ENDPOINTS.beginProvisioning) {
|
||||
return exactKeys(payload, ['locale']) && (payload.locale === undefined || payload.locale === 'zh-CN')
|
||||
? null : 'provision.begin received unsupported fields.';
|
||||
}
|
||||
if ([WECOM_ENDPOINTS.pollProvisioning, WECOM_ENDPOINTS.cancelProvisioning].includes(endpoint)) {
|
||||
return exactKeys(payload, ['attemptId']) && validId(payload.attemptId)
|
||||
? null : `${endpoint} requires an attemptId.`;
|
||||
}
|
||||
if (endpoint === WECOM_ENDPOINTS.reconnectBot) {
|
||||
return exactKeys(payload, ['botId']) && validId(payload.botId) ? null : 'bot.reconnect requires a botId.';
|
||||
}
|
||||
if (endpoint === WECOM_ENDPOINTS.deleteBot) {
|
||||
return exactKeys(payload, ['botId', 'confirm']) && validId(payload.botId) && payload.confirm === true
|
||||
? null : 'bot.delete requires a botId and confirm=true.';
|
||||
}
|
||||
return 'Unknown Enterprise WeChat 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 withEncodedQr(value, encodeQr) {
|
||||
if (!value || typeof value.verificationUrl !== 'string') return sanitizePublic(value);
|
||||
return sanitizePublic({ ...value, qrCodeDataUrl: await encodeQr(value.verificationUrl) });
|
||||
}
|
||||
|
||||
async function publicStatus(status, encodeQr) {
|
||||
const value = structuredClone(status);
|
||||
if (value?.provisioning) value.provisioning = await withEncodedQr(value.provisioning, encodeQr);
|
||||
return sanitizePublic(value);
|
||||
}
|
||||
|
||||
export function createWecomRpcHandler(controller, { encodeQr = qrDataUrl } = {}) {
|
||||
for (const method of ['status', 'startProvisioning', 'registrationStatus', 'cancelProvisioning', 'reconnectBot', 'deleteBot']) {
|
||||
if (typeof controller?.[method] !== 'function') {
|
||||
throw new TypeError(`A complete Enterprise WeChat controller is required (${method})`);
|
||||
}
|
||||
}
|
||||
const qrCache = new Map();
|
||||
const cachedEncode = (url) => {
|
||||
let encoded = qrCache.get(url);
|
||||
if (!encoded) {
|
||||
if (qrCache.size >= 16) qrCache.delete(qrCache.keys().next().value);
|
||||
encoded = Promise.resolve().then(() => encodeQr(url));
|
||||
qrCache.set(url, encoded);
|
||||
}
|
||||
return encoded;
|
||||
};
|
||||
return async (endpoint, payload, signal) => {
|
||||
if (signal?.aborted) return { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } };
|
||||
if (!WECOM_RPC_ENDPOINTS.includes(endpoint)) {
|
||||
return { ok: false, error: { code: 'bad-request', message: 'Unknown Enterprise WeChat endpoint.' } };
|
||||
}
|
||||
const invalid = payloadFailure(endpoint, payload);
|
||||
if (invalid) return { ok: false, error: { code: 'bad-request', message: invalid } };
|
||||
try {
|
||||
let value;
|
||||
if (endpoint === WECOM_ENDPOINTS.status) value = await publicStatus(await controller.status(), cachedEncode);
|
||||
else if (endpoint === WECOM_ENDPOINTS.beginProvisioning) {
|
||||
value = await withEncodedQr(await controller.startProvisioning(), cachedEncode);
|
||||
} else if (endpoint === WECOM_ENDPOINTS.pollProvisioning) {
|
||||
const current = await controller.registrationStatus(payload.attemptId);
|
||||
if (!current) return { ok: false, error: { code: 'bad-request', message: 'The provisioning attempt no longer exists.' } };
|
||||
value = await withEncodedQr(current, cachedEncode);
|
||||
} else if (endpoint === WECOM_ENDPOINTS.cancelProvisioning) {
|
||||
value = sanitizePublic(await controller.cancelProvisioning(payload.attemptId));
|
||||
} else if (endpoint === WECOM_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: 'wecom-operation-failed', message: '企业微信操作失败,请稍后重试。' } };
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export function installWecomRpc(ctx, controller, options) {
|
||||
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' },
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue