Skip to content

Commit fdeda44

Browse files
author
Sami
committed
Authorize join alerts from the snapshot, and bound their cost
Three defects, all at inputs nobody had fed this code. Stale role authorization (found by Wren, reproduced live by Max against a real relay; a ship blocker). The effect gated on `useMyRelayMembershipLookupQuery`, which is invalidated only by this client's own membership mutations. `staleTime` marks data stale without scheduling a refetch, and the global QueryClient disables focus refetch, so a viewer demoted by ANOTHER admin kept a cached owner/admin role for as long as the app stayed open — and kept learning every later joiner's identity through OS notifications from a role they no longer held. Authorization now comes from the snapshot in hand. The relay stamps every row as `["member", pubkey, role]` in `publish_nip43_membership_locked`, so the viewer's own role always rides in the event, and the snapshot that revokes authorization is the same one that would disclose the join. Checking it there closes the race in one read; an async invalidation cannot beat the handler it races. Fails closed when the viewer is absent from the roster entirely. Unbounded notification fan-out. A snapshot is a whole roster, not an event per join, so a bulk add alerted once per key: measured at 248 OS notifications from a single 250-key snapshot, delivered through a serial await loop. Above three joins the batch collapses to one summary, and the profile fetch is skipped since its result would be unused. kind:8000 REQ amplification. The accelerator refetched 1:1 per delta — 250 deltas cost 250 REQ frames. REQ is billed against the same per-principal `WsEvents` budget as the user's own sends (default 10/s over a 5s window, `admission.rs` + `connection.rs`), so a bulk add could rate-limit an owner out of their own app: the damage lands on their message sends and channel opens, not on this feature. Refetches now coalesce on a 500ms trailing window; one snapshot is authoritative for the whole burst, so the trailing edge loses nothing. The `snapshot()` test helper stamped every member `"member"`, including the viewer — a fixture that could not express the demotion this gate turns on. It now carries the viewer's role, defaulting to owner. That fixture gap is why the existing suite went red on the first version of this fix: the tests were right and the fixture was unrealistic. Three mutants killed, control green before and after each: role gate removed (restores Wren's blocker, 2 arms fail), cap removed (restores the 248-banner fan-out), debounce removed (restores 1:1 REQ). Five new arms, including a positive control proving an authorized admin still alerts — a gate that refused everything would otherwise pass every negative assertion. Gates after merging main: pnpm typecheck rc=0, pnpm check rc=0 (same pre-existing 1 warning/2 infos), pnpm test 4321/4321. Co-authored-by: Sami <f4a42a97e594b77bdbd8ee35191c8b28a94a4cb871d96f32921558275421fb68@buzz.block.builderlab.xyz> Signed-off-by: Sami <f4a42a97e594b77bdbd8ee35191c8b28a94a4cb871d96f32921558275421fb68@buzz.block.builderlab.xyz>
1 parent 3b63c1a commit fdeda44

3 files changed

Lines changed: 334 additions & 12 deletions

File tree

