fix: enforce channel-level RBAC across WS broadcasts, REST endpoints, and frontend reactivity
Wire the bitwise permission engine end-to-end: - Add sendToChannel() to ConnectionManager, filtering WS recipients by VIEW_CHANNEL - Convert 6 channel-scoped events (messages, typing, reactions) from sendToServer to sendToChannel - Add broadcastOverrideChange() to push channel_updated/channel_deleted per-user on override mutations - Bridge legacy server_members.role TEXT to member_roles junction table on PATCH - Add pushReadyPayload() to force re-sync frontend store after role changes - Filter channels by VIEW_CHANNEL in GET /api/servers/:id to prevent initial load data leak - Pre-compute viewers before CASCADE delete on channel_deleted - Fix frontend channel event handlers to upsert/cleanup channelToServerMap and channelPermissions - Add ChannelSettingsModal with Private Channel toggle and gear icon in ChannelSidebar
This commit is contained in:
@@ -4,6 +4,7 @@ import { getDb, schema } from '../db/index.js';
|
||||
import { authenticate } from '../utils/auth.js';
|
||||
import { generateSnowflake } from '../utils/snowflake.js';
|
||||
import { isMember, hasPermission, getChannelServerId, PermissionBits, computePermissions } from '../utils/permissions.js';
|
||||
import { permissionsToString } from '@opencord/shared/src/permissions.js';
|
||||
import { connectionManager } from '../ws/handler.js';
|
||||
import type {
|
||||
CreateChannelRequest,
|
||||
@@ -23,6 +24,38 @@ function rowToChannel(row: typeof schema.channels.$inferSelect): Channel {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* After a channel override changes, notify each server member:
|
||||
* - VIEW_CHANNEL holders receive channel_updated (with their myPermissions)
|
||||
* - Non-viewers receive channel_deleted to remove the channel from their UI
|
||||
*/
|
||||
function broadcastOverrideChange(serverId: string, channelId: string): void {
|
||||
const db = getDb();
|
||||
const channel = db.select().from(schema.channels).where(eq(schema.channels.id, channelId)).get();
|
||||
if (!channel) return;
|
||||
|
||||
const channelData = rowToChannel(channel);
|
||||
|
||||
for (const [userId, serverIds] of connectionManager.getUserServerEntries()) {
|
||||
if (!serverIds.has(serverId)) continue;
|
||||
|
||||
const perms = computePermissions(userId, serverId, channelId);
|
||||
if ((perms & PermissionBits.VIEW_CHANNEL) !== 0n) {
|
||||
connectionManager.sendToUser(userId, {
|
||||
type: 'channel_updated',
|
||||
channel: { ...channelData, myPermissions: permissionsToString(perms) },
|
||||
serverId,
|
||||
});
|
||||
} else {
|
||||
connectionManager.sendToUser(userId, {
|
||||
type: 'channel_deleted',
|
||||
channelId,
|
||||
serverId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function channelRoutes(app: FastifyInstance): Promise<void> {
|
||||
// GET /api/servers/:id/channels - List channels in a server
|
||||
app.get<{ Params: { id: string } }>('/api/servers/:id/channels', {
|
||||
@@ -177,8 +210,8 @@ export async function channelRoutes(app: FastifyInstance): Promise<void> {
|
||||
|
||||
const channelData = rowToChannel(updated);
|
||||
|
||||
// Broadcast channel_updated to all server members
|
||||
connectionManager.sendToServer(serverId, {
|
||||
// Broadcast channel_updated to members with VIEW_CHANNEL
|
||||
connectionManager.sendToChannel(serverId, id, {
|
||||
type: 'channel_updated',
|
||||
channel: channelData,
|
||||
serverId,
|
||||
@@ -204,16 +237,26 @@ export async function channelRoutes(app: FastifyInstance): Promise<void> {
|
||||
return reply.code(403).send({ error: 'Missing MANAGE_CHANNELS permission', statusCode: 403 });
|
||||
}
|
||||
|
||||
// Collect viewers BEFORE deleting (overrides CASCADE-delete with the channel)
|
||||
const viewerIds: string[] = [];
|
||||
for (const [uid, serverIds] of connectionManager.getUserServerEntries()) {
|
||||
if (serverIds.has(serverId)) {
|
||||
const perms = computePermissions(uid, serverId, id);
|
||||
if ((perms & PermissionBits.VIEW_CHANNEL) !== 0n) {
|
||||
viewerIds.push(uid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Delete messages in channel (attachments cascade), then channel
|
||||
db.delete(schema.messages).where(eq(schema.messages.channelId, id)).run();
|
||||
db.delete(schema.channels).where(eq(schema.channels.id, id)).run();
|
||||
|
||||
// Broadcast channel_deleted to all server members
|
||||
connectionManager.sendToServer(serverId, {
|
||||
type: 'channel_deleted',
|
||||
channelId: id,
|
||||
serverId,
|
||||
});
|
||||
// Broadcast channel_deleted only to users who could see the channel
|
||||
const deleteEvent = { type: 'channel_deleted' as const, channelId: id, serverId };
|
||||
for (const uid of viewerIds) {
|
||||
connectionManager.sendToUser(uid, deleteEvent);
|
||||
}
|
||||
|
||||
return reply.code(200).send({ success: true });
|
||||
});
|
||||
@@ -303,6 +346,9 @@ export async function channelRoutes(app: FastifyInstance): Promise<void> {
|
||||
}).run();
|
||||
});
|
||||
|
||||
// Notify all server members of the permission change
|
||||
broadcastOverrideChange(channel.serverId, id);
|
||||
|
||||
return reply.code(200).send({ success: true });
|
||||
});
|
||||
|
||||
@@ -331,6 +377,9 @@ export async function channelRoutes(app: FastifyInstance): Promise<void> {
|
||||
)
|
||||
).run();
|
||||
|
||||
// Notify all server members of the permission change
|
||||
broadcastOverrideChange(channel.serverId, id);
|
||||
|
||||
return reply.code(200).send({ success: true });
|
||||
},
|
||||
);
|
||||
|
||||
@@ -3,8 +3,8 @@ import { eq, and, inArray } from 'drizzle-orm';
|
||||
import { getDb, schema } from '../db/index.js';
|
||||
import { authenticate } from '../utils/auth.js';
|
||||
import { generateSnowflake } from '../utils/snowflake.js';
|
||||
import { isMember, isServerOwner, hasPermission, PermissionBits } from '../utils/permissions.js';
|
||||
import { DEFAULT_EVERYONE_PERMISSIONS, permissionsToString } from '@opencord/shared/src/permissions.js';
|
||||
import { isMember, isServerOwner, hasPermission, computePermissions, PermissionBits } from '../utils/permissions.js';
|
||||
import { DEFAULT_EVERYONE_PERMISSIONS, ALL_PERMISSIONS, permissionsToString } from '@opencord/shared/src/permissions.js';
|
||||
import crypto from 'crypto';
|
||||
import { connectionManager } from '../ws/handler.js';
|
||||
import type {
|
||||
@@ -228,9 +228,15 @@ export async function serverRoutes(app: FastifyInstance): Promise<void> {
|
||||
})
|
||||
.filter((m): m is MemberWithUser => m !== null);
|
||||
|
||||
// Filter channels by VIEW_CHANNEL permission before returning
|
||||
const visibleChannels = channels.filter(ch => {
|
||||
const perms = computePermissions(request.userId, id, ch.id);
|
||||
return (perms & PermissionBits.VIEW_CHANNEL) !== 0n;
|
||||
});
|
||||
|
||||
const result: ServerWithChannelsAndMembers = {
|
||||
...rowToServer(server),
|
||||
channels: channels.map(rowToChannel),
|
||||
channels: visibleChannels.map(rowToChannel),
|
||||
members,
|
||||
roles: roles.map(r => ({
|
||||
id: r.id,
|
||||
@@ -518,6 +524,54 @@ export async function serverRoutes(app: FastifyInstance): Promise<void> {
|
||||
))
|
||||
.run();
|
||||
|
||||
// Bridge legacy role string to bitwise member_roles
|
||||
if (role === 'admin') {
|
||||
// Find or create Admin role for this server (matches migrate.ts convention)
|
||||
const adminPerms = permissionsToString(ALL_PERMISSIONS);
|
||||
let adminRole = db.select().from(schema.roles)
|
||||
.where(and(
|
||||
eq(schema.roles.serverId, id),
|
||||
eq(schema.roles.name, 'Admin'),
|
||||
eq(schema.roles.permissions, adminPerms),
|
||||
))
|
||||
.get();
|
||||
|
||||
if (!adminRole) {
|
||||
const adminRoleId = `${id}-admin`;
|
||||
db.insert(schema.roles).values({
|
||||
id: adminRoleId,
|
||||
serverId: id,
|
||||
name: 'Admin',
|
||||
color: '#e74c3c',
|
||||
position: 1,
|
||||
permissions: adminPerms,
|
||||
createdAt: Date.now(),
|
||||
}).run();
|
||||
adminRole = db.select().from(schema.roles).where(eq(schema.roles.id, adminRoleId)).get();
|
||||
}
|
||||
|
||||
if (adminRole) {
|
||||
// Assign the Admin role (no-op if already assigned)
|
||||
db.insert(schema.memberRoles).values({
|
||||
serverId: id,
|
||||
userId: uid,
|
||||
roleId: adminRole.id,
|
||||
}).onConflictDoNothing().run();
|
||||
}
|
||||
} else if (role === 'member') {
|
||||
// Remove all explicit role assignments (demote to @everyone only)
|
||||
// @everyone is implicit via computePermissions, never stored in member_roles
|
||||
db.delete(schema.memberRoles)
|
||||
.where(and(
|
||||
eq(schema.memberRoles.serverId, id),
|
||||
eq(schema.memberRoles.userId, uid),
|
||||
))
|
||||
.run();
|
||||
}
|
||||
|
||||
// Force target user's client to re-sync with their new permissions
|
||||
connectionManager.pushReadyPayload(uid);
|
||||
|
||||
const updatedMember = db.select()
|
||||
.from(schema.serverMembers)
|
||||
.where(and(
|
||||
|
||||
@@ -210,8 +210,8 @@ function handleMessageCreate(event: Record<string, unknown>, userId: string): vo
|
||||
|
||||
const messageWithUser = getMessageWithUser(messageId);
|
||||
if (messageWithUser) {
|
||||
// Broadcast to all server members (including sender)
|
||||
connectionManager.sendToServer(serverId, {
|
||||
// Broadcast to members with VIEW_CHANNEL on this channel
|
||||
connectionManager.sendToChannel(serverId, channelId, {
|
||||
type: 'message_created',
|
||||
message: messageWithUser,
|
||||
});
|
||||
@@ -255,7 +255,7 @@ function handleMessageEdit(event: Record<string, unknown>, userId: string): void
|
||||
|
||||
const updatedMessage = getMessageWithUser(messageId);
|
||||
if (updatedMessage) {
|
||||
connectionManager.sendToServer(serverId, {
|
||||
connectionManager.sendToChannel(serverId, message.channelId, {
|
||||
type: 'message_updated',
|
||||
message: updatedMessage,
|
||||
});
|
||||
@@ -293,7 +293,7 @@ function handleMessageDelete(event: Record<string, unknown>, userId: string): vo
|
||||
db.delete(schema.attachments).where(eq(schema.attachments.messageId, messageId)).run();
|
||||
db.delete(schema.messages).where(eq(schema.messages.id, messageId)).run();
|
||||
|
||||
connectionManager.sendToServer(serverId, {
|
||||
connectionManager.sendToChannel(serverId, message.channelId, {
|
||||
type: 'message_deleted',
|
||||
messageId,
|
||||
channelId: message.channelId,
|
||||
@@ -317,8 +317,8 @@ function handleTypingStart(event: Record<string, unknown>, userId: string, usern
|
||||
clearTimeout(existing);
|
||||
}
|
||||
|
||||
// Broadcast typing event (exclude sender)
|
||||
connectionManager.sendToServer(serverId, {
|
||||
// Broadcast typing event to channel viewers (exclude sender)
|
||||
connectionManager.sendToChannel(serverId, channelId, {
|
||||
type: 'typing',
|
||||
channelId,
|
||||
userId,
|
||||
@@ -728,7 +728,7 @@ function handleReactionAdd(event: Record<string, unknown>, userId: string): void
|
||||
createdAt: Date.now(),
|
||||
}).run();
|
||||
|
||||
connectionManager.sendToServer(serverId, {
|
||||
connectionManager.sendToChannel(serverId, message.channelId, {
|
||||
type: 'reaction_added',
|
||||
messageId,
|
||||
reaction: {
|
||||
@@ -766,7 +766,7 @@ function handleReactionRemove(event: Record<string, unknown>, userId: string): v
|
||||
.run();
|
||||
|
||||
if (result.changes > 0) {
|
||||
connectionManager.sendToServer(serverId, {
|
||||
connectionManager.sendToChannel(serverId, message.channelId, {
|
||||
type: 'reaction_removed',
|
||||
messageId,
|
||||
userId,
|
||||
|
||||
@@ -425,6 +425,29 @@ class ConnectionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** Send to server members who have VIEW_CHANNEL on the given channel. */
|
||||
sendToChannel(serverId: string, channelId: string, event: ServerEvent, excludeUserId?: string): void {
|
||||
const message = JSON.stringify(event);
|
||||
for (const [userId, serverIds] of this.userServers) {
|
||||
if (serverIds.has(serverId) && userId !== excludeUserId) {
|
||||
const perms = computePermissions(userId, serverId, channelId);
|
||||
if ((perms & PermissionBits.VIEW_CHANNEL) !== 0n) {
|
||||
const connections = this.getUserConnections(userId);
|
||||
for (const ws of connections) {
|
||||
if (ws.readyState === 1) {
|
||||
ws.send(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Expose userServers iterator for pre-delete viewer collection. */
|
||||
getUserServerEntries(): IterableIterator<[string, Set<string>]> {
|
||||
return this.userServers.entries();
|
||||
}
|
||||
|
||||
/** Send to all DM channel members (queries dm_members table). */
|
||||
sendToDmMembers(dmChannelId: string, event: ServerEvent, excludeUserId?: string): void {
|
||||
const db = getDb();
|
||||
@@ -470,6 +493,20 @@ class ConnectionManager {
|
||||
getAllOnlineUserIds(): string[] {
|
||||
return Array.from(this.connections.keys());
|
||||
}
|
||||
|
||||
/** Push a fresh ready payload to a specific user, forcing full store re-sync. */
|
||||
pushReadyPayload(userId: string): void {
|
||||
const connections = this.getUserConnections(userId);
|
||||
if (connections.size === 0) return;
|
||||
|
||||
const readyData = buildReadyPayload(userId);
|
||||
const message = JSON.stringify({ type: 'ready', ...readyData });
|
||||
for (const ws of connections) {
|
||||
if (ws.readyState === 1) {
|
||||
ws.send(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const connectionManager = new ConnectionManager();
|
||||
|
||||
@@ -134,6 +134,14 @@ export const api = {
|
||||
},
|
||||
sendMessage: (channelId: string, data: CreateMessageRequest) =>
|
||||
request<MessageWithUser>('POST', `/channels/${channelId}/messages`, data),
|
||||
getOverrides: (channelId: string) =>
|
||||
request<{ channelId: string; targetType: string; targetId: string; allow: string; deny: string }[]>(
|
||||
'GET', `/channels/${channelId}/overrides`
|
||||
),
|
||||
putOverride: (channelId: string, data: { targetType: string; targetId: string; allow: string; deny: string }) =>
|
||||
request<{ success: boolean }>('PUT', `/channels/${channelId}/overrides`, data),
|
||||
deleteOverride: (channelId: string, targetType: string, targetId: string) =>
|
||||
request<{ success: boolean }>('DELETE', `/channels/${channelId}/overrides/${targetType}/${targetId}`),
|
||||
},
|
||||
|
||||
messages: {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { CreateChannelModal } from '../modals/CreateChannel';
|
||||
import { InviteModal } from '../modals/InviteModal';
|
||||
import { UserSettingsModal } from '../modals/UserSettings';
|
||||
import { ServerSettingsModal } from '../modals/ServerSettings';
|
||||
import { ChannelSettingsModal } from '../modals/ChannelSettingsModal';
|
||||
import { NewDmModal } from '../modals/NewDmModal';
|
||||
import { AddDmMemberModal } from '../modals/AddDmMemberModal';
|
||||
import { IncomingCallModal } from '../voice/IncomingCallModal';
|
||||
@@ -236,6 +237,7 @@ export function AppLayout() {
|
||||
<InviteModal />
|
||||
<UserSettingsModal />
|
||||
<ServerSettingsModal />
|
||||
<ChannelSettingsModal />
|
||||
<NewDmModal />
|
||||
<AddDmMemberModal />
|
||||
<IncomingCallModal />
|
||||
|
||||
@@ -344,7 +344,22 @@ export function ChannelSidebar() {
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" className="flex-shrink-0 opacity-60">
|
||||
<path d="M5.88657 21C5.57547 21 5.3399 20.7189 5.39427 20.4126L6.00001 17H2.59511C2.28449 17 2.04905 16.7198 2.10259 16.4138L2.27759 15.4138C2.31946 15.1746 2.52722 15 2.77011 15H6.35001L7.41001 9H4.00511C3.69449 9 3.45905 8.71977 3.51259 8.41381L3.68759 7.41381C3.72946 7.17456 3.93722 7 4.18011 7H7.76001L8.39677 3.41262C8.43914 3.17391 8.64664 3 8.88907 3H9.87344C10.1845 3 10.4201 3.28107 10.3657 3.58738L9.76001 7H15.76L16.3968 3.41262C16.4391 3.17391 16.6466 3 16.8891 3H17.8734C18.1845 3 18.4201 3.28107 18.3657 3.58738L17.76 7H21.1649C21.4755 7 21.711 7.28023 21.6574 7.58619L21.4824 8.58619C21.4406 8.82544 21.2328 9 20.9899 9H17.41L16.35 15H19.7549C20.0655 15 20.301 15.2802 20.2474 15.5862L20.0724 16.5862C20.0306 16.8254 19.8228 17 19.5799 17H16L15.3632 20.5874C15.3209 20.8261 15.1134 21 14.8709 21H13.8866C13.5755 21 13.3399 20.7189 13.3943 20.4126L14 17H8.00001L7.36325 20.5874C7.32088 20.8261 7.11337 21 6.87094 21H5.88657ZM9.41001 9L8.35001 15H14.35L15.41 9H9.41001Z" />
|
||||
</svg>
|
||||
<span className={`truncate text-[15px] ${isUnread ? 'font-bold' : 'font-medium'}`}>{channel.name}</span>
|
||||
<span className={`truncate text-[15px] flex-1 text-left ${isUnread ? 'font-bold' : 'font-medium'}`}>{channel.name}</span>
|
||||
{canManageChannels && (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 24 24"
|
||||
fill="currentColor"
|
||||
className="flex-shrink-0 opacity-0 group-hover:opacity-100 text-discord-text-muted hover:text-discord-text-primary transition-opacity"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
openModal('channelSettings', { channelId: channel.id });
|
||||
}}
|
||||
>
|
||||
<path d="M19.14 12.94c.04-.3.06-.61.06-.94 0-.32-.02-.64-.07-.94l2.03-1.58c.18-.14.23-.41.12-.61l-1.92-3.32c-.12-.22-.37-.29-.59-.22l-2.39.96c-.5-.38-1.03-.7-1.62-.94l-.36-2.54c-.04-.24-.24-.41-.48-.41h-3.84c-.24 0-.43.17-.47.41l-.36 2.54c-.59.24-1.13.57-1.62.94l-2.39-.96c-.22-.08-.47 0-.59.22L2.74 8.87c-.12.21-.08.47.12.61l2.03 1.58c-.05.3-.07.62-.07.94s.02.64.07.94l-2.03 1.58c-.18.14-.23.41-.12.61l1.92 3.32c.12.22.37.29.59.22l2.39-.96c.5.38 1.03.7 1.62.94l.36 2.54c.05.24.24.41.48.41h3.84c.24 0 .44-.17.47-.41l.36-2.54c.59-.24 1.13-.56 1.62-.94l2.39.96c.22.08.47 0 .59-.22l1.92-3.32c.12-.22.07-.47-.12-.61l-2.01-1.58zM12 15.6c-1.98 0-3.6-1.62-3.6-3.6s1.62-3.6 3.6-3.6 3.6 1.62 3.6 3.6-1.62 3.6-3.6 3.6z" />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Modal } from '../ui/Modal';
|
||||
import { useUIStore } from '../../stores/uiStore';
|
||||
import { useServerStore } from '../../stores/serverStore';
|
||||
import { api } from '../../api/client';
|
||||
import { PermissionBits, permissionsToString, stringToPermissions } from '../../utils/permissions';
|
||||
|
||||
interface ChannelOverride {
|
||||
channelId: string;
|
||||
targetType: string;
|
||||
targetId: string;
|
||||
allow: string;
|
||||
deny: string;
|
||||
}
|
||||
|
||||
export function ChannelSettingsModal() {
|
||||
const activeModal = useUIStore((s) => s.activeModal);
|
||||
const modalData = useUIStore((s) => s.modalData);
|
||||
const closeModal = useUIStore((s) => s.closeModal);
|
||||
const currentServerId = useServerStore((s) => s.currentServerId);
|
||||
const channels = useServerStore((s) => s.channels);
|
||||
|
||||
const [isPrivate, setIsPrivate] = useState(false);
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isFetching, setIsFetching] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
const isOpen = activeModal === 'channelSettings';
|
||||
const channelId = modalData?.channelId as string | undefined;
|
||||
const channel = channels.find(c => c.id === channelId);
|
||||
|
||||
// Fetch overrides when modal opens
|
||||
useEffect(() => {
|
||||
if (!isOpen || !channelId || !currentServerId) {
|
||||
setIsFetching(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsFetching(true);
|
||||
setError('');
|
||||
|
||||
api.channels.getOverrides(channelId)
|
||||
.then((overrides: ChannelOverride[]) => {
|
||||
// Check if @everyone role (id === serverId) has VIEW_CHANNEL denied
|
||||
const everyoneOverride = overrides.find(
|
||||
o => o.targetType === 'role' && o.targetId === currentServerId
|
||||
);
|
||||
if (everyoneOverride) {
|
||||
const denyBits = stringToPermissions(everyoneOverride.deny);
|
||||
setIsPrivate((denyBits & PermissionBits.VIEW_CHANNEL) !== 0n);
|
||||
} else {
|
||||
setIsPrivate(false);
|
||||
}
|
||||
})
|
||||
.catch((err: Error) => {
|
||||
setError(err.message || 'Failed to load channel overrides');
|
||||
})
|
||||
.finally(() => {
|
||||
setIsFetching(false);
|
||||
});
|
||||
}, [isOpen, channelId, currentServerId]);
|
||||
|
||||
if (!isOpen || !channel || !channelId || !currentServerId) return null;
|
||||
|
||||
const handleToggle = async () => {
|
||||
setError('');
|
||||
setIsLoading(true);
|
||||
|
||||
try {
|
||||
if (!isPrivate) {
|
||||
// Make private: deny VIEW_CHANNEL for @everyone role
|
||||
await api.channels.putOverride(channelId, {
|
||||
targetType: 'role',
|
||||
targetId: currentServerId,
|
||||
allow: '0',
|
||||
deny: permissionsToString(PermissionBits.VIEW_CHANNEL),
|
||||
});
|
||||
setIsPrivate(true);
|
||||
} else {
|
||||
// Make public: remove the @everyone VIEW_CHANNEL deny override
|
||||
await api.channels.deleteOverride(channelId, 'role', currentServerId);
|
||||
setIsPrivate(false);
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to update channel privacy');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Modal isOpen={isOpen} onClose={closeModal} title="Channel Settings" maxWidth="max-w-md">
|
||||
<div className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-xs font-bold text-discord-text-secondary uppercase mb-2">
|
||||
Channel
|
||||
</label>
|
||||
<div className="flex items-center gap-2 text-discord-text-primary">
|
||||
<svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor" className="opacity-60 flex-shrink-0">
|
||||
<path d="M5.88657 21C5.57547 21 5.3399 20.7189 5.39427 20.4126L6.00001 17H2.59511C2.28449 17 2.04905 16.7198 2.10259 16.4138L2.27759 15.4138C2.31946 15.1746 2.52722 15 2.77011 15H6.35001L7.41001 9H4.00511C3.69449 9 3.45905 8.71977 3.51259 8.41381L3.68759 7.41381C3.72946 7.17456 3.93722 7 4.18011 7H7.76001L8.39677 3.41262C8.43914 3.17391 8.64664 3 8.88907 3H9.87344C10.1845 3 10.4201 3.28107 10.3657 3.58738L9.76001 7H15.76L16.3968 3.41262C16.4391 3.17391 16.6466 3 16.8891 3H17.8734C18.1845 3 18.4201 3.28107 18.3657 3.58738L17.76 7H21.1649C21.4755 7 21.711 7.28023 21.6574 7.58619L21.4824 8.58619C21.4406 8.82544 21.2328 9 20.9899 9H17.41L16.35 15H19.7549C20.0655 15 20.301 15.2802 20.2474 15.5862L20.0724 16.5862C20.0306 16.8254 19.8228 17 19.5799 17H16L15.3632 20.5874C15.3209 20.8261 15.1134 21 14.8709 21H13.8866C13.5755 21 13.3399 20.7189 13.3943 20.4126L14 17H8.00001L7.36325 20.5874C7.32088 20.8261 7.11337 21 6.87094 21H5.88657ZM9.41001 9L8.35001 15H14.35L15.41 9H9.41001Z" />
|
||||
</svg>
|
||||
<span className="text-sm font-medium">{channel.name}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="p-2 bg-discord-red/10 border border-discord-red/30 rounded text-discord-text-danger text-sm">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="pt-2 border-t border-discord-bg-tertiary">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-discord-text-primary">Private Channel</div>
|
||||
<div className="text-xs text-discord-text-muted mt-0.5">
|
||||
Only selected members and roles will be able to view this channel.
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
onClick={handleToggle}
|
||||
disabled={isLoading || isFetching}
|
||||
className={`relative w-10 h-6 rounded-full transition-colors flex-shrink-0 ml-4 ${
|
||||
isFetching
|
||||
? 'bg-discord-bg-tertiary opacity-50 cursor-wait'
|
||||
: isPrivate
|
||||
? 'bg-discord-green'
|
||||
: 'bg-discord-bg-tertiary'
|
||||
} ${isLoading ? 'opacity-70 cursor-wait' : 'cursor-pointer'}`}
|
||||
aria-label={isPrivate ? 'Make channel public' : 'Make channel private'}
|
||||
>
|
||||
<div
|
||||
className={`absolute top-1 w-4 h-4 bg-white rounded-full shadow transition-transform ${
|
||||
isPrivate ? 'translate-x-5' : 'translate-x-1'
|
||||
}`}
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{isPrivate && !isFetching && (
|
||||
<div className="flex items-start gap-2 p-2 bg-discord-bg-tertiary/50 rounded text-xs text-discord-text-muted">
|
||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" className="flex-shrink-0 mt-0.5 text-discord-text-secondary">
|
||||
<path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z" />
|
||||
</svg>
|
||||
<span>
|
||||
This channel is hidden from members without explicit access. Users with the Administrator permission or server owners can always see all channels.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -318,29 +318,51 @@ function handleEvent(event: ServerEvent): void {
|
||||
}
|
||||
|
||||
case 'channel_created': {
|
||||
const { currentServerId: curServerId, channels: curChannels, setChannels } = useServerStore.getState();
|
||||
const { currentServerId: curServerId, channels: curChannels, setChannels, channelToServerMap, channelPermissions } = useServerStore.getState();
|
||||
if (event.serverId === curServerId) {
|
||||
// Deduplicate: only add if not already present
|
||||
if (!curChannels.find(c => c.id === event.channel.id)) {
|
||||
setChannels([...curChannels, event.channel].sort((a, b) => a.position - b.position));
|
||||
}
|
||||
}
|
||||
// Update auxiliary maps
|
||||
channelToServerMap.set(event.channel.id, event.serverId);
|
||||
if (event.channel.myPermissions) {
|
||||
channelPermissions.set(event.channel.id, event.channel.myPermissions);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'channel_updated': {
|
||||
const { currentServerId: curServerId2, channels: curChannels2, setChannels: setChannels2 } = useServerStore.getState();
|
||||
const { currentServerId: curServerId2, channels: curChannels2, setChannels: setChannels2, channelPermissions: chPermsMap2 } = useServerStore.getState();
|
||||
if (event.serverId === curServerId2) {
|
||||
setChannels2(curChannels2.map(c => c.id === event.channel.id ? event.channel : c).sort((a, b) => a.position - b.position));
|
||||
const exists = curChannels2.some(c => c.id === event.channel.id);
|
||||
if (exists) {
|
||||
// Replace existing channel data
|
||||
setChannels2(curChannels2.map(c => c.id === event.channel.id ? event.channel : c).sort((a, b) => a.position - b.position));
|
||||
} else {
|
||||
// Upsert: user just gained access to this channel
|
||||
setChannels2([...curChannels2, event.channel].sort((a, b) => a.position - b.position));
|
||||
// Populate channelToServerMap for the new channel
|
||||
const { channelToServerMap: ctsMmap } = useServerStore.getState();
|
||||
ctsMmap.set(event.channel.id, event.serverId);
|
||||
}
|
||||
}
|
||||
// Sync channelPermissions with the server's computed value
|
||||
if (event.channel.myPermissions) {
|
||||
chPermsMap2.set(event.channel.id, event.channel.myPermissions);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case 'channel_deleted': {
|
||||
const { currentServerId: curServerId3, channels: curChannels3, setChannels: setChannels3 } = useServerStore.getState();
|
||||
const { currentServerId: curServerId3, channels: curChannels3, setChannels: setChannels3, channelPermissions: chPermsMap3, channelToServerMap: ctsMap3 } = useServerStore.getState();
|
||||
if (event.serverId === curServerId3) {
|
||||
setChannels3(curChannels3.filter(c => c.id !== event.channelId));
|
||||
}
|
||||
// Clean up auxiliary maps
|
||||
chPermsMap3.delete(event.channelId);
|
||||
ctsMap3.delete(event.channelId);
|
||||
// If the user is currently viewing this channel, navigate away
|
||||
{
|
||||
const { currentChannelId } = useChatStore.getState();
|
||||
|
||||
@@ -9,6 +9,7 @@ type ModalType =
|
||||
| 'invite'
|
||||
| 'userSettings'
|
||||
| 'serverSettings'
|
||||
| 'channelSettings'
|
||||
| 'imagePreview'
|
||||
| 'newDm'
|
||||
| 'addDmMember'
|
||||
|
||||
Reference in New Issue
Block a user