@botharness/im-provider 4.32.0-botharness.16 → 4.32.0-botharness.21
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/PROVENANCE.json +9 -9
- package/lib/client.js +8 -5
- package/lib/index.js +305 -308
- package/package.json +6 -5
- package/plugin-src/host/app-setup.mjs +244 -0
- package/plugin-src/host/build.mjs +3 -2
- package/plugin-src/host/channels/qq/production.mjs +7 -1
- package/plugin-src/host/channels/shared/startup.mjs +3 -0
- package/plugin-src/host/delivery-adapter.mjs +15 -0
- package/plugin-src/host/delivery-service.mjs +103 -3
- package/plugin-src/host/index.mjs +15 -2
- package/plugin-src/host/qq-sdk-observation-patch.mjs +53 -0
- package/src/channels/discord/discord-api.mjs +9 -0
- package/src/channels/discord/discord-controller.mjs +1 -2
- package/src/channels/discord/discord-runtime.mjs +13 -0
- package/src/channels/discord/reachable-conversations.mjs +211 -0
- package/src/channels/feishu/external-cards.mjs +63 -6
- package/src/channels/feishu/external-reactions.mjs +36 -0
- package/src/channels/feishu/feishu-runtime.mjs +95 -2
- package/src/channels/feishu/multi-bot-controller.mjs +78 -4
- package/src/channels/qq/config-store.mjs +1 -0
- package/src/channels/qq/external-addressing.mjs +6 -0
- package/src/channels/qq/external-consumer.mjs +214 -0
- package/src/channels/qq/external-files.mjs +50 -0
- package/src/channels/qq/external-images.mjs +109 -0
- package/src/channels/qq/external-mentions.mjs +32 -0
- package/src/channels/qq/external-post.mjs +51 -0
- package/src/channels/qq/external-voice.mjs +32 -0
- package/src/channels/qq/native-gateway-diagnostics.mjs +86 -0
- package/src/channels/qq/native-reply-observations.mjs +143 -0
- package/src/channels/qq/native-transport-diagnostics.mjs +42 -0
- package/src/channels/qq/qq-controller.mjs +105 -1
- package/src/channels/qq/qq-runtime.mjs +259 -12
- package/src/channels/qq/sdk-frame-observation.mjs +31 -0
- package/src/channels/qq/voice-attachment.mjs +3 -0
- package/src/channels/shared/i18n-en/qq.mjs +4 -0
- package/src/channels/shared/i18n-en/weixin.mjs +1 -0
- package/src/channels/shared/token-bot-controller.mjs +26 -0
- package/src/channels/slack/reachable-conversations.mjs +136 -0
- package/src/channels/slack/slack-api.mjs +9 -1
- package/src/channels/slack/slack-controller.mjs +25 -2
- package/src/channels/slack/slack-runtime.mjs +23 -0
- package/src/channels/weixin/connection-error.en.mjs +1 -0
- package/src/channels/weixin/connection-error.mjs +1 -0
- package/src/channels/weixin/weixin-controller.mjs +23 -2
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
const sourceRoot = fileURLToPath(new URL('../../', import.meta.url));
|
|
7
|
+
const observerModule = resolve(sourceRoot, 'src/channels/qq/sdk-frame-observation.mjs');
|
|
8
|
+
const inputs = {
|
|
9
|
+
'QQBot.js': '0ee621d964824a41690827936f86b383e51e603dc19aa9e5a9492f77ca44a7d6',
|
|
10
|
+
'gateway-connection.js': '4ee50dc8670de41089b593181df3fc2e17ef574aec3c04c73da54a7be7c79555',
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
function replace(source, before, after) {
|
|
14
|
+
if (source.split(before).length !== 2) throw Error('QQ SDK observation patch seam differs');
|
|
15
|
+
return source.replace(before, after);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function patchQqObservationSource(name, source) {
|
|
19
|
+
if (!inputs[name] || createHash('sha256').update(source).digest('hex') !== inputs[name])
|
|
20
|
+
throw Error('QQ SDK observation patch requires the exact reviewed SDK 1.0.4 input');
|
|
21
|
+
if (name === 'QQBot.js') return replace(source, 'intents: this.opts.intents,',
|
|
22
|
+
'intents: this.opts.intents,\n onGatewayObservation: this.opts.onGatewayObservation,');
|
|
23
|
+
source = replace(source, '\n shouldRefreshToken = false;',
|
|
24
|
+
'\n shouldRefreshToken = false;\n observationConnection = 0;\n observationFrame = 0;');
|
|
25
|
+
source = replace(source, 'this.currentWs = ws;',
|
|
26
|
+
'this.currentWs = ws;\n const connection = ++this.observationConnection;');
|
|
27
|
+
source = replace(source, 'ws.on("message", async (data) => {\n try {',
|
|
28
|
+
`ws.on("message", async (data) => {
|
|
29
|
+
const frame = ++this.observationFrame;
|
|
30
|
+
const observer = !this.isAborted && this.currentWs === ws ? this.opts.onGatewayObservation : undefined;
|
|
31
|
+
const evidence = { connection, frame, bytes: typeof observer === 'function' ? frameBytes(data) : null };
|
|
32
|
+
observeFrame(observer, { ...evidence, phase: 'received' });
|
|
33
|
+
let decoded = false;
|
|
34
|
+
try {`);
|
|
35
|
+
source = replace(source, 'const { op, d, s, t } = payload;',
|
|
36
|
+
`const { op, d, s, t } = payload;
|
|
37
|
+
decoded = true;
|
|
38
|
+
observeFrame(observer, { ...evidence, phase: 'decoded', ...frameEnvelope(op, t, s) });`);
|
|
39
|
+
source = replace(source, 'catch (err) {\n log?.error(`[${account.accountId}] Message parse error:',
|
|
40
|
+
'catch (err) {\n observeFrame(observer, { ...evidence, phase: decoded ? "processing-refused" : "parse-refused" });\n log?.error(`[${account.accountId}] Message parse error:');
|
|
41
|
+
return `import { frameBytes, frameEnvelope, observeFrame } from ${JSON.stringify(observerModule)};\n${source}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const qqSdkObservationPatch = {
|
|
45
|
+
name: 'qq-sdk-1.0.4-metadata-observation',
|
|
46
|
+
setup(build) {
|
|
47
|
+
build.onLoad({ filter: /[/\\]qqbot-nodejs[/\\]dist[/\\](?:QQBot\.js|protocol[/\\]gateway[/\\]gateway-connection\.js)$/ }, async args => {
|
|
48
|
+
const name = args.path.split(/[/\\]/).at(-1);
|
|
49
|
+
const source = await readFile(args.path, 'utf8');
|
|
50
|
+
return { contents: patchQqObservationSource(name, source), loader: 'js', resolveDir: resolve(args.path, '..') };
|
|
51
|
+
});
|
|
52
|
+
},
|
|
53
|
+
};
|
|
@@ -136,6 +136,15 @@ export class DiscordApi {
|
|
|
136
136
|
return this.#request(`guilds/${snowflake(guildId, 'guild id')}`, { method: 'GET', signal });
|
|
137
137
|
}
|
|
138
138
|
|
|
139
|
+
listCurrentGuilds({after,limit=100,signal}={}) {
|
|
140
|
+
const query=new URLSearchParams({limit:String(limit),...(after?{after:snowflake(after,'guild cursor')}:{})});
|
|
141
|
+
return this.#request(`users/@me/guilds?${query}`,{method:'GET',signal});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
getGuildChannels({guildId,signal}={}) {
|
|
145
|
+
return this.#request(`guilds/${snowflake(guildId,'guild id')}/channels`,{method:'GET',signal});
|
|
146
|
+
}
|
|
147
|
+
|
|
139
148
|
getGuildMember({ guildId, userId, signal } = {}) {
|
|
140
149
|
return this.#request(`guilds/${snowflake(guildId, 'guild id')}/members/${snowflake(userId, 'user id')}`, { method: 'GET', signal });
|
|
141
150
|
}
|
|
@@ -13,8 +13,7 @@ export class DiscordController extends TokenBotController {
|
|
|
13
13
|
deriveIdentity: deriveDiscordBotIdentity,
|
|
14
14
|
maskPlatformId: maskDiscordBotId,
|
|
15
15
|
checkedDelivery: {
|
|
16
|
-
capabilities: ['proactive-text-checked', 'exclusive-text-consumer', 'ordinary-text-consumer', 'reply-text-checked',
|
|
17
|
-
'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'reply-mention-checked',
|
|
16
|
+
capabilities: ['proactive-text-checked', 'proactive-receipt-checked', 'proactive-fence-checked', 'reachable-conversations-checked', 'exclusive-text-consumer', 'ordinary-text-consumer', 'reply-text-checked', 'reply-context-checked', 'reply-receipt-checked', 'reply-fence-checked', 'reply-mention-checked',
|
|
18
17
|
'history-text-checked', 'thread-history-text-checked', 'source-file-checked', 'reply-file-checked'],
|
|
19
18
|
inspectAccount: async (token, config, { signal }) => {
|
|
20
19
|
const api = (options.createApi ?? (args => new DiscordApi(args)))({ token });
|
|
@@ -7,6 +7,7 @@ import { captureContextEnhancement } from '../shared/context-enhancement.mjs';
|
|
|
7
7
|
import { evaluateInboundAccess } from '../shared/inbound-access.mjs';
|
|
8
8
|
import { externalAttachments, readExternalFile, replyExternalFile } from './external-files.mjs';
|
|
9
9
|
import { DiscordApi } from './discord-api.mjs';
|
|
10
|
+
import { createDiscordReachable } from './reachable-conversations.mjs';
|
|
10
11
|
import { createDiscordHistoryReader } from './history-reader.mjs';
|
|
11
12
|
import { createDiscordBridgeStatus, DiscordHarnessBridge } from './discord-bridge.mjs';
|
|
12
13
|
import { discordRefusal, verifiedDiscordAccount, discordMessageContentAllowed, inspectDiscordSourceChannel, normalizeDiscordExternalText,
|
|
@@ -568,6 +569,7 @@ export class DiscordRuntime {
|
|
|
568
569
|
#externalSourceFiles;
|
|
569
570
|
#externalOrdinaryText;
|
|
570
571
|
#ordinaryAuthorized = false;
|
|
572
|
+
#reachable = createDiscordReachable();
|
|
571
573
|
#readHistory = createDiscordHistoryReader();
|
|
572
574
|
|
|
573
575
|
constructor({
|
|
@@ -621,6 +623,14 @@ export class DiscordRuntime {
|
|
|
621
623
|
return this.#bridge.sendConnectionTest(text);
|
|
622
624
|
}
|
|
623
625
|
|
|
626
|
+
listReachableConversations(options = {}) {
|
|
627
|
+
return this.#reachable.list(this.#checkedLifetime(options.signal), options);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
postConversationChecked(id,text,options = {}) {
|
|
631
|
+
return this.#reachable.post(this.#checkedLifetime(options.signal), id, text, options);
|
|
632
|
+
}
|
|
633
|
+
|
|
624
634
|
async sendProactiveText(target, text, options = {}) {
|
|
625
635
|
if (this.#config.consumerMode === 'external-consumer') {
|
|
626
636
|
const checked = this.#checkedLifetime(options.signal);
|
|
@@ -628,6 +638,8 @@ export class DiscordRuntime {
|
|
|
628
638
|
if (target?.kind !== 'channel') throw discordRefusal('invalid-target');
|
|
629
639
|
const channel = await inspectDiscordSourceChannel(checked.api, target.route?.channelId, checked.account, checked.signal, { forReply: true });
|
|
630
640
|
checked.assertCurrent();
|
|
641
|
+
if(options.beforeSend!==undefined&&options.beforeSend()!==true)throw discordRefusal('send-permission-denied');
|
|
642
|
+
checked.assertCurrent();
|
|
631
643
|
return sendDiscordCheckedText(checked.api, checked.account, channel, text, { ...options, signal: checked.signal });
|
|
632
644
|
}
|
|
633
645
|
if (!this.#status.ready || !this.#bridge) {
|
|
@@ -694,6 +706,7 @@ export class DiscordRuntime {
|
|
|
694
706
|
|
|
695
707
|
async #start() {
|
|
696
708
|
await this.stop();
|
|
709
|
+
this.#reachable = createDiscordReachable();
|
|
697
710
|
this.#ordinaryAuthorized = false;
|
|
698
711
|
this.#stopped = false;
|
|
699
712
|
this.#sessionId = null;
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import {
|
|
3
|
+
discordChannelPermissions,
|
|
4
|
+
discordRefusal,
|
|
5
|
+
discordSnowflake,
|
|
6
|
+
sendDiscordCheckedText,
|
|
7
|
+
} from './external-consumer.mjs';
|
|
8
|
+
|
|
9
|
+
const REQUIRED = (1n << 10n) | (1n << 11n);
|
|
10
|
+
const MESSAGE_CHANNELS = new Set([0, 2, 5, 13]);
|
|
11
|
+
const denied = (error) =>
|
|
12
|
+
[401, 403, 404].includes(error?.status) ||
|
|
13
|
+
['reply-permission-denied', 'send-permission-denied'].includes(error?.code);
|
|
14
|
+
|
|
15
|
+
function preflightFailure(error, checked) {
|
|
16
|
+
if (checked.signal.aborted) return discordRefusal('cancelled');
|
|
17
|
+
if (['capability-unavailable', 'cancelled', 'bad-request'].includes(error?.code)) return error;
|
|
18
|
+
return discordRefusal(denied(error) ? 'send-permission-denied' : 'send-preflight-unavailable');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function canSpeak(guild, member, channel, account) {
|
|
22
|
+
if (
|
|
23
|
+
!MESSAGE_CHANNELS.has(channel?.type) ||
|
|
24
|
+
!discordSnowflake(channel.id) ||
|
|
25
|
+
channel.guild_id !== guild.id
|
|
26
|
+
)
|
|
27
|
+
return false;
|
|
28
|
+
if (member.communication_disabled_until) {
|
|
29
|
+
const until = Date.parse(member.communication_disabled_until);
|
|
30
|
+
if (!Number.isFinite(until) || until > Date.now()) return false;
|
|
31
|
+
}
|
|
32
|
+
return (
|
|
33
|
+
(discordChannelPermissions(guild, member, channel, account.userId) & REQUIRED) === REQUIRED
|
|
34
|
+
);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function createDiscordReachable() {
|
|
38
|
+
const secret = randomBytes(32);
|
|
39
|
+
const sign = (payload) => createHmac('sha256', secret).update(payload).digest('base64url');
|
|
40
|
+
const encode = (state, account) => {
|
|
41
|
+
const payload = Buffer.from(
|
|
42
|
+
JSON.stringify({ ...state, user: account.userId, expires: Date.now() + 15 * 60_000 }),
|
|
43
|
+
).toString('base64url');
|
|
44
|
+
return `${payload}.${sign(payload)}`;
|
|
45
|
+
};
|
|
46
|
+
const decode = (cursor, account) => {
|
|
47
|
+
if (cursor === undefined) return { after: undefined, guild: 0, channel: 0 };
|
|
48
|
+
if (
|
|
49
|
+
typeof cursor !== 'string' ||
|
|
50
|
+
cursor.length > 2048 ||
|
|
51
|
+
!/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(cursor)
|
|
52
|
+
)
|
|
53
|
+
throw discordRefusal('bad-request');
|
|
54
|
+
const [payload, signature] = cursor.split('.');
|
|
55
|
+
const expected = sign(payload);
|
|
56
|
+
if (
|
|
57
|
+
signature.length !== expected.length ||
|
|
58
|
+
!timingSafeEqual(Buffer.from(signature), Buffer.from(expected))
|
|
59
|
+
)
|
|
60
|
+
throw discordRefusal('bad-request');
|
|
61
|
+
let state;
|
|
62
|
+
try {
|
|
63
|
+
state = JSON.parse(Buffer.from(payload, 'base64url').toString());
|
|
64
|
+
} catch {
|
|
65
|
+
throw discordRefusal('bad-request');
|
|
66
|
+
}
|
|
67
|
+
if (
|
|
68
|
+
state.user !== account.userId ||
|
|
69
|
+
!Number.isSafeInteger(state.expires) ||
|
|
70
|
+
state.expires <= Date.now() ||
|
|
71
|
+
(state.after !== undefined && !discordSnowflake(state.after)) ||
|
|
72
|
+
!Number.isSafeInteger(state.guild) ||
|
|
73
|
+
state.guild < 0 ||
|
|
74
|
+
state.guild >= 100 ||
|
|
75
|
+
!Number.isSafeInteger(state.channel) ||
|
|
76
|
+
state.channel < 0 ||
|
|
77
|
+
state.channel > 500
|
|
78
|
+
)
|
|
79
|
+
throw discordRefusal('bad-request');
|
|
80
|
+
return state;
|
|
81
|
+
};
|
|
82
|
+
return {
|
|
83
|
+
async list(checked, { cursor } = {}) {
|
|
84
|
+
const state = decode(cursor, checked.account);
|
|
85
|
+
try {
|
|
86
|
+
checked.assertCurrent();
|
|
87
|
+
const guilds = await checked.api.listCurrentGuilds({
|
|
88
|
+
after: state.after,
|
|
89
|
+
limit: 100,
|
|
90
|
+
signal: checked.signal,
|
|
91
|
+
});
|
|
92
|
+
checked.assertCurrent();
|
|
93
|
+
if (
|
|
94
|
+
!Array.isArray(guilds) ||
|
|
95
|
+
guilds.length > 100 ||
|
|
96
|
+
guilds.some((g) => !discordSnowflake(g?.id))
|
|
97
|
+
)
|
|
98
|
+
throw discordRefusal('send-preflight-unavailable');
|
|
99
|
+
const conversations = [];
|
|
100
|
+
for (let gi = state.guild; gi < guilds.length; gi++) {
|
|
101
|
+
const guildId = guilds[gi].id;
|
|
102
|
+
let guild, member, channels;
|
|
103
|
+
try {
|
|
104
|
+
[guild, member, channels] = await Promise.all([
|
|
105
|
+
checked.api.getGuild({ guildId, signal: checked.signal }),
|
|
106
|
+
checked.api.getGuildMember({
|
|
107
|
+
guildId,
|
|
108
|
+
userId: checked.account.userId,
|
|
109
|
+
signal: checked.signal,
|
|
110
|
+
}),
|
|
111
|
+
checked.api.getGuildChannels({ guildId, signal: checked.signal }),
|
|
112
|
+
]);
|
|
113
|
+
} catch (error) {
|
|
114
|
+
if (denied(error)) continue;
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
checked.assertCurrent();
|
|
118
|
+
if (guild?.id !== guildId || !Array.isArray(channels) || channels.length > 500)
|
|
119
|
+
throw discordRefusal('send-preflight-unavailable');
|
|
120
|
+
for (let ci = gi === state.guild ? state.channel : 0; ci < channels.length; ci++) {
|
|
121
|
+
if (!canSpeak(guild, member, channels[ci], checked.account)) continue;
|
|
122
|
+
const channel = channels[ci];
|
|
123
|
+
conversations.push({
|
|
124
|
+
id: channel.id,
|
|
125
|
+
kind: 'group',
|
|
126
|
+
name: `${guilds[gi].name || guildId} / ${channel.name || channel.id}`,
|
|
127
|
+
});
|
|
128
|
+
if (conversations.length === 100) {
|
|
129
|
+
const next =
|
|
130
|
+
ci + 1 < channels.length
|
|
131
|
+
? { after: state.after, guild: gi, channel: ci + 1 }
|
|
132
|
+
: gi + 1 < guilds.length
|
|
133
|
+
? { after: state.after, guild: gi + 1, channel: 0 }
|
|
134
|
+
: guilds.length === 100
|
|
135
|
+
? { after: guilds.at(-1).id, guild: 0, channel: 0 }
|
|
136
|
+
: undefined;
|
|
137
|
+
checked.assertCurrent();
|
|
138
|
+
return {
|
|
139
|
+
version: 1,
|
|
140
|
+
conversations,
|
|
141
|
+
hasMore: !!next,
|
|
142
|
+
...(next ? { cursor: encode(next, checked.account) } : {}),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
checked.assertCurrent();
|
|
148
|
+
if (guilds.length === 100 && guilds.at(-1).id === state.after)
|
|
149
|
+
throw discordRefusal('send-preflight-unavailable');
|
|
150
|
+
return {
|
|
151
|
+
version: 1,
|
|
152
|
+
conversations,
|
|
153
|
+
hasMore: guilds.length === 100,
|
|
154
|
+
...(guilds.length === 100
|
|
155
|
+
? { cursor: encode({ after: guilds.at(-1).id, guild: 0, channel: 0 }, checked.account) }
|
|
156
|
+
: {}),
|
|
157
|
+
};
|
|
158
|
+
} catch (error) {
|
|
159
|
+
throw preflightFailure(error, checked);
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
async post(checked, id, text, { beforeSend } = {}) {
|
|
163
|
+
if (
|
|
164
|
+
!discordSnowflake(id) ||
|
|
165
|
+
typeof text !== 'string' ||
|
|
166
|
+
!text.trim() ||
|
|
167
|
+
text.length > 2000 ||
|
|
168
|
+
typeof beforeSend !== 'function'
|
|
169
|
+
)
|
|
170
|
+
throw discordRefusal('bad-request');
|
|
171
|
+
try {
|
|
172
|
+
checked.assertCurrent();
|
|
173
|
+
const channel = await checked.api.getChannel({ channelId: id, signal: checked.signal });
|
|
174
|
+
checked.assertCurrent();
|
|
175
|
+
if (channel?.id !== id || !discordSnowflake(channel.guild_id))
|
|
176
|
+
throw discordRefusal('send-permission-denied');
|
|
177
|
+
const [guild, member] = await Promise.all([
|
|
178
|
+
checked.api.getGuild({ guildId: channel.guild_id, signal: checked.signal }),
|
|
179
|
+
checked.api.getGuildMember({
|
|
180
|
+
guildId: channel.guild_id,
|
|
181
|
+
userId: checked.account.userId,
|
|
182
|
+
signal: checked.signal,
|
|
183
|
+
}),
|
|
184
|
+
]);
|
|
185
|
+
checked.assertCurrent();
|
|
186
|
+
if (guild?.id !== channel.guild_id || !canSpeak(guild, member, channel, checked.account))
|
|
187
|
+
throw discordRefusal('send-permission-denied');
|
|
188
|
+
} catch (error) {
|
|
189
|
+
throw preflightFailure(error, checked);
|
|
190
|
+
}
|
|
191
|
+
checked.assertCurrent();
|
|
192
|
+
if (beforeSend() !== true) throw discordRefusal('send-permission-denied');
|
|
193
|
+
checked.assertCurrent();
|
|
194
|
+
try {
|
|
195
|
+
return await sendDiscordCheckedText(
|
|
196
|
+
checked.api,
|
|
197
|
+
checked.account,
|
|
198
|
+
{ channelId: id, conversationId: id },
|
|
199
|
+
text,
|
|
200
|
+
{ signal: checked.signal, receipt: true },
|
|
201
|
+
);
|
|
202
|
+
} catch (error) {
|
|
203
|
+
throw discordRefusal(
|
|
204
|
+
error?.code === 'reply-permission-denied'
|
|
205
|
+
? 'send-permission-denied'
|
|
206
|
+
: 'send-result-unknown',
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
}
|
|
@@ -6,28 +6,85 @@ const identifier = (value, prefix) => typeof value === 'string' && value.length
|
|
|
6
6
|
const text = (value, max) => typeof value === 'string' && value.length > 0 && value.length <= max;
|
|
7
7
|
|
|
8
8
|
export function externalApprovalCard(value) {
|
|
9
|
+
if (value?.kind === 'pairing') return externalPairingCard(value);
|
|
9
10
|
if (!value || !uuid.test(value.requestId ?? '') || !text(value.title, 120) || !text(value.detail, 16000)
|
|
10
11
|
|| !['pending', 'web-required', 'allowed-once', 'rejected', 'expired', 'executed', 'execution-failed', 'execution-unknown', 'test'].includes(value.status)) refuse('bad-request');
|
|
11
12
|
const elements = [{ tag: 'div', text: { tag: 'plain_text', content: value.detail } }];
|
|
12
|
-
if (value.
|
|
13
|
+
if (value.rules !== undefined && (!Array.isArray(value.rules) || ![1, 2].includes(value.rules.length)
|
|
14
|
+
|| value.rules[0] !== 'exact' || (value.rules.length === 2 && value.rules[1] !== 'all-opaque'))) refuse('bad-request');
|
|
15
|
+
if (value.ruleConfirmation !== undefined && (!uuid.test(value.ruleConfirmation.id ?? '') || !['exact', 'all-opaque'].includes(value.ruleConfirmation.kind))) refuse('bad-request');
|
|
16
|
+
const ruleAction = (action, label, type = 'default') => ({ tag: 'button', type,
|
|
17
|
+
text: { tag: 'plain_text', content: label }, value: { namespace: 'botharness/approval-rule-v1', requestId: value.requestId, action,
|
|
18
|
+
...(value.ruleConfirmation ? { confirmationId: value.ruleConfirmation.id } : {}) } });
|
|
19
|
+
if (value.status === 'pending' && value.ruleConfirmation) elements.push({ tag: 'action', actions: [
|
|
20
|
+
...(value.ruleConfirmation.kind === 'all-opaque'
|
|
21
|
+
? [ruleAction('confirm-all-opaque', 'Confirm ALL opaque tools / 确认全部不透明工具', 'danger')]
|
|
22
|
+
: [ruleAction('confirm-exact', 'Confirm matching rule / 确认保存匹配规则', 'primary')]),
|
|
23
|
+
ruleAction('cancel-rule', 'Back / 返回'),
|
|
24
|
+
] });
|
|
25
|
+
else if (value.status === 'pending') elements.push({ tag: 'action', actions: [
|
|
13
26
|
{ tag: 'button', type: 'primary', text: { tag: 'plain_text', content: 'Allow once / 允许一次' }, value: { namespace: 'botharness/approval-v1', requestId: value.requestId, action: 'allowed-once' } },
|
|
14
27
|
{ tag: 'button', type: 'danger', text: { tag: 'plain_text', content: 'Reject / 拒绝' }, value: { namespace: 'botharness/approval-v1', requestId: value.requestId, action: 'rejected' } },
|
|
28
|
+
...(value.rules ? [ruleAction('preview-exact', 'Allow matching operations… / 批准匹配操作…')] : []),
|
|
29
|
+
...(value.rules?.includes('all-opaque') ? [ruleAction('preview-all-opaque', 'All opaque tools in this scope… / 此范围内全部不透明工具…', 'danger')] : []),
|
|
15
30
|
] });
|
|
16
|
-
|
|
31
|
+
// Both the initial card and later PATCH need shared mode for receiver-visible updates.
|
|
32
|
+
return JSON.stringify({ config: { wide_screen_mode: true, update_multi: true }, header: { title: { tag: 'plain_text', content: value.title }, template: 'blue' }, elements });
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function externalPairingCard(value) {
|
|
36
|
+
if (!uuid.test(value?.requestId ?? '') || !text(value.title, 120) || !text(value.detail, 16000)
|
|
37
|
+
|| !['pending', 'approved', 'rejected', 'expired', 'unavailable'].includes(value.status)
|
|
38
|
+
|| !Array.isArray(value.roles) || value.roles.length > 20
|
|
39
|
+
|| value.roles.some(role => !uuid.test(role?.id ?? '') || !text(role.name, 80) || !Number.isSafeInteger(role.revision) || role.revision < 1)
|
|
40
|
+
|| !Number.isSafeInteger(value.page) || !Number.isSafeInteger(value.pages) || value.pages < 1 || value.pages > 3 || value.page < 0 || value.page >= value.pages
|
|
41
|
+
|| (value.selectedRoleId !== undefined && !uuid.test(value.selectedRoleId))) refuse('bad-request');
|
|
42
|
+
const elements = [{ tag: 'div', text: { tag: 'plain_text', content: value.detail } }];
|
|
43
|
+
const action = (name, label, type = 'default') => ({ tag: 'button', type, text: { tag: 'plain_text', content: label },
|
|
44
|
+
value: { namespace: 'botharness/pairing-v1', requestId: value.requestId, action: name,
|
|
45
|
+
...(name === 'approve-pairing' ? { roleId: value.selectedRoleId } : {}) } });
|
|
46
|
+
if (value.status === 'pending') {
|
|
47
|
+
if (value.roles.length) elements.push({ tag: 'action', actions: [{ tag: 'select_static',
|
|
48
|
+
placeholder: { tag: 'plain_text', content: `Choose Role / 选择角色 (${value.page + 1}/${value.pages})` },
|
|
49
|
+
options: value.roles.map(role => ({ text: { tag: 'plain_text', content: role.name }, value: role.id })),
|
|
50
|
+
value: { namespace: 'botharness/pairing-v1', requestId: value.requestId, action: 'select-role' } }] });
|
|
51
|
+
const buttons = [];
|
|
52
|
+
if (value.page > 0) buttons.push(action('previous-roles', 'Previous / 上一页'));
|
|
53
|
+
if (value.page + 1 < value.pages) buttons.push(action('next-roles', 'Next / 下一页'));
|
|
54
|
+
if (value.selectedRoleId) buttons.push(action('approve-pairing', 'Approve pairing / 批准配对', 'primary'));
|
|
55
|
+
buttons.push(action('reject-pairing', 'Reject / 拒绝', 'danger'));
|
|
56
|
+
elements.push({ tag: 'action', actions: buttons });
|
|
57
|
+
}
|
|
58
|
+
return JSON.stringify({ config: { wide_screen_mode: true, update_multi: true }, header: { title: { tag: 'plain_text', content: value.title }, template: 'blue' }, elements });
|
|
17
59
|
}
|
|
18
60
|
|
|
19
61
|
export function normalizeExternalCardAction(event, identity) {
|
|
20
62
|
const appId = event?.header?.app_id ?? event?.app_id;
|
|
21
63
|
if (appId !== undefined && appId !== identity.appId) refuse('account-changed');
|
|
22
64
|
const value = event?.action?.value;
|
|
23
|
-
if (
|
|
65
|
+
if (!['botharness/approval-v1', 'botharness/pairing-v1', 'botharness/approval-rule-v1'].includes(value?.namespace)) return null;
|
|
24
66
|
const actorId = event?.operator?.open_id;
|
|
25
67
|
const messageId = event?.context?.open_message_id;
|
|
26
68
|
const conversationId = event?.context?.open_chat_id;
|
|
27
69
|
if (!identifier(actorId, 'ou') || !identifier(messageId, 'om') || !identifier(conversationId, 'oc')
|
|
28
|
-
||
|
|
29
|
-
|| !['allowed-once', 'rejected'].includes(value.action)
|
|
70
|
+
|| !uuid.test(value.requestId ?? '')
|
|
30
71
|
|| !/^[a-f0-9]{64}$/.test(identity.fingerprint ?? '')) refuse('invalid-inbound');
|
|
72
|
+
if (value.namespace === 'botharness/approval-rule-v1') {
|
|
73
|
+
if (event.action.tag !== 'button' || !['preview-exact', 'confirm-exact', 'preview-all-opaque', 'confirm-all-opaque', 'cancel-rule'].includes(value.action)
|
|
74
|
+
|| (['preview-exact', 'preview-all-opaque'].includes(value.action) ? value.confirmationId !== undefined : !uuid.test(value.confirmationId ?? ''))) refuse('invalid-inbound');
|
|
75
|
+
return Object.freeze({ kind: 'approval-rule', version: 1, channel: 'feishu', botId: identity.botId, fingerprint: identity.fingerprint,
|
|
76
|
+
actorId, messageId, conversationId, requestId: value.requestId, action: value.action,
|
|
77
|
+
...(value.confirmationId ? { confirmationId: value.confirmationId } : {}) });
|
|
78
|
+
}
|
|
79
|
+
if (value.namespace === 'botharness/pairing-v1') {
|
|
80
|
+
const roleId = value.action === 'select-role' ? event.action.option : value.roleId;
|
|
81
|
+
if (!['select-role', 'approve-pairing', 'reject-pairing', 'next-roles', 'previous-roles'].includes(value.action)
|
|
82
|
+
|| event.action.tag !== (value.action === 'select-role' ? 'select_static' : 'button')
|
|
83
|
+
|| (['select-role', 'approve-pairing'].includes(value.action) ? !uuid.test(roleId ?? '') : roleId !== undefined)) refuse('invalid-inbound');
|
|
84
|
+
return Object.freeze({ kind: 'pairing', version: 1, channel: 'feishu', botId: identity.botId, fingerprint: identity.fingerprint,
|
|
85
|
+
actorId, messageId, conversationId, requestId: value.requestId, action: value.action, ...(roleId ? { roleId } : {}) });
|
|
86
|
+
}
|
|
87
|
+
if (event.action.tag !== 'button' || !['allowed-once', 'rejected'].includes(value.action)) refuse('invalid-inbound');
|
|
31
88
|
return Object.freeze({ version: 1, channel: 'feishu', botId: identity.botId, fingerprint: identity.fingerprint,
|
|
32
89
|
actorId, messageId, conversationId, requestId: value.requestId, action: value.action });
|
|
33
90
|
}
|
|
@@ -38,7 +95,7 @@ export async function replyExternalApprovalCard(client, route, card, { signal, a
|
|
|
38
95
|
const current = await qualifyExternalReply(client, route, signal);
|
|
39
96
|
if (current.actorId !== route.actorId) refuse('stale-route');
|
|
40
97
|
const chat = await client.im.v1.chat.get({ path: { chat_id: route.conversationId } }, { signal });
|
|
41
|
-
if (chat?.code !== 0 ||
|
|
98
|
+
if (chat?.code !== 0 || !(card.kind === 'pairing' ? ['p2p', 'group'] : ['p2p']).includes(chat?.data?.chat_mode)) refuse('stale-route');
|
|
42
99
|
assertCurrent?.();
|
|
43
100
|
signal?.throwIfAborted();
|
|
44
101
|
if (typeof beforeSend !== 'function' || beforeSend() !== true) refuse('stale-route');
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { qualifyExternalReply } from './reply-context.mjs';
|
|
2
|
+
|
|
3
|
+
const refuse = code => { throw Object.assign(new Error(code), { code }); };
|
|
4
|
+
const emojiTypes = Object.freeze({ received: 'GLANCE', answered: 'DONE' });
|
|
5
|
+
const permissionCodes = new Set([99991672, 99991679, 231002, 231008, 231018, 231019, 231020, 231021, 231022]);
|
|
6
|
+
|
|
7
|
+
// Never retry a possibly accepted platform write. The consumer owns durable
|
|
8
|
+
// attempt deduplication; this operation only validates the source and writes.
|
|
9
|
+
export async function reactExternalMessage(client, identity, route, reaction,
|
|
10
|
+
{ signal, assertCurrent, beforeSend } = {}) {
|
|
11
|
+
if (!Object.hasOwn(emojiTypes, reaction) || typeof beforeSend !== 'function') refuse('bad-request');
|
|
12
|
+
assertCurrent();
|
|
13
|
+
const qualified = await qualifyExternalReply(client, route, signal);
|
|
14
|
+
if (qualified.actorId !== route.actorId) refuse('stale-route');
|
|
15
|
+
assertCurrent();
|
|
16
|
+
if (beforeSend() !== true) refuse('stale-route');
|
|
17
|
+
signal?.throwIfAborted();
|
|
18
|
+
let result;
|
|
19
|
+
try {
|
|
20
|
+
result = await client.im.v1.messageReaction.create({
|
|
21
|
+
path: { message_id: route.messageId },
|
|
22
|
+
data: { reaction_type: { emoji_type: emojiTypes[reaction] } },
|
|
23
|
+
}, { signal });
|
|
24
|
+
} catch (error) {
|
|
25
|
+
if (permissionCodes.has(error?.response?.data?.code)) refuse('reaction-permission-denied');
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
28
|
+
if (permissionCodes.has(result?.code))
|
|
29
|
+
refuse('reaction-permission-denied');
|
|
30
|
+
if (typeof result?.code !== 'number' || result.code === 231015) refuse('reaction-result-unknown');
|
|
31
|
+
if (result.code !== 0) refuse('reaction-provider-rejected');
|
|
32
|
+
if (typeof result.data?.reaction_id !== 'string' || !result.data.reaction_id ||
|
|
33
|
+
result.data.operator?.operator_type !== 'app' || result.data.operator.operator_id !== identity.appId ||
|
|
34
|
+
result.data.reaction_type?.emoji_type !== emojiTypes[reaction]) refuse('reaction-result-unknown');
|
|
35
|
+
return { accepted: true };
|
|
36
|
+
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { consumeExternalCardAction } from './external-cards.mjs';
|
|
2
|
+
import { reactExternalMessage } from './external-reactions.mjs';
|
|
2
3
|
import { createExternalNameCache, externalNames } from './external-names.mjs';
|
|
3
4
|
import { qualifyExternalReply } from './reply-context.mjs';
|
|
4
5
|
import { readExternalHistory } from './history-reader.mjs';
|
|
@@ -700,7 +701,82 @@ export class FeishuRuntime {
|
|
|
700
701
|
});
|
|
701
702
|
}
|
|
702
703
|
|
|
703
|
-
async
|
|
704
|
+
async #canPostToGroup(conversationId, { signal } = {}) {
|
|
705
|
+
signal?.throwIfAborted();
|
|
706
|
+
this.#abortController.signal.throwIfAborted();
|
|
707
|
+
if (!this.#status.ready || !this.#client)
|
|
708
|
+
throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
|
|
709
|
+
const client = this.#client;
|
|
710
|
+
// This native endpoint requires the caller to be a member. Metadata or a
|
|
711
|
+
// previously observed inbound message is insufficient proof of membership.
|
|
712
|
+
let cursor;
|
|
713
|
+
let setting;
|
|
714
|
+
const seen = new Set();
|
|
715
|
+
for (let page = 0; page < 10; page++) {
|
|
716
|
+
const response = await client.im.v1.chatModeration.get({path: {chat_id: conversationId},
|
|
717
|
+
params: {user_id_type: 'open_id', page_size: 100, ...(cursor ? {page_token: cursor} : {})}});
|
|
718
|
+
signal?.throwIfAborted();
|
|
719
|
+
this.#abortController.signal.throwIfAborted();
|
|
720
|
+
if (this.#client !== client) throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
|
|
721
|
+
if (response?.code !== 0) return false;
|
|
722
|
+
const data = response.data;
|
|
723
|
+
if (page === 0) setting = data?.moderation_setting;
|
|
724
|
+
if (data?.moderation_setting !== setting) return false;
|
|
725
|
+
if (setting === 'all_members') return true;
|
|
726
|
+
if (!this.#botOpenId || !['only_owner', 'moderator_list'].includes(setting) || !Array.isArray(data.items)) return false;
|
|
727
|
+
if (data.items.some(item => item.user_id_type === 'open_id' && item.user_id === this.#botOpenId)) return true;
|
|
728
|
+
if (data.has_more !== true) return false;
|
|
729
|
+
cursor = data.page_token;
|
|
730
|
+
if (typeof cursor !== 'string' || !cursor || cursor.length > 2048 || seen.has(cursor)) break;
|
|
731
|
+
seen.add(cursor);
|
|
732
|
+
}
|
|
733
|
+
throw Object.assign(new Error('send-preflight-unavailable'), { code: 'send-preflight-unavailable' });
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
async listReachableConversations({ signal, cursor } = {}) {
|
|
737
|
+
if (cursor !== undefined && (typeof cursor !== 'string' || !cursor || cursor.length > 2048))
|
|
738
|
+
throw Object.assign(new Error('bad-request'), { code: 'bad-request' });
|
|
739
|
+
signal?.throwIfAborted();
|
|
740
|
+
if (!this.#status.ready || !this.#client)
|
|
741
|
+
throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
|
|
742
|
+
const client = this.#client;
|
|
743
|
+
const response = await client.im.v1.chat.list({params: {page_size: 100,
|
|
744
|
+
...(cursor ? {page_token: cursor} : {})}});
|
|
745
|
+
signal?.throwIfAborted();
|
|
746
|
+
this.#abortController.signal.throwIfAborted();
|
|
747
|
+
if (this.#client !== client) throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
|
|
748
|
+
if (response?.code !== 0 || !Array.isArray(response.data?.items) || response.data.items.length > 100)
|
|
749
|
+
throw Object.assign(new Error('provider-unavailable'), { code: 'provider-unavailable' });
|
|
750
|
+
const conversations = [];
|
|
751
|
+
for (const value of response.data.items) {
|
|
752
|
+
if (typeof value?.chat_id !== 'string' || !value.chat_id || value.chat_status === 'dissolved'
|
|
753
|
+
|| value.chat_status === 'dissolved_save' || value.chat_mode === 'p2p') continue;
|
|
754
|
+
if (await this.#canPostToGroup(value.chat_id, {signal}))
|
|
755
|
+
conversations.push({id: value.chat_id, kind: 'group', name: typeof value.name === 'string' ? value.name : value.chat_id});
|
|
756
|
+
}
|
|
757
|
+
return {version: 1, conversations, hasMore: response.data.has_more === true,
|
|
758
|
+
...(response.data.has_more ? {cursor: response.data.page_token} : {})};
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
async postConversationChecked(conversationId, text, options = {}) {
|
|
762
|
+
if (typeof conversationId !== 'string' || !/^oc_[A-Za-z0-9]+$/.test(conversationId)
|
|
763
|
+
|| conversationId.length > 512 || typeof text !== 'string' || !text.trim()
|
|
764
|
+
|| typeof options.beforeSend !== 'function')
|
|
765
|
+
throw Object.assign(new Error('bad-request'), { code: 'bad-request' });
|
|
766
|
+
let allowed;
|
|
767
|
+
try { allowed = await this.#canPostToGroup(conversationId, options); }
|
|
768
|
+
catch (error) {
|
|
769
|
+
if (options.signal?.aborted || this.#abortController.signal.aborted)
|
|
770
|
+
throw Object.assign(new Error('cancelled'), {code: 'cancelled'});
|
|
771
|
+
throw Object.assign(new Error('send-preflight-unavailable'), {code: 'send-preflight-unavailable', cause: error});
|
|
772
|
+
}
|
|
773
|
+
if (!allowed)
|
|
774
|
+
throw Object.assign(new Error('send-permission-denied'), { code: 'send-permission-denied' });
|
|
775
|
+
return this.sendProactiveText({kind: 'group', route: {chatId: conversationId}}, text,
|
|
776
|
+
{...options, receipt: true});
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
async sendProactiveText(target, text, { signal, format = 'plain', receipt = false, beforeSend } = {}) {
|
|
704
780
|
if (!this.#status.ready || !this.#client) {
|
|
705
781
|
const error = new Error('飞书机器人尚未连接');
|
|
706
782
|
error.code = 'bot-not-connected';
|
|
@@ -731,7 +807,14 @@ export class FeishuRuntime {
|
|
|
731
807
|
const content = format === 'markdown'
|
|
732
808
|
? { schema: '2.0', body: { elements: [{ tag: 'markdown', content: text }] } }
|
|
733
809
|
: { text };
|
|
734
|
-
const
|
|
810
|
+
const client = this.#client;
|
|
811
|
+
const allowed = beforeSend === undefined || (typeof beforeSend === 'function' && beforeSend() === true);
|
|
812
|
+
signal?.throwIfAborted();
|
|
813
|
+
this.#abortController.signal.throwIfAborted();
|
|
814
|
+
if (this.#client !== client || !this.#status.ready)
|
|
815
|
+
throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
|
|
816
|
+
if (!allowed) throw Object.assign(new Error('send-permission-denied'), { code: 'send-permission-denied' });
|
|
817
|
+
const response = await client.im.v1.message.create({
|
|
735
818
|
params: { receive_id_type: receiveIdType },
|
|
736
819
|
data: {
|
|
737
820
|
receive_id: receiveId,
|
|
@@ -752,6 +835,16 @@ export class FeishuRuntime {
|
|
|
752
835
|
return { sent: true, receipt: { version: 1, messageId, conversationId } };
|
|
753
836
|
}
|
|
754
837
|
|
|
838
|
+
async reactionChecked(identity, route, reaction, { signal, beforeSend } = {}) {
|
|
839
|
+
const client = this.#client;
|
|
840
|
+
const assertCurrent = () => {
|
|
841
|
+
signal?.throwIfAborted();
|
|
842
|
+
if (!client || this.#client !== client || this.#consumerMode !== 'external-consumer')
|
|
843
|
+
throw Object.assign(new Error('bot-not-connected'), { code: 'bot-not-connected' });
|
|
844
|
+
};
|
|
845
|
+
return reactExternalMessage(client, identity, route, reaction, { signal, beforeSend, assertCurrent });
|
|
846
|
+
}
|
|
847
|
+
|
|
755
848
|
async approvalCardChecked(identity, route, card, { signal, beforeSend, update = false } = {}) {
|
|
756
849
|
const client = this.#client;
|
|
757
850
|
const assertCurrent = () => {
|