mirror of
https://github.com/hansjone/dsh-im-ops.git
synced 2026-10-09 04:13:17 +08:00
237 lines
8.2 KiB
JavaScript
237 lines
8.2 KiB
JavaScript
import QRCode from 'qrcode';
|
|
import { resolveRpcAuthority } from '../../rpc-authority.mjs';
|
|
|
|
export const DINGTALK_RPC_CHANNEL = '/dingtalk';
|
|
export const DINGTALK_ENDPOINTS = Object.freeze({
|
|
status: 'connection.status',
|
|
beginProvisioning: 'provision.begin',
|
|
pollProvisioning: 'provision.poll',
|
|
cancelProvisioning: 'provision.cancel',
|
|
bindCredentials: 'bot.bind-credentials',
|
|
reconnectBot: 'bot.reconnect',
|
|
deleteBot: 'bot.delete',
|
|
approveSender: 'bot.sender.approve',
|
|
revokeSender: 'bot.sender.revoke',
|
|
});
|
|
export const DINGTALK_RPC_ENDPOINTS = Object.freeze(Object.values(DINGTALK_ENDPOINTS));
|
|
|
|
const FORBIDDEN_PUBLIC_KEYS = new Set([
|
|
'clientSecret',
|
|
'client_secret',
|
|
'deviceCode',
|
|
'device_code',
|
|
'secretRef',
|
|
'staffId',
|
|
'senderStaffId',
|
|
'verificationUrl',
|
|
'verificationUri',
|
|
'userCode',
|
|
]);
|
|
|
|
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 validCredential(value, maxLength) {
|
|
return typeof value === 'string' && value.trim().length > 0 && value.length <= maxLength;
|
|
}
|
|
|
|
function payloadFailure(endpoint, payload) {
|
|
if (!isRecord(payload)) return 'Payload must be an object.';
|
|
if (endpoint === DINGTALK_ENDPOINTS.status) {
|
|
return exactKeys(payload, []) ? null : 'connection.status does not accept fields.';
|
|
}
|
|
if (endpoint === DINGTALK_ENDPOINTS.beginProvisioning) {
|
|
return exactKeys(payload, ['locale']) && (payload.locale === undefined || payload.locale === 'zh-CN')
|
|
? null
|
|
: 'provision.begin received unsupported fields.';
|
|
}
|
|
if ([DINGTALK_ENDPOINTS.pollProvisioning, DINGTALK_ENDPOINTS.cancelProvisioning].includes(endpoint)) {
|
|
return exactKeys(payload, ['attemptId']) && validId(payload.attemptId)
|
|
? null
|
|
: `${endpoint} requires an attemptId.`;
|
|
}
|
|
if (endpoint === DINGTALK_ENDPOINTS.bindCredentials) {
|
|
return exactKeys(payload, ['clientId', 'clientSecret'])
|
|
&& validCredential(payload.clientId, 256)
|
|
&& validCredential(payload.clientSecret, 1024)
|
|
? null
|
|
: 'bot.bind-credentials requires Client ID and Client Secret.';
|
|
}
|
|
if (endpoint === DINGTALK_ENDPOINTS.reconnectBot) {
|
|
return exactKeys(payload, ['botId']) && validId(payload.botId)
|
|
? null
|
|
: 'bot.reconnect requires a botId.';
|
|
}
|
|
if (endpoint === DINGTALK_ENDPOINTS.deleteBot) {
|
|
return exactKeys(payload, ['botId', 'confirm']) && validId(payload.botId) && payload.confirm === true
|
|
? null
|
|
: 'bot.delete requires a botId and confirm=true.';
|
|
}
|
|
if (endpoint === DINGTALK_ENDPOINTS.approveSender) {
|
|
return exactKeys(payload, ['botId', 'requestId', 'confirm'])
|
|
&& validId(payload.botId)
|
|
&& validId(payload.requestId)
|
|
&& payload.confirm === true
|
|
? null
|
|
: 'bot.sender.approve requires botId, requestId, and confirm=true.';
|
|
}
|
|
if (endpoint === DINGTALK_ENDPOINTS.revokeSender) {
|
|
return exactKeys(payload, ['botId', 'senderKey', 'confirm'])
|
|
&& validId(payload.botId)
|
|
&& validId(payload.senderKey)
|
|
&& payload.confirm === true
|
|
? null
|
|
: 'bot.sender.revoke requires botId, senderKey, and confirm=true.';
|
|
}
|
|
return 'Unknown DingTalk endpoint.';
|
|
}
|
|
|
|
function badRequest(message) {
|
|
return { ok: false, error: { code: 'bad-request', message } };
|
|
}
|
|
|
|
function cancelled() {
|
|
return { ok: false, error: { code: 'cancelled', message: 'The request was cancelled.' } };
|
|
}
|
|
|
|
function internalFailure() {
|
|
return {
|
|
ok: false,
|
|
error: { code: 'dingtalk-operation-failed', message: '钉钉操作失败,请稍后重试。' },
|
|
};
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
function assertController(controller) {
|
|
for (const method of [
|
|
'status',
|
|
'startProvisioning',
|
|
'registrationStatus',
|
|
'cancelProvisioning',
|
|
'bindCredentials',
|
|
'reconnectBot',
|
|
'deleteBot',
|
|
'approveSender',
|
|
'revokeSender',
|
|
]) {
|
|
if (typeof controller?.[method] !== 'function') {
|
|
throw new TypeError(`A complete DingTalk controller is required (${method})`);
|
|
}
|
|
}
|
|
}
|
|
|
|
export function createDingtalkRpcHandler(controller, { encodeQr = qrDataUrl } = {}) {
|
|
assertController(controller);
|
|
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 cancelled();
|
|
if (!DINGTALK_RPC_ENDPOINTS.includes(endpoint)) return badRequest('Unknown DingTalk endpoint.');
|
|
const invalid = payloadFailure(endpoint, payload);
|
|
if (invalid) return badRequest(invalid);
|
|
|
|
try {
|
|
let value;
|
|
if (endpoint === DINGTALK_ENDPOINTS.status) {
|
|
value = await publicStatus(await controller.status(), cachedEncode);
|
|
} else if (endpoint === DINGTALK_ENDPOINTS.beginProvisioning) {
|
|
const started = await controller.startProvisioning({ signal });
|
|
if (signal?.aborted) {
|
|
await controller.cancelProvisioning(started.attemptId);
|
|
return cancelled();
|
|
}
|
|
value = await withEncodedQr(started, cachedEncode);
|
|
} else if (endpoint === DINGTALK_ENDPOINTS.pollProvisioning) {
|
|
const current = await controller.registrationStatus(payload.attemptId);
|
|
if (!current) return badRequest('The provisioning attempt no longer exists.');
|
|
value = await withEncodedQr(current, cachedEncode);
|
|
} else if (endpoint === DINGTALK_ENDPOINTS.cancelProvisioning) {
|
|
value = await controller.cancelProvisioning(payload.attemptId);
|
|
if (!value) return badRequest('The provisioning attempt no longer exists.');
|
|
value = sanitizePublic(value);
|
|
} else if (endpoint === DINGTALK_ENDPOINTS.bindCredentials) {
|
|
value = await publicStatus(await controller.bindCredentials(payload), cachedEncode);
|
|
} else if (endpoint === DINGTALK_ENDPOINTS.reconnectBot) {
|
|
value = await publicStatus(await controller.reconnectBot(payload.botId), cachedEncode);
|
|
} else if (endpoint === DINGTALK_ENDPOINTS.deleteBot) {
|
|
value = await publicStatus(await controller.deleteBot(payload.botId), cachedEncode);
|
|
} else if (endpoint === DINGTALK_ENDPOINTS.approveSender) {
|
|
value = await publicStatus(
|
|
await controller.approveSender(payload.botId, payload.requestId),
|
|
cachedEncode,
|
|
);
|
|
} else {
|
|
value = await publicStatus(
|
|
await controller.revokeSender(payload.botId, payload.senderKey),
|
|
cachedEncode,
|
|
);
|
|
}
|
|
return signal?.aborted ? cancelled() : { ok: true, value };
|
|
} catch {
|
|
return signal?.aborted ? cancelled() : internalFailure();
|
|
}
|
|
};
|
|
}
|
|
|
|
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: resolveRpcAuthority(authority) },
|
|
);
|
|
}
|