Skip to content

Commit 5bbdd5c

Browse files
matt2eclaude
andcommitted
fix(desktop): bound and cancel invite-handoff join policy discovery
A receipt-less buzz://join claim first discovers the relay's join policy through the webview fetch path, which had no deadline, no body cap, and no way to cancel. A relay whose /api/join-policy blackholed, trickled, or streamed an oversized body left onboarding on "Accepting your invite…" forever, and cancelling did not stop the download. The webview branch of getJoinPolicy now matches the native fetch_join_policy bounds: one 15 s deadline covers the headers and the whole body, and the body is capped at 4 MiB while it streams (a larger declared Content-Length fails up front). A timeout surfaces as "The community's join policy took too long to load.", which the claiming stage shows with Retry. getJoinPolicy takes an optional AbortSignal, and useClaimInvite aborts the pending lookup when its transaction is cancelled, replaced, or unmounted. The existing transaction fence still drops any late settlement. The useClaimInvite jsdom suite gains a journey with a suspended /api/join-policy: no error at 14.999 s, a retryable timeout at 15 s with zero claims, then a retry that claims once against a policy-free relay. The single cancel test becomes a cancel/reopen table. Each row asserts the lookup's signal is aborted and that a late policy response neither claims nor moves the cleared or replacement transaction. A getJoinPolicy test rejects both a streamed and a declared body over 4 MiB. Removing the abort, the fence, the timer, or the cap each fails its test. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Matt Toohey <[email protected]>
1 parent 33a779f commit 5bbdd5c

4 files changed

Lines changed: 202 additions & 33 deletions

File tree

‎desktop/src/features/onboarding/useClaimInvite.jsdom-test.mjs‎

Lines changed: 98 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import assert from "node:assert/strict";
2-
import test from "node:test";
2+
import test, { mock } from "node:test";
33
import { act, cleanup, render, waitFor } from "@testing-library/react";
44
import React from "react";
55
import { createRoot } from "react-dom/client";
@@ -200,32 +200,38 @@ test("policy lookup failure never claims and can be retried", async () => {
200200
}
201201
});
202202

