Skip to content

Commit d6f0748

Browse files
committed
fix(communities): preserve admission recovery intent
Verify the current profile after acknowledged publication before saving membership or clearing recovery. Retain drafts through read failures, missing or superseded profiles, and stale completions. Persist canonical journal origins, retain unresolved legacy aliases independently, and preserve the newest draft when restored mappings overlap. Add regression coverage for both P2 findings and recovery boundaries, and update the manual fixture and ownership documentation. Signed-off-by: Matt Toohey <[email protected]>
1 parent 78d986c commit d6f0748

7 files changed

Lines changed: 446 additions & 36 deletions

File tree

‎docs/communities.md‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,10 @@ membership locally without publishing. New setup shows the relay's join policy,
3535
optional invite code, then a profile prefilled from the local default. Invite
3636
admission uses the relay's policy receipt and signed claim endpoints. Profile
3737
publication uses a signed kind:0 event and requires a matching accepted receipt
38-
before the client saves the completed membership. Rejected setup retains input
39-
and does not replace the currently selected community. An admitted invite is a
40-
remote side effect and is not undone if later profile setup fails or is cancelled.
38+
and current profile readback before the client saves the completed membership.
39+
Rejected setup retains input and does not replace the currently selected community.
40+
An admitted invite is a remote side effect and is not undone if later profile
41+
setup fails or is cancelled.
4142

4243
Profile editing preserves existing fields that this editor does not expose.
4344
After a confirmed Settings save, the profile also becomes the device-local
@@ -107,8 +108,13 @@ not become a deployment or enrollment command.
107108

108109
The native dialog journals an unfinished join before policy/claim dispatch and a
109110
submitted profile before publication. Records are partitioned by public viewer
110-
and canonical community ID. They contain only a transaction ID, destination and
111-
optional profile draft, never invite codes, policy receipts or private keys.
111+
and canonical HTTPS origin, independent of configured aliases. Existing alias
112+
records normalize to origins when their mapping is available and are persisted
113+
on the next journal write. Unresolved legacy aliases are retained independently:
114+
they do not block other joins or recovery, and become available again after
115+
restoring their original mapping. Records contain only a transaction ID,
116+
destination and optional profile draft, never invite codes, policy receipts or
117+
private keys.
112118
Storage failure blocks the remote operation. Completing a native join requires
113119
successful local membership persistence before clearing its recovery record.
114120

@@ -118,7 +124,10 @@ strong consistency. Successful access resumes profile setup even if the profile
118124
does not exist yet; it never requires reusing an expired invite after admission.
119125
Network failure retains the record for retry. Confirmed access denial returns to
120126
the policy/invite step, where the user can supply a valid code and current consent.
121-
Profile readback avoids repeating a publication whose receipt was lost. Late
127+
Profile readback avoids repeating a publication whose receipt was lost. An accepted
128+
publication also requires a fresh matching profile read before saving membership
129+
and clearing the journal. Failed reads, missing profiles and superseded writes
130+
retain the submitted draft for explicit retry, including after restart. Late
122131
completions cannot advance an unmounted dialog or a replaced transaction.
123132

124133
Saved memberships are restored through the existing session owner. Uncertain
@@ -185,8 +194,10 @@ selected-only restore, retry registration and equivalent-URL selection. Existing
185194
late responses, delivery and revocation.
186195

187196
`native-join.test.tsx` mounts the real dialog, community service and native adapter
188-
with fixture IPC to cover claim/profile response loss, persistence failure,
189-
interrupted setup, alias recovery and selected-only restart. `native-api.test.ts`
197+
with fixture IPC to cover claim/profile response loss, acknowledged but superseded
198+
or missing profiles, read and persistence failures, interrupted setup, alias
199+
recovery and selected-only restart. `join-journal.test.ts` covers alias addition,
200+
removal and unresolved legacy records across restarts. `native-api.test.ts`
190201
and `relay/native.test.ts` cover routing, verification, live auth, capacity,
191202
receipt correlation and expired-event readback. `app/services.test.ts` exercises
192203
native composition, failure/retry and development precedence. Rust tests cover