‎desktop/src/features/community-members/lib/joinAlerts.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,3 +208,20 @@ export function joinAlertTitle(communityName: string | null | undefined) {
208208
export function joinAlertBody(displayName: string) {
209209
return `${displayName} joined`;
210210
}
211+
212+
/**
213+
* Most per-key notifications emitted for a single snapshot.
214+
*
215+
* Above this, one summary replaces the batch. A snapshot is a whole roster, not
216+
* an event per join, so a bulk import or an invite link shared into a group
217+
* chat lands every new key at once: without a cap that is one OS notification
218+
* per member (measured: a 250-key snapshot emitted 248 banners in a serial
219+
* loop). The cap is deliberately small — past a handful the individual
220+
* identities are unreadable as notifications anyway, and the useful signal is
221+
* that a batch arrived.
222+
*/
223+
export const JOIN_ALERT_MAX_INDIVIDUAL = 3;
224+
225+
export function joinAlertSummaryBody(count: number) {
226+
return `${count} new members joined`;
227+
}

‎desktop/src/features/community-members/useCommunityJoinAlerts.test.mjs‎

Lines changed: 237 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -254,20 +254,36 @@ import {
254254
const VIEWER = "a".repeat(64);
255255
const ALICE = "b".repeat(64);
256256
const BOB = "c".repeat(64);
257+
const CAROL = "d".repeat(64);
257258
const COMMUNITY_A = "community-a";
258259
const COMMUNITY_B = "community-b";
259260

260261
const KIND_SNAPSHOT = 13534;
261262
const KIND_MEMBER_ADDED = 8000;
262263

263-
/** A kind:13534 membership snapshot carrying the given roster. */
264-
function snapshot(rosterPubkeys, { id = "snap-1", createdAt = 1000 } = {}) {
264+
/**
265+
* A kind:13534 membership snapshot carrying the given roster.
266+
*
267+
* The viewer is stamped `owner` unless `viewerRole` says otherwise, mirroring
268+
* the relay: `publish_nip43_membership_locked` emits `["member", pubkey, role]`
269+
* for every row, so the viewer's own authorization always rides in the
270+
* snapshot. A fixture that stamped everyone `member` could not express the
271+
* demotion this hook now gates on.
272+
*/
273+
function snapshot(
274+
rosterPubkeys,
275+
{ id = "snap-1", createdAt = 1000, viewerRole = "owner" } = {},
276+
) {
265277
return {
266278
id,
267279
pubkey: "f".repeat(64),
268280
created_at: createdAt,
269281
kind: KIND_SNAPSHOT,
270-
tags: rosterPubkeys.map((pubkey) => ["member", pubkey, "member"]),
282+
tags: rosterPubkeys.map((pubkey) => [
283+
"member",
284+
pubkey,
285+
pubkey === VIEWER ? viewerRole : "member",
286+
]),
271287
content: "",
272288
sig: "s".repeat(128),
273289
};
@@ -441,6 +457,20 @@ async function settle(iterations = 4) {
441457
}
442458
}
443459

460+
/**
461+
* Advance past the kind:8000 refetch debounce, then settle.
462+
*
463+
* The accelerator coalesces refetches on a 500ms trailing window so a bulk add
464+
* costs one REQ instead of one per member; anything asserting on a refetch has
465+
* to outwait that window or it is asserting on a timer that has not fired.
466+
*/
467+
async function settleAfterRefreshDebounce() {
468+
await act(async () => {
469+
await new Promise((r) => setTimeout(r, 600));
470+
});
471+
await settle();
472+
}
473+
444474
function ledgerKeys() {
445475
return [...storage.keys()].filter((key) =>
446476
key.startsWith("buzz-community-join-seen.v1"),
@@ -585,7 +615,7 @@ describe("useCommunityJoinAlerts — mounted subscription behaviour", () => {
585615
snapshot([VIEWER, ALICE, BOB], { id: "snap-replay", createdAt: 2000 }),
586616
);
587617
relay.emitReconnect();
588-
await settle();
618+
await settleAfterRefreshDebounce();
589619

590620
assert.ok(
591621
relay.counts().fetchFirstEventCalls > before,
@@ -605,7 +635,7 @@ describe("useCommunityJoinAlerts — mounted subscription behaviour", () => {
605635
}),
606636
);
607637
relay.emitReconnect();
608-
await settle();
638+
await settleAfterRefreshDebounce();
609639

610640
assert.equal(
611641
notifications.length,
@@ -651,7 +681,7 @@ describe("useCommunityJoinAlerts — mounted subscription behaviour", () => {
651681
content: "",
652682
sig: "s".repeat(128),
653683
});
654-
await settle();
684+
await settleAfterRefreshDebounce();
655685

656686
assert.ok(
657687
relay.counts().fetchFirstEventCalls > before,
@@ -676,7 +706,7 @@ describe("useCommunityJoinAlerts — mounted subscription behaviour", () => {
676706
content: "",
677707
sig: "s".repeat(128),
678708
});
679-
await settle();
709+
await settleAfterRefreshDebounce();
680710

681711
assert.equal(notifications.length, 1);
682712

@@ -877,6 +907,206 @@ describe("useCommunityJoinAlerts — mounted subscription behaviour", () => {
877907
"the seeding snapshot must still refresh the roster panel",
878908
);
879909

910+
await unmount();
911+
});
912+
/**
913+
* Authorization must come from the snapshot in hand, not the cached role that
914+
* mounted the effect.
915+
*
916+
* `useMyRelayMembershipLookupQuery` is invalidated only by this client's own
917+
* membership mutations, and `staleTime` marks data stale without scheduling a
918+
* refetch — so a viewer demoted by ANOTHER admin keeps a cached owner/admin
919+
* role for as long as the app stays open. Found by Wren, reproduced live by
920+
* Max against a real relay: the demoted viewer kept learning every later
921+
* joiner's identity.
922+
*
923+
* The demotion and the join ride in the SAME snapshot, which is the racy
924+
* shape: an async invalidation cannot beat the handler it is racing.
925+
*/
926+
it("stops alerting when the snapshot itself demotes the viewer", async () => {
927+
const relay = installRelayStub();
928+
const { render, unmount } = mountHook({ role: "admin" });
929+
930+
await render();
931+
await settle();
932+
933+
relay.emitSnapshot(snapshot([VIEWER, ALICE], { viewerRole: "admin" }));
934+
await settle();
935+
936+
// Positive control: still admin, so a genuine join must alert. Without
937+
// this, a gate that refused everything would pass the assertions below.
938+
relay.emitSnapshot(
939+
snapshot([VIEWER, ALICE, BOB], { id: "snap-join", viewerRole: "admin" }),
940+
);
941+
await settle();
942+
assert.equal(notifications.length, 1, "precondition: admin still alerts");
943+
944+
const ledgerBefore = storage.get(joinAlertStorageKey(COMMUNITY_A, VIEWER));
945+
946+
// Remote demotion + a new member, in one authoritative snapshot.
947+
relay.emitSnapshot(
948+
snapshot([VIEWER, ALICE, BOB, CAROL], {
949+
id: "snap-demote",
950+
createdAt: 4000,
951+
viewerRole: "member",
952+
}),
953+
);
954+
await settle();
955+
956+
assert.equal(
957+
notifications.length,
958+
1,
959+
"a demoted viewer must not be told who joined",
960+
);
961+
assert.equal(
962+
storage.get(joinAlertStorageKey(COMMUNITY_A, VIEWER)),
963+
ledgerBefore,
964+
"the ledger must not advance on a snapshot the viewer is not authorized for",
965+
);
966+
967+
await unmount();
968+
});
969+
970+
/**
971+
* Removal is the same disclosure as demotion, and `find` returning undefined
972+
* is a different code path from a role that is present but wrong.
973+
*/
974+
it("stops alerting when the viewer is dropped from the roster entirely", async () => {
975+
const relay = installRelayStub();
976+
const { render, unmount } = mountHook({ role: "owner" });
977+
978+
await render();
979+
await settle();
980+
981+
relay.emitSnapshot(snapshot([VIEWER, ALICE]));
982+
await settle();
983+
984+
// Viewer absent from the snapshot; a new key arrives alongside.
985+
relay.emitSnapshot({
986+
id: "snap-removed",
987+
pubkey: "f".repeat(64),
988+
created_at: 5000,
989+
kind: KIND_SNAPSHOT,
990+
tags: [
991+
["member", ALICE, "member"],
992+
["member", BOB, "member"],
993+
],
994+
content: "",
995+
sig: "s".repeat(128),
996+
});
997+
await settle();
998+
999+
assert.equal(
1000+
notifications.length,
1001+
0,
1002+
"a removed viewer must learn nothing about later joins",
1003+
);
1004+
1005+
await unmount();
1006+
});
1007+
1008+
/**
1009+
* A snapshot is a whole roster, so a bulk add lands every new key at once.
1010+
* Uncapped that is one OS notification per member — measured at 248 banners
1011+
* for a 250-key snapshot, delivered through a serial await loop.
1012+
*/
1013+
it("collapses a bulk join into one summary instead of a banner per member", async () => {
1014+
const relay = installRelayStub();
1015+
const { render, unmount } = mountHook();
1016+
1017+
await render();
1018+
await settle();
1019+
1020+
relay.emitSnapshot(snapshot([VIEWER, ALICE]));
1021+
await settle();
1022+
1023+
const bulk = [];
1024+
for (let i = 0; i < 40; i++) {
1025+
bulk.push(`${i.toString(16).padStart(2, "0").repeat(31)}ff`);
1026+
}
1027+
relay.emitSnapshot(
1028+
snapshot([VIEWER, ALICE, ...bulk], { id: "snap-bulk", createdAt: 6000 }),
1029+
);
1030+
await settle(10);
1031+
1032+
assert.equal(notifications.length, 1, "one summary, not one per member");
1033+
assert.equal(notifications[0].body, "40 new members joined");
1034+
1035+
await unmount();
1036+
});
1037+
1038+
/**
1039+
* Below the cap the alert still names people — the summary must not swallow
1040+
* the ordinary one-or-two-join case the feature exists for.
1041+
*/
1042+
it("still names individuals for a small batch", async () => {
1043+
const relay = installRelayStub();
1044+
const { render, unmount } = mountHook();
1045+
1046+
await render();
1047+
await settle();
1048+
1049+
relay.emitSnapshot(snapshot([VIEWER, ALICE]));
1050+
await settle();
1051+
1052+
relay.emitSnapshot(
1053+
snapshot([VIEWER, ALICE, BOB, CAROL], {
1054+
id: "snap-two",
1055+
createdAt: 7000,
1056+
}),
1057+
);
1058+
await settle(10);
1059+
1060+
assert.equal(notifications.length, 2, "two joins, two named alerts");
1061+
assert.ok(
1062+
notifications.every((entry) => entry.body.endsWith(" joined")),
1063+
"each alert names the joiner rather than summarizing",
1064+
);
1065+
1066+
await unmount();
1067+
});
1068+
1069+
/**
1070+
* Each refetch is a REQ frame billed against the same per-principal WsEvents
1071+
* budget as the user's own sends (default 10/s over a 5s window), and a bulk
1072+
* add emits one kind:8000 per member. Uncoalesced that was 250 REQs for 250
1073+
* deltas — spending the budget the owner needs to send messages and open
1074+
* channels.
1075+
*/
1076+
it("coalesces a burst of kind:8000 deltas into a single refetch", async () => {
1077+
const relay = installRelayStub();
1078+
const { render, unmount } = mountHook();
1079+
1080+
await render();
1081+
await settle();
1082+
1083+
relay.emitSnapshot(snapshot([VIEWER, ALICE]));
1084+
await settle();
1085+
1086+
const before = relay.counts().fetchFirstEventCalls;
1087+
relay.setRefetchSnapshot(
1088+
snapshot([VIEWER, ALICE], { id: "snap-burst", createdAt: 8000 }),
1089+
);
1090+
1091+
for (let i = 0; i < 50; i++) {
1092+
relay.emitDelta({
1093+
id: `burst-${i}`,
1094+
pubkey: "f".repeat(64),
1095+
created_at: 8000 + i,
1096+
kind: KIND_MEMBER_ADDED,
1097+
tags: [["p", BOB]],
1098+
content: "",
1099+
sig: "s".repeat(128),
1100+
});
1101+
}
1102+
await settleAfterRefreshDebounce();
1103+
1104+
assert.equal(
1105+
relay.counts().fetchFirstEventCalls - before,
1106+
1,
1107+
"50 deltas must cost exactly one REQ, not 50",
1108+
);
1109+
8801110
await unmount();
8811111
});
8821112
});

0 commit comments

Comments
 (0)