Skip to content

Commit fd55ab6

Browse files
authored
fix(desktop): keep machine onboarding for unrecognized identities after reset (#2244)
1 parent ec0e450 commit fd55ab6

7 files changed

Lines changed: 286 additions & 22 deletions

File tree

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -375,7 +375,10 @@ const overrides = new Map([
375375
// queued to split when ProfileSettingsCard is broken into sub-components.
376376
// +20 lines: scroll-position save/restore across avatar editor open/close
377377
// to prevent layout shift from the Sign Out section causing a viewport jump.
378-
["src/features/settings/ui/ProfileSettingsCard.tsx", 1033],
378+
// +11 lines: signout-dev-webview-state — clear localStorage/sessionStorage
379+
// on successful signOut() resolve so dev-build webview state doesn't survive
380+
// a reset and vouch for the fresh key. Comment explains the race/redundancy.
381+
["src/features/settings/ui/ProfileSettingsCard.tsx", 1044],
379382
// keyring-dev-isolation: keyring_service() fn (7 lines) replaces the const
380383
// to return "buzz-desktop-dev" in debug builds. Load-bearing isolation fix.
381384
// +10 (1042 -> 1052): media_fetch_client with redirect::Policy::none() so a

‎desktop/src/app/App.tsx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -259,9 +259,11 @@ function AppReady({
259259
}
260260

261261
function CommunityApp({
262+
currentPubkey,
262263
onBackToMachineConfig,
263264
sharedIdentity,
264265
}: {
266+
currentPubkey: string | null;
265267
onBackToMachineConfig: () => void;
266268
sharedIdentity: boolean;
267269
}) {
@@ -325,6 +327,7 @@ function CommunityApp({
325327
relayUrl: transaction.relayUrl,
326328
token: transaction.token,
327329
reposDir: transaction.reposDir,
330+
pubkey: currentPubkey ?? undefined,
328331
addedAt: new Date().toISOString(),
329332
});
330333
communityOnboarding.update({
@@ -340,6 +343,7 @@ function CommunityApp({
340343
addCommunity,
341344
communities,
342345
communityOnboarding,
346+
currentPubkey,
343347
reconnectCommunity,
344348
switchCommunity,
345349
]);
@@ -494,7 +498,9 @@ function MachineBootstrap({ sharedIdentity }: { sharedIdentity: boolean }) {
494498
const { activeCommunity } = useCommunities();
495499
const communityOnboarding = useCommunityOnboarding();
496500
const machine = useMachineOnboardingState({
497-
hasConfiguredCommunity: activeCommunity !== null,
501+
activeCommunityPubkey: activeCommunity
502+
? (activeCommunity.pubkey ?? null)
503+
: undefined,
498504
isSharedIdentity: sharedIdentity,
499505
});
500506
const [machineInitialPage, setMachineInitialPage] =
@@ -548,6 +554,7 @@ function MachineBootstrap({ sharedIdentity }: { sharedIdentity: boolean }) {
548554
if (machine.stage === "ready") {
549555
return (
550556
<CommunityApp
557+
currentPubkey={machine.currentPubkey}
551558
onBackToMachineConfig={reopenMachineConfig}
552559
sharedIdentity={sharedIdentity}
553560
/>

‎desktop/src/app/AppShell.tsx‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -789,7 +789,11 @@ export function AppShell() {
789789
isCreateChannelOpen={isCreateChannelOpen}
790790
isPresencePending={presenceSession.isPending}
791791
onAddCommunity={(community) => {
792-
const id = communitiesHook.addCommunity(community);
792+
const id = communitiesHook.addCommunity({
793+
...community,
794+
pubkey:
795+
community.pubkey ?? identityQuery.data?.pubkey,
796+
});
793797
handleSwitchCommunity(id);
794798
}}
795799
onAddCommunityOpenChange={
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
import {
5+
migrateMachineOnboardingCompletion,
6+
readMachineOnboardingCompletion,
7+
} from "./machineOnboarding.ts";
8+
9+
// machineOnboarding.ts reads/writes window.localStorage directly, so we inject
10+
// a minimal in-memory storage into globalThis.window before each test and
11+
// restore it afterward.
12+
13+
function createMemoryStorage(initial = {}) {
14+
const values = new Map(Object.entries(initial));
15+
return {
16+
getItem: (key) => values.get(key) ?? null,
17+
setItem: (key, value) => values.set(key, String(value)),
18+
removeItem: (key) => values.delete(key),
19+
clear: () => values.clear(),
20+
key: (index) => Array.from(values.keys())[index] ?? null,
21+
get length() {
22+
return values.size;
23+
},
24+
};
25+
}
26+
27+
function withFakeWindow(initial, fn) {
28+
const prev = globalThis.window;
29+
const storage = createMemoryStorage(initial);
30+
globalThis.window = {
31+
localStorage: storage,
32+
// location.href without a machineOnboarding=1 param → forceMachineOnboarding() returns false
33+
location: { href: "http://localhost/" },
34+
};
35+
try {
36+
return fn(storage);
37+
} finally {
38+
globalThis.window = prev;
39+
}
40+
}
41+
42+
const PUBKEY_A =
43+
"aaaaaa1111112222223333334444445555556666667777778888889999990000aa";
44+
const PUBKEY_B =
45+
"bbbbbb1111112222223333334444445555556666667777778888889999990000bb";
46+
const LEGACY_KEY = `buzz-onboarding-complete.v1:${PUBKEY_A}`;
47+
const V2_KEY = `buzz-machine-onboarding-complete.v2:${PUBKEY_A}`;
48+
49+
// ── Fix A regression case ────────────────────────────────────────────────────
50+
51+
test("migrate_mismatched_community_pubkey_does_not_vouch_for_current_key", () => {
52+
// Community pubkey is PUBKEY_B (stale from a previous identity); current
53+
// pubkey is PUBKEY_A (freshly generated after a dev reset). The mismatch
54+
// must NOT grant completion.
55+
withFakeWindow({}, (storage) => {
56+
const result = migrateMachineOnboardingCompletion(
57+
PUBKEY_A,
58+
PUBKEY_B, // activeCommunityPubkey — a different identity's community
59+
false,
60+
);
61+
assert.equal(result, false, "mismatched pubkey must not vouch");
62+
assert.equal(
63+
storage.getItem(V2_KEY),
64+
null,
65+
"completion must not be written to storage",
66+
);
67+
assert.equal(
68+
readMachineOnboardingCompletion(PUBKEY_A),
69+
false,
70+
"readMachineOnboardingCompletion must return false",
71+
);
72+
});
73+
});
74+
75+
// ── Matching pubkey vouches ──────────────────────────────────────────────────
76+
77+
test("migrate_matching_community_pubkey_vouches_for_current_key", () => {
78+
// Community pubkey matches current pubkey → legitimate veteran, grant.
79+
withFakeWindow({}, (storage) => {
80+
const result = migrateMachineOnboardingCompletion(
81+
PUBKEY_A,
82+
PUBKEY_A, // same pubkey — community belongs to this identity
83+
false,
84+
);
85+
assert.equal(result, true, "matching pubkey must vouch");
86+
assert.equal(storage.getItem(V2_KEY), "true");
87+
assert.equal(readMachineOnboardingCompletion(PUBKEY_A), true);
88+
});
89+
});
90+
91+
// ── Absent community pubkey — regression case (Thufir pass 1) ───────────────
92+
93+
test("migrate_absent_community_pubkey_does_not_vouch_for_fresh_identity", () => {
94+
// Stale current-format community with no pubkey stamp (created before the
95+
// stamp was added, or from an older build) + freshly generated identity
96+
// after a dev reset. The absent pubkey must NOT vouch — this was the
97+
// reachable producer of the half-onboarded state.
98+
withFakeWindow({}, (storage) => {
99+
const result = migrateMachineOnboardingCompletion(
100+
PUBKEY_A,
101+
null, // absent pubkey — could be legacy OR an unstamped modern entry
102+
false,
103+
);
104+
assert.equal(
105+
result,
106+
false,
107+
"absent pubkey must not vouch for a fresh identity",
108+
);
109+
assert.equal(
110+
storage.getItem(V2_KEY),
111+
null,
112+
"completion must not be written to storage",
113+
);
114+
});
115+
});
116+
117+
// ── No community configured ──────────────────────────────────────────────────
118+
119+
test("migrate_no_community_does_not_vouch_for_current_key", () => {
120+
// `undefined` = no active community at all.
121+
withFakeWindow({}, (storage) => {
122+
const result = migrateMachineOnboardingCompletion(
123+
PUBKEY_A,
124+
undefined, // no community
125+
false,
126+
);
127+
assert.equal(result, false, "no community must not vouch");
128+
assert.equal(storage.getItem(V2_KEY), null);
129+
});
130+
});
131+
132+
// ── Legacy onboarding completion still grants (pubkey-scoped) ───────────────
133+
134+
test("migrate_legacy_completion_key_still_grants_migration", () => {
135+
withFakeWindow({ [LEGACY_KEY]: "true" }, (storage) => {
136+
const result = migrateMachineOnboardingCompletion(
137+
PUBKEY_A,
138+
undefined, // no community — but legacy key is present
139+
false,
140+
);
141+
assert.equal(result, true, "legacy completion key must grant migration");
142+
assert.equal(storage.getItem(V2_KEY), "true");
143+
});
144+
});
145+
146+
// ── Shared identity grants regardless of community ───────────────────────────
147+
148+
test("migrate_shared_identity_grants_regardless_of_community", () => {
149+
withFakeWindow({}, () => {
150+
const result = migrateMachineOnboardingCompletion(
151+
PUBKEY_A,
152+
undefined, // no community
153+
true, // isSharedIdentity
154+
);
155+
assert.equal(result, true, "shared identity must always grant");
156+
});
157+
});
158+
159+
// ── Already-completed v2 key returns true without re-writing ─────────────────
160+
161+
test("migrate_already_completed_pubkey_returns_true_immediately", () => {
162+
withFakeWindow({ [V2_KEY]: "true" }, (storage) => {
163+
// Pass mismatched community to prove early-exit, not community vouching.
164+
const result = migrateMachineOnboardingCompletion(
165+
PUBKEY_A,
166+
PUBKEY_B,
167+
false,
168+
);
169+
assert.equal(result, true, "already-completed pubkey must return true");
170+
// Value was already there; the function should not have touched it
171+
// (but a redundant write is also acceptable — just verify it's still true).
172+
assert.equal(storage.getItem(V2_KEY), "true");
173+
});
174+
});

‎desktop/src/features/onboarding/machineOnboarding.ts‎

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,27 @@ function clearMachineOnboardingCompletion(pubkey: string | null) {
3636
}
3737

3838
function forceMachineOnboarding() {
39-
if (!import.meta.env.DEV || typeof window === "undefined") return false;
39+
if (!import.meta.env?.DEV || typeof window === "undefined") return false;
4040
return (
4141
new URL(window.location.href).searchParams.get("machineOnboarding") === "1"
4242
);
4343
}
4444

45-
function migrateMachineOnboardingCompletion(
45+
/** @internal Exported for unit testing only. */
46+
export function migrateMachineOnboardingCompletion(
4647
pubkey: string,
47-
hasConfiguredCommunity: boolean,
48+
/**
49+
* The `pubkey` field of the active community from localStorage, or
50+
* `undefined` if no community is configured. Community-creation paths stamp
51+
* the current identity's pubkey on write; absent pubkey (`null`) therefore
52+
* indicates a legacy entry that pre-dates the stamp and is NOT treated as a
53+
* voucher. Pass `undefined` when there is no active community at all.
54+
*
55+
* Using the community's own pubkey prevents a freshly generated post-reset
56+
* key from being vouched for by a stale community entry that survived the
57+
* webview wipe.
58+
*/
59+
activeCommunityPubkey: string | null | undefined,
4860
isSharedIdentity: boolean,
4961
) {
5062
if (forceMachineOnboarding()) return false;
@@ -54,9 +66,20 @@ function migrateMachineOnboardingCompletion(
5466
window.localStorage.getItem(
5567
completionKey(LEGACY_ONBOARDING_COMPLETION_STORAGE_KEY, pubkey),
5668
) === "true";
69+
70+
// A community entry vouches for the current pubkey only when its recorded
71+
// pubkey matches. Absent pubkey (legacy entries predating the stamp) and
72+
// no community at all (undefined) do not vouch — after community creation
73+
// paths stamp pubkey on write, absent means the entry pre-dates the stamp
74+
// and cannot be trusted to identify which identity created it.
75+
const communityVouchesForPubkey =
76+
activeCommunityPubkey !== undefined &&
77+
activeCommunityPubkey !== null &&
78+
activeCommunityPubkey === pubkey;
79+
5780
if (
5881
!completedLegacyOnboarding &&
59-
!hasConfiguredCommunity &&
82+
!communityVouchesForPubkey &&
6083
!isSharedIdentity
6184
) {
6285
return false;
@@ -74,10 +97,10 @@ function identitySettled(status: QueryStatus, isFetching: boolean) {
7497
}
7598

7699
export function useMachineOnboardingState({
77-
hasConfiguredCommunity,
100+
activeCommunityPubkey,
78101
isSharedIdentity,
79102
}: {
80-
hasConfiguredCommunity: boolean;
103+
activeCommunityPubkey: string | null | undefined;
81104
isSharedIdentity: boolean;
82105
}) {
83106
const queryClient = useQueryClient();
@@ -130,7 +153,7 @@ export function useMachineOnboardingState({
130153
if (
131154
migrateMachineOnboardingCompletion(
132155
currentPubkey,
133-
hasConfiguredCommunity,
156+
activeCommunityPubkey,
134157
isSharedIdentity,
135158
)
136159
) {
@@ -139,7 +162,7 @@ export function useMachineOnboardingState({
139162
setEvaluatedPubkey(currentPubkey);
140163
}, [
141164
currentPubkey,
142-
hasConfiguredCommunity,
165+
activeCommunityPubkey,
143166
identityLost,
144167
identityQuery.status,
145168
isSharedIdentity,

‎desktop/src/features/settings/ui/ProfileSettingsCard.tsx‎

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1009,13 +1009,27 @@ export function ProfileSettingsCard({
10091009
onClick={() => {
10101010
setIsSignOutPending(true);
10111011
// Keep the pending state if signOut() resolves before restart.
1012-
signOut().catch((err: unknown) => {
1013-
setIsSignOutPending(false);
1014-
setIsSignOutOpen(false);
1015-
toast.error(
1016-
err instanceof Error ? err.message : "Sign out failed.",
1017-
);
1018-
});
1012+
signOut()
1013+
.then(() => {
1014+
// Clear web storage for this origin on the success path
1015+
// only. This covers dev builds where the Rust webview wipe
1016+
// targets the .app-bundle WebKit dir (missing in `tauri
1017+
// dev`), preventing stale community config from vouching
1018+
// for the fresh key on next boot. In production the Rust
1019+
// wipe already handles this; the clear here is redundant
1020+
// but harmless. The restart may race this clear — that is
1021+
// acceptable; Fix A (pubkey-scoped heuristic) is the
1022+
// correctness gate.
1023+
window.localStorage.clear();
1024+
window.sessionStorage.clear();
1025+
})
1026+
.catch((err: unknown) => {
1027+
setIsSignOutPending(false);
1028+
setIsSignOutOpen(false);
1029+
toast.error(
1030+
err instanceof Error ? err.message : "Sign out failed.",
1031+
);
1032+
});
10191033
}}
10201034
>
10211035
{isSignOutPending ? "Signing out…" : "Delete My Data"}

0 commit comments

Comments
 (0)