From ed9e39d0bd898d3b8924d97fa01d01692fa09fda Mon Sep 17 00:00:00 2001 From: Theodore Li Date: Wed, 8 Apr 2026 15:30:29 -0700 Subject: [PATCH 1/2] fix(error): catch socket auth error as 4xx --- apps/sim/app/api/auth/socket-token/route.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/apps/sim/app/api/auth/socket-token/route.ts b/apps/sim/app/api/auth/socket-token/route.ts index 2a6965ee06..ad1f1ee1ff 100644 --- a/apps/sim/app/api/auth/socket-token/route.ts +++ b/apps/sim/app/api/auth/socket-token/route.ts @@ -23,6 +23,14 @@ export async function POST() { return NextResponse.json({ token: response.token }) } catch (error) { + // better-auth's sessionMiddleware throws APIError("UNAUTHORIZED") with no message + // when the session is missing/expired — surface this as a 401, not a 500. + const apiError = error as { statusCode?: number; status?: string } + if (apiError.statusCode === 401 || apiError.status === 'UNAUTHORIZED') { + logger.warn('Socket token request with invalid/expired session') + return NextResponse.json({ error: 'Authentication required' }, { status: 401 }) + } + logger.error('Failed to generate socket token', { error: error instanceof Error ? error.message : String(error), stack: error instanceof Error ? error.stack : undefined, From ff5c846ad77987d2ca9f74acaba263f80bd82425 Mon Sep 17 00:00:00 2001 From: Theodore Li Date: Wed, 8 Apr 2026 15:58:41 -0700 Subject: [PATCH 2/2] Switch to type guard --- apps/sim/app/api/auth/socket-token/route.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/sim/app/api/auth/socket-token/route.ts b/apps/sim/app/api/auth/socket-token/route.ts index ad1f1ee1ff..810f149b8b 100644 --- a/apps/sim/app/api/auth/socket-token/route.ts +++ b/apps/sim/app/api/auth/socket-token/route.ts @@ -25,8 +25,12 @@ export async function POST() { } catch (error) { // better-auth's sessionMiddleware throws APIError("UNAUTHORIZED") with no message // when the session is missing/expired — surface this as a 401, not a 500. - const apiError = error as { statusCode?: number; status?: string } - if (apiError.statusCode === 401 || apiError.status === 'UNAUTHORIZED') { + if ( + error instanceof Error && + ('statusCode' in error || 'status' in error) && + ((error as Record).statusCode === 401 || + (error as Record).status === 'UNAUTHORIZED') + ) { logger.warn('Socket token request with invalid/expired session') return NextResponse.json({ error: 'Authentication required' }, { status: 401 }) }