Polish off all our gross edges around frontend/backend Public name management

This commit is contained in:
Jack Kingsman
2026-03-15 18:20:43 -07:00
parent c76f230c9f
commit c809dad05d
46 changed files with 211 additions and 40 deletions
+10
View File
@@ -0,0 +1,10 @@
PUBLIC_CHANNEL_KEY = "8B3387E9C5CDEA6AC9E5EDBAA115CD72"
PUBLIC_CHANNEL_NAME = "Public"
def is_public_channel_key(key: str) -> bool:
return key.upper() == PUBLIC_CHANNEL_KEY
def is_public_channel_name(name: str) -> bool:
return name.casefold() == PUBLIC_CHANNEL_NAME.casefold()
+5 -7
View File
@@ -17,6 +17,7 @@ from contextlib import asynccontextmanager
from meshcore import EventType, MeshCore
from app.channel_constants import PUBLIC_CHANNEL_KEY, PUBLIC_CHANNEL_NAME
from app.config import settings
from app.event_handlers import cleanup_expired_acks
from app.models import Contact, ContactUpsert
@@ -443,16 +444,13 @@ async def ensure_default_channels() -> None:
This seeds the canonical Public channel row in the database if it is missing
or misnamed. It does not make the channel undeletable through the router.
"""
# Public channel - no hashtag, specific well-known key
PUBLIC_CHANNEL_KEY_HEX = "8B3387E9C5CDEA6AC9E5EDBAA115CD72"
# Check by KEY (not name) since that's what's fixed
existing = await ChannelRepository.get_by_key(PUBLIC_CHANNEL_KEY_HEX)
if not existing or existing.name != "Public":
existing = await ChannelRepository.get_by_key(PUBLIC_CHANNEL_KEY)
if not existing or existing.name != PUBLIC_CHANNEL_NAME:
logger.info("Ensuring default Public channel exists with correct name")
await ChannelRepository.upsert(
key=PUBLIC_CHANNEL_KEY_HEX,
name="Public",
key=PUBLIC_CHANNEL_KEY,
name=PUBLIC_CHANNEL_NAME,
is_hashtag=False,
on_radio=existing.on_radio if existing else False,
)
+47 -7
View File
@@ -4,6 +4,12 @@ from hashlib import sha256
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
from app.channel_constants import (
PUBLIC_CHANNEL_KEY,
PUBLIC_CHANNEL_NAME,
is_public_channel_key,
is_public_channel_name,
)
from app.models import Channel, ChannelDetail, ChannelMessageCounts, ChannelTopSender
from app.region_scope import normalize_region_scope
from app.repository import ChannelRepository, MessageRepository
@@ -62,10 +68,31 @@ async def create_channel(request: CreateChannelRequest) -> Channel:
Channels are NOT pushed to radio on creation. They are loaded to the radio
automatically when sending a message (see messages.py send_channel_message).
"""
is_hashtag = request.name.startswith("#")
requested_name = request.name
is_hashtag = requested_name.startswith("#")
# Determine the channel secret
if request.key and not is_hashtag:
# Reserve the canonical Public room so it cannot drift to another key,
# and the well-known Public key cannot be renamed to something else.
if is_public_channel_name(requested_name):
if request.key:
try:
key_bytes = bytes.fromhex(request.key)
if len(key_bytes) != 16:
raise HTTPException(
status_code=400,
detail="Channel key must be exactly 16 bytes (32 hex chars)",
)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid hex string for key") from None
if key_bytes.hex().upper() != PUBLIC_CHANNEL_KEY:
raise HTTPException(
status_code=400,
detail=f'"{PUBLIC_CHANNEL_NAME}" must use the canonical Public key',
)
key_hex = PUBLIC_CHANNEL_KEY
channel_name = PUBLIC_CHANNEL_NAME
is_hashtag = False
elif request.key and not is_hashtag:
try:
key_bytes = bytes.fromhex(request.key)
if len(key_bytes) != 16:
@@ -74,17 +101,25 @@ async def create_channel(request: CreateChannelRequest) -> Channel:
)
except ValueError:
raise HTTPException(status_code=400, detail="Invalid hex string for key") from None
key_hex = key_bytes.hex().upper()
if is_public_channel_key(key_hex):
raise HTTPException(
status_code=400,
detail=f'The canonical Public key may only be used for "{PUBLIC_CHANNEL_NAME}"',
)
channel_name = requested_name
else:
# Derive key from name hash (same as meshcore library does)
key_bytes = sha256(request.name.encode("utf-8")).digest()[:16]
key_bytes = sha256(requested_name.encode("utf-8")).digest()[:16]
key_hex = key_bytes.hex().upper()
channel_name = requested_name
key_hex = key_bytes.hex().upper()
logger.info("Creating channel %s: %s (hashtag=%s)", key_hex, request.name, is_hashtag)
logger.info("Creating channel %s: %s (hashtag=%s)", key_hex, channel_name, is_hashtag)
# Store in database only - radio sync happens at send time
await ChannelRepository.upsert(
key=key_hex,
name=request.name,
name=channel_name,
is_hashtag=is_hashtag,
on_radio=False,
)
@@ -140,6 +175,11 @@ async def delete_channel(key: str) -> dict:
Note: This does not clear the channel from the radio. The radio's channel
slots are managed separately (channels are loaded temporarily when sending).
"""
if is_public_channel_key(key):
raise HTTPException(
status_code=400, detail="The canonical Public channel cannot be deleted"
)
logger.info("Deleting channel %s from database", key)
await ChannelRepository.delete(key)
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+2 -1
View File
@@ -6,6 +6,7 @@ import { ContactPathDiscoveryModal } from './ContactPathDiscoveryModal';
import { ChannelFloodScopeOverrideModal } from './ChannelFloodScopeOverrideModal';
import { isFavorite } from '../utils/favorites';
import { handleKeyboardActivate } from '../utils/a11y';
import { isPublicChannelKey } from '../utils/publicChannel';
import { stripRegionScopePrefix } from '../utils/regionScope';
import { isPrefixOnlyContact } from '../utils/pubkey';
import { ContactAvatar } from './ContactAvatar';
@@ -379,7 +380,7 @@ export function ChatHeader({
)}
</button>
)}
{!(conversation.type === 'channel' && conversation.name === 'Public') && (
{!(conversation.type === 'channel' && isPublicChannelKey(conversation.id)) && (
<button
className="p-1 rounded hover:bg-destructive/10 text-muted-foreground hover:text-destructive text-lg leading-none transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => {
+2 -1
View File
@@ -16,6 +16,7 @@ import {
hasRoutingOverride,
parsePathHops,
} from '../utils/pathUtils';
import { isPublicChannelKey } from '../utils/publicChannel';
import { getMapFocusHash } from '../utils/urlHash';
import { isFavorite } from '../utils/favorites';
import { handleKeyboardActivate } from '../utils/a11y';
@@ -611,7 +612,7 @@ function MostActiveRoomsSection({
onKeyDown={onNavigateToChannel ? handleKeyboardActivate : undefined}
onClick={() => onNavigateToChannel?.(room.channel_key)}
>
{room.channel_name.startsWith('#') || room.channel_name === 'Public'
{room.channel_name.startsWith('#') || isPublicChannelKey(room.channel_key)
? room.channel_name
: `#${room.channel_name}`}
</span>
+3 -2
View File
@@ -30,6 +30,7 @@ import {
type SidebarSortableSection,
type SortOrder,
} from '../utils/conversationState';
import { isPublicChannelKey } from '../utils/publicChannel';
import { getContactDisplayName } from '../utils/pubkey';
import { handleKeyboardActivate } from '../utils/a11y';
import { ContactAvatar } from './ContactAvatar';
@@ -254,8 +255,8 @@ export function Sidebar({
() =>
[...uniqueChannels].sort((a, b) => {
// Public channel always sorts to the top
if (a.name === 'Public') return -1;
if (b.name === 'Public') return 1;
if (isPublicChannelKey(a.key)) return -1;
if (isPublicChannelKey(b.key)) return 1;
if (sectionSortOrders.channels === 'recent') {
const timeA = getLastMessageTime('channel', a.key);
+5 -10
View File
@@ -4,10 +4,9 @@ import { takePrefetchOrFetch } from '../prefetch';
import { toast } from '../components/ui/sonner';
import * as messageCache from '../messageCache';
import { getContactDisplayName } from '../utils/pubkey';
import { findPublicChannel, PUBLIC_CHANNEL_KEY, PUBLIC_CHANNEL_NAME } from '../utils/publicChannel';
import type { Channel, Contact, Conversation } from '../types';
const PUBLIC_CHANNEL_KEY = '8B3387E9C5CDEA6AC9E5EDBAA115CD72';
interface UseContactsAndChannelsArgs {
setActiveConversation: (conv: Conversation | null) => void;
pendingDeleteFallbackRef: MutableRefObject<boolean>;
@@ -121,14 +120,12 @@ export function useContactsAndChannels({
messageCache.remove(key);
const refreshedChannels = await api.getChannels();
setChannels(refreshedChannels);
const publicChannel =
refreshedChannels.find((c) => c.key === PUBLIC_CHANNEL_KEY) ||
refreshedChannels.find((c) => c.name === 'Public');
const publicChannel = findPublicChannel(refreshedChannels);
hasSetDefaultConversation.current = true;
setActiveConversation({
type: 'channel',
id: publicChannel?.key || PUBLIC_CHANNEL_KEY,
name: publicChannel?.name || 'Public',
name: publicChannel?.name || PUBLIC_CHANNEL_NAME,
});
toast.success('Channel deleted');
} catch (err) {
@@ -151,14 +148,12 @@ export function useContactsAndChannels({
setContacts((prev) => prev.filter((c) => c.public_key !== publicKey));
const refreshedChannels = await api.getChannels();
setChannels(refreshedChannels);
const publicChannel =
refreshedChannels.find((c) => c.key === PUBLIC_CHANNEL_KEY) ||
refreshedChannels.find((c) => c.name === 'Public');
const publicChannel = findPublicChannel(refreshedChannels);
hasSetDefaultConversation.current = true;
setActiveConversation({
type: 'channel',
id: publicChannel?.key || PUBLIC_CHANNEL_KEY,
name: publicChannel?.name || 'Public',
name: publicChannel?.name || PUBLIC_CHANNEL_NAME,
});
toast.success('Contact deleted');
} catch (err) {
+3 -6
View File
@@ -10,11 +10,10 @@ import {
getReopenLastConversationEnabled,
saveLastViewedConversation,
} from '../utils/lastViewedConversation';
import { findPublicChannel } from '../utils/publicChannel';
import { getContactDisplayName } from '../utils/pubkey';
import type { Channel, Contact, Conversation } from '../types';
const PUBLIC_CHANNEL_KEY = '8B3387E9C5CDEA6AC9E5EDBAA115CD72';
interface UseConversationRouterArgs {
channels: Channel[];
contacts: Contact[];
@@ -44,7 +43,7 @@ export function useConversationRouter({
}, []);
const getPublicChannelConversation = useCallback((): Conversation | null => {
const publicChannel = channels.find((c) => c.name === 'Public');
const publicChannel = findPublicChannel(channels);
if (!publicChannel) return null;
return {
type: 'channel',
@@ -221,9 +220,7 @@ export function useConversationRouter({
return;
}
const publicChannel =
channels.find((c) => c.key === PUBLIC_CHANNEL_KEY) ||
channels.find((c) => c.name === 'Public');
const publicChannel = findPublicChannel(channels);
if (!publicChannel) return;
hasSetDefaultConversation.current = true;
@@ -3,6 +3,7 @@ import { describe, expect, it, vi } from 'vitest';
import { ChatHeader } from '../components/ChatHeader';
import type { Channel, Contact, Conversation, Favorite, PathDiscoveryResponse } from '../types';
import { PUBLIC_CHANNEL_KEY } from '../utils/publicChannel';
function makeChannel(key: string, name: string, isHashtag: boolean): Channel {
return { key, name, is_hashtag: isHashtag, on_radio: false, last_read_at: null };
@@ -169,6 +170,25 @@ describe('ChatHeader key visibility', () => {
expect(onToggleNotifications).toHaveBeenCalledTimes(1);
});
it('hides the delete button for the canonical Public channel', () => {
const channel = makeChannel(PUBLIC_CHANNEL_KEY, 'Public', false);
const conversation: Conversation = { type: 'channel', id: PUBLIC_CHANNEL_KEY, name: 'Public' };
render(<ChatHeader {...baseProps} conversation={conversation} channels={[channel]} />);
expect(screen.queryByRole('button', { name: 'Delete' })).not.toBeInTheDocument();
});
it('still shows the delete button for non-canonical channels named Public', () => {
const key = 'AB'.repeat(16);
const channel = makeChannel(key, 'Public', false);
const conversation: Conversation = { type: 'channel', id: key, name: 'Public' };
render(<ChatHeader {...baseProps} conversation={conversation} channels={[channel]} />);
expect(screen.getByRole('button', { name: 'Delete' })).toBeInTheDocument();
});
it('opens path discovery modal for contacts and runs the request on demand', async () => {
const pubKey = '21'.repeat(32);
const contact: Contact = {
+35
View File
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { Sidebar } from '../components/Sidebar';
import { CONTACT_TYPE_REPEATER, type Channel, type Contact, type Favorite } from '../types';
import { getStateKey, type ConversationTimes } from '../utils/conversationState';
import { PUBLIC_CHANNEL_KEY } from '../utils/publicChannel';
function makeChannel(key: string, name: string): Channel {
return {
@@ -316,4 +317,38 @@ describe('Sidebar section summaries', () => {
expect(getContactsOrder()).toEqual(['Zed', 'Amy']);
expect(getRepeatersOrder()).toEqual(['Zulu Relay', 'Alpha Relay']);
});
it('pins only the canonical Public channel to the top of channel sorting', () => {
const publicChannel = makeChannel(PUBLIC_CHANNEL_KEY, 'Public');
const fakePublic = makeChannel('DD'.repeat(16), 'Public');
const alphaChannel = makeChannel('CC'.repeat(16), '#alpha');
const onSelectConversation = vi.fn();
render(
<Sidebar
contacts={[]}
channels={[fakePublic, alphaChannel, publicChannel]}
activeConversation={null}
onSelectConversation={onSelectConversation}
onNewMessage={vi.fn()}
lastMessageTimes={{}}
unreadCounts={{}}
mentions={{}}
showCracker={false}
crackerRunning={false}
onToggleCracker={vi.fn()}
onMarkAllRead={vi.fn()}
favorites={[]}
legacySortOrder="alpha"
/>
);
fireEvent.click(screen.getAllByText('Public')[0]);
expect(onSelectConversation).toHaveBeenCalledWith({
type: 'channel',
id: PUBLIC_CHANNEL_KEY,
name: 'Public',
});
});
});
+6 -5
View File
@@ -13,6 +13,7 @@ import {
resolveContactFromHashToken,
} from '../utils/urlHash';
import type { Channel, Contact } from '../types';
import { PUBLIC_CHANNEL_KEY } from '../utils/publicChannel';
describe('parseHashConversation', () => {
let originalHash: string;
@@ -149,7 +150,7 @@ describe('parseHashConversation', () => {
describe('resolveChannelFromHashToken', () => {
const channels: Channel[] = [
{
key: 'ABCDEF0123456789ABCDEF0123456789',
key: PUBLIC_CHANNEL_KEY,
name: 'Public',
is_hashtag: false,
on_radio: true,
@@ -172,13 +173,13 @@ describe('resolveChannelFromHashToken', () => {
];
it('prefers stable key lookup (case-insensitive)', () => {
const result = resolveChannelFromHashToken('abcdef0123456789abcdef0123456789', channels);
expect(result?.key).toBe('ABCDEF0123456789ABCDEF0123456789');
const result = resolveChannelFromHashToken(PUBLIC_CHANNEL_KEY.toLowerCase(), channels);
expect(result?.key).toBe(PUBLIC_CHANNEL_KEY);
});
it('supports legacy name-based hash lookup', () => {
it('resolves legacy Public hashes to the canonical Public key', () => {
const result = resolveChannelFromHashToken('Public', channels);
expect(result?.key).toBe('ABCDEF0123456789ABCDEF0123456789');
expect(result?.key).toBe(PUBLIC_CHANNEL_KEY);
});
it('supports legacy hashtag hash without leading #', () => {
+12
View File
@@ -0,0 +1,12 @@
import type { Channel } from '../types';
export const PUBLIC_CHANNEL_KEY = '8B3387E9C5CDEA6AC9E5EDBAA115CD72';
export const PUBLIC_CHANNEL_NAME = 'Public';
export function isPublicChannelKey(key: string): boolean {
return key.toUpperCase() === PUBLIC_CHANNEL_KEY;
}
export function findPublicChannel(channels: Channel[]): Channel | undefined {
return channels.find((channel) => isPublicChannelKey(channel.key));
}
+8
View File
@@ -1,4 +1,5 @@
import type { Channel, Contact, Conversation } from '../types';
import { findPublicChannel, PUBLIC_CHANNEL_NAME } from './publicChannel';
import { getContactDisplayName } from './pubkey';
interface ParsedHashConversation {
@@ -77,6 +78,13 @@ export function resolveChannelFromHashToken(token: string, channels: Channel[]):
const byKey = channels.find((c) => c.key.toLowerCase() === normalizedToken.toLowerCase());
if (byKey) return byKey;
// Legacy Public hashes should resolve to the canonical Public key, not any
// arbitrary row that happens to share the display name.
if (normalizedToken.toLowerCase() === PUBLIC_CHANNEL_NAME.toLowerCase()) {
const publicChannel = findPublicChannel(channels);
if (publicChannel) return publicChannel;
}
// Backward compatibility for legacy name-based hashes.
return (
channels.find((c) => c.name === normalizedToken || c.name === `#${normalizedToken}`) || null
+3 -1
View File
@@ -1,10 +1,12 @@
import { test, expect } from '@playwright/test';
import { createChannel, deleteChannel, getChannels } from '../helpers/api';
const PUBLIC_CHANNEL_KEY = '8B3387E9C5CDEA6AC9E5EDBAA115CD72';
test.describe('Conversation deletion flow', () => {
test.beforeAll(async () => {
const channels = await getChannels();
if (!channels.some((c) => c.name === 'Public')) {
if (!channels.some((c) => c.key === PUBLIC_CHANNEL_KEY)) {
await createChannel('Public');
}
});
+50
View File
@@ -5,6 +5,7 @@ from unittest.mock import patch
import pytest
from app.channel_constants import PUBLIC_CHANNEL_KEY, PUBLIC_CHANNEL_NAME
from app.repository import ChannelRepository, MessageRepository
@@ -77,6 +78,55 @@ class TestCreateChannel:
assert channel.flood_scope_override is None
class TestPublicChannelProtection:
@pytest.mark.asyncio
async def test_create_public_uses_canonical_key(self, test_db):
from app.routers.channels import CreateChannelRequest, create_channel
result = await create_channel(CreateChannelRequest(name="Public"))
assert result.key == PUBLIC_CHANNEL_KEY
assert result.name == PUBLIC_CHANNEL_NAME
assert result.is_hashtag is False
@pytest.mark.asyncio
async def test_create_public_rejects_conflicting_key(self, test_db, client):
response = await client.post(
"/api/channels",
json={"name": "Public", "key": "AA" * 16},
)
assert response.status_code == 400
assert "canonical Public key" in response.json()["detail"]
assert await ChannelRepository.get_by_key("AA" * 16) is None
@pytest.mark.asyncio
async def test_create_non_public_rejects_public_key(self, test_db, client):
response = await client.post(
"/api/channels",
json={"name": "Ops", "key": PUBLIC_CHANNEL_KEY},
)
assert response.status_code == 400
assert PUBLIC_CHANNEL_NAME in response.json()["detail"]
@pytest.mark.asyncio
async def test_delete_public_channel_is_rejected(self, test_db, client):
await ChannelRepository.upsert(
key=PUBLIC_CHANNEL_KEY,
name=PUBLIC_CHANNEL_NAME,
is_hashtag=False,
on_radio=False,
)
response = await client.delete(f"/api/channels/{PUBLIC_CHANNEL_KEY}")
assert response.status_code == 400
assert "cannot be deleted" in response.json()["detail"]
channel = await ChannelRepository.get_by_key(PUBLIC_CHANNEL_KEY)
assert channel is not None
class TestChannelDetail:
"""Test GET /api/channels/{key}/detail."""