Skip to content

Commit 6ea7a2b

Browse files
tlongwell-blocknpub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyfWren
authored
fix(desktop): preserve early relay auth challenges (block#3320)
## Summary - buffer native WebSocket frames until `plugin:websocket|connect` returns the socket ID and the NIP-42 auth waiter is installed - drain those frames in order before normal inbound handling begins - add a deterministic E2E seam and regression for an AUTH challenge delivered before connect resolves ## Root cause The native WebSocket task starts forwarding relay frames before the connect command returns its socket ID. Buzz relay sends the NIP-42 AUTH challenge immediately on connection, so Desktop could process that challenge while `wsId` and `authRequest` were still unset. The challenge was discarded, the cold connection failed authentication, and the first plain-text send failed. Channel history still appeared because it loads through the Tauri channel-window command rather than this frontend WebSocket. ## Verification - deterministic regression is red before the fix (`connecting` after 5s) and green after it - `pnpm test`: 3,721 passed - `pnpm build:e2e`: passed - focused early-AUTH E2E: passed - existing failed-initial-dial E2E: passed - `pnpm typecheck`: passed - Biome + file-size pre-commit checks: passed The complete 7-test relay-reconnect file passed once before the final line-count-only compaction. After that compaction, two full-file reruns each had the same unrelated startup-seam flake in the existing initial-dial test; both the new test and that existing test pass independently at the committed HEAD. --------- Signed-off-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@buzz.block.builderlab.xyz> Signed-off-by: Wren <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@buzz.block.builderlab.xyz> Co-authored-by: npub1jh9wn95s0472h86ahapupaf7m6kx4v9sx2n0atj2hltcfer8k06s5n3pyf <95cae996907d7cab9f5dbf43c0f53edeac6ab0b032a6feae4abfd784e467b3f5@buzz.block.builderlab.xyz> Co-authored-by: Wren <5217c5c2f7bfb4333e46d17c98a9255a52dadee18dcd43a43536b95e6776dfa0@buzz.block.builderlab.xyz>
1 parent 78267b0 commit 6ea7a2b

7 files changed

Lines changed: 202 additions & 33 deletions

File tree

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,28 @@ export type AuthOkDecision = "authenticated" | "retry" | "terminal";
2626

2727
export const MAX_CONSECUTIVE_AUTH_REJECTIONS = 3;
2828

29+
export type RelayAuthRequest = {
30+
pendingEventId: string;
31+
resolve: () => void;
32+
reject: (error: Error) => void;
33+
timeout: number;
34+
};
35+
36+
export function armRelayAuthentication(
37+
timeoutMs: number,
38+
setRequest: (request: RelayAuthRequest) => void,
39+
onTimeout: (error: Error) => void,
40+
): Promise<void> {
41+
return new Promise((resolve, reject) => {
42+
const timeout = window.setTimeout(() => {
43+
const error = new Error("Relay authentication timed out.");
44+
onTimeout(error);
45+
reject(error);
46+
}, timeoutMs);
47+
setRequest({ pendingEventId: "", resolve, reject, timeout });
48+
});
49+
}
50+
2951
/** Tracks consecutive AUTH rejections across reconnect attempts. */
3052
export class AuthOkTracker {
3153
private consecutiveRejections = 0;

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

Lines changed: 27 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,12 @@ import {
6767
STALL_IDLE_TIMEOUT_MS,
6868
} from "@/shared/api/relayClientTimings";
6969
import { closeWebSocket } from "@/shared/api/relayWebSocketClose";
70-
import { AuthOkTracker } from "@/shared/api/relayAuthPolicy";
70+
import {
71+
armRelayAuthentication,
72+
AuthOkTracker,
73+
type RelayAuthRequest,
74+
} from "@/shared/api/relayAuthPolicy";
75+
import { createRelayInboundBuffer } from "@/shared/api/relayInboundBuffer";
7176
import { buildThreadReferenceTags } from "@/features/messages/lib/threading";
7277

7378
export class RelayClient {
@@ -78,12 +83,7 @@ export class RelayClient {
7883
private reconnectWaiters = new RelayReconnectWaiters();
7984
private reconnectDelayMs = RECONNECT_BASE_DELAY_MS;
8085
private keepAliveRequested = false;
81-
private authRequest: {
82-
pendingEventId: string;
83-
resolve: () => void;
84-
reject: (error: Error) => void;
85-
timeout: number;
86-
} | null = null;
86+
private authRequest: RelayAuthRequest | null = null;
8787
private subscriptions = new Map<string, RelaySubscription>();
8888
private pendingEvents = new Map<string, PendingEvent>();
8989
private eventBuffer: Array<{ subId: string; event: RelayEvent }> = [];
@@ -96,7 +96,6 @@ export class RelayClient {
9696
private stabilityTimer: number | null = null;
9797
private visibleChannelId: string | null = null;
9898
private authOkTracker = new AuthOkTracker();
99-
10099
private terminal = false;
101100

102101
private connectionStateEmitter = new RelayConnectionStateEmitter("idle");
@@ -530,17 +529,19 @@ export class RelayClient {
530529
this.connectionStateEmitter.set(
531530
this.hasConnectedOnce ? "reconnecting" : "connecting",
532531
);
533-
534532
const generation = ++this.connectionGeneration;
535-
this.onMessageChannel = new Channel<unknown>((message) => {
536-
void this.handleWsMessage(message, generation).catch((error) => {
533+
const inbound = createRelayInboundBuffer(
534+
(message) => this.handleWsMessage(message, generation),
535+
(error) => {
537536
if (generation !== this.connectionGeneration) return;
538537
this.resetConnection(
539538
this.normalizeRelayError(error, "Relay connection errored."),
540539
);
541-
});
542-
});
543-
540+
},
541+
);
542+
this.onMessageChannel = new Channel<unknown>((message) =>
543+
inbound.receive(message),
544+
);
544545
try {
545546
if (!this.relayUrl) {
546547
this.relayUrl = await getRelayWsUrl();
@@ -556,22 +557,21 @@ export class RelayClient {
556557
}
557558
this.wsId = wsId;
558559

559-
await new Promise<void>((resolve, reject) => {
560-
const timeout = window.setTimeout(() => {
561-
const error = new Error("Relay authentication timed out.");
560+
const authentication = armRelayAuthentication(
561+
AUTH_TIMEOUT_MS,
562+
(request) => {
563+
this.authRequest = request;
564+
},
565+
(error) => {
562566
this.authRequest = null;
563567
this.resetConnection(error);
564-
reject(error);
565-
}, AUTH_TIMEOUT_MS);
566-
567-
this.authRequest = {
568-
pendingEventId: "",
569-
resolve,
570-
reject,
571-
timeout,
572-
};
573-
});
568+
},
569+
);
574570

571+
const drain = inbound.drain();
572+
await Promise.race([drain, authentication, inbound.overflow]);
573+
await drain;
574+
await authentication;
575575
this.stabilityTimer = window.setTimeout(() => {
576576
this.stabilityTimer = null;
577577
this.reconnectDelayMs = RECONNECT_BASE_DELAY_MS;
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
import {
5+
createRelayInboundBuffer,
6+
MAX_PENDING_RELAY_FRAMES,
7+
} from "./relayInboundBuffer.ts";
8+
9+
test("drains queued frames in order, including frames received during drain", async () => {
10+
const handled = [];
11+
let releaseFirst;
12+
const firstBlocked = new Promise((resolve) => {
13+
releaseFirst = resolve;
14+
});
15+
const inbound = createRelayInboundBuffer(async (message) => {
16+
handled.push(message);
17+
if (message === "first") await firstBlocked;
18+
}, assert.fail);
19+
20+
inbound.receive("first");
21+
const drain = inbound.drain();
22+
inbound.receive("second");
23+
releaseFirst();
24+
await drain;
25+
inbound.receive("live");
26+
await new Promise((resolve) => setTimeout(resolve));
27+
28+
assert.deepEqual(handled, ["first", "second", "live"]);
29+
});
30+
31+
test("rejects, resets, and stops accepting frames when the cap is exceeded", async () => {
32+
let overflowError;
33+
const inbound = createRelayInboundBuffer(
34+
async () => {},
35+
(error) => {
36+
overflowError = error;
37+
},
38+
);
39+
for (let i = 0; i < MAX_PENDING_RELAY_FRAMES + 1; i++) inbound.receive(i);
40+
41+
await assert.rejects(
42+
inbound.overflow,
43+
/Relay sent too many frames while connecting/,
44+
);
45+
assert.match(overflowError.message, /too many frames/);
46+
});
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
export const MAX_PENDING_RELAY_FRAMES = 256;
2+
3+
export function createRelayInboundBuffer(
4+
handle: (message: unknown) => Promise<void>,
5+
onError: (error: unknown) => void,
6+
) {
7+
let pending: unknown[] | null | undefined = [];
8+
let rejectOverflow = (_error: Error) => {};
9+
const overflow = new Promise<never>((_resolve, reject) => {
10+
rejectOverflow = reject;
11+
});
12+
void overflow.catch(() => {});
13+
14+
return {
15+
overflow,
16+
receive(message: unknown) {
17+
if (pending === null) {
18+
void handle(message).catch(onError);
19+
return;
20+
}
21+
if (pending === undefined) return;
22+
if (pending.length >= MAX_PENDING_RELAY_FRAMES) {
23+
pending = undefined;
24+
const error = new Error("Relay sent too many frames while connecting.");
25+
rejectOverflow(error);
26+
onError(error);
27+
return;
28+
}
29+
pending.push(message);
30+
},
31+
async drain() {
32+
while (pending?.length) await handle(pending.shift());
33+
if (pending) pending = null;
34+
},
35+
};
36+
}

‎desktop/src/testing/e2eBridge.ts‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,10 @@ type E2eConfig = {
411411
nostrBindSignDelayMs?: number;
412412
/** Reject successive mock WebSocket connect attempts, then resume. */
413413
websocketConnectErrors?: string[];
414+
/** Deliver AUTH synchronously, before the mock connect command resolves. */
415+
websocketAuthBeforeConnectResolves?: boolean;
416+
/** Stall the first AUTH signing command forever; later attempts complete. */
417+
stallFirstAuthSigning?: boolean;
414418
stallWebsocketSends?: boolean;
415419
userSearchDelayMs?: number;
416420
// NIP-IA gate inputs — see tests/helpers/bridge.ts:MockBridgeOptions for
@@ -3062,6 +3066,7 @@ const mockAuthResponses: Array<{ success: boolean; message: string }> = [];
30623066
const mockChannelHistoryCloses: string[] = [];
30633067
let mockWebsocketUnavailable = false;
30643068
const relayWebsocketConnectAttemptStarts: number[] = [];
3069+
let mockAuthSigningAttempts = 0;
30653070
let mockWebsocketSendMutexWedged = false;
30663071
let mockClosedChannelLiveSubscription = false;
30673072
const realSockets = new Map<number, WebSocket>();
@@ -9757,9 +9762,14 @@ async function connectMockSocket(args: { onMessage: unknown }) {
97579762
subscriptions: new Map(),
97589763
});
97599764

9760-
window.setTimeout(() => {
9765+
if (getConfig()?.mock?.websocketAuthBeforeConnectResolves) {
97619766
sendWsText(handler, ["AUTH", `mock-challenge-${wsId}`]);
9762-
}, 0);
9767+
await new Promise<void>((resolve) => window.setTimeout(resolve, 50));
9768+
} else {
9769+
window.setTimeout(() => {
9770+
sendWsText(handler, ["AUTH", `mock-challenge-${wsId}`]);
9771+
}, 0);
9772+
}
97639773

97649774
return wsId;
97659775
}
@@ -10248,6 +10258,7 @@ export function maybeInstallE2eTauriMocks() {
1024810258
mockAuthResponses.length = 0;
1024910259
mockChannelHistoryCloses.length = 0;
1025010260
relayWebsocketConnectAttemptStarts.length = 0;
10261+
mockAuthSigningAttempts = 0;
1025110262
deferredSendMessageLiveEchoes.length = 0;
1025210263
deferredLinkPreviewMetadataQueue = [];
1025310264
deferredLinkPreviewUploadQueue = [];
@@ -13131,6 +13142,13 @@ export function maybeInstallE2eTauriMocks() {
1313113142
case "nip44_decrypt_from_self":
1313213143
return (payload as { ciphertext: string }).ciphertext;
1313313144
case "create_auth_event":
13145+
mockAuthSigningAttempts++;
13146+
if (
13147+
getConfig()?.mock?.stallFirstAuthSigning &&
13148+
mockAuthSigningAttempts === 1
13149+
) {
13150+
return new Promise<string>(() => {});
13151+
}
1313413152
if (identity) {
1313513153
return JSON.stringify(
1313613154
await signWithIdentity(identity, {

‎desktop/tests/e2e/relay-reconnect.spec.ts‎

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,7 @@ async function getMockWebsocketConnectAttempts(
8080
) {
8181
return page.evaluate(() => {
8282
const getAttempts = window.__BUZZ_E2E_GET_WEBSOCKET_CONNECT_ATTEMPTS__;
83-
if (!getAttempts) {
84-
throw new Error("E2E websocket attempt seam is not installed.");
85-
}
86-
return getAttempts();
83+
return getAttempts?.() ?? [];
8784
});
8885
}
8986

@@ -168,6 +165,52 @@ test.beforeEach(async ({ page }) => {
168165
await installMockBridge(page);
169166
});
170167

168+
test("stalled early AUTH signing times out and starts a replacement dial", async ({
169+
page,
170+
}) => {
171+
test.setTimeout(40_000);
172+
await installMockBridge(page, {
173+
websocketAuthBeforeConnectResolves: true,
174+
stallFirstAuthSigning: true,
175+
});
176+
await page.goto("/");
177+
178+
await expect
179+
.poll(() => getMockWebsocketConnectAttempts(page), { timeout: 32_000 })
180+
.toHaveLength(2);
181+
await expect
182+
.poll(
183+
() =>
184+
page.evaluate(() => window.__BUZZ_E2E_GET_RELAY_CONNECTION_STATE__?.()),
185+
{ timeout: 5_000 },
186+
)
187+
.toBe("connected");
188+
});
189+
190+
test("AUTH arriving before connect resolves does not lose the first send", async ({
191+
page,
192+
}) => {
193+
await installMockBridge(page, {
194+
websocketAuthBeforeConnectResolves: true,
195+
});
196+
await page.goto("/");
197+
await expect
198+
.poll(
199+
() =>
200+
page.evaluate(() => window.__BUZZ_E2E_GET_RELAY_CONNECTION_STATE__?.()),
201+
{ timeout: 5_000 },
202+
)
203+
.toBe("connected");
204+
await page.getByTestId("channel-general").click();
205+
await expect(page.getByTestId("chat-title")).toHaveText("general");
206+
207+
const message = `first send after early auth ${Date.now()}`;
208+
await page.getByTestId("message-input").fill(message);
209+
await page.getByTestId("send-message").click();
210+
211+
await expect(page.getByTestId("message-timeline")).toContainText(message);
212+
});
213+
171214
test("failed initial relay dial retries automatically", async ({ page }) => {
172215
await installMockBridge(page, {
173216
websocketConnectErrors: ["mock relay pod unavailable"],

‎desktop/tests/helpers/bridge.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,10 @@ type MockBridgeOptions = {
354354
nostrBindSignDelayMs?: number;
355355
/** Reject successive mock WebSocket connect attempts, then resume. */
356356
websocketConnectErrors?: string[];
357+
/** Deliver AUTH synchronously, before the mock connect command resolves. */
358+
websocketAuthBeforeConnectResolves?: boolean;
359+
/** Stall the first AUTH signing command forever; later attempts complete. */
360+
stallFirstAuthSigning?: boolean;
357361
stallWebsocketSends?: boolean;
358362
userSearchDelayMs?: number;
359363
// NIP-IA gate inputs — drive the archive-button gate matrix in

0 commit comments

Comments
 (0)