Skip to content

Commit ca92ffe

Browse files
matt2eclaude
andcommitted
feat(communities): add Leave community to the rail menu
Leaving a saved community now confirms in an alert dialog, publishes a signed NIP-43 leave request (kind 28936) to that community's relay by origin, and only then forgets it on this device: the membership is dropped, a left selection falls back to Personal space, the retained session is disposed, and the origin+viewer partitions of view state, channel heads, read state, outbox, quick reactions and channel setups are purged. A relay answering that the viewer is not a member counts as already absent and removes the community with an informational toast; any other refusal or an unreachable relay keeps the membership with an error toast so the item can be tried again. The development broker gains a scoped `leave` route, the native adapter a matching `leave` request, and the Rust signer allowlists only the empty protected shape of kind 28936. Opening the menu or leaving never acquires an inactive community's session. Co-Authored-By: Claude Fable 5.1 <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent 3515e04 commit ca92ffe

26 files changed

Lines changed: 1124 additions & 77 deletions

‎dev/relay-broker-api.test.mjs‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2114,6 +2114,112 @@ test("member change receipts must match the signed command", async () => {
21142114
}
21152115
});
21162116

2117+
test("leave requests sign the exact NIP-43 shape for the selected community only", async () => {
2118+
const { h, post } = await communityAdmin((call) =>
2119+
Response.json({ accepted: true, event_id: call.body.id, message: "" }),
2120+
);
2121+
try {
2122+
const response = await post("leave", {});
2123+
expect(response.status).toBe(200);
2124+
const sent = h.calls.at(-1);
2125+
expect(sent.url).toBe(`${fixtureRelayUrl}/events`);
2126+
expect(verifyEvent(sent.body)).toBe(true);
2127+
expect(sent.body).toMatchObject({
2128+
kind: 28936,
2129+
tags: [["-"]],
2130+
content: "",
2131+
pubkey: h.event.pubkey,
2132+
created_at: Math.floor(Date.now() / 1000),
2133+
});
2134+
expect(await response.json()).toMatchObject({
2135+
accepted: true,
2136+
event_id: sent.body.id,
2137+
});
2138+
// The request body carries nothing: a client cannot smuggle another kind
2139+
// or extra tags into the signed event.
2140+
const shaped = await post("leave", {
2141+
kind: 9031,
2142+
tags: [["p", "a".repeat(64)]],
2143+
content: "bye",
2144+
});
2145+
expect(shaped.status).toBe(200);
2146+
expect(h.calls.at(-1).body).toMatchObject({
2147+
kind: 28936,
2148+
tags: [["-"]],
2149+
content: "",
2150+
});
2151+
// Unscoped requests name no community to leave.
2152+
expect((await h.post("leave", {})).status).toBe(400);
2153+
expect(h.calls).toHaveLength(2);
2154+
} finally {
2155+
await h.close();
2156+
}
2157+
});
2158+
2159+
test("leave receipts must match the signed request", async () => {
2160+
const { h, post } = await communityAdmin(() =>
2161+
Response.json({ accepted: true, event_id: "wrong" }),
2162+
);
2163+
try {
2164+
const response = await post("leave", {});
2165+
expect(response.status).toBe(502);
2166+
expect(await response.json()).toEqual({
2167+
error: "Leave request could not be confirmed",
2168+
});
2169+
} finally {
2170+
await h.close();
2171+
}
2172+
});
2173+
2174+
test.each([
2175+
[
2176+
400,
2177+
"invalid: you are not a relay member",
2178+
"invalid: you are not a relay member",
2179+
],
2180+
[
2181+
400,
2182+
"invalid: relay membership is not enabled",
2183+
"invalid: relay membership is not enabled",
2184+
],
2185+
[
2186+
400,
2187+
"invalid: relay owner cannot leave",
2188+
"invalid: relay owner cannot leave",
2189+
],
2190+
[
2191+
403,
2192+
"blocked: you are banned from this community",
2193+
"blocked: you are banned from this community",
2194+
],
2195+
[
2196+
503,
2197+
"community writes are temporarily unavailable",
2198+
"community writes are temporarily unavailable",
2199+
],
2200+
// Admin refusals are not leave refusals.
2201+
[400, "invalid: cannot remove yourself", "Relay request failed (400)"],
2202+
[
2203+
400,
2204+
"invalid: database error: connection reset <script>",
2205+
"Relay request failed (400)",
2206+
],
2207+
])(
2208+
"leave refusal %i %j is surfaced only when whitelisted",
2209+
async (status, error, shown) => {
2210+
const { h, post } = await communityAdmin(() =>
2211+
Response.json({ error }, { status }),
2212+
);
2213+
try {
2214+
const response = await post("leave", {});
2215+
expect(response.status).toBe(status);
2216+
expect((await response.json()).error).toBe(shown);
2217+
} finally {
2218+
await h.close();
2219+
}
2220+
},
2221+
);
2222+
21172223
test.each([
21182224
[400, "invalid: cannot remove yourself", "invalid: cannot remove yourself"],
21192225
[

‎dev/relay-broker.mjs‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ import {
3030
inviteRequest,
3131
memberCommand,
3232
} from "./community-admin.mjs";
33+
import {
34+
leaveRefusal,
35+
leaveRequestTemplate,
36+
} from "../src/features/communities/leave-protocol.ts";
3337
import {
3438
directMessageEvent,
3539
directMessageReceipt,
@@ -1946,6 +1950,7 @@ export function relayBrokerPlugin({
19461950
"/api/relay/accept-policy",
19471951
"/api/relay/invite",
19481952
"/api/relay/member",
1953+
"/api/relay/leave",
19491954
"/api/relay/gifs",
19501955
"/api/relay/workflow-runs",
19511956
"/api/relay/project-git",
@@ -2126,18 +2131,29 @@ export function relayBrokerPlugin({
21262131
const policy = route === "/api/relay/accept-policy";
21272132
const invite = route === "/api/relay/invite";
21282133
const member = route === "/api/relay/member";
2134+
const leave = route === "/api/relay/leave";
21292135
const gifs = route === "/api/relay/gifs";
21302136
// Only these routes may surface an exact, allowed relay refusal.
21312137
const refusal =
2132-
invite || member ? adminReason : claim ? claimReason : undefined;
2133-
if (invite || member) {
2138+
invite || member
2139+
? adminReason
2140+
: claim
2141+
? claimReason
2142+
: leave
2143+
? leaveRefusal
2144+
: undefined;
2145+
if (invite || member || leave) {
21342146
// Community-bound only; the relay remains the authority for roles.
21352147
if (!scoped)
21362148
return json(res, 400, { error: "Select a community first" });
21372149
try {
2150+
// The viewer's own leave request has one shape; the body carries nothing.
21382151
filters = invite
21392152
? inviteRequest(filters)
2140-
: finalizeEvent(memberCommand(filters), key);
2153+
: finalizeEvent(
2154+
leave ? leaveRequestTemplate() : memberCommand(filters),
2155+
key,
2156+
);
21412157
} catch (error) {
21422158
return json(res, 400, { error: error.message, sent: false });
21432159
}
@@ -2390,6 +2406,7 @@ export function relayBrokerPlugin({
23902406
!policy &&
23912407
!invite &&
23922408
!member &&
2409+
!leave &&
23932410
!gifs &&
23942411
!workflowPath &&
23952412
!readPublishing &&
@@ -2454,7 +2471,7 @@ export function relayBrokerPlugin({
24542471
workflowPath ??
24552472
(gifs
24562473
? gifSearchPath
2457-
: profile || directMessage || member
2474+
: profile || directMessage || member || leave
24582475
? "/events"
24592476
: claim
24602477
? "/api/invites/claim"
@@ -2618,16 +2635,18 @@ export function relayBrokerPlugin({
26182635
});
26192636
}
26202637
}
2621-
if (profile || member) {
2638+
if (profile || member || leave) {
26222639
const receipt = JSON.parse(text);
26232640
if (
26242641
receipt.event_id !== filters.id ||
26252642
typeof receipt.accepted !== "boolean"
26262643
)
26272644
return json(res, 502, {
2628-
error: member
2629-
? "Member change could not be confirmed"
2630-
: "Profile publication could not be confirmed",
2645+
error: leave
2646+
? "Leave request could not be confirmed"
2647+
: member
2648+
? "Member change could not be confirmed"
2649+
: "Profile publication could not be confirmed",
26312650
});
26322651
}
26332652
res.writeHead(200, {

‎docs/communities.md‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -70,11 +70,18 @@ space. Personal space
7070
clears selection without forgetting memberships. The rail’s Add control opens the
7171
existing join dialog; displaying saved communities reads relay metadata but does not open sessions for them.
7272
Right-click a saved community (or press the ContextMenu key or Shift+F10 on it)
73-
for Mark all as read, Copy community URL, Invite to community and Community
74-
settings. Only the selected community can be marked read, and only while its read
75-
state syncs; Invite shows only where the viewer owns or administers the selected
76-
community and this build can mint invites. Copy and Community settings work on
77-
inactive communities without opening their sessions. Messages shows an intentional
73+
for Mark all as read, Copy community URL, Invite to community, Community
74+
settings and, last, Leave community. Only the selected community can be marked
75+
read, and only while its read state syncs; Invite shows only where the viewer
76+
owns or administers the selected community and this build can mint invites. Copy,
77+
Community settings and Leave work on inactive communities without opening their
78+
sessions. Leave asks for confirmation, then sends a signed NIP-43 leave request
79+
(kind 28936) to that community's relay before the device forgets it: the relay
80+
accepting, or answering that the viewer is not a member, removes the community
81+
here and clears its drafts, reading positions and other device state; any other
82+
refusal or an unreachable relay keeps the membership and reports the failure so
83+
Leave can be tried again. A left community that was selected lands on Personal
84+
space. Messages shows an intentional
7885
empty state there. Try drafting in A, switching to B, then returning to A.
7986
Selected channels, drafts and reading offsets are partitioned by the canonical
8087
community origin and viewer; channel IDs alone are not sufficient keys.
@@ -103,9 +110,9 @@ not a plugin key service.
103110

104111
Packaged builds do not include the broker. Native macOS, Windows and Linux
105112
[identity import/create](identity.md) and the shared native relay adapter provide
106-
discovery, admission, profile publication, authenticated reads and supported event
107-
writes. Windows/Linux installed-app acceptance remains unverified. Community
108-
creation/removal and background connection eviction are not implemented. Native
113+
discovery, admission, leave requests, profile publication, authenticated reads and
114+
supported event writes. Windows/Linux installed-app acceptance remains unverified.
115+
Community creation and background connection eviction are not implemented. Native
109116
agent enrollment has its own [local control contract](agent-control.md). Avatar
110117
uploads still require the development media host. Agents have local
111118
configuration plus separately scoped participation; selecting a community must
@@ -190,7 +197,14 @@ backup; same-origin plugin JavaScript is trusted and can invoke that IPC too.
190197
## Verification
191198

192199
`src/features/communities/service.test.ts` covers no-community initialization,
193-
local profiles, scoped view intent, session retention and selective restoration.
200+
local profiles, scoped view intent, session retention, selective restoration and
201+
leaving (membership removal, Personal space fallback, session disposal, purged
202+
device state and the last community). `CommunityRail.test.tsx` covers the leave
203+
flow end to end against the broker route: confirm, publish, then remove; cancel;
204+
refusals and timeouts that keep the membership; the already-absent answer; the
205+
in-flight state; and that no inactive session is acquired. `device-state.test.ts`
206+
covers the per-origin purge. The broker and native adapter tests sign the exact
207+
leave shape and pass through only the relay's known refusals.
194208
`broker.test.ts` runs real localhost HTTP with signed fixture events to verify
195209
multi-community routing, profile publication, invite claims, and a captured send
196210
after opening another community. `destination.test.ts` checks normalization and

‎docs/identity.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,8 @@ NIP-11 `self` establishes relay authority; the operator-contact `pubkey` is not
8282
a substitute. The existing live owner handles WSS/NIP-42 authentication and
8383
signature verification. IPC permissions remain limited to the main WebView.
8484

85-
Community admission, kind-0 profile reads/publication and the adapter's advertised
85+
Community admission, kind-0 profile reads/publication, the NIP-43 leave request
86+
(kind 28936, signed only in its empty protected shape) and the adapter's advertised
8687
message/event writes use this identity. [Join recovery](communities.md#packaged-admission-and-recovery)
8788
records public progress before remote changes. The existing durable outbox retains
8889
uncertain delivery across restart; retry uses the same signed event with fresh HTTP

‎docs/shell-design.md‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,8 @@ Unavailable or unsupported images fall back to a saved icon or name initial.
117117
Each saved community has a context menu (right-click, the ContextMenu key or
118118
Shift+F10, labelled “Actions for <name>”) built from the shared context-menu
119119
primitives, in the original's order: Mark all as read, then Copy community URL,
120-
Invite to community and Community settings. Copy writes the canonical HTTPS
120+
Invite to community and Community settings, then a separator and the destructive
121+
Leave community. Copy writes the canonical HTTPS
121122
origin and reports through the host toast stack. Mark all as read acts only on
122123
the selected community's ready session and only while its read state can sync;
123124
elsewhere it stays visible but disabled with a note saying why. Invite to
@@ -126,7 +127,16 @@ roster names the viewer an owner or admin (the same derivation the Invites
126127
settings card uses), and never in native builds, which cannot mint invites; it
127128
opens the Invites settings card scoped to that community. Community settings is
128129
on every community and opens Settings scoped to that community's origin, which
129-
selects it on the way. Closing a menu opened from the keyboard returns focus to
130+
selects it on the way. Leave community is on every community and opens an alert
131+
dialog owned by the rail (“Leave <name>?”) whose destructive confirm shows a
132+
pending state while the request runs; the menu item itself is disabled and reads
133+
“Leaving…” for that community until the relay answers. The rail publishes the
134+
NIP-43 leave request to the community's relay by origin, then asks the
135+
communities service to forget it; the relay's acceptance or its "not a member"
136+
answer removes the community and reports through the toast stack, while any
137+
other failure keeps the membership and reports the reason. Focus returns to the
138+
community when it is still saved and to Personal space once it is gone. Closing
139+
a menu opened from the keyboard returns focus to
130140
that community; closing one opened by pointer restores whatever had focus
131141
before, so a right-click while typing does not move the caret to the rail.
132142
Opening a menu or running any item never acquires an inactive session, and the

‎docs/unread.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,9 @@ for newer manual-unread intent.
148148
## Durable sync and privacy
149149

150150
The journal is separate from disposable message caches in `buzz-read-state-v1`,
151-
partitioned by relay/community scope and viewer. IndexedDB strict read/write
151+
partitioned by relay/community scope and viewer. Leaving a community deletes that
152+
partition along with the community's other device state; other partitions are
153+
untouched. IndexedDB strict read/write
152154
transactions merge concurrent local windows; Web Locks serialize the publisher.
153155
Without host decoding the capability is `unsupported`; without safe serialized
154156
sign/publish it is `read-only`. Read sync requires `frontier-sync`. Local manual

‎src-tauri/src/relay.rs‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,12 @@ fn validate_event(community: &str, event: &EventTemplate) -> Result<()> {
7979
{
8080
return Err("Relay authentication does not match this community".into());
8181
}
82+
} else if event.kind == 28936 {
83+
// A NIP-43 leave request revokes the signer's own membership: empty
84+
// content and exactly the NIP-70 protected tag, nothing else.
85+
if !event.content.is_empty() || event.tags != vec![vec!["-".to_string()]] {
86+
return Err("A leave request carries no content or other tags".into());
87+
}
8288
} else if !matches!(
8389
event.kind,
8490
0 | 7 | 9 | 1984 | 9000 | 9001 | 20001 | 30315 | 40003 | 40100 | 42000

‎src-tauri/src/relay/tests.rs‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,41 @@ fn websocket_auth_is_bound_to_the_captured_community() {
5252
assert!(validate_event("https://relay.test", &event).is_err());
5353
}
5454

55+
#[test]
56+
fn leave_requests_sign_only_the_protected_empty_shape() {
57+
let leave = |content: &str, tags: Vec<Vec<String>>| EventTemplate {
58+
kind: 28936,
59+
created_at: 1,
60+
content: content.into(),
61+
tags,
62+
};
63+
let protected = || vec![vec!["-".to_string()]];
64+
assert!(validate_event("https://relay.test", &leave("", protected())).is_ok());
65+
for rejected in [
66+
leave("bye", protected()),
67+
leave("", vec![]),
68+
leave("", vec![vec!["-".into(), "x".into()]]),
69+
leave(
70+
"",
71+
vec![vec!["-".into()], vec!["h".into(), "channel".into()]],
72+
),
73+
leave("", vec![vec!["p".into(), "a".repeat(64)]]),
74+
] {
75+
assert!(validate_event("https://relay.test", &rejected).is_err());
76+
}
77+
// Member commands stay owner/admin-only on the broker; native signs none.
78+
assert!(validate_event(
79+
"https://relay.test",
80+
&EventTemplate {
81+
kind: 9031,
82+
created_at: 1,
83+
content: "".into(),
84+
tags: vec![vec!["p".into(), "a".repeat(64)]],
85+
}
86+
)
87+
.is_err());
88+
}
89+
5590
fn fixture_server(response: &'static str) -> (Url, std::thread::JoinHandle<(String, String)>) {
5691
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
5792
let url = Url::parse(&format!("http://{}/query", listener.local_addr().unwrap())).unwrap();

‎src/features/channel-templates/setup.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,20 @@ type Progress = {
2727
operations: Record<string, string>;
2828
};
2929

30+
const receiptPrefix = (scope: string) => `buzz-channel-setup.v2:${scope}:`;
31+
32+
/** Drops one community's unfinished setup receipts once the viewer has left it;
33+
* their operations have no outbox left to retire against. */
34+
export function forgetChannelSetups(scope: string) {
35+
const prefix = receiptPrefix(scope);
36+
const stale: string[] = [];
37+
for (let index = 0; index < localStorage.length; index++) {
38+
const key = localStorage.key(index);
39+
if (key?.startsWith(prefix)) stale.push(key);
40+
}
41+
for (const key of stale) localStorage.removeItem(key);
42+
}
43+
3044
/** Frozen intent only. Signing, publication and delivery evidence stay in Outbox. */
3145
export function createChannelSetup({
3246
scope,
@@ -63,7 +77,7 @@ export function createChannelSetup({
6377
}) {
6478
// A separate namespace leaves historical single-slot and experimental v1
6579
// receipts byte-for-byte intact. They never become an implicit new Create.
66-
const prefix = `buzz-channel-setup.v2:${scope}:`;
80+
const prefix = receiptPrefix(scope);
6781
const encoder = new TextEncoder();
6882
let pending: Progress | undefined;
6983
let admitting: ReturnType<typeof run> | undefined;

0 commit comments

Comments
 (0)