Skip to content

Commit d0ab3fd

Browse files
loganjnpub1z3hmzc9ryehxzedl5wzlvpyvja0d483peaja5zt6pd0209f9x2jspe2dxhnpub13n66s06epmqf2kc3v373ez8hj65cuzyvxzjf93vwpervxqn2u7jq2qd9je
authored
fix(channels): strip leading hash prefixes from names (#2250)
Signed-off-by: Logan Johnson <[email protected]> Signed-off-by: npub1z3hmzc9ryehxzedl5wzlvpyvja0d483peaja5zt6pd0209f9x2jspe2dxh <146fb160a3266e6165bfa385f6048c975eda9e21cf65da097a0b5ea7952532a5@buzz.block.builderlab.xyz> Signed-off-by: npub13n66s06epmqf2kc3v373ez8hj65cuzyvxzjf93vwpervxqn2u7jq2qd9je <8cf5a83f590ec0955b11647d1c88f796a98e088c30a492c58e0e46c3026ae7a4@buzz.block.builderlab.xyz> Co-authored-by: npub1z3hmzc9ryehxzedl5wzlvpyvja0d483peaja5zt6pd0209f9x2jspe2dxh <146fb160a3266e6165bfa385f6048c975eda9e21cf65da097a0b5ea7952532a5@buzz.block.builderlab.xyz> Co-authored-by: npub13n66s06epmqf2kc3v373ez8hj65cuzyvxzjf93vwpervxqn2u7jq2qd9je <8cf5a83f590ec0955b11647d1c88f796a98e088c30a492c58e0e46c3026ae7a4@buzz.block.builderlab.xyz>
1 parent 06e3d82 commit d0ab3fd

10 files changed

Lines changed: 190 additions & 8 deletions

File tree

‎crates/buzz-core/src/channel.rs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,16 @@
77
use std::fmt;
88
use std::str::FromStr;
99

10+
/// Returns the canonical display name for a channel.
11+
///
12+
/// Channel names are rendered with a leading `#` by clients, so surrounding
13+
/// whitespace and user-supplied hash prefixes are removed here to keep the
14+
/// stored name prefix-free.
15+
pub fn canonical_channel_name(name: &str) -> &str {
16+
name.trim_start_matches(|c: char| c == '#' || c.is_whitespace())
17+
.trim_end()
18+
}
19+
1020
/// Whether a channel is publicly visible or invite-only.
1121
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1222
pub enum ChannelVisibility {
@@ -167,3 +177,22 @@ impl FromStr for MemberRole {
167177
}
168178
}
169179
}
180+
181+
#[cfg(test)]
182+
mod tests {
183+
use super::canonical_channel_name;
184+
185+
#[test]
186+
fn channel_names_trim_whitespace_and_drop_all_leading_hashes() {
187+
assert_eq!(canonical_channel_name("channel"), "channel");
188+
assert_eq!(canonical_channel_name("#channel"), "channel");
189+
assert_eq!(canonical_channel_name("###channel"), "channel");
190+
assert_eq!(canonical_channel_name(" ###channel "), "channel");
191+
assert_eq!(canonical_channel_name("# channel"), "channel");
192+
assert_eq!(canonical_channel_name("### channel "), "channel");
193+
assert_eq!(canonical_channel_name(" ### "), "");
194+
assert_eq!(canonical_channel_name("# #"), "");
195+
assert_eq!(canonical_channel_name("### ###"), "");
196+
assert_eq!(canonical_channel_name("channel#topic"), "channel#topic");
197+
}
198+
}

‎crates/buzz-db/src/channel.rs‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,11 @@ pub async fn create_channel(
101101
)));
102102
}
103103

104+
let name = buzz_core::channel::canonical_channel_name(name);
105+
if name.trim().is_empty() {
106+
return Err(DbError::InvalidData("channel name is required".into()));
107+
}
108+
104109
let id = Uuid::new_v4();
105110

106111
let mut tx = pool.begin().await?;
@@ -191,6 +196,11 @@ pub async fn create_channel_with_id(
191196
));
192197
}
193198

