@@ -285,5 +285,63 @@ describe('auth.ts', () => {
285
285
} ) ;
286
286
} ) ;
287
287
} ) ;
288
+
289
+ describe ( 'when called outside of middleware' , ( ) => {
290
+ it ( 'should fall back to reading session from cookie and redirect to logout URL' , async ( ) => {
291
+ const nextCookies = await cookies ( ) ;
292
+
293
+ // Don't set x-workos-middleware header to simulate being outside middleware
294
+ // This will cause withAuth to throw
295
+
296
+ // Set up a session cookie with a valid access token
297
+ const mockSession = {
298
+ accessToken : await generateTestToken ( ) ,
299
+ refreshToken : 'refresh_token' ,
300
+ user : { id : 'user_123' } ,
301
+ } ;
302
+
303
+ const encryptedSession = await sealData ( mockSession , {
304
+ password : process . env . WORKOS_COOKIE_PASSWORD as string ,
305
+ } ) ;
306
+
307
+ nextCookies . set ( 'wos-session' , encryptedSession ) ;
308
+
309
+ jest
310
+ . spyOn ( workos . userManagement , 'getLogoutUrl' )
311
+ . mockReturnValue ( 'https://api.workos.com/user_management/sessions/logout?session_id=session_123' ) ;
312
+
313
+ await signOut ( ) ;
314
+
315
+ // Cookie should be deleted
316
+ const sessionCookie = nextCookies . get ( 'wos-session' ) ;
317
+ expect ( sessionCookie ) . toBeUndefined ( ) ;
318
+
319
+ // Should redirect to WorkOS logout URL with session ID
320
+ expect ( redirect ) . toHaveBeenCalledTimes ( 1 ) ;
321
+ expect ( redirect ) . toHaveBeenCalledWith (
322
+ 'https://api.workos.com/user_management/sessions/logout?session_id=session_123' ,
323
+ ) ;
324
+ expect ( workos . userManagement . getLogoutUrl ) . toHaveBeenCalledWith (
325
+ expect . objectContaining ( {
326
+ sessionId : expect . stringMatching ( / ^ s e s s i o n _ / ) ,
327
+ } ) ,
328
+ ) ;
329
+ } ) ;
330
+
331
+ it ( 'should throw the original error when no session cookie exists outside middleware' , async ( ) => {
332
+ const nextCookies = await cookies ( ) ;
333
+
334
+ // Don't set x-workos-middleware header to simulate being outside middleware
335
+ // Set a cookie to verify it gets deleted
336
+ nextCookies . set ( 'wos-session' , 'dummy-value' ) ;
337
+
338
+ // Should throw the error from withAuth since we can't recover
339
+ await expect ( signOut ( ) ) . rejects . toThrow ( / Y o u a r e c a l l i n g ' w i t h A u t h ' / ) ;
340
+
341
+ // Cookie should still be deleted even though it throws
342
+ const sessionCookie = nextCookies . get ( 'wos-session' ) ;
343
+ expect ( sessionCookie ) . toBeUndefined ( ) ;
344
+ } ) ;
345
+ } ) ;
288
346
} ) ;
289
347
} ) ;
0 commit comments