@usehercules/auth 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usehercules/auth",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "Authentication utilities for Hercules applications using OIDC",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -27,9 +27,9 @@
27
27
  },
28
28
  "dependencies": {
29
29
  "jwt-decode": "^4.0.0",
30
- "oidc-client-ts": "^3.4.1",
30
+ "oidc-client-ts": "^3.5.0",
31
31
  "react-oidc-context": "^3.3.1",
32
- "zod": "^4.3.6"
32
+ "zod": "^4.4.3"
33
33
  },
34
34
  "peerDependencies": {
35
35
  "convex": "^1.29.0",
@@ -38,15 +38,15 @@
38
38
  "devDependencies": {
39
39
  "@testing-library/jest-dom": "^6.9.1",
40
40
  "@testing-library/react": "^16.3.2",
41
- "@types/react": "^19.2.14",
41
+ "@types/react": "^19.2.17",
42
42
  "@types/react-dom": "^19.2.3",
43
- "convex": "^1.38.0",
44
- "jsdom": "^28.1.0",
45
- "react": "^19.2.4",
46
- "react-dom": "^19.2.4",
47
- "tsdown": "^0.18.4",
48
- "typescript": "^5.9.3",
49
- "vitest": "^4.1.0"
43
+ "convex": "^1.42.1",
44
+ "jsdom": "^29.1.1",
45
+ "react": "^19.2.7",
46
+ "react-dom": "^19.2.7",
47
+ "tsdown": "^0.22.8",
48
+ "typescript": "^6.0.3",
49
+ "vitest": "^4.1.11"
50
50
  },
51
51
  "scripts": {
52
52
  "build": "tsdown",
@@ -23,9 +23,7 @@ vi.mock("react-oidc-context", () => ({
23
23
  type CapturedUseAuth = () => {
24
24
  isLoading: boolean;
25
25
  isAuthenticated: boolean;
26
- fetchAccessToken: (args: {
27
- forceRefreshToken: boolean;
28
- }) => Promise<string | null>;
26
+ fetchAccessToken: (args: { forceRefreshToken: boolean }) => Promise<string | null>;
29
27
  };
30
28
 
31
29
  let capturedUseAuth: CapturedUseAuth | null = null;
@@ -200,11 +198,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
200
198
 
201
199
  resolveSilent?.({ id_token: "fresh-token" });
202
200
 
203
- [firstToken, secondToken, thirdToken] = await Promise.all([
204
- first,
205
- second,
206
- third,
207
- ]);
201
+ [firstToken, secondToken, thirdToken] = await Promise.all([first, second, third]);
208
202
  });
209
203
 
210
204
  expect(firstToken).toBe("fresh-token");
@@ -252,9 +246,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
252
246
  const { result, rerender } = renderUseAuth();
253
247
  const firstFetch = result.current.fetchAccessToken;
254
248
 
255
- expect(
256
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
257
- ).toBe(FIRST_TOKEN);
249
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(FIRST_TOKEN);
258
250
 
259
251
  setAuthState({
260
252
  user: {
@@ -265,9 +257,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
265
257
  rerender();
266
258
 
267
259
  expect(result.current.fetchAccessToken).toBe(firstFetch);
268
- expect(
269
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
270
- ).toBe(SECOND_TOKEN);
260
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(SECOND_TOKEN);
271
261
  });
272
262
 
273
263
  it("re-identifies fetchAccessToken when the subject changes", async () => {
@@ -285,9 +275,7 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
285
275
  });
286
276
  rerender();
287
277
 
288
- expect(
289
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
290
- ).toBe(BOB_TOKEN);
278
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(BOB_TOKEN);
291
279
  expect(result.current.fetchAccessToken).not.toBe(aliceFetch);
292
280
  });
293
281
 
@@ -313,8 +301,6 @@ describe("ConvexProviderWithHerculesAuth fetchAccessToken", () => {
313
301
  rerender();
314
302
 
315
303
  expect(result.current.fetchAccessToken).not.toBe(firstFetch);
316
- expect(
317
- await result.current.fetchAccessToken({ forceRefreshToken: false }),
318
- ).toBe(SECOND_TOKEN);
304
+ expect(await result.current.fetchAccessToken({ forceRefreshToken: false })).toBe(SECOND_TOKEN);
319
305
  });
320
306
  });