‎src/features/communities/CommunityDialog.test.tsx‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,17 @@ afterEach(() => {
3232
});
3333

3434
it("publishes a description-only edit to an existing community profile", async () => {
35-
api.inspectProfile.mockResolvedValueOnce({
36-
exists: true,
37-
existing: { name: "Fixture", about: "Before" },
38-
profile: { name: "Fixture", picture: "", about: "Before" },
39-
});
35+
api.inspectProfile
36+
.mockResolvedValueOnce({
37+
exists: true,
38+
existing: { name: "Fixture", about: "Before" },
39+
profile: { name: "Fixture", picture: "", about: "Before" },
40+
})
41+
.mockResolvedValueOnce({
42+
exists: true,
43+
existing: { name: "Fixture", about: "After" },
44+
profile: { name: "Fixture", picture: "", about: "After" },
45+
});
4046
const user = userEvent.setup();
4147
vi.stubGlobal(
4248
"fetch",
@@ -73,6 +79,7 @@ it("publishes a description-only edit to an existing community profile", async (
7379
{ name: "Fixture", picture: "", about: "After" },
7480
{ name: "Fixture", about: "Before" },
7581
);
82+
await waitFor(() => expect(communities.joined).toHaveBeenCalledOnce());
7683
});
7784

7885
it("opens with an unchanged over-limit profile and blocks publishing it", async () => {
@@ -223,11 +230,21 @@ it.each([
223230

224231
it("explains an inherited invalid avatar when editing at join and recovers on replacement", async () => {
225232
const picture = "http://images.example/avatar.png";
226-
api.inspectProfile.mockResolvedValueOnce({
227-
exists: true,
228-
existing: { name: "Fixture", picture },
229-
profile: { name: "Fixture", picture, about: "" },
230-
});
233+
api.inspectProfile
234+
.mockResolvedValueOnce({
235+
exists: true,
236+
existing: { name: "Fixture", picture },
237+
profile: { name: "Fixture", picture, about: "" },
238+
})
239+
.mockResolvedValueOnce({
240+
exists: true,
241+
existing: {},
242+
profile: {
243+
name: "Fixture changed",
244+
picture: "https://images.example/new.png",
245+
about: "",
246+
},
247+
});
231248
vi.stubGlobal(
232249
"fetch",
233250
vi.fn(async (url: string) => {
@@ -274,6 +291,7 @@ it("explains an inherited invalid avatar when editing at join and recovers on re
274291
},
275292
{ name: "Fixture", picture },
276293
);
294+
await waitFor(() => expect(communities.joined).toHaveBeenCalledOnce());
277295
});
278296

279297
it("keeps join unavailable after native identity hydration, but still saves a local profile", async () => {

‎src/features/communities/CommunityDialog.tsx‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -196,8 +196,25 @@ export function CommunityDialog({
196196
const transaction = journal?.begin(id, profile);
197197
const found = journal ? await inspectProfile(id) : original;
198198
if (!current(transaction)) return;
199-
if (!found?.exists || !profilesEqual(profile, found.profile))
200-
await publishProfile(id, profile, found?.existing ?? {});
199+
const next =
200+
found?.exists && profilesEqual(profile, found.profile)
201+
? profile
202+
: {
203+
...profile,
204+
name: profile.name.trim(),
205+
about: profile.about?.trim() ?? "",
206+
};
207+
if (!found?.exists || !profilesEqual(next, found.profile)) {
208+
await publishProfile(id, next, found?.existing ?? {});
209+
if (!current(transaction)) return;
210+
// An accepted replaceable event may already be superseded.
211+
const confirmed = await inspectProfile(id);
212+
if (!current(transaction)) return;
213+
if (!confirmed.exists || !profilesEqual(confirmed.profile, next))
214+
throw new Error(
215+
"Your profile change is not current. Your edits are retained; try again.",
216+
);
217+
}
201218
if (!current(transaction)) return;
202219
communities.joined(
203220
{
@@ -210,7 +227,7 @@ export function CommunityDialog({
210227
? { icon: info.icon }
211228
: {}),
212229
},
213-
profileDefault(profile, communities.snapshot().profile, id),
230+
profileDefault(next, communities.snapshot().profile, id),
214231
);
215232
if (transaction) journal?.finish(transaction);
216233
onJoined?.(id);

‎src/features/communities/join-journal.test.ts‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,17 @@
11
// @vitest-environment jsdom
22
import { afterEach, expect, it, vi } from "vitest";
33
import { createJoinJournal } from "./join-journal";
4+
import * as destinations from "./destination";
5+
6+
const viewer = "a".repeat(64);
7+
const key = `buzz-community-joins.v1:${viewer}`;
8+
const resolveDestination = destinations.communityDestination;
9+
function restart(aliases: Record<string, string>) {
10+
vi.spyOn(destinations, "communityDestination").mockImplementation((value) =>
11+
resolveDestination(value, aliases),
12+
);
13+
return createJoinJournal(viewer);
14+
}
415

516
afterEach(() => {
617
localStorage.clear();
@@ -32,3 +43,113 @@ it("preserves malformed recovery data instead of overwriting it before a new cla
3243
);
3344
expect(localStorage.getItem(key)).toBe("corrupt");
3445
});
46+
47+
it("recovers the same draft when an alias is added and removed across restarts", () => {
48+
const initial = restart({}).begin("wss://ONE.test:443/", {
49+
name: "Saved draft",
50+
picture: "",
51+
});
52+
const aliased = restart({ primary: "https://one.test" });
53+
expect(aliased.latest()).toEqual(initial);
54+
expect(aliased.get("primary")).toEqual(initial);
55+
expect(aliased.current(initial)).toBe(true);
56+
const replacement = aliased.begin("primary");
57+
expect(replacement.profile).toEqual(initial.profile);
58+
expect(aliased.current(initial)).toBe(false);
59+
aliased.finish(initial);
60+
61+
const unaliased = restart({});
62+
expect(unaliased.latest()).toEqual(replacement);
63+
expect(unaliased.get("https://one.test")).toEqual(replacement);
64+
expect(unaliased.current(replacement)).toBe(true);
65+
unaliased.finish(replacement);
66+
expect(unaliased.latest()).toBeUndefined();
67+
});
68+
69+
it("normalizes existing alias records to origins on the next journal write", () => {
70+
const legacy = {
71+
id: "legacy",
72+
community: "primary",
73+
profile: { name: "Legacy draft", picture: "" },
74+
};
75+
localStorage.setItem(key, JSON.stringify([legacy]));
76+
const configured = restart({ primary: "https://one.test" });
77+
expect(configured.get("primary")).toEqual({
78+
...legacy,
79+
community: "https://one.test",
80+
});
81+
configured.begin("https://two.test");
82+
expect(restart({}).get("https://one.test")?.profile).toEqual(legacy.profile);
83+
});
84+
85+
it("retains unresolved legacy aliases without blocking unrelated recovery or joins", () => {
86+
const known = restart({}).begin("https://two.test");
87+
const unresolved = {
88+
id: "unresolved",
89+
community: "old-alias",
90+
profile: { name: "Keep me", picture: "", about: "Unfinished" },
91+
};
92+
localStorage.setItem(key, JSON.stringify([known, unresolved]));
93+
const journal = restart({});
94+
expect(journal.latest()).toEqual(known);
95+
expect(journal.get("https://two.test")).toEqual(known);
96+
const other = journal.begin("https://three.test");
97+
journal.finish(known);
98+
journal.finish(other);
99+
expect(journal.latest()).toBeUndefined();
100+
expect(JSON.parse(localStorage.getItem(key) ?? "null")).toEqual([unresolved]);
101+
102+
const restored = restart({ "old-alias": "https://one.test" });
103+
expect(restored.latest()).toEqual({
104+
...unresolved,
105+
community: "https://one.test",
106+
});
107+
expect(restored.begin("https://one.test").profile).toEqual(
108+
unresolved.profile,
109+
);
110+
});
111+
112+
it("keeps the newest draft when a restored alias resolves to an already pending origin", () => {
113+
localStorage.setItem(
114+
key,
115+
JSON.stringify([
116+
{
117+
id: "legacy",
118+
community: "old-alias",
119+
profile: { name: "Old draft", picture: "" },
120+
},
121+
]),
122+
);
123+
const newer = restart({}).begin("https://one.test", {
124+
name: "New draft",
125+
picture: "",
126+
});
127+
const restored = restart({ "old-alias": "https://one.test" });
128+
expect(restored.latest()).toEqual(newer);
129+
expect(restored.get("old-alias")).toEqual(newer);
130+
expect(restored.get("https://one.test")).toEqual(newer);
131+
const retry = restored.begin("old-alias");
132+
expect(retry.profile).toEqual(newer.profile);
133+
expect(restored.current(newer)).toBe(false);
134+
restored.finish(retry);
135+
expect(restored.latest()).toBeUndefined();
136+
expect(JSON.parse(localStorage.getItem(key) ?? "null")).toEqual([]);
137+
});
138+
139+
it("preserves recovery records when device storage cannot be read", () => {
140+
const journal = restart({});
141+
const entry = journal.begin("https://one.test", {
142+
name: "Keep me",
143+
picture: "",
144+
});
145+
const reads = vi
146+
.spyOn(Storage.prototype, "getItem")
147+
.mockImplementation(() => {
148+
throw new Error("Storage unavailable");
149+
});
150+
expect(() => journal.begin("https://two.test")).toThrow(
151+
"Could not read unfinished",
152+
);
153+
reads.mockRestore();
154+
expect(journal.latest()).toEqual(entry);
155+
});

‎src/features/communities/join-journal.ts‎

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { communityDestination } from "./destination";
1+
import { communityDestination, isCommunityAlias } from "./destination";
22
import type { PersonalProfile } from "./service";
33

44
export type PendingJoin = {
@@ -19,7 +19,6 @@ export function createJoinJournal(viewer: string) {
1919
!entry ||
2020
typeof entry.id !== "string" ||
2121
typeof entry.community !== "string" ||
22-
communityDestination(entry.community).id !== entry.community ||
2322
(entry.profile !== undefined &&
2423
(!entry.profile ||
2524
typeof entry.profile.name !== "string" ||
@@ -28,6 +27,12 @@ export function createJoinJournal(viewer: string) {
2827
typeof entry.profile.about !== "string")))
2928
)
3029
throw new Error();
30+
try {
31+
entry.community = communityDestination(entry.community).url;
32+
} catch (reason) {
33+
// Retain legacy aliases until their deployment mapping is restored.
34+
if (!isCommunityAlias(entry.community)) throw reason;
35+
}
3136
}
3237
return entries;
3338
} catch {
@@ -46,15 +51,22 @@ export function createJoinJournal(viewer: string) {
4651
}
4752
}
4853
return {
49-
latest: () => read().at(-1),
50-
get: (community: string) =>
51-
read().find((entry) => entry.community === community),
54+
latest: () =>
55+
read()
56+
.filter((entry) => !isCommunityAlias(entry.community))
57+
.at(-1),
58+
get(community: string) {
59+
const origin = communityDestination(community).url;
60+
return read()
61+
.filter((entry) => entry.community === origin)
62+
.at(-1);
63+
},
5264
begin(community: string, profile?: PersonalProfile): PendingJoin {
5365
const entries = read();
54-
community = communityDestination(community).id;
66+
community = communityDestination(community).url;
5567
const draft =
5668
profile ??
57-
entries.find((item) => item.community === community)?.profile;
69+
entries.filter((item) => item.community === community).at(-1)?.profile;
5870
const entry = {
5971
id: crypto.randomUUID(),
6072
community,

0 commit comments

Comments
 (0)