From d5f97d20736b28ed2b0e5e54f7f07df25f240c6c Mon Sep 17 00:00:00 2001 From: Story Crater Bot <19826264+Riotpiaole@users.noreply.github.com> Date: Thu, 3 Sep 2026 20:38:42 -0700 Subject: [PATCH] fix: add error handling and local dev fallback for auth - Handle getAccessToken failure gracefully - Support LLM_API_TOKEN env var for local dev (bypasses OAuth) - Better error messages for missing credentials --- app/api/chat/route.ts | 14 ++++++++++++-- lib/auth.ts | 13 ++++++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts index 4871e9f..7cca1b1 100644 --- a/app/api/chat/route.ts +++ b/app/api/chat/route.ts @@ -135,9 +135,19 @@ GOOD example: BAD: "Rock resolved the Terraform configuration drift issue by implementing automated drift detection and real-time visibility into discrepancies..." — this is garbage. Never do this.` export async function POST(request: NextRequest) { + let token: string + + try { + token = await getAccessToken() + } catch (error) { + console.error('Failed to get access token:', error) + return new Response( + JSON.stringify({ error: 'Authentication failed - check AUTHENTIK_CLIENT_ID/SECRET' }), + { status: 500, headers: { 'Content-Type': 'application/json' } } + ) + } + try { - // Get OAuth token (cached, auto-refreshes) - const token = await getAccessToken() const { message } = await request.json() const response = await fetch(LLM_API_URL, { diff --git a/lib/auth.ts b/lib/auth.ts index f7881ed..93ce1fa 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -19,8 +19,16 @@ let cachedToken: CachedToken | null = null /** * Get a valid access token, fetching a new one if expired. * Tokens are cached with 60s buffer before expiry. + * + * For local dev: set LLM_API_TOKEN env var to skip OAuth. */ export async function getAccessToken(): Promise { + // Local dev fallback - use static token if set + const staticToken = process.env.LLM_API_TOKEN + if (staticToken) { + return staticToken + } + const now = Date.now() // Return cached token if still valid (with 60s buffer) @@ -33,7 +41,10 @@ export async function getAccessToken(): Promise { const tokenUrl = process.env.AUTHENTIK_TOKEN_URL || 'https://authentik.riotpiao.com/application/o/token/' if (!clientId || !clientSecret) { - throw new Error('AUTHENTIK_CLIENT_ID and AUTHENTIK_CLIENT_SECRET must be set') + throw new Error( + 'Missing OAuth credentials. Set AUTHENTIK_CLIENT_ID + AUTHENTIK_CLIENT_SECRET, ' + + 'or LLM_API_TOKEN for local dev.' + ) } const response = await fetch(tokenUrl, {