@@ -39,10 +39,7 @@ function useUseAuthFromHercules() {
39
39
  if (!forceRefreshToken) {
40
40
  return currentToken ?? null;
41
41
  }
42
- if (
43
- currentToken != null &&
44
- !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)
45
- ) {
42
+ if (currentToken != null && !tokenExpiresWithin(currentToken, REFRESH_THRESHOLD_MS)) {
46
43
  return currentToken;
47
44
  }
48
45
  if (inFlightRefresh.current) {
@@ -50,10 +47,7 @@ function useUseAuthFromHercules() {
50
47
  }
51
48
  const refresh = withRefreshLock(async () => {
52
49
  const tokenAfterLock = idTokenRef.current;
53
- if (
54
- tokenAfterLock != null &&
55
- !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)
56
- ) {
50
+ if (tokenAfterLock != null && !tokenExpiresWithin(tokenAfterLock, REFRESH_THRESHOLD_MS)) {
57
51
  return tokenAfterLock;
58
52
  }
59
53
  try {
@@ -7,10 +7,7 @@ type Queue = {
7
7
 
8
8
  const mutexes = new Map<string, Queue>();
9
9
 
10
- async function manualMutex<T>(
11
- key: string,
12
- callback: () => Promise<T>,
13
- ): Promise<T> {
10
+ async function manualMutex<T>(key: string, callback: () => Promise<T>): Promise<T> {
14
11
  return new Promise<T>((resolve, reject) => {
15
12
  const wrapped = () =>
16
13
  callback()
@@ -40,9 +37,7 @@ async function manualMutex<T>(
40
37
  });
41
38
  }
42
39
 
43
- export async function withRefreshLock<T>(
44
- callback: () => Promise<T>,
45
- ): Promise<T> {
40
+ export async function withRefreshLock<T>(callback: () => Promise<T>): Promise<T> {
46
41
  if (typeof navigator !== "undefined" && navigator.locks) {
47
42
  return navigator.locks.request(REFRESH_LOCK_KEY, callback);
48
43
  }
@@ -0,0 +1,487 @@
1
+ import { act, renderHook, waitFor } from "@testing-library/react";
2
+ import {
3
+ InMemoryWebStorage,
4
+ User,
5
+ UserManager,
6
+ WebStorageStateStore,
7
+ type NavigateParams,
8
+ type UserManagerSettings,
9
+ } from "oidc-client-ts";
10
+ import { AuthProvider, useAuth } from "react-oidc-context";
11
+ import type { PropsWithChildren } from "react";
12
+ import { afterEach, describe, expect, it, vi } from "vitest";
13
+ import { HerculesUserManager } from "./user-manager";
14
+
15
+ const AUTHORITY = "https://tenant.hercules-auth.com";
16
+ const END_SESSION = "https://auth.example.com/api/auth/oauth2/end-session";
17
+ const CLIENT_ID = "configured-client";
18
+ const RETURN_URI = "https://app.example.com";
19
+ const managers: UserManager[] = [];
20
+
21
+ function token(claims: Record<string, unknown>): string {
22
+ const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
23
+ return `${encode({ alg: "RS256" })}.${encode(claims)}.synthetic-signature`;
24
+ }
25
+
26
+ function user(idToken?: string, profile: Record<string, unknown> = {}): User {
27
+ const now = Math.floor(Date.now() / 1000);
28
+ return new User({
29
+ id_token: idToken,
30
+ access_token: "opaque-access-token",
31
+ refresh_token: "opaque-refresh-token",
32
+ token_type: "Bearer",
33
+ scope: "openid offline_access",
34
+ expires_at: now + 3600,
35
+ profile: {
36
+ iss: AUTHORITY,
37
+ aud: CLIENT_ID,
38
+ sub: "end-user",
39
+ iat: now,
40
+ exp: now + 3600,
41
+ ...profile,
42
+ },
43
+ });
44
+ }
45
+
46
+ function fixture(
47
+ settings: Partial<UserManagerSettings> = {},
48
+ Manager: typeof UserManager = HerculesUserManager,
49
+ ) {
50
+ const events: string[] = [];
51
+ const navigate = vi.fn(async (params: NavigateParams) => {
52
+ events.push("navigate");
53
+ return { url: params.url };
54
+ });
55
+ const close = vi.fn();
56
+ const navigator = {
57
+ prepare: vi.fn(async () => ({ navigate, close })),
58
+ callback: vi.fn(async () => {}),
59
+ };
60
+ const manager = new Manager(
61
+ {
62
+ authority: AUTHORITY,
63
+ client_id: CLIENT_ID,
64
+ redirect_uri: `${RETURN_URI}/auth/callback`,
65
+ post_logout_redirect_uri: RETURN_URI,
66
+ automaticSilentRenew: false,
67
+ userStore: new WebStorageStateStore({ store: new InMemoryWebStorage() }),
68
+ stateStore: new WebStorageStateStore({ store: new InMemoryWebStorage() }),
69
+ metadata: {
70
+ issuer: AUTHORITY,
71
+ authorization_endpoint: `${AUTHORITY}/api/auth/oauth2/authorize`,
72
+ end_session_endpoint: END_SESSION,
73
+ revocation_endpoint: `${AUTHORITY}/api/auth/oauth2/revoke`,
74
+ },
75
+ ...settings,
76
+ },
77
+ navigator,
78
+ navigator,
79
+ navigator,
80
+ );
81
+ manager.events.addUserUnloaded(() => {
82
+ events.push("unloaded");
83
+ });
84
+ managers.push(manager);
85
+ return { manager, navigate, close, events };
86
+ }
87
+
88
+ function navigationUrl(navigate: ReturnType<typeof fixture>["navigate"]): URL {
89
+ const params = navigate.mock.calls[0]?.[0];
90
+ expect(params).toBeDefined();
91
+ return new URL(params!.url);
92
+ }
93
+
94
+ afterEach(async () => {
95
+ for (const manager of managers.splice(0)) {
96
+ manager.stopSilentRenew();
97
+ await manager.events.unload();
98
+ }
99
+ vi.unstubAllGlobals();
100
+ });
101
+
102
+ describe("HerculesUserManager signoutRedirect", () => {
103
+ it.each([
104
+ { name: "missing", sid: undefined },
105
+ { name: "null", sid: null },
106
+ { name: "empty", sid: "" },
107
+ { name: "numeric", sid: 0 },
108
+ { name: "boolean", sid: false },
109
+ { name: "an array", sid: [] },
110
+ { name: "an object", sid: {} },
111
+ ])("uses confirmation when the literal ID-token sid is $name", async ({ sid }) => {
112
+ const { manager, navigate, events } = fixture();
113
+ const fetch = vi.fn();
114
+ vi.stubGlobal("fetch", fetch);
115
+ await manager.storeUser(user(token({ sid }), { sid: "profile-is-not-the-ID-token" }));
116
+
117
+ await manager.signoutRedirect();
118
+
119
+ const url = navigationUrl(navigate);
120
+ expect(url.origin + url.pathname).toBe(END_SESSION);
121
+ expect(url.searchParams.has("id_token_hint")).toBe(false);
122
+ expect(url.searchParams.get("client_id")).toBe(CLIENT_ID);
123
+ expect(url.searchParams.get("post_logout_redirect_uri")).toBe(RETURN_URI);
124
+ expect(await manager.getUser()).toBeNull();
125
+ expect(events).toEqual(["unloaded", "navigate"]);
126
+ expect(fetch).not.toHaveBeenCalled();
127
+ });
128
+
129
+ it("uses configured routing instead of claims in the omitted hint", async () => {
130
+ const { manager, navigate } = fixture();
131
+ await manager.storeUser(
132
+ user(token({ sid: null, iss: "https://untrusted.example.com", aud: "another-client" })),
133
+ );
134
+
135
+ await manager.signoutRedirect();
136
+
137
+ const url = navigationUrl(navigate);
138
+ expect(url.origin + url.pathname).toBe(END_SESSION);
139
+ expect(url.searchParams.get("client_id")).toBe(CLIENT_ID);
140
+ });
141
+
142
+ it("includes the configured client even without a return URI", async () => {
143
+ const { manager, navigate } = fixture({ post_logout_redirect_uri: "" });
144
+ await manager.storeUser(user(token({ sid: null })));
145
+
146
+ await manager.signoutRedirect();
147
+
148
+ const url = navigationUrl(navigate);
149
+ expect(url.searchParams.has("post_logout_redirect_uri")).toBe(false);
150
+ expect(url.searchParams.get("client_id")).toBe(CLIENT_ID);
151
+ });
152
+
153
+ it.each([
154
+ {
155
+ name: "a session-bound token whose profile omits sid",
156
+ idToken: token({ sid: "session-id" }),
157
+ extraQueryParams: {},
158
+ },
159
+ { name: "an unreadable token", idToken: "not-a-jwt", extraQueryParams: {} },
160
+ { name: "no ID token", idToken: undefined, extraQueryParams: {} },
161
+ {
162
+ name: "duplicate hints",
163
+ idToken: token({ sid: null }),
164
+ extraQueryParams: { id_token_hint: token({ sid: null }) },
165
+ },
166
+ {
167
+ name: "a different explicit client",
168
+ idToken: token({ sid: null }),
169
+ extraQueryParams: { client_id: "another-client" },
170
+ },
171
+ ])("keeps the upstream URL byte-for-byte for $name", async ({ idToken, extraQueryParams }) => {
172
+ const original = fixture({ extraQueryParams }, UserManager);
173
+ const adapted = fixture({ extraQueryParams });
174
+ await original.manager.storeUser(user(idToken));
175
+ await adapted.manager.storeUser(user(idToken));
176
+
177
+ await original.manager.signoutRedirect();
178
+ await adapted.manager.signoutRedirect();
179
+
180
+ expect(adapted.navigate.mock.calls[0]?.[0]).toEqual(original.navigate.mock.calls[0]?.[0]);
181
+ expect(adapted.events).toEqual(original.events);
182
+ });
183
+
184
+ it("leaves duplicate client IDs to existing provider validation", async () => {
185
+ const settings = {
186
+ metadata: {
187
+ issuer: AUTHORITY,
188
+ end_session_endpoint: `${END_SESSION}?client_id=${CLIENT_ID}`,
189
+ },
190
+ extraQueryParams: { client_id: CLIENT_ID },
191
+ };
192
+ const original = fixture(settings, UserManager);
193
+ const adapted = fixture(settings);
194
+ await original.manager.storeUser(user(token({ sid: null })));
195
+ await adapted.manager.storeUser(user(token({ sid: null })));
196
+
197
+ await original.manager.signoutRedirect();
198
+ await adapted.manager.signoutRedirect();
199
+
200
+ expect(adapted.navigate.mock.calls[0]?.[0]).toEqual(original.navigate.mock.calls[0]?.[0]);
201
+ });
202
+
203
+ it.each(["signoutPopup", "signoutSilent"] as const)("does not change %s", async (method) => {
204
+ const { manager, navigate } = fixture();
205
+ const idToken = token({ sid: null });
206
+ await manager.storeUser(user(idToken));
207
+
208
+ await manager[method]();
209
+
210
+ expect(navigationUrl(navigate).searchParams.get("id_token_hint")).toBe(idToken);
211
+ });
212
+
213
+ it("does not replace an explicitly supplied session-bound hint", async () => {
214
+ const { manager, navigate } = fixture();
215
+ const supplied = token({ sid: "explicit-session" });
216
+ await manager.storeUser(user(token({ sid: null })));
217
+
218
+ await manager.signoutRedirect({ id_token_hint: supplied });
219
+
220
+ expect(navigationUrl(navigate).searchParams.get("id_token_hint")).toBe(supplied);
221
+ });
222
+
223
+ it("preserves state storage, callback data, and navigator parameters", async () => {
224
+ const { manager, navigate } = fixture({ iframeScriptOrigin: "https://bridge.example.com" });
225
+ await manager.storeUser(user(token({ sid: null })));
226
+
227
+ await manager.signoutRedirect({ state: { returnTo: "/settings" }, url_state: "client-state" });
228
+
229
+ const url = navigationUrl(navigate);
230
+ const state = url.searchParams.get("state");
231
+ expect(state).toContain("client-state");
232
+ expect(navigate.mock.calls[0]?.[0].scriptOrigin).toBe("https://bridge.example.com");
233
+ const callback = await manager.signoutRedirectCallback(
234
+ `${RETURN_URI}?state=${encodeURIComponent(state!)}`,
235
+ );
236
+ expect(callback.userState).toEqual({ returnTo: "/settings" });
237
+ });
238
+
239
+ it.each([
240
+ { types: undefined, expected: ["access_token", "refresh_token"] },
241
+ { types: ["refresh_token"] as const, expected: ["refresh_token"] },
242
+ ])("preserves configured revocation order: $expected", async ({ types, expected }) => {
243
+ const { manager, navigate, events } = fixture({
244
+ revokeTokensOnSignout: true,
245
+ ...(types ? { revokeTokenTypes: [...types] } : {}),
246
+ });
247
+ const fetch = vi.fn(async (_input: unknown, init?: RequestInit) => {
248
+ const body = new URLSearchParams(String(init?.body));
249
+ events.push(`revoke:${body.get("token_type_hint")}`);
250
+ return new Response("{}", { headers: { "content-type": "application/json" } });
251
+ });
252
+ vi.stubGlobal("fetch", fetch);
253
+ await manager.storeUser(user(token({ sid: null })));
254
+
255
+ await manager.signoutRedirect();
256
+
257
+ expect(events).toEqual([...expected.map((type) => `revoke:${type}`), "unloaded", "navigate"]);
258
+ expect(navigationUrl(navigate).searchParams.has("id_token_hint")).toBe(false);
259
+ });
260
+
261
+ it("does not reread a user written after the upstream removal", async () => {
262
+ const { manager, navigate, events } = fixture();
263
+ await manager.storeUser(user(token({ sid: null })));
264
+ const readUser = vi.spyOn(manager.settings.userStore, "get");
265
+ manager.events.addUserUnloaded(async () => {
266
+ await manager.storeUser(user(token({ sid: null, iat: 2 })));
267
+ });
268
+
269
+ await manager.signoutRedirect();
270
+
271
+ expect(readUser).toHaveBeenCalledOnce();
272
+ expect(events).toEqual(["unloaded", "navigate"]);
273
+ expect(navigationUrl(navigate).searchParams.has("id_token_hint")).toBe(false);
274
+ });
275
+
276
+ it("delegates navigator failure and close to the upstream error path", async () => {
277
+ const { manager, navigate, close, events } = fixture();
278
+ const error = new Error("navigation failed");
279
+ navigate.mockRejectedValueOnce(error);
280
+ await manager.storeUser(user(token({ sid: null })));
281
+
282
+ await expect(manager.signoutRedirect()).rejects.toThrow(error);
283
+
284
+ expect(close).toHaveBeenCalledOnce();
285
+ expect(events).toEqual(["unloaded"]);
286
+ });
287
+
288
+ it("leaves loading and revocation errors inside the existing React navigator action", async () => {
289
+ const { manager, navigate, close, events } = fixture({ revokeTokensOnSignout: true });
290
+ let rejectRevocation!: (error: Error) => void;
291
+ vi.stubGlobal(
292
+ "fetch",
293
+ vi.fn(
294
+ () =>
295
+ new Promise<Response>((_resolve, reject) => {
296
+ rejectRevocation = reject;
297
+ }),
298
+ ),
299
+ );
300
+ await manager.storeUser(user(token({ sid: null })));
301
+ const { result } = renderHook(() => useAuth(), {
302
+ wrapper: ({ children }: PropsWithChildren) => (
303
+ <AuthProvider userManager={manager}>{children}</AuthProvider>
304
+ ),
305
+ });
306
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
307
+
308
+ let signout!: ReturnType<typeof manager.signoutRedirect>;
309
+ act(() => {
310
+ signout = result.current.signoutRedirect();
311
+ });
312
+ await waitFor(() => expect(result.current.activeNavigator).toBe("signoutRedirect"));
313
+ await waitFor(() => expect(rejectRevocation).toBeDefined());
314
+ await act(async () => {
315
+ rejectRevocation(new Error("revocation failed"));
316
+ await signout;
317
+ });
318
+
319
+ expect(result.current.activeNavigator).toBeUndefined();
320
+ expect(result.current.error?.source).toBe("signoutRedirect");
321
+ expect(navigate).not.toHaveBeenCalled();
322
+ expect(close).toHaveBeenCalledOnce();
323
+ expect(events).toEqual([]);
324
+ expect(await manager.getUser()).not.toBeNull();
325
+ });
326
+ });
327
+
328
+ describe("HerculesUserManager signoutRedirect inside a frame", () => {
329
+ afterEach(() => {
330
+ vi.restoreAllMocks();
331
+ });
332
+
333
+ function simulateFrame() {
334
+ vi.spyOn(window, "top", "get").mockReturnValue({} as Window);
335
+ }
336
+
337
+ function stubEndSession(events: string[]) {
338
+ const fetch = vi.fn(async (input: unknown, init?: RequestInit) => {
339
+ if (init?.mode === "no-cors") {
340
+ events.push("end-session");
341
+ } else {
342
+ events.push(`revoke:${new URLSearchParams(String(init?.body)).get("token_type_hint")}`);
343
+ }
344
+ return new Response("{}", { headers: { "content-type": "application/json" } });
345
+ });
346
+ vi.stubGlobal("fetch", fetch);
347
+ return fetch;
348
+ }
349
+
350
+ function endSessionUrl(fetch: ReturnType<typeof stubEndSession>): URL {
351
+ const call = fetch.mock.calls.find(([, init]) => init?.mode === "no-cors");
352
+ expect(call).toBeDefined();
353
+ return new URL(String(call![0]));
354
+ }
355
+
356
+ it.each([
357
+ { name: "a different top window", top: () => ({}) as Window },
358
+ {
359
+ name: "an inaccessible top window",
360
+ top: (): Window => {
361
+ throw new DOMException("Blocked a frame", "SecurityError");
362
+ },
363
+ },
364
+ ])("ends the session in the background under $name", async ({ top }) => {
365
+ vi.spyOn(window, "top", "get").mockImplementation(top);
366
+ const { manager, navigate, events } = fixture();
367
+ const fetch = stubEndSession(events);
368
+ const idToken = token({ sid: "session-id" });
369
+ await manager.storeUser(user(idToken));
370
+
371
+ await manager.signoutRedirect();
372
+
373
+ expect(navigate).not.toHaveBeenCalled();
374
+ expect(events).toEqual(["unloaded", "end-session"]);
375
+ const url = endSessionUrl(fetch);
376
+ expect(url.origin + url.pathname).toBe(END_SESSION);
377
+ expect(url.searchParams.get("id_token_hint")).toBe(idToken);
378
+ expect(url.searchParams.get("post_logout_redirect_uri")).toBe(RETURN_URI);
379
+ expect(fetch).toHaveBeenCalledWith(url.toString(), {
380
+ mode: "no-cors",
381
+ credentials: "omit",
382
+ signal: expect.any(AbortSignal),
383
+ });
384
+ expect(await manager.getUser()).toBeNull();
385
+ });
386
+
387
+ it("applies the sessionless hint transform to the background request", async () => {
388
+ simulateFrame();
389
+ const { manager, navigate, events } = fixture();
390
+ const fetch = stubEndSession(events);
391
+ await manager.storeUser(user(token({ sid: null })));
392
+
393
+ await manager.signoutRedirect();
394
+
395
+ expect(navigate).not.toHaveBeenCalled();
396
+ const url = endSessionUrl(fetch);
397
+ expect(url.searchParams.has("id_token_hint")).toBe(false);
398
+ expect(url.searchParams.get("client_id")).toBe(CLIENT_ID);
399
+ });
400
+
401
+ it("keeps navigating when the app redirects its top window", async () => {
402
+ simulateFrame();
403
+ const { manager, navigate, events } = fixture({ redirectTarget: "top" });
404
+ const fetch = stubEndSession(events);
405
+ await manager.storeUser(user(token({ sid: "session-id" })));
406
+
407
+ await manager.signoutRedirect();
408
+
409
+ expect(navigate).toHaveBeenCalledOnce();
410
+ expect(fetch).not.toHaveBeenCalled();
411
+ });
412
+
413
+ it("keeps configured revocation before the background request", async () => {
414
+ simulateFrame();
415
+ const { manager, navigate, events } = fixture({ revokeTokensOnSignout: true });
416
+ stubEndSession(events);
417
+ await manager.storeUser(user(token({ sid: "session-id" })));
418
+
419
+ await manager.signoutRedirect();
420
+
421
+ expect(navigate).not.toHaveBeenCalled();
422
+ expect(events).toEqual([
423
+ "revoke:access_token",
424
+ "revoke:refresh_token",
425
+ "unloaded",
426
+ "end-session",
427
+ ]);
428
+ });
429
+
430
+ it("signs out locally when the background request fails", async () => {
431
+ simulateFrame();
432
+ const { manager, close, events } = fixture();
433
+ vi.stubGlobal(
434
+ "fetch",
435
+ vi.fn(async () => {
436
+ throw new TypeError("Failed to fetch");
437
+ }),
438
+ );
439
+ await manager.storeUser(user(token({ sid: "session-id" })));
440
+
441
+ await expect(manager.signoutRedirect()).resolves.toBeUndefined();
442
+
443
+ expect(close).not.toHaveBeenCalled();
444
+ expect(events).toEqual(["unloaded"]);
445
+ expect(await manager.getUser()).toBeNull();
446
+ });
447
+
448
+ it("stops waiting for a background request that hangs", async () => {
449
+ simulateFrame();
450
+ const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(AbortSignal.abort());
451
+ const { manager, events } = fixture();
452
+ vi.stubGlobal(
453
+ "fetch",
454
+ vi.fn(async (_input: unknown, init?: RequestInit) => {
455
+ init?.signal?.throwIfAborted();
456
+ return new Promise<Response>(() => {});
457
+ }),
458
+ );
459
+ await manager.storeUser(user(token({ sid: "session-id" })));
460
+
461
+ await expect(manager.signoutRedirect()).resolves.toBeUndefined();
462
+
463
+ expect(timeout).toHaveBeenCalledWith(5000);
464
+ expect(events).toEqual(["unloaded"]);
465
+ });
466
+
467
+ it("settles the React navigator action as signed out", async () => {
468
+ simulateFrame();
469
+ const { manager, events } = fixture();
470
+ stubEndSession(events);
471
+ await manager.storeUser(user(token({ sid: "session-id" })));
472
+ const { result } = renderHook(() => useAuth(), {
473
+ wrapper: ({ children }: PropsWithChildren) => (
474
+ <AuthProvider userManager={manager}>{children}</AuthProvider>
475
+ ),
476
+ });
477
+ await waitFor(() => expect(result.current.isAuthenticated).toBe(true));
478
+
479
+ await act(async () => {
480
+ await result.current.signoutRedirect();
481
+ });
482
+
483
+ expect(result.current.isAuthenticated).toBe(false);
484
+ expect(result.current.activeNavigator).toBeUndefined();
485
+ expect(result.current.error).toBeUndefined();
486
+ });
487
+ });