203-
test("cancelled policy discovery cannot claim after its response arrives", async () => {
203+
test("suspended policy discovery times out retryably without claiming", async () => {
204204
localStorage.clear();
205205
const original = globalThis.fetch;
206-
let resolvePolicy;
206+
let lookups = 0;
207207
let started;
208208
const lookupStarted = new Promise((resolve) => {
209209
started = resolve;
210210
});
211-
const response = new Promise((resolve) => {
212-
resolvePolicy = resolve;
213-
});
214-
let claims = 0;
215-
globalThis.fetch = async (url) => {
211+
const claimReceipts = [];
212+
globalThis.fetch = async (url, options) => {
216213
if (String(url).endsWith("/api/join-policy")) {
214+
lookups++;
215+
if (lookups > 1) return Response.json({});
217216
started();
218-
return response;
217+
// A blackholed relay: nothing settles until the request is aborted.
218+
return new Promise((_, reject) =>
219+
options.signal.addEventListener("abort", () =>
220+
reject(new DOMException("aborted", "AbortError")),
221+
),
222+
);
219223
}
220-
claims++;
221-
throw new Error("unexpected claim");
224+
claimReceipts.push(JSON.parse(options.body).policy_receipt);
225+
return Response.json({
226+
status: "joined",
227+
community_id: "id",
228+
host: "relay.example",
229+
role: "member",
230+
});
222231
};
232+
mock.timers.enable({ apis: ["setTimeout"] });
223233
try {
224-
startCommunityOnboarding({
225-
source: "deep-link-join",
226-
relayUrl: "wss://relay.example",
227-
inviteCode: "code",
228-
});
234+
startCommunityOnboarding(linkJoin);
229235
render(
230236
React.createElement(
231237
CommunityOnboardingProvider,
@@ -234,16 +240,88 @@ test("cancelled policy discovery cannot claim after its response arrives", async
234240
),
235241
);
236242
await lookupStarted;
237-
await act(async () => controls.clear());
238-
await act(async () => resolvePolicy(Response.json({})));
239-
assert.equal(controls.transaction, null);
240-
assert.equal(claims, 0);
243+
await act(async () => mock.timers.tick(14_999));
244+
assert.equal(controls.transaction.error, undefined);
245+
await act(async () => mock.timers.tick(1));
246+
mock.timers.reset();
247+
await waitFor(() =>
248+
assert.equal(
249+
controls.transaction.error,
250+
"The community's join policy took too long to load.",
251+
),
252+
);
253+
assert.equal(controls.transaction.stage, "claiming");
254+
assert.deepEqual(claimReceipts, []);
255+
// Retry, as the claiming stage's button does; this relay has no policy.
256+
await act(async () => controls.update({ error: undefined }));
257+
await waitFor(() => assert.equal(controls.transaction.stage, "connecting"));
258+
assert.equal(lookups, 2);
259+
assert.deepEqual(claimReceipts, [undefined]);
241260
} finally {
261+
mock.timers.reset();
242262
cleanup();
243263
globalThis.fetch = original;
244264
}
245265
});
246266

267+
// Cancelling, or reopening the link mid-lookup, aborts the pending discovery.
268+
// Its late settlement (here a response that ignores the abort) must not move
269+
// the cleared or replacement transaction.
270+
for (const [name, interrupt] of [
271+
["cancelled", () => controls.clear()],
272+
["reopened", () => controls.start(linkJoin)],
273+
]) {
274+
test(`${name} policy discovery is aborted and cannot settle afterwards`, async () => {
275+
localStorage.clear();
276+
const original = globalThis.fetch;
277+
const signals = [];
278+
let resolvePolicy;
279+
let started;
280+
const lookupStarted = new Promise((resolve) => {
281+
started = resolve;
282+
});
283+
let claims = 0;
284+
globalThis.fetch = async (url, options) => {
285+
if (String(url).endsWith("/api/join-policy")) {
286+
signals.push(options.signal);
287+
if (signals.length > 1) return new Promise(() => {});
288+
started();
289+
return new Promise((resolve) => {
290+
resolvePolicy = resolve;
291+
});
292+
}
293+
claims++;
294+
throw new Error("unexpected claim");
295+
};
296+
try {
297+
startCommunityOnboarding(linkJoin);
298+
render(
299+
React.createElement(
300+
CommunityOnboardingProvider,
301+
null,
302+
React.createElement(Claim),
303+
),
304+
);
305+
await lookupStarted;
306+
await act(async () => interrupt());
307+
assert.equal(signals[0].aborted, true);
308+
await act(async () => resolvePolicy(Response.json({ policy })));
309+
if (name === "cancelled") {
310+
assert.equal(controls.transaction, null);
311+
} else {
312+
await waitFor(() => assert.equal(signals.length, 2));
313+
assert.equal(signals[1].aborted, false);
314+
assert.equal(controls.transaction.stage, "claiming");
315+
assert.equal(controls.transaction.error, undefined);
316+
}
317+
assert.equal(claims, 0);
318+
} finally {
319+
cleanup();
320+
globalThis.fetch = original;
321+
}
322+
});
323+
}
324+
247325
for (const [sentinel, guidance] of [
248326
[
249327
"invite_restricted",

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ import { claimInvite, getJoinPolicy } from "@/shared/api/invites";
1111
* Drive the `claiming` stage after machine onboarding completes: claim the
1212
* invite with the user's final identity, then advance to `connecting`.
1313
* Completion is fenced by transaction ID so cancelling or replacing the
14-
* transaction while the request is pending cannot mutate the replacement.
14+
* transaction while the request is pending cannot mutate the replacement;
15+
* the same change aborts a pending policy lookup.
1516
*
1617
* The error guard keeps a failed claim parked on the caller's Retry
1718
* affordance — without it the effect refires on the error-bearing transaction
@@ -21,10 +22,12 @@ export function useClaimInvite() {
2122
const { transaction, update } = useCommunityOnboarding();
2223
const [isPending, setIsPending] = React.useState(false);
2324
const currentTransaction = React.useRef(transaction);
25+
const policyLookup = React.useRef<AbortController | null>(null);
2426
React.useEffect(() => {
2527
currentTransaction.current = transaction;
2628
return () => {
2729
currentTransaction.current = null;
30+
policyLookup.current?.abort();
2831
};
2932
}, [transaction]);
3033

@@ -33,9 +36,11 @@ export function useClaimInvite() {
3336
return;
3437
}
3538
setIsPending(true);
39+
const lookup = new AbortController();
40+
policyLookup.current = lookup;
3641
void (async () => {
3742
const policy = !transaction.policyReceipt
38-
? await getJoinPolicy(transaction.relayUrl, "webview")
43+
? await getJoinPolicy(transaction.relayUrl, "webview", lookup.signal)
3944
: null;
4045
if (currentTransaction.current !== transaction) return;
4146
if (policy) {

‎desktop/src/shared/api/invites.test.mjs‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,33 @@ test("getJoinPolicy fails closed on a policy endpoint error", async () => {
5353
);
5454
});
5555

56+
test("getJoinPolicy refuses a webview response past the 4 MiB native cap", async () => {
57+
const oversized = 4 * 1024 * 1024 + 1;
58+
// Streamed without a length, then declared up front.
59+
const streamed = new ReadableStream({
60+
start(controller) {
61+
controller.enqueue(new TextEncoder().encode('{"policy":null,"pad":"'));
62+
controller.enqueue(new Uint8Array(oversized).fill(0x61));
63+
controller.enqueue(new TextEncoder().encode('"}'));
64+
controller.close();
65+
},
66+
});
67+
for (const response of [
68+
new Response(streamed, { status: 200 }),
69+
new Response("{}", {
70+
status: 200,
71+
headers: { "content-length": String(oversized) },
72+
}),
73+
]) {
74+
await withFetch(response, () =>
75+
assert.rejects(
76+
getJoinPolicy("wss://relay.example", "webview"),
77+
/oversized join policy/,
78+
),
79+
);
80+
}
81+
});
82+
5683
test("getJoinPolicy maps the native command response", async () => {
5784
const previousWindow = globalThis.window;
5885
globalThis.window = {

‎desktop/src/shared/api/invites.ts‎

Lines changed: 70 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ const NIP98_KIND = 27235;
2121
// connect timeout (a minute or more on macOS).
2222
const INVITE_REQUEST_TIMEOUT_MS = 15_000;
2323

24+
// Matches the native fetch_join_policy cap: each relay policy document is at
25+
// most 256 KiB, and four MiB covers two maximally escaped documents plus the
26+
// response envelope.
27+
const MAX_JOIN_POLICY_RESPONSE_BYTES = 4 * 1024 * 1024;
28+
2429
export type MintedInvite = {
2530
code: string;
2631
expiresAt: number;
@@ -127,10 +132,42 @@ export function isJoinPolicyDiscoveryCandidate(relayWsUrl: string): boolean {
127132
}
128133
}
129134

130-
/** Fetch relay-hosted policy content for any join surface. */
135+
/** Read a JSON body, refusing it once it streams past `maxBytes`. */
136+
async function readBoundedJson(
137+
response: Response,
138+
maxBytes: number,
139+
): Promise<unknown> {
140+
if (Number(response.headers.get("content-length")) > maxBytes) {
141+
throw new Error("relay returned oversized join policy");
142+
}
143+
const reader = response.body?.getReader();
144+
const decoder = new TextDecoder();
145+
let size = 0;
146+
let text = "";
147+
while (reader) {
148+
const { done, value } = await reader.read();
149+
if (done) break;
150+
size += value.byteLength;
151+
if (size > maxBytes) {
152+
void reader.cancel();
153+
throw new Error("relay returned oversized join policy");
154+
}
155+
text += decoder.decode(value, { stream: true });
156+
}
157+
return JSON.parse(text + decoder.decode());
158+
}
159+
160+
/**
161+
* Fetch relay-hosted policy content for any join surface.
162+
*
163+
* The webview transport mirrors the native command's bounds: one deadline
164+
* covers the headers and the whole body, and the body is capped while it
165+
* streams. `signal` lets the caller abandon the request early.
166+
*/
131167
export async function getJoinPolicy(
132168
relayWsUrl: string,
133169
transport: "native" | "webview",
170+
signal?: AbortSignal,
134171
): Promise<JoinPolicy | null> {
135172
type RawJoinPolicy = {
136173
terms_markdown?: string;
@@ -145,16 +182,38 @@ export async function getJoinPolicy(
145182
});
146183
} else {
147184
const base = relayHttpFromWs(relayWsUrl);
148-
const response = await fetch(`${base.replace(/\/+$/, "")}/api/join-policy`);
149-
// Relays predating join-policy support have no configured policy.
150-
if (response.status === 404) return null;
151-
if (!response.ok) throw new Error(`HTTP ${response.status}`);
152-
raw =
153-
(
154-
(await response.json()) as {
155-
policy?: RawJoinPolicy;
156-
}
157-
).policy ?? null;
185+
const controller = new AbortController();
186+
const abort = () => controller.abort();
187+
signal?.addEventListener("abort", abort, { once: true });
188+
let timedOut = false;
189+
const timer = setTimeout(() => {
190+
timedOut = true;
191+
controller.abort();
192+
}, INVITE_REQUEST_TIMEOUT_MS);
193+
try {
194+
if (signal?.aborted) abort();
195+
const response = await fetch(
196+
`${base.replace(/\/+$/, "")}/api/join-policy`,
197+
{ signal: controller.signal },
198+
);
199+
// Relays predating join-policy support have no configured policy.
200+
if (response.status === 404) return null;
201+
if (!response.ok) throw new Error(`HTTP ${response.status}`);
202+
raw =
203+
(
204+
(await readBoundedJson(response, MAX_JOIN_POLICY_RESPONSE_BYTES)) as {
205+
policy?: RawJoinPolicy;
206+
}
207+
).policy ?? null;
208+
} catch (error) {
209+
if (timedOut) {
210+
throw new Error("The community's join policy took too long to load.");
211+
}
212+
throw error;
213+
} finally {
214+
clearTimeout(timer);
215+
signal?.removeEventListener("abort", abort);
216+
}
158217
}
159218
return raw
160219
? {

0 commit comments

Comments
 (0)