Skip to content

Commit a1d1703

Browse files
matt2eJitter
andcommitted
fix(invites): collect native consent for app invite handoff
Co-authored-by: Jitter <d14dfe033ef0f809866f9f984de04821b0d900d7652fd85a54776ee40ca3a68f@buzz.block.builderlab.xyz> Signed-off-by: Matt Toohey <[email protected]>
1 parent d676c7b commit a1d1703

16 files changed

Lines changed: 848 additions & 135 deletions

‎desktop/src/features/onboarding/communityOnboarding.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export type CommunityOnboardingSource =
1515
| "deep-link-join";
1616

1717
export type CommunityOnboardingStage =
18+
| "invite-consent"
1819
| "claiming"
1920
| "connecting"
2021
| "profile"
@@ -61,6 +62,7 @@ export type CommunityOnboardingTransactionPatch = Partial<
6162
Pick<
6263
CommunityOnboardingTransaction,
6364
| "stage"
65+
| "policyReceipt"
6466
| "relayUrl"
6567
| "communityId"
6668
| "previousCommunityId"
@@ -106,6 +108,7 @@ function isTransaction(
106108
typeof transaction.createdAt === "string" &&
107109
typeof transaction.updatedAt === "string" &&
108110
[
111+
"invite-consent",
109112
"claiming",
110113
"connecting",
111114
"profile",

‎desktop/src/features/onboarding/ui/CommunityOnboardingFlow.tsx‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import { cn } from "@/shared/lib/cn";
3030
import { useSystemColorScheme } from "@/shared/theme/useSystemColorScheme";
3131
import { Button } from "@/shared/ui/button";
3232
import { Dialog, DialogContent, DialogTitle } from "@/shared/ui/dialog";
33+
import { InviteRedeemForm } from "./InviteRedeemForm";
3334
import { MembershipDenied } from "./MembershipDenied";
3435
import { ONBOARDING_PRIMARY_CTA_CLASS } from "./OnboardingChrome";
3536
import { OnboardingCard, useOnboardingCardLayout } from "./OnboardingCard";
@@ -525,8 +526,28 @@ export function CommunityOnboardingFlow({
525526
)}
526527
data-testid="community-onboarding-body"
527528
>
528-
{transaction.stage === "claiming" ||
529-
transaction.stage === "connecting" ? (
529+
{transaction.stage === "invite-consent" ? (
530+
<>
531+
<h1 className="mb-6 text-title font-normal">
532+
Join {transaction.communityName}
533+
</h1>
534+
<InviteRedeemForm
535+
key={`${transaction.id}:${transaction.inviteCode}`}
536+
initialValue={`buzz://join?${new URLSearchParams({ relay: transaction.relayUrl, code: transaction.inviteCode ?? "" })}`}
537+
readOnlyInvite
538+
error={null}
539+
isRedeeming={false}
540+
onCancel={onCancel}
541+
onRedeem={(_relayUrl, _inviteCode, policyReceipt) =>
542+
update(
543+
{ policyReceipt, stage: "claiming", error: undefined },
544+
transaction.id,
545+
)
546+
}
547+
/>
548+
</>
549+
) : transaction.stage === "claiming" ||
550+
transaction.stage === "connecting" ? (
530551
<>
531552
<Users className="mx-auto h-10 w-10" />
532553
<h1 className="mt-5 text-title font-normal">

‎desktop/src/features/onboarding/ui/InviteRedeemForm.tsx‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ type InviteRedeemFormProps = {
5252
defaultRelayUrl?: string;
5353
error: string | null;
5454
initialValue?: string;
55+
readOnlyInvite?: boolean;
5556
isRedeeming: boolean;
5657
onCancel: () => void;
5758
onConnect?: (relayWsUrl: string) => void;
@@ -64,6 +65,7 @@ export function InviteRedeemForm({
6465
defaultRelayUrl,
6566
error,
6667
initialValue = "",
68+
readOnlyInvite = false,
6769
isRedeeming,
6870
onCancel,
6971
onConnect,
@@ -405,7 +407,8 @@ export function InviteRedeemForm({
405407
<Input
406408
autoComplete="off"
407409
autoCorrect="off"
408-
autoFocus
410+
autoFocus={!readOnlyInvite}
411+
readOnly={readOnlyInvite}
409412
className={
410413
isAddCommunity
411414
? "h-11 rounded-xl border-input bg-muted/40 px-3 shadow-none transition-colors duration-150 ease-out hover:border-muted-foreground/40 focus-visible:border-muted-foreground/50 focus-visible:ring-0"
Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
import React from "react";
4+
import { render, waitFor, cleanup, act } from "@testing-library/react";
5+
import {
6+
CommunityOnboardingProvider,
7+
useCommunityOnboarding,
8+
startCommunityOnboarding,
9+
} from "./communityOnboarding.tsx";
10+
import { useClaimInvite } from "./useClaimInvite.ts";
11+
12+
let controls;
13+
function Claim() {
14+
controls = useCommunityOnboarding();
15+
useClaimInvite();
16+
return null;
17+
}
18+
const policy = {
19+
version: "v1",
20+
terms_markdown: "Terms",
21+
age_attestation_required: false,
22+
};
23+
const tauri = {
24+
invoke: async (command) => {
25+
if (command === "sign_event")
26+
return JSON.stringify({ id: "signed", tags: [] });
27+
throw new Error(`Unexpected command ${command}`);
28+
},
29+
};
30+
window.__TAURI_INTERNALS__ = tauri;
31+
globalThis.__TAURI_INTERNALS__ = tauri;
32+
33+
for (const configured of [true, false]) {
34+
test(`receipt-less invite ${configured ? "waits for native consent" : "claims a policy-free relay"}`, async () => {
35+
localStorage.clear();
36+
const requests = [];
37+
const original = globalThis.fetch;
38+
globalThis.fetch = async (url) => {
39+
requests.push(String(url));
40+
if (String(url).endsWith("/api/join-policy"))
41+
return Response.json(configured ? { policy } : {});
42+
return Response.json({
43+
status: "joined",
44+
community_id: "id",
45+
host: "relay.example",
46+
role: "member",
47+
});
48+
};
49+
try {
50+
startCommunityOnboarding({
51+
source: "deep-link-join",
52+
relayUrl: "wss://relay.example",
53+
inviteCode: "code",
54+
});
55+
render(
56+
React.createElement(
57+
CommunityOnboardingProvider,
58+
null,
59+
React.createElement(Claim),
60+
),
61+
);
62+
await waitFor(() =>
63+
assert.equal(
64+
controls.transaction.stage,
65+
configured ? "invite-consent" : "connecting",
66+
),
67+
);
68+
assert.equal(
69+
requests.filter((url) => url.endsWith("/claim")).length,
70+
configured ? 0 : 1,
71+
);
72+
} finally {
73+
cleanup();
74+
globalThis.fetch = original;
75+
}
76+
});
77+
}
78+
79+
test("rejected receipt returns to native consent and clears the stale proof", async () => {
80+
localStorage.clear();
81+
const original = globalThis.fetch;
82+
globalThis.fetch = async () =>
83+
Response.json({ error: "join_policy_required" }, { status: 403 });
84+
try {
85+
startCommunityOnboarding({
86+
source: "deep-link-join",
87+
relayUrl: "wss://relay.example",
88+
inviteCode: "code",
89+
policyReceipt: "expired",
90+
});
91+
render(
92+
React.createElement(
93+
CommunityOnboardingProvider,
94+
null,
95+
React.createElement(Claim),
96+
),
97+
);
98+
await waitFor(() =>
99+
assert.equal(controls.transaction.stage, "invite-consent"),
100+
);
101+
assert.equal(controls.transaction.policyReceipt, undefined);
102+
assert.equal(controls.transaction.error, undefined);
103+
} finally {
104+
cleanup();
105+
globalThis.fetch = original;
106+
}
107+
});
108+
109+
test("policy lookup failure never claims and can be retried", async () => {
110+
localStorage.clear();
111+
const original = globalThis.fetch;
112+
let failed = true;
113+
let claims = 0;
114+
globalThis.fetch = async (url) => {
115+
if (String(url).endsWith("/api/join-policy")) {
116+
if (failed) throw new Error("offline");
117+
return Response.json({ policy });
118+
}
119+
claims++;
120+
throw new Error("unexpected claim");
121+
};
122+
try {
123+
startCommunityOnboarding({
124+
source: "deep-link-join",
125+
relayUrl: "wss://relay.example",
126+
inviteCode: "code",
127+
});
128+
render(
129+
React.createElement(
130+
CommunityOnboardingProvider,
131+
null,
132+
React.createElement(Claim),
133+
),
134+
);
135+
await waitFor(() => assert.equal(controls.transaction.error, "offline"));
136+
failed = false;
137+
await act(async () => controls.update({ error: undefined }));
138+
await waitFor(() =>
139+
assert.equal(controls.transaction.stage, "invite-consent"),
140+
);
141+
assert.equal(claims, 0);
142+
} finally {
143+
cleanup();
144+
globalThis.fetch = original;
145+
}
146+
});
147+
148+
test("cancelled policy discovery cannot claim after its response arrives", async () => {
149+
localStorage.clear();
150+
const original = globalThis.fetch;
151+
let resolvePolicy;
152+
let started;
153+
const lookupStarted = new Promise((resolve) => {
154+
started = resolve;
155+
});
156+
const response = new Promise((resolve) => {
157+
resolvePolicy = resolve;
158+
});
159+
let claims = 0;
160+
globalThis.fetch = async (url) => {
161+
if (String(url).endsWith("/api/join-policy")) {
162+
started();
163+
return response;
164+
}
165+
claims++;
166+
throw new Error("unexpected claim");
167+
};
168+
try {
169+
startCommunityOnboarding({
170+
source: "deep-link-join",
171+
relayUrl: "wss://relay.example",
172+
inviteCode: "code",
173+
});
174+
render(
175+
React.createElement(
176+
CommunityOnboardingProvider,
177+
null,
178+
React.createElement(Claim),
179+
),
180+
);
181+
await lookupStarted;
182+
await act(async () => controls.clear());
183+
await act(async () => resolvePolicy(Response.json({})));
184+
assert.equal(controls.transaction, null);
185+
assert.equal(claims, 0);
186+
} finally {
187+
cleanup();
188+
globalThis.fetch = original;
189+
}
190+
});

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

Lines changed: 39 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import {
66
isInviteExhaustedError,
77
isInviteExpiredError,
88
} from "@/shared/api/inviteHelpers";
9-
import { claimInvite } from "@/shared/api/invites";
9+
import { claimInvite, getJoinPolicy } from "@/shared/api/invites";
1010

1111
/**
1212
* Drive the `claiming` stage after machine onboarding completes: claim the
@@ -21,21 +21,48 @@ import { claimInvite } from "@/shared/api/invites";
2121
export function useClaimInvite() {
2222
const { transaction, update } = useCommunityOnboarding();
2323
const [isPending, setIsPending] = React.useState(false);
24+
const currentTransaction = React.useRef(transaction);
25+
React.useEffect(() => {
26+
currentTransaction.current = transaction;
27+
return () => {
28+
currentTransaction.current = null;
29+
};
30+
}, [transaction]);
2431

2532
React.useEffect(() => {
2633
if (transaction?.stage !== "claiming" || transaction.error || isPending) {
2734
return;
2835
}
2936
setIsPending(true);
30-
void claimInvite(
31-
transaction.relayUrl,
32-
transaction.inviteCode ?? "",
33-
transaction.policyReceipt,
34-
)
35-
.then(() => {
36-
update({ stage: "connecting", error: undefined }, transaction.id);
37-
})
38-
.catch((error: unknown) =>
37+
void (async () => {
38+
const policy = !transaction.policyReceipt
39+
? await getJoinPolicy(transaction.relayUrl, "webview")
40+
: null;
41+
if (currentTransaction.current !== transaction) return;
42+
if (policy) {
43+
update({ stage: "invite-consent" }, transaction.id);
44+
return;
45+
}
46+
await claimInvite(
47+
transaction.relayUrl,
48+
transaction.inviteCode ?? "",
49+
transaction.policyReceipt,
50+
);
51+
update({ stage: "connecting", error: undefined }, transaction.id);
52+
})()
53+
.catch((error: unknown) => {
54+
if (currentTransaction.current !== transaction) return;
55+
if (inviteErrorMessage(error).includes("join_policy_required")) {
56+
update(
57+
{
58+
stage: "invite-consent",
59+
policyReceipt: undefined,
60+
error: undefined,
61+
},
62+
transaction.id,
63+
);
64+
return;
65+
}
3966
update(
4067
{
4168
error: isInviteExpiredError(error)
@@ -45,8 +72,8 @@ export function useClaimInvite() {
4572
: inviteErrorMessage(error),
4673
},
4774
transaction.id,
48-
),
49-
)
75+
);
76+
})
5077
.finally(() => setIsPending(false));
5178
}, [isPending, transaction, update]);
5279
}

0 commit comments

Comments
 (0)