From adb318db95a5a7385e801ee4f01f1c0ea62e423c Mon Sep 17 00:00:00 2001 From: Den Delimarsky Date: Sat, 21 Nov 2026 08:20:47 -0800 Subject: [PATCH 1/2] Add a thread-only general forum channel to DISCORD_CHANNELS Discord cannot convert a text channel into a forum, so making #general thread-only means creating a new forum channel in the General category. The existing #general text channel is left untouched and must be retired by hand once people have moved over. --- src/config/channels.ts | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/config/channels.ts b/src/config/channels.ts index 158a8649..1e2fb0fa 100644 --- a/src/config/channels.ts +++ b/src/config/channels.ts @@ -160,7 +160,20 @@ export type DiscordChannelConfig = DiscordAdoptedChannelConfig | DiscordNewChann * defaultSortOrder: 'creation_date', * }, */ -export const DISCORD_CHANNELS: readonly DiscordChannelConfig[] = []; +export const DISCORD_CHANNELS: readonly DiscordChannelConfig[] = [ + // Thread-only replacement for the #general text channel: a new forum channel, because + // Discord cannot convert the existing text channel. The old #general is left in place + // and must be retired by hand once people have moved over. + { + name: 'general', + type: 'forum', + parentId: '1358869848138059967', // General + topic: 'General discussion. Every post opens a thread, so start one per topic.', + defaultSortOrder: 'latest_activity', + defaultForumLayout: 'list', + defaultAutoArchiveDuration: 10080, + }, +]; /** Pulumi resource name for a channel entry (stable across deploys). */ export function discordChannelResourceName(channel: DiscordChannelConfig): string { From 18e5a63928a9e5d26e079f5d5df31cfbc38842ac Mon Sep 17 00:00:00 2001 From: Den Delimarsky Date: Sat, 21 Nov 2026 08:28:33 -0800 Subject: [PATCH 2/2] Make #general thread-only in place with permission overwrites Replace the new forum channel with a policy on the existing #general text channel: @everyone is denied SEND_MESSAGES and allowed CREATE_PUBLIC_THREADS and SEND_MESSAGES_IN_THREADS, so members can only start threads and reply in them. Moderators and community managers keep SEND_MESSAGES. Add permissionOverwrites to channel entries to support this. Pulumi owns only the declared permissions: other bits on the same overwrite and overwrites for other roles or members are preserved, and permissions removed from config are cleared on the next deploy. --- README.md | 3 +- scripts/test-config.ts | 146 ++++++++++++++++++++ src/config/channels.ts | 220 ++++++++++++++++++++++++++++--- src/config/discordPermissions.ts | 56 ++++++++ src/discord.ts | 120 ++++++++++++++--- 5 files changed, 508 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index d3aed82e..af677cb6 100644 --- a/README.md +++ b/README.md @@ -102,7 +102,8 @@ Channels listed in [`src/config/channels.ts`](src/config/channels.ts) are manage }, ``` -- **Thread-only channels are a channel type, not a setting.** Discord has no "require threads" switch; thread-only behaviour exists only as `forum` and `media` channels, and the API cannot convert a text channel into one. To make an existing channel thread-only, declare a new `forum`/`media` channel (without `id`) and retire the old channel by hand. Declaring `type: 'forum'` on the `id` of a text channel fails the deploy with an error saying so. +- **Thread-only channels are a channel type or a permission policy, not a setting.** Discord has no "require threads" switch. `forum` and `media` channels are thread-only by type, but the API cannot convert a text channel into one: declaring `type: 'forum'` on the `id` of a text channel fails the deploy with an error saying so. To make an existing text channel thread-only in place, keeping its ID and history, adopt it by `id` and declare `permissionOverwrites` that deny `SEND_MESSAGES` to `DISCORD_EVERYONE_ROLE` and allow `CREATE_PUBLIC_THREADS` and `SEND_MESSAGES_IN_THREADS`; members can then only start threads and reply in them. Add an overwrite allowing `SEND_MESSAGES` for any role that should still post at the top level (`#general` does this for moderators and community managers). +- **Permission overwrites are managed per permission.** Each `permissionOverwrites` entry names a role from `roles.ts` (or `DISCORD_EVERYONE_ROLE`) and the permissions to `allow` and `deny`, limited to the allowlist in [`discordPermissions.ts`](src/config/discordPermissions.ts). Pulumi owns only the listed permissions: other permissions on the same overwrite, and overwrites for other roles or members, stay as they are on Discord. Removing a permission or an entry clears just those bits on the next deploy. The bot needs **Manage Roles** to write overwrites, and Discord only lets it allow or deny permissions it holds itself. Administrators bypass overwrites. - **Channels are never deleted.** Removing an entry only drops the resource from Pulumi state; the channel and its history stay on Discord. Changing an entry's `id` or `type` likewise adopts/creates the new channel and leaves the old one alone. - Only declared settings are managed. `name` is required when creating a channel and optional when adopting one by `id`; declare it only if you want it enforced. Validation (`npm run check`) rejects a missing name on a new channel, names outside 1-100 characters, topics over Discord's limit (1024 for text, 4096 for forum/media), malformed snowflakes, duplicate entries, more than 20 tags, `requireTag` with no tags to pick from, and forum/media settings on text channels (`defaultForumLayout` is forum-only). It prints a `WARNING:` without failing for names with uppercase letters or spaces (Discord normalizes those, so the declared name would never match) and for `requireTag` on an adopted channel that declares no `availableTags` (it relies on the tags already on Discord; the deploy fails if there are none). - `position` is applied on creation only. Discord renumbers positions whenever channels move, so it is not checked or re-applied afterwards; reorder channels in Discord. diff --git a/scripts/test-config.ts b/scripts/test-config.ts index 15307b14..dd50f077 100644 --- a/scripts/test-config.ts +++ b/scripts/test-config.ts @@ -31,14 +31,20 @@ import { getDiscordChannelConfigErrors, getDiscordChannelConfigWarnings, getDiscordChannelDrift, + getDiscordPermissionOverwriteDrift, + planDiscordPermissionOverwrites, + resolveDiscordPermissionOverwrite, + DISCORD_EVERYONE_ROLE, type DiscordChannelApiResponse, type DiscordChannelConfig, type DiscordNewChannelConfig, } from '../src/config/channels'; import { DISCORD_ROLE_PERMISSION_BITS, + discordChannelPermissionBitfield, discordPermissionBitfield, getDiscordRolePermissionErrors, + mergeDiscordPermissionOverwrite, mergeDiscordRolePermissions, } from '../src/config/discordPermissions'; @@ -678,6 +684,146 @@ test('Tag drift ignores Discord tag IDs and ordering but catches changed tags', ); }); +// Discord channel permission overwrites +console.log('\nTesting Discord channel permission overwrites...\n'); +const SEND = (1n << 11n).toString(); // SEND_MESSAGES +const THREADS = ((1n << 35n) | (1n << 38n)).toString(); // CREATE_PUBLIC_THREADS | SEND_MESSAGES_IN_THREADS +const VIEW = (1n << 10n).toString(); // VIEW_CHANNEL, not managed +const THREAD_ONLY = resolveDiscordPermissionOverwrite( + { + role: DISCORD_EVERYONE_ROLE, + deny: ['SEND_MESSAGES'], + allow: ['CREATE_PUBLIC_THREADS', 'SEND_MESSAGES_IN_THREADS'], + }, + OTHER_SNOWFLAKE +); +test('Channel permission bits match the Discord API', () => + discordChannelPermissionBitfield(['SEND_MESSAGES']) === '2048' && + discordChannelPermissionBitfield(['CREATE_PUBLIC_THREADS']) === '34359738368' && + discordChannelPermissionBitfield(['CREATE_PRIVATE_THREADS']) === '68719476736' && + discordChannelPermissionBitfield(['SEND_MESSAGES_IN_THREADS']) === '274877906944' && + discordChannelPermissionBitfield([]) === '0'); +test('An overwrite resolves to the role ID and allow/deny bitfields', () => + THREAD_ONLY.id === OTHER_SNOWFLAKE && THREAD_ONLY.deny === SEND && THREAD_ONLY.allow === THREADS); +test('Overwrite merge keeps unmanaged bits and moves a bit declared on the other side', () => { + // VIEW_CHANNEL denied by hand stays; SEND_MESSAGES allowed by hand becomes denied + const live = { allow: SEND, deny: VIEW }; + const merged = mergeDiscordPermissionOverwrite(live, undefined, { allow: THREADS, deny: SEND }); + return merged.allow === THREADS && merged.deny === (BigInt(VIEW) | BigInt(SEND)).toString(); +}); +test('Overwrite merge clears bits that were declared before and no longer are', () => { + const live = { allow: THREADS, deny: (BigInt(VIEW) | BigInt(SEND)).toString() }; + const merged = mergeDiscordPermissionOverwrite(live, THREAD_ONLY, undefined); + return merged.allow === '0' && merged.deny === VIEW; +}); +test('Overwrite plan writes a missing overwrite and nothing once it is live', () => { + const plan = planDiscordPermissionOverwrites([], undefined, [THREAD_ONLY]); + const live = [{ ...THREAD_ONLY, type: 0 }]; + return ( + plan.length === 1 && + plan[0].id === OTHER_SNOWFLAKE && + plan[0].allow === THREADS && + plan[0].deny === SEND && + planDiscordPermissionOverwrites(live, [THREAD_ONLY], [THREAD_ONLY]).length === 0 + ); +}); +test('Overwrite plan leaves overwrites that were never declared alone', () => { + const live = [ + { id: SNOWFLAKE, type: 1, allow: SEND, deny: '0' }, + { ...THREAD_ONLY, type: 0 }, + ]; + return planDiscordPermissionOverwrites(live, [THREAD_ONLY], [THREAD_ONLY]).length === 0; +}); +test('Overwrite plan clears an overwrite that was removed from config', () => { + const live = [{ id: OTHER_SNOWFLAKE, type: 0, allow: THREADS, deny: SEND }]; + const plan = planDiscordPermissionOverwrites(live, [THREAD_ONLY], undefined); + return plan.length === 1 && plan[0].allow === '0' && plan[0].deny === '0'; +}); +test('Overwrite drift fires only when a declared permission is missing live', () => { + const drift = (permission_overwrites: DiscordChannelApiResponse['permission_overwrites']) => { + const state = discordChannelStateFromApi({ ...TEXT_API, permission_overwrites }); + return getDiscordPermissionOverwriteDrift([THREAD_ONLY], state).join(','); + }; + const live = (allow: string, deny: string) => [{ id: OTHER_SNOWFLAKE, type: 0, allow, deny }]; + const withHandSetBits = (BigInt(VIEW) | BigInt(SEND)).toString(); + const bare = discordChannelStateFromApi(TEXT_API); + return ( + drift(live(THREADS, SEND)) === '' && + // Extra bits set by hand are not drift + drift(live(THREADS, withHandSetBits)) === '' && + drift(live(THREADS, '0')) === OTHER_SNOWFLAKE && + drift(undefined) === OTHER_SNOWFLAKE && + getDiscordPermissionOverwriteDrift(undefined, bare).length === 0 + ); +}); +test('Channel payloads never contain permission overwrites', () => { + const config: DiscordNewChannelConfig = { + name: 'a', + type: 'text', + permissionOverwrites: [{ role: DISCORD_EVERYONE_ROLE, deny: ['SEND_MESSAGES'] }], + }; + return ( + !('permission_overwrites' in discordChannelPayloadFromConfig(config)) && + !('permission_overwrites' in discordChannelCreatePayloadFromConfig(config)) + ); +}); +test('Channel validation accepts thread-only overwrites on an adopted text channel', () => + isClean([ + { + id: SNOWFLAKE, + type: 'text', + permissionOverwrites: [ + { + role: DISCORD_EVERYONE_ROLE, + deny: ['SEND_MESSAGES'], + allow: ['CREATE_PUBLIC_THREADS', 'SEND_MESSAGES_IN_THREADS'], + }, + { role: ROLE_IDS.MODERATORS, allow: ['SEND_MESSAGES'] }, + ], + }, + ])); +test('Channel validation rejects bad permission overwrites', () => { + const withOverwrites = (permissionOverwrites: unknown): DiscordChannelConfig[] => [ + { id: SNOWFLAKE, type: 'text', permissionOverwrites } as unknown as DiscordChannelConfig, + ]; + return ( + hasErrorMatching( + withOverwrites([{ role: 'no-such-role', deny: ['SEND_MESSAGES'] }]), + /"no-such-role" names a role that is not in roles.ts or has no Discord role/ + ) && + // GitHub-only role: no Discord role to attach the overwrite to + hasErrorMatching( + withOverwrites([{ role: ROLE_IDS.SECURITY_TEAM, deny: ['SEND_MESSAGES'] }]), + /has no Discord role/ + ) && + hasErrorMatching( + withOverwrites([ + { role: DISCORD_EVERYONE_ROLE, deny: ['SEND_MESSAGES'] }, + { role: DISCORD_EVERYONE_ROLE, allow: ['CREATE_PUBLIC_THREADS'] }, + ]), + /"@everyone" is declared twice/ + ) && + hasErrorMatching( + withOverwrites([{ role: DISCORD_EVERYONE_ROLE }]), + /allows and denies nothing/ + ) && + hasErrorMatching( + withOverwrites([{ role: DISCORD_EVERYONE_ROLE, deny: ['ADMINISTRATOR'] }]), + /deny permission "ADMINISTRATOR" which is not allowed/ + ) && + hasErrorMatching( + withOverwrites([{ role: DISCORD_EVERYONE_ROLE, allow: ['SEND_MESSAGES', 'SEND_MESSAGES'] }]), + /lists allow permission "SEND_MESSAGES" twice/ + ) && + hasErrorMatching( + withOverwrites([ + { role: DISCORD_EVERYONE_ROLE, allow: ['SEND_MESSAGES'], deny: ['SEND_MESSAGES'] }, + ]), + /both allows and denies "SEND_MESSAGES"/ + ) + ); +}); + // Discord role permissions console.log('\nTesting Discord role permissions...\n'); const EMOJI = (1n << 18n).toString(); // USE_EXTERNAL_EMOJIS diff --git a/src/config/channels.ts b/src/config/channels.ts index 1e2fb0fa..c988c657 100644 --- a/src/config/channels.ts +++ b/src/config/channels.ts @@ -1,11 +1,15 @@ // Discord channels managed by Pulumi (the DiscordChannel resource in src/discord.ts). // // Thread-only channels: Discord has no "require threads" switch on a text channel. -// Thread-only behaviour exists only as the GUILD_FORUM (15) and GUILD_MEDIA (16) -// channel types, where every post opens a thread. The API converts text <-> -// announcement channels only, so an existing text channel can NEVER become a forum. -// To make an existing channel thread-only, declare a NEW forum/media channel here -// (without `id`) and retire the old channel by hand once people have moved over. +// There are two ways to get one: +// - Channel type: GUILD_FORUM (15) and GUILD_MEDIA (16) channels, where every post +// opens a thread. The API converts text <-> announcement channels only, so an +// existing text channel can NEVER become a forum; declare a NEW forum/media channel +// here (without `id`) and retire the old channel by hand once people have moved over. +// - Channel policy: adopt the existing text channel and declare `permissionOverwrites` +// that deny SEND_MESSAGES to @everyone while allowing CREATE_PUBLIC_THREADS and +// SEND_MESSAGES_IN_THREADS. The channel keeps its ID and history; members can only +// start threads and talk inside them. // // Each entry works in one of two modes: // - `id` set: the existing channel with that snowflake is adopted and the settings @@ -25,8 +29,36 @@ // (`discord-channel-`), so renaming a channel created without `id` creates // a second channel. Adopt it by its `id` first if you want to rename it in place. +import { + DISCORD_CHANNEL_PERMISSION_BITS, + discordChannelPermissionBitfield, + isDiscordChannelPermission, + mergeDiscordPermissionOverwrite, + type DiscordChannelPermission, +} from './discordPermissions'; +import { ROLE_IDS, type RoleId } from './roleIds'; +import { ROLES } from './roles'; + export type DiscordChannelType = 'text' | 'forum' | 'media'; +/** Overwrite target for the guild's @everyone role (every member) */ +export const DISCORD_EVERYONE_ROLE = '@everyone'; + +/** + * Channel-level permissions for one role. Pulumi owns only the permissions listed here: + * other permissions on the same overwrite, and overwrites for other roles or members, + * are left as they are on Discord. Removing an entry or a permission later clears just + * those bits (back to inheriting), it does not flip them. + */ +export interface DiscordPermissionOverwriteConfig { + /** A role from roles.ts that has a Discord role, or DISCORD_EVERYONE_ROLE */ + role: RoleId | typeof DISCORD_EVERYONE_ROLE; + /** Permissions granted in this channel (allowlist in discordPermissions.ts) */ + allow?: readonly DiscordChannelPermission[]; + /** Permissions denied in this channel */ + deny?: readonly DiscordChannelPermission[]; +} + /** Allowed values (minutes) for defaultAutoArchiveDuration. */ export const DISCORD_AUTO_ARCHIVE_DURATIONS = [60, 1440, 4320, 10080] as const; export type DiscordAutoArchiveDuration = (typeof DISCORD_AUTO_ARCHIVE_DURATIONS)[number]; @@ -75,6 +107,11 @@ interface DiscordChannelSettings { defaultAutoArchiveDuration?: DiscordAutoArchiveDuration; /** Slowmode (seconds) applied to newly created threads */ defaultThreadRateLimitPerUser?: number; + /** + * Per-role permission overwrites on this channel. Omit to leave the channel's + * permissions entirely untouched. The bot needs Manage Roles to apply them. + */ + permissionOverwrites?: readonly DiscordPermissionOverwriteConfig[]; // --- forum/media only --- /** @@ -131,6 +168,20 @@ export type DiscordChannelConfig = DiscordAdoptedChannelConfig | DiscordNewChann * defaultAutoArchiveDuration: 4320, * }, * + * // Make an existing text channel thread-only by policy: nobody posts at the top + * // level, everyone can start threads and reply in them + * { + * id: '1234567890123456789', + * type: 'text', + * permissionOverwrites: [ + * { + * role: DISCORD_EVERYONE_ROLE, + * deny: ['SEND_MESSAGES'], + * allow: ['CREATE_PUBLIC_THREADS', 'SEND_MESSAGES_IN_THREADS'], + * }, + * ], + * }, + * * // Create a new thread-only forum channel (an existing text channel cannot be * // converted; create the forum, then retire the old channel by hand) * { @@ -161,17 +212,21 @@ export type DiscordChannelConfig = DiscordAdoptedChannelConfig | DiscordNewChann * }, */ export const DISCORD_CHANNELS: readonly DiscordChannelConfig[] = [ - // Thread-only replacement for the #general text channel: a new forum channel, because - // Discord cannot convert the existing text channel. The old #general is left in place - // and must be retired by hand once people have moved over. + // #general is thread-only by policy: members cannot post at the top level, only start + // threads and reply in them. Moderators and community managers can still post there + // (announcements, redirects); administrators bypass overwrites anyway. { - name: 'general', - type: 'forum', - parentId: '1358869848138059967', // General - topic: 'General discussion. Every post opens a thread, so start one per topic.', - defaultSortOrder: 'latest_activity', - defaultForumLayout: 'list', - defaultAutoArchiveDuration: 10080, + id: '1358869848138059969', + type: 'text', + permissionOverwrites: [ + { + role: DISCORD_EVERYONE_ROLE, + deny: ['SEND_MESSAGES'], + allow: ['CREATE_PUBLIC_THREADS', 'SEND_MESSAGES_IN_THREADS'], + }, + { role: ROLE_IDS.MODERATORS, allow: ['SEND_MESSAGES'] }, + { role: ROLE_IDS.COMMUNITY_MANAGERS, allow: ['SEND_MESSAGES'] }, + ], }, ]; @@ -350,6 +405,54 @@ export function validateDiscordChannels( ); } + if (channel.permissionOverwrites !== undefined) { + const seenRoles = new Set(); + for (const overwrite of channel.permissionOverwrites) { + const overwriteLabel = `${label} permission overwrite for "${overwrite.role}"`; + if ( + overwrite.role !== DISCORD_EVERYONE_ROLE && + !ROLES.some((role) => role.id === overwrite.role && role.discord !== undefined) + ) { + errors.push( + `${overwriteLabel} names a role that is not in roles.ts or has no Discord role` + ); + } + if (seenRoles.has(overwrite.role)) { + errors.push(`${overwriteLabel} is declared twice; merge them into one entry`); + } + seenRoles.add(overwrite.role); + + const allow: readonly string[] = overwrite.allow ?? []; + const deny: readonly string[] = overwrite.deny ?? []; + if (allow.length === 0 && deny.length === 0) { + errors.push(`${overwriteLabel} allows and denies nothing; remove it or add permissions`); + } + for (const [side, permissions] of [ + ['allow', allow], + ['deny', deny], + ] as const) { + const seenPermissions = new Set(); + for (const permission of permissions) { + if (!isDiscordChannelPermission(permission)) { + errors.push( + `${overwriteLabel} has ${side} permission "${permission}" which is not allowed ` + + `(allowed: ${Object.keys(DISCORD_CHANNEL_PERMISSION_BITS).join(', ')})` + ); + } + if (seenPermissions.has(permission)) { + errors.push(`${overwriteLabel} lists ${side} permission "${permission}" twice`); + } + seenPermissions.add(permission); + } + } + for (const permission of allow) { + if (deny.includes(permission)) { + errors.push(`${overwriteLabel} both allows and denies "${permission}"`); + } + } + } + } + if (!threadOnly) { for (const field of [ 'requireTag', @@ -488,6 +591,29 @@ export interface DiscordChannelApiResponse { default_reaction_emoji?: DiscordEmojiApi | null; default_sort_order?: number | null; default_forum_layout?: number | null; + permission_overwrites?: DiscordPermissionOverwriteApi[]; +} + +export interface DiscordPermissionOverwriteApi { + /** Role or user snowflake; the @everyone role has the guild's ID */ + id: string; + /** 0 for a role, 1 for a member */ + type: number; + allow: string; + deny: string; +} + +/** Overwrite type for a role, the only kind this config declares */ +export const DISCORD_OVERWRITE_TYPE_ROLE = 0; + +/** + * A declared overwrite with its role resolved to a Discord role ID and its permissions + * to decimal-string bitfields: what the DiscordChannel resource takes as input. + */ +export interface DiscordResolvedPermissionOverwrite { + id: string; + allow: string; + deny: string; } export interface DiscordForumTagApi { @@ -539,6 +665,8 @@ export interface DiscordChannelState { defaultReactionEmoji: DiscordEmojiState | null; defaultSortOrder: DiscordSortOrder | null; defaultForumLayout: DiscordForumLayout | null; + /** Every overwrite on the channel, managed or not */ + permissionOverwrites: DiscordPermissionOverwriteApi[]; } function emojiStateFromApi(emoji: DiscordEmojiApi | null | undefined): DiscordEmojiState | null { @@ -579,9 +707,71 @@ export function discordChannelStateFromApi( defaultReactionEmoji: emojiStateFromApi(channel.default_reaction_emoji), defaultSortOrder: keyForValue(DISCORD_SORT_ORDER_IDS, channel.default_sort_order), defaultForumLayout: keyForValue(DISCORD_FORUM_LAYOUT_IDS, channel.default_forum_layout), + permissionOverwrites: (channel.permission_overwrites ?? []).map((overwrite) => ({ + id: overwrite.id, + type: overwrite.type, + allow: overwrite.allow, + deny: overwrite.deny, + })), + }; +} + +/** + * Resolve a declared overwrite for the role with the given Discord role ID (the guild + * ID for DISCORD_EVERYONE_ROLE). + */ +export function resolveDiscordPermissionOverwrite( + overwrite: DiscordPermissionOverwriteConfig, + discordRoleId: string +): DiscordResolvedPermissionOverwrite { + return { + id: discordRoleId, + allow: discordChannelPermissionBitfield(overwrite.allow ?? []), + deny: discordChannelPermissionBitfield(overwrite.deny ?? []), }; } +/** + * The overwrites to write (PUT /channels/{id}/permissions/{overwrite id}) so the live + * channel carries the declared permissions, with the full allow/deny value for each. + * Only overwrites declared now or previously are considered, and only those whose live + * value would change are returned, so an empty result means in sync. `previous` is what + * Pulumi declared on the last deploy; bits dropped since then are cleared. + */ +export function planDiscordPermissionOverwrites( + live: readonly DiscordPermissionOverwriteApi[], + previous: readonly DiscordResolvedPermissionOverwrite[] | undefined, + next: readonly DiscordResolvedPermissionOverwrite[] | undefined +): DiscordResolvedPermissionOverwrite[] { + const ids = new Set([...(previous ?? []), ...(next ?? [])].map((overwrite) => overwrite.id)); + const changes: DiscordResolvedPermissionOverwrite[] = []; + for (const id of ids) { + const current = live.find((overwrite) => overwrite.id === id) ?? { allow: '0', deny: '0' }; + const merged = mergeDiscordPermissionOverwrite( + current, + previous?.find((overwrite) => overwrite.id === id), + next?.find((overwrite) => overwrite.id === id) + ); + if (merged.allow !== current.allow || merged.deny !== current.deny) { + changes.push({ id, ...merged }); + } + } + return changes; +} + +/** + * IDs of the declared overwrites whose live value lacks a declared permission. Empty + * means in sync; permissions the config does not declare never count as drift. + */ +export function getDiscordPermissionOverwriteDrift( + overwrites: readonly DiscordResolvedPermissionOverwrite[] | undefined, + state: DiscordChannelState +): string[] { + // `permissionOverwrites` is missing from state written before overwrites were managed + const live = state.permissionOverwrites ?? []; + return planDiscordPermissionOverwrites(live, undefined, overwrites).map((change) => change.id); +} + /** * Build the body for PATCH /channels/{id} (Modify Channel) from the declared config. * Only declared settings are sent (`name` included: an adopted channel without one keeps diff --git a/src/config/discordPermissions.ts b/src/config/discordPermissions.ts index 250cc105..032f475c 100644 --- a/src/config/discordPermissions.ts +++ b/src/config/discordPermissions.ts @@ -48,6 +48,62 @@ export function mergeDiscordRolePermissions( return ((BigInt(live) & ~previous) | next).toString(); } +/** + * Permissions that may be allowed or denied per channel through `permissionOverwrites` + * in channels.ts. Separate from the role allowlist above: these are only ever applied + * to one channel, never granted server-wide on a role. Limited to the posting + * permissions needed to make a text channel thread-only; extend in a reviewed PR. + */ +export const DISCORD_CHANNEL_PERMISSION_BITS = { + SEND_MESSAGES: 1n << 11n, + CREATE_PUBLIC_THREADS: 1n << 35n, + CREATE_PRIVATE_THREADS: 1n << 36n, + SEND_MESSAGES_IN_THREADS: 1n << 38n, +} as const; + +export type DiscordChannelPermission = keyof typeof DISCORD_CHANNEL_PERMISSION_BITS; + +export function isDiscordChannelPermission(value: string): value is DiscordChannelPermission { + return Object.prototype.hasOwnProperty.call(DISCORD_CHANNEL_PERMISSION_BITS, value); +} + +/** Bitfield for a list of channel permission names, as a decimal string. */ +export function discordChannelPermissionBitfield( + permissions: readonly DiscordChannelPermission[] +): string { + return permissions + .reduce((bits, name) => bits | DISCORD_CHANNEL_PERMISSION_BITS[name], 0n) + .toString(); +} + +/** The allow/deny bitfields (decimal strings) of one channel permission overwrite */ +export interface DiscordPermissionOverwriteBits { + allow: string; + deny: string; +} + +/** + * The allow/deny values to write to a channel permission overwrite so that Pulumi owns + * only the bits it declared, following the same rules as mergeDiscordRolePermissions: + * bits never managed are left as they are live, bits declared now are set, and bits + * declared previously but no longer are cleared. A bit declared on one side is also + * cleared from the other, since a permission cannot be both allowed and denied. + */ +export function mergeDiscordPermissionOverwrite( + live: DiscordPermissionOverwriteBits, + previouslyManaged: DiscordPermissionOverwriteBits | undefined, + managed: DiscordPermissionOverwriteBits | undefined +): DiscordPermissionOverwriteBits { + const previousAllow = BigInt(previouslyManaged?.allow ?? '0'); + const previousDeny = BigInt(previouslyManaged?.deny ?? '0'); + const nextAllow = BigInt(managed?.allow ?? '0'); + const nextDeny = BigInt(managed?.deny ?? '0'); + return { + allow: ((BigInt(live.allow) & ~previousAllow & ~nextDeny) | nextAllow).toString(), + deny: ((BigInt(live.deny) & ~previousDeny & ~nextAllow) | nextDeny).toString(), + }; +} + /** Errors for permission names that are duplicated or not on the allowlist. */ export function getDiscordRolePermissionErrors( roleName: string, diff --git a/src/discord.ts b/src/discord.ts index a3903d88..e6a99c40 100644 --- a/src/discord.ts +++ b/src/discord.ts @@ -5,6 +5,8 @@ import type { RoleId } from './config/roleIds'; import { DISCORD_CHANNELS, DISCORD_CHANNEL_TYPE_IDS, + DISCORD_EVERYONE_ROLE, + DISCORD_OVERWRITE_TYPE_ROLE, discordChannelCreatePayloadFromConfig, discordChannelPayloadFromConfig, discordChannelRequireTagError, @@ -12,9 +14,13 @@ import { discordChannelStateFromApi, discordChannelTypeName, getDiscordChannelDrift, + getDiscordPermissionOverwriteDrift, + planDiscordPermissionOverwrites, + resolveDiscordPermissionOverwrite, type DiscordChannelApiResponse, type DiscordChannelConfig, type DiscordChannelState, + type DiscordResolvedPermissionOverwrite, } from './config/channels'; import { discordPermissionBitfield, @@ -519,6 +525,11 @@ interface DiscordChannelInputs { guildId: string; channel: DiscordChannelConfig; token: string; + /** + * The channel's declared permission overwrites with roles resolved to Discord role + * IDs. Absent for channels that declare none: their permissions are never written. + */ + permissionOverwrites?: DiscordResolvedPermissionOverwrite[]; } interface DiscordChannelOutputs extends DiscordChannelInputs { @@ -576,33 +587,64 @@ function assertDiscordChannelMatches( } /** - * Apply the declared settings to a live channel if they differ, and return the - * resulting state. Tag IDs and unmanaged flag bits come from `live`. + * Apply the declared settings and permission overwrites to a live channel where they + * differ, and return the resulting state. Tag IDs and unmanaged flag bits come from + * `live`. `previousOverwrites` are the overwrites declared on the last deploy, so + * permissions dropped from the config since then are cleared. */ async function reconcileDiscordChannel( token: string, guildId: string, config: DiscordChannelConfig, - live: DiscordChannelApiResponse + live: DiscordChannelApiResponse, + overwrites?: DiscordResolvedPermissionOverwrite[], + previousOverwrites?: DiscordResolvedPermissionOverwrite[] ): Promise { assertDiscordChannelMatches(guildId, config, live); - const current = discordChannelStateFromApi(live); - const drift = getDiscordChannelDrift(config, current); - if (drift.length === 0) return current; + let state = discordChannelStateFromApi(live); + if (getDiscordChannelDrift(config, state).length > 0) { + // Turning on REQUIRE_TAG with no tags to pick from would make Discord reject every post + const requireTagError = discordChannelRequireTagError(config, state); + if (requireTagError !== undefined) { + throw new Error(`${discordChannelLabel(live.id, config)}: ${requireTagError}`); + } - // Turning on REQUIRE_TAG with no tags to pick from would make Discord reject every post - const requireTagError = discordChannelRequireTagError(config, current); - if (requireTagError !== undefined) { - throw new Error(`${discordChannelLabel(live.id, config)}: ${requireTagError}`); + const updated = await discordFetch(token, `/channels/${live.id}`, { + method: 'PATCH', + headers: DISCORD_CHANNEL_AUDIT_LOG_HEADERS, + body: JSON.stringify(discordChannelPayloadFromConfig(config, state)), + }); + state = discordChannelStateFromApi(updated); } - const updated = await discordFetch(token, `/channels/${live.id}`, { - method: 'PATCH', - headers: DISCORD_CHANNEL_AUDIT_LOG_HEADERS, - body: JSON.stringify(discordChannelPayloadFromConfig(config, current)), - }); - return discordChannelStateFromApi(updated); + // One PUT per overwrite that differs, so overwrites Pulumi does not declare (other + // roles, members) are never rewritten + const changes = planDiscordPermissionOverwrites( + state.permissionOverwrites, + previousOverwrites, + overwrites + ); + for (const change of changes) { + await discordFetch(token, `/channels/${live.id}/permissions/${change.id}`, { + method: 'PUT', + headers: DISCORD_CHANNEL_AUDIT_LOG_HEADERS, + body: JSON.stringify({ + type: DISCORD_OVERWRITE_TYPE_ROLE, + allow: change.allow, + deny: change.deny, + }), + }); + } + if (changes.length === 0) return state; + + return { + ...state, + permissionOverwrites: [ + ...state.permissionOverwrites.filter((o) => !changes.some((change) => change.id === o.id)), + ...changes.map((change) => ({ ...change, type: DISCORD_OVERWRITE_TYPE_ROLE })), + ], + }; } /** Deep equality for the JSON-like values Pulumi hands to the provider (key order ignored) */ @@ -638,10 +680,13 @@ const discordChannelProvider: pulumi.dynamic.ResourceProvider = { const inputsChanged = olds.guildId !== news.guildId || olds.token !== news.token || - !jsonEqual(olds.channel, news.channel); + !jsonEqual(olds.channel, news.channel) || + !jsonEqual(olds.permissionOverwrites, news.permissionOverwrites); // `state` is the live state from the last create/update/refresh const drifted = - olds.state === undefined || getDiscordChannelDrift(news.channel, olds.state).length > 0; + olds.state === undefined || + getDiscordChannelDrift(news.channel, olds.state).length > 0 || + getDiscordPermissionOverwriteDrift(news.permissionOverwrites, olds.state).length > 0; return { changes: inputsChanged || drifted, @@ -667,7 +712,13 @@ const discordChannelProvider: pulumi.dynamic.ResourceProvider = { }); } - const state = await reconcileDiscordChannel(token, guildId, channel, live); + const state = await reconcileDiscordChannel( + token, + guildId, + channel, + live, + inputs.permissionOverwrites + ); return { id: live.id, @@ -713,13 +764,20 @@ const discordChannelProvider: pulumi.dynamic.ResourceProvider = { async update( id: string, - _olds: DiscordChannelOutputs, + olds: DiscordChannelOutputs, news: DiscordChannelInputs ): Promise> { // Re-read before patching so tag IDs and unmanaged flag bits are current even // when the last refresh is stale const live = await discordFetch(news.token, `/channels/${id}`); - const state = await reconcileDiscordChannel(news.token, news.guildId, news.channel, live); + const state = await reconcileDiscordChannel( + news.token, + news.guildId, + news.channel, + live, + news.permissionOverwrites, + olds.permissionOverwrites + ); return { outs: { @@ -750,6 +808,7 @@ class DiscordChannel extends pulumi.dynamic.Resource { guildId: pulumi.Input; channel: pulumi.Input; token: pulumi.Input; + permissionOverwrites?: pulumi.Input[]>; }, opts?: pulumi.CustomResourceOptions ) { @@ -863,10 +922,29 @@ if (DISCORD_ENABLED) { // Manage the channels declared in channels.ts (adopted by id, or created) DISCORD_CHANNELS.forEach((channel) => { + // Resolve each overwrite's role to its Discord role ID; @everyone has the guild's ID + const permissionOverwrites = channel.permissionOverwrites?.map((overwrite) => { + if (overwrite.role === DISCORD_EVERYONE_ROLE) { + return pulumi.output(resolveDiscordPermissionOverwrite(overwrite, guildId)); + } + const discordRole = roleLookup.get(overwrite.role)?.discord?.role; + if (discordRole === undefined) { + throw new Error( + `Discord channel "${channel.id ?? channel.name}" has a permission overwrite for ` + + `"${overwrite.role}", which has no Discord role` + ); + } + return roles[discordRole].roleId.apply((roleId) => + resolveDiscordPermissionOverwrite(overwrite, roleId) + ); + }); + channels[channel.id ?? channel.name] = new DiscordChannel(discordChannelResourceName(channel), { guildId, channel, token: botToken, + // Omitted entirely for channels without overwrites, as for role permissions above + ...(permissionOverwrites && { permissionOverwrites }), }); }); }