199+
let name = buzz_core::channel::canonical_channel_name(name);
200+
if name.trim().is_empty() {
201+
return Err(DbError::InvalidData("channel name is required".into()));
202+
}
203+
194204
let mut tx = pool.begin().await?;
195205

196206
let rows_affected = sqlx::query(
@@ -1041,7 +1051,7 @@ pub async fn update_channel(
10411051
pool: &PgPool,
10421052
community_id: CommunityId,
10431053
channel_id: Uuid,
1044-
updates: ChannelUpdate,
1054+
mut updates: ChannelUpdate,
10451055
) -> Result<ChannelRecord> {
10461056
if updates.name.is_none()
10471057
&& updates.description.is_none()
@@ -1053,6 +1063,13 @@ pub async fn update_channel(
10531063
));
10541064
}
10551065

1066+
if let Some(name) = updates.name.as_mut() {
1067+
*name = buzz_core::channel::canonical_channel_name(name).to_owned();
1068+
if name.is_empty() {
1069+
return Err(DbError::InvalidData("channel name is required".into()));
1070+
}
1071+
}
1072+
10561073
// Build SET clause dynamically — only include fields that are provided.
10571074
// Track parameter index for positional placeholders.
10581075
let mut set_parts: Vec<String> = Vec::new();

‎crates/buzz-relay/src/handlers/ingest.rs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2039,7 +2039,11 @@ async fn ingest_event_inner(
20392039
});
20402040
if create_name
20412041
.as_ref()
2042-
.map(|n| n.trim().is_empty())
2042+
.map(|n| {
2043+
buzz_core::channel::canonical_channel_name(n)
2044+
.trim()
2045+
.is_empty()
2046+
})
20432047
.unwrap_or(true)
20442048
{
20452049
return Err(IngestError::Rejected(
@@ -2082,6 +2086,7 @@ async fn ingest_event_inner(
20822086

20832087
if let Some(client_uuid) = channel_id {
20842088
let name = create_name.unwrap_or_default();
2089+
let name = buzz_core::channel::canonical_channel_name(&name);
20852090

20862091
let description = event.tags.iter().find_map(|t| {
20872092
if t.kind().to_string() == "about" {
@@ -2099,7 +2104,7 @@ async fn ingest_event_inner(
20992104
.create_channel_with_id(
21002105
tenant.community(),
21012106
client_uuid,
2102-
&name,
2107+
name,
21032108
channel_type,
21042109
visibility,
21052110
description.as_deref(),

‎crates/buzz-relay/src/handlers/side_effects.rs‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,22 @@ pub async fn validate_admin_event(
445445
}
446446
}
447447

448+
// Validate channel names before storage. A name made entirely of
449+
// display-prefix hashes becomes empty after canonicalization.
450+
for t in event.tags.iter() {
451+
if t.kind().to_string() == "name" {
452+
match t.content() {
453+
Some(v)
454+
if !buzz_core::channel::canonical_channel_name(v)
455+
.trim()
456+
.is_empty() => {}
457+
_ => {
458+
return Err(anyhow::anyhow!("channel name is required"));
459+
}
460+
}
461+
}
462+
}
463+
448464
// Validate visibility values before storage.
449465
for t in event.tags.iter() {
450466
if t.kind().to_string() == "visibility" {

‎crates/buzz-sdk/src/builders.rs‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -620,9 +620,18 @@ pub fn build_update_channel(
620620
));
621621
}
622622
}
623+
if name
624+
.map(buzz_core::channel::canonical_channel_name)
625+
.is_some_and(|name| name.trim().is_empty())
626+
{
627+
return Err(SdkError::InvalidTag("channel name is required".into()));
628+
}
623629
let mut tags = vec![tag(&["h", &channel_id.to_string()])?];
624630
if let Some(n) = name {
625-
tags.push(tag(&["name", n])?);
631+
tags.push(tag(&[
632+
"name",
633+
buzz_core::channel::canonical_channel_name(n),
634+
])?);
626635
}
627636
if let Some(a) = about {
628637
tags.push(tag(&["about", a])?);
@@ -670,6 +679,10 @@ pub fn build_create_channel(
670679
about: Option<&str>,
671680
ttl: Option<i32>,
672681
) -> Result<EventBuilder, SdkError> {
682+
let name = buzz_core::channel::canonical_channel_name(name);
683+
if name.trim().is_empty() {
684+
return Err(SdkError::InvalidTag("channel name is required".into()));
685+
}
673686
let mut tags = vec![tag(&["h", &channel_id.to_string()])?, tag(&["name", name])?];
674687
if let Some(v) = visibility {
675688
tags.push(tag(&["visibility", v.as_str()])?);
@@ -2381,6 +2394,21 @@ mod tests {
23812394
assert!(has_tag(&ev, "about", "new about"));
23822395
}
23832396

2397+
#[test]
2398+
fn update_channel_strips_all_leading_hashes_from_name() {
2399+
let ev =
2400+
sign(build_update_channel(uuid(), Some(" ###new-name "), None, None, None).unwrap());
2401+
assert!(has_tag(&ev, "name", "new-name"));
2402+
}
2403+
2404+
#[test]
2405+
fn update_channel_rejects_hash_only_name() {
2406+
assert!(matches!(
2407+
build_update_channel(uuid(), Some(" ### "), None, None, None),
2408+
Err(SdkError::InvalidTag(_))
2409+
));
2410+
}
2411+
23842412
#[test]
23852413
fn update_channel_visibility_and_ttl() {
23862414
let cid = uuid();
@@ -2471,6 +2499,37 @@ mod tests {
24712499
assert!(has_tag(&ev, "name", "dev"));
24722500
}
24732501

2502+
#[test]
2503+
fn create_channel_strips_all_leading_hashes_from_name() {
2504+
let ev = sign(
2505+
build_create_channel(
2506+
uuid(),
2507+
" ###dev ",
2508+
None::<Visibility>,
2509+
None::<ChannelKind>,
2510+
None,
2511+
None,
2512+
)
2513+
.unwrap(),
2514+
);
2515+
assert!(has_tag(&ev, "name", "dev"));
2516+
}
2517+
2518+
#[test]
2519+
fn create_channel_rejects_hash_only_name() {
2520+
assert!(matches!(
2521+
build_create_channel(
2522+
uuid(),
2523+
" ### ",
2524+
None::<Visibility>,
2525+
None::<ChannelKind>,
2526+
None,
2527+
None,
2528+
),
2529+
Err(SdkError::InvalidTag(_))
2530+
));
2531+
}
2532+
24742533
#[test]
24752534
fn create_channel_ephemeral_emits_ttl() {
24762535
let cid = uuid();

‎crates/buzz-sdk/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,8 @@ pub struct CustomEmoji {
7474
pub url: String,
7575
}
7676

77+
/// Return a channel name without client-rendered leading hash prefixes.
78+
pub use buzz_core::channel::canonical_channel_name;
7779
/// Channel type.
7880
pub use buzz_core::channel::ChannelType as ChannelKind;
7981
/// Channel visibility.

‎desktop/src-tauri/src/events.rs‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,10 @@ pub fn build_create_channel(
148148
about: Option<&str>,
149149
ttl_seconds: Option<i32>,
150150
) -> Result<EventBuilder, String> {
151+
let name = buzz_sdk_pkg::canonical_channel_name(name);
152+
if name.trim().is_empty() {
153+
return Err("channel name is required".into());
154+
}
151155
let mut tags = vec![
152156
tag(vec!["h", &channel_id.to_string()])?,
153157
tag(vec!["name", name])?,
@@ -194,6 +198,10 @@ pub fn build_update_channel(
194198
return Err("visibility must be \"open\" or \"private\"".into());
195199
}
196200
}
201+
let name = name.map(buzz_sdk_pkg::canonical_channel_name);
202+
if name.is_some_and(|name| name.trim().is_empty()) {
203+
return Err("channel name is required".into());
204+
}
197205
let mut tags = vec![tag(vec!["h", &channel_id.to_string()])?];
198206
if let Some(n) = name {
199207
tags.push(tag(vec!["name", n])?);
@@ -842,7 +850,12 @@ pub fn build_approval_deny(token: &str, note: Option<&str>) -> Result<EventBuild
842850
mod tests {
843851
use super::*;
844852
use nostr::Keys;
845-
853+
#[test]
854+
fn channel_builders_reject_hash_only_names() {
855+
let channel_id = Uuid::new_v4();
856+
assert!(build_create_channel(channel_id, "###", "open", "stream", None, None).is_err());
857+
assert!(build_update_channel(channel_id, Some("###"), None, None, None).is_err());
858+
}
846859
/// Builder layout regression for the NIP-IA owner-of-agent archive flow.
847860
/// Compares against `docs/nips/NIP-IA.md` §Vector 1.
848861
#[test]
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
import {
5+
canonicalChannelName,
6+
channelNamesMatch,
7+
} from "./canonicalChannelName.ts";
8+
9+
test("canonicalChannelName strips interleaved leading hashes and whitespace", () => {
10+
assert.equal(canonicalChannelName("channel"), "channel");
11+
assert.equal(canonicalChannelName("#channel"), "channel");
12+
assert.equal(canonicalChannelName(" ### channel "), "channel");
13+
assert.equal(canonicalChannelName("# #"), "");
14+
assert.equal(canonicalChannelName("### ###"), "");
15+
assert.equal(canonicalChannelName("channel#topic"), "channel#topic");
16+
});
17+
18+
test("channelNamesMatch canonicalizes both legacy names and search input", () => {
19+
assert.equal(channelNamesMatch("#general", "general"), true);
20+
assert.equal(channelNamesMatch("general", " #GENERAL "), true);
21+
assert.equal(channelNamesMatch("#random", "general"), false);
22+
});
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
/**
2+
* Returns the stored form of a channel name after removing the display prefix.
3+
* Keep this aligned with `buzz_core::channel::canonical_channel_name`.
4+
*/
5+
export function canonicalChannelName(name: string): string {
6+
return name.replace(/^[#\s]+/u, "").trimEnd();
7+
}
8+
9+
export function channelNamesMatch(left: string, right: string): boolean {
10+
return (
11+
canonicalChannelName(left).toLowerCase() ===
12+
canonicalChannelName(right).toLowerCase()
13+
);
14+
}

‎desktop/src/features/channels/ui/ChannelBrowserDialog.tsx‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@ import {
99
} from "lucide-react";
1010

1111
import type { Channel } from "@/shared/api/types";
12+
import {
13+
canonicalChannelName,
14+
channelNamesMatch,
15+
} from "@/features/channels/lib/canonicalChannelName";
1216
import { scoreChannelMatch } from "@/features/channels/lib/channelSearchScore";
1317
import {
1418
type ChannelSortMode,
@@ -127,8 +131,9 @@ export function ChannelBrowserDialog({
127131
left: 0,
128132
width: 0,
129133
});
130-
const deferredQuery = React.useDeferredValue(query.trim().toLowerCase());
131-
const trimmedQuery = query.trim();
134+
const canonicalQuery = canonicalChannelName(query);
135+
const deferredQuery = React.useDeferredValue(canonicalQuery.toLowerCase());
136+
const trimmedQuery = canonicalQuery;
132137
// Immediate (non-deferred) lowercased query. The create row's visibility
133138
// (via hasExactMatch) and its label both read from the live query so they
134139
// can never disagree for a frame while the fuzzy filter catches up.
@@ -244,7 +249,7 @@ export function ChannelBrowserDialog({
244249
channels.some(
245250
(channel) =>
246251
channel.channelType !== "dm" &&
247-
channel.name.toLowerCase() === normalizedQuery &&
252+
channelNamesMatch(channel.name, normalizedQuery) &&
248253
(channelTypeFilter
249254
? channel.channelType === channelTypeFilter
250255
: true),

0 commit comments

Comments
 (0)