Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/discord-managed-role-mentions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Checked Discord managed-role mentions

The exclusive Discord Consumer recognizes native user mentions of the authenticated Bot and mentions of its own current integration-managed role. Names and arbitrary roles do not supply addressing authority.

For a role mention, the Runtime checks the original channel/guild, native guild roles and Bot member before normalization. The role's string ID must appear in `mention_roles`; its current `managed` field must be true, `tags.bot_id` must equal the authenticated Bot user ID, and the current Bot member must hold that role. The guild's everyone role never qualifies. Reuse existing native source inspection without another Gateway connection or persistent role cache.

The event preserves original text, source/reply association and user mentions. A managed role is not fabricated as a user mention. Ordinary collection remains separately opted in; unrelated role/everyone/here messages may be ordinary context only under that policy. Existing human-only, account, permission, route and receiver-lifetime checks still apply. The standalone Discord Session runner is unchanged.

Recognition does not grant Message Content intent or make Discord deliver unavailable content. Fresh native delivery and original-location replies must be qualified on the selected App; source tests are not native Discord acceptance.

References: [Role and role-tag structures](https://docs.discord.com/developers/topics/permissions#role-object), [Message mention fields](https://docs.discord.com/developers/resources/message#message-object), [BotHarness #1615](https://github.com/BotHarness/DeepSeekBot/issues/1615).
522 changes: 261 additions & 261 deletions lib/index.js

Large diffs are not rendered by default.

20 changes: 15 additions & 5 deletions src/channels/discord/discord-runtime.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { DiscordApi } from './discord-api.mjs';
import { createDiscordReachable } from './reachable-conversations.mjs';
import { createDiscordHistoryReader } from './history-reader.mjs';
import { createDiscordBridgeStatus, DiscordHarnessBridge } from './discord-bridge.mjs';
import { discordRefusal, verifiedDiscordAccount, discordMessageContentAllowed, inspectDiscordSourceChannel, normalizeDiscordExternalText,
import { discordRefusal, discordSnowflake, verifiedDiscordAccount, discordMessageContentAllowed, discordMessageMentionsAccount, inspectDiscordSourceChannel, normalizeDiscordExternalText,
qualifyDiscordReply, sendDiscordReply, sendDiscordCheckedText } from './external-consumer.mjs';

const DISCORD_GATEWAY_INTENTS = (1 << 0) | (1 << 9) | (1 << 12) | (1 << 15);
Expand Down Expand Up @@ -939,19 +939,29 @@ export class DiscordRuntime {
if (!this.#account || !this.#status.ready || generation !== this.#generation
|| !message?.guild_id || message.webhook_id || message.author?.id === this.#account.userId
|| !Array.isArray(message.mentions)) return;
const mentioned = message.mentions.some(user => user.id === this.#account.userId);
if (message.author?.bot === true && !mentioned) return;
if (!mentioned && (!this.#ordinaryAuthorized || this.#externalOrdinaryText() !== true
let mentioned = message.mentions.some(user => user.id === this.#account.userId);
const roleCandidate = Array.isArray(message.mention_roles) && message.mention_roles.some(discordSnowflake);
if (message.author?.bot === true && !mentioned && !roleCandidate) return;
if (!mentioned && !roleCandidate && (!this.#ordinaryAuthorized || this.#externalOrdinaryText() !== true
|| typeof message.content !== 'string' || !message.content.trim())) return;
const checked = this.#checkedLifetime();
let channel;
if (!mentioned && roleCandidate) {
channel = await inspectDiscordSourceChannel(checked.api, message.channel_id, checked.account, checked.signal);
checked.assertCurrent();
mentioned = discordMessageMentionsAccount(message, checked.account, channel);
}
if (!mentioned) {
if (message.author?.bot === true) return;
if (!this.#ordinaryAuthorized || this.#externalOrdinaryText() !== true
|| typeof message.content !== 'string' || !message.content.trim()) return;
const application = await checked.api.getCurrentApplication({ signal: checked.signal });
if (verifiedDiscordAccount({ id: checked.account.userId, bot: true }, application).fingerprint !== checked.account.fingerprint)
throw discordRefusal('account-changed');
checked.assertCurrent();
if (!discordMessageContentAllowed(application) || this.#externalOrdinaryText() !== true) return;
}
const channel = await inspectDiscordSourceChannel(checked.api, message.channel_id, checked.account, checked.signal);
channel ??= await inspectDiscordSourceChannel(checked.api, message.channel_id, checked.account, checked.signal);
let event = normalizeDiscordExternalText(message, { botId: this.#config.botId, account: checked.account,
channel, eventId: `gateway:${this.#sessionId}:${sequence}`, ordinaryText: !mentioned });
checked.assertCurrent();
Expand Down
13 changes: 12 additions & 1 deletion src/channels/discord/external-consumer.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,11 @@ export async function inspectDiscordSourceChannel(api, channelId, account, signa
signal?.throwIfAborted();
const name = [guild.name, parent.name].every(value => typeof value === 'string' && value.trim())
? `${guild.name.trim()} #${parent.name.trim()}`.slice(0, 512) : undefined;
const ownManagedRoleIds = guild.roles.filter(role => discordSnowflake(role.id)
&& role.id !== guild.id && role.managed === true && role.tags?.bot_id === account.userId
&& member.roles.includes(role.id)).map(role => role.id);
return { guildId: guild.id, conversationId: parent.id, channelId: channel.id, ...(name ? { name } : {}),
...(ownManagedRoleIds.length ? { ownManagedRoleIds } : {}),
...(isThread ? { threadId: channel.id } : {}) };
} catch (error) { throw nativeFailure(error, 'source-not-found'); }
}
Expand All @@ -115,14 +119,21 @@ export function normalizeDiscordHistoryText(message, identity) {
return normalizeDiscordHumanText(message, identity, false);
}

/** Role ownership comes only from the checked current guild/member, never message text or names. */
export function discordMessageMentionsAccount(message, account, channel) {
return message.mentions.some(user => user.id === account.userId)
|| (Array.isArray(message.mention_roles) && message.mention_roles.some(roleId =>
discordSnowflake(roleId) && channel.ownManagedRoleIds?.includes(roleId)));
}

function normalizeDiscordHumanText(message, { botId, account, channel, eventId }, requireMention, allowBots = false) {
if (!discordSnowflake(message?.id) || !discordSnowflake(message?.author?.id)
|| (message.author.bot === true && !allowBots) || message.webhook_id || message.author.id === account.userId
|| ![0, 19].includes(message.type) || typeof message.content !== 'string' || !message.content.trim()
|| message.content.length > 16000 || !Array.isArray(message.mentions)) return null;
if (message.guild_id !== channel.guildId || message.channel_id !== channel.channelId)
throw discordRefusal('stale-route');
const mentionedAccount = message.mentions.some(user => user.id === account.userId);
const mentionedAccount = discordMessageMentionsAccount(message, account, channel);
if ((requireMention || message.author.bot === true) && !mentionedAccount) return null;
const timestamp = Date.parse(message.timestamp);
if (!Number.isFinite(timestamp) || typeof eventId !== 'string' || !eventId || eventId.length > 512)
Expand Down
102 changes: 102 additions & 0 deletions test/channels/discord/external-consumer.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,108 @@ function ordinaryRuntimeFixture({ enabled = true, optedIn = true, thread = true
async dispatch(message) { socket.packet({ op: 0, t: 'MESSAGE_CREATE', s: 42, d: message }); await flush(); } };
}

test('own managed-role mention reaches the checked consumer without ordinary-message opt-in', async () => {
const f = ordinaryRuntimeFixture({ enabled: false, optedIn: false, thread: false });
f.guild.roles.push({ id: ids.role, managed: true, tags: { bot_id: ids.bot }, permissions: '0' });
f.member.roles.push(ids.role);
f.message.mentions = [];
f.message.mention_roles = [ids.role];
f.message.content = `<@&${ids.role}> QA managed role`;
try {
await f.runtime.start();
await f.dispatch(f.message);
assert.equal(f.received.length, 1, 'the App-owned managed role must address its bound Bot');
assert.equal(f.received[0].mentionedAccount, true);
assert.equal(f.received[0].text, f.message.content);
const result = await f.runtime.replyChecked(f.received[0].reply, 'QA managed-role reply', {
beforeSend: () => true, receipt: true,
});
assert.equal(result.receipt.messageId, ids.sent);
assert.equal(f.sends[0].channelId, ids.channel);
} finally { await f.runtime.stop(); }
});

test('role addressing requires current native managed ownership and exact role IDs, never names or member roles alone', async () => {
const f = ordinaryRuntimeFixture({ optedIn: false, thread: false });
const role = { id: ids.role, managed: true, tags: { bot_id: ids.bot }, permissions: '0', name: 'QA Bot' };
f.guild.roles.push(role);
f.member.roles.push(ids.role);
const message = { ...f.message, mentions: [], mention_roles: [ids.role], content: `<@&${ids.role}> QA` };
try {
await f.runtime.start();
for (const tags of [undefined, { bot_id: ids.actor }, { bot_id: Number(ids.bot) }, { integration_id: ids.bot }]) {
role.tags = tags;
await f.dispatch(message);
assert.equal(f.received.length, 0);
}
role.tags = { bot_id: ids.bot }; role.managed = false;
await f.dispatch(message); assert.equal(f.received.length, 0);
role.managed = true; f.member.roles = [];
await f.dispatch(message); assert.equal(f.received.length, 0);
f.member.roles = [ids.role];
for (const mention_roles of [[], undefined, null, [ids.actor], [Number(ids.role)], [ids.guild]]) {
await f.dispatch({ ...message, mention_roles, mention_everyone: true });
assert.equal(f.received.length, 0);
}
// Message-authored role metadata cannot replace the native guild proof.
role.tags = { bot_id: ids.actor };
await f.dispatch({ ...message, roles: [{ ...role, tags: { bot_id: ids.bot } }] });
assert.equal(f.received.length, 0);
role.tags = { bot_id: ids.bot };
await f.dispatch(message); assert.equal(f.received.length, 1);
// A changed guild role is checked again; no process-local role ownership cache survives it.
role.tags = { bot_id: ids.actor };
await f.dispatch(message); assert.equal(f.received.length, 1);
assert.equal(f.sends.length, 0);
} finally { await f.runtime.stop(); }
});

test('another Bot reaches the consumer through the own managed role but never through an unrelated role', async () => {
const f = ordinaryRuntimeFixture({ thread: false });
f.guild.roles.push({ id: ids.role, managed: true, tags: { bot_id: ids.bot }, permissions: '0' });
f.member.roles.push(ids.role);
const message = { ...f.message, author: { id: ids.actor, username: 'Peer Bot', bot: true }, mentions: [] };
try {
await f.runtime.start();
await f.dispatch({ ...message, mention_roles: [ids.guild], content: `<@&${ids.guild}> QA` });
assert.equal(f.received.length, 0);
await f.dispatch({ ...message, mention_roles: [ids.role], content: `<@&${ids.role}> QA` });
assert.equal(f.received.length, 1);
assert.equal(f.received[0].mentionedAccount, true);
} finally { await f.runtime.stop(); }
});

test('ordinary collection retains unrelated role mentions as context while own managed roles address the Bot in a native thread', async () => {
const f = ordinaryRuntimeFixture();
f.guild.roles.push({ id: ids.role, managed: true, tags: { bot_id: ids.bot }, permissions: '0' });
f.member.roles.push(ids.role);
try {
await f.runtime.start();
await f.dispatch({ ...f.ordinaryMessage, mention_roles: [ids.actor], mention_everyone: true });
assert.equal(f.received[0].mentionedAccount, false);
await f.dispatch({ ...f.ordinaryMessage, mention_roles: [ids.role] });
assert.equal(f.received[1].mentionedAccount, true);
assert.equal(f.received[1].reply.threadId, ids.thread);
assert.equal(f.received[1].reply.conversationId, ids.channel);
assert.deepEqual(f.received[1].mentions, [], 'a native role is not fabricated as a user mention');
} finally { await f.runtime.stop(); }
});

test('stopped receiver cannot deliver a managed-role mention after its native ownership lookup finishes', async () => {
const f = ordinaryRuntimeFixture({ optedIn: false });
f.guild.roles.push({ id: ids.role, managed: true, tags: { bot_id: ids.bot }, permissions: '0' });
f.member.roles.push(ids.role);
let finish;
try {
await f.runtime.start();
f.api.getGuild = () => new Promise(resolve => { finish = () => resolve(f.guild); });
await f.dispatch({ ...f.message, mentions: [], mention_roles: [ids.role] });
assert.equal(typeof finish, 'function');
await f.runtime.stop(); finish(); await flush();
assert.equal(f.received.length, 0);
} finally { await f.runtime.stop(); }
});

test('ordinary Gateway requires consumer opt-in AND native approval; OFF retains mention replies without privileged intent', async () => {
for (const enabled of [false, true]) for (const optedIn of [false, true]) {
const f = ordinaryRuntimeFixture({ enabled, optedIn });
Expand Down
Loading