feat(security): switch auth to HttpOnly cookies and add server actions
This commit is contained in:
143
app/actions/auth.ts
Normal file
143
app/actions/auth.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
'use server'
|
||||
|
||||
import { cookies } from 'next/headers'
|
||||
|
||||
const AUTH_API_URL = process.env.NEXT_PUBLIC_AUTH_API_URL || process.env.NEXT_PUBLIC_AUTH_URL || 'http://localhost:8081'
|
||||
|
||||
interface AuthResponse {
|
||||
access_token: string
|
||||
refresh_token: string
|
||||
id_token: string
|
||||
expires_in: number
|
||||
}
|
||||
|
||||
interface UserPayload {
|
||||
sub: string
|
||||
email?: string
|
||||
totp_enabled?: boolean
|
||||
}
|
||||
|
||||
export async function exchangeAuthCode(code: string, codeVerifier: string, redirectUri: string) {
|
||||
try {
|
||||
const res = await fetch(`${AUTH_API_URL}/oauth/token`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
client_id: 'analytics-app',
|
||||
redirect_uri: redirectUri,
|
||||
code_verifier: codeVerifier,
|
||||
}),
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json()
|
||||
throw new Error(data.error || 'Failed to exchange token')
|
||||
}
|
||||
|
||||
const data: AuthResponse = await res.json()
|
||||
|
||||
// * Decode payload (without verification, we trust the direct channel to Auth Server)
|
||||
const payloadPart = data.access_token.split('.')[1]
|
||||
const payload: UserPayload = JSON.parse(Buffer.from(payloadPart, 'base64').toString())
|
||||
|
||||
// * Set Cookies
|
||||
const cookieStore = await cookies()
|
||||
|
||||
// * Access Token
|
||||
cookieStore.set('access_token', data.access_token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: 60 * 15 // 15 minutes (short lived)
|
||||
})
|
||||
|
||||
// * Refresh Token (Long lived)
|
||||
cookieStore.set('refresh_token', data.refresh_token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24 * 30 // 30 days
|
||||
})
|
||||
|
||||
return {
|
||||
success: true,
|
||||
user: {
|
||||
id: payload.sub,
|
||||
email: payload.email || 'user@ciphera.net',
|
||||
totp_enabled: payload.totp_enabled || false
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('Auth Exchange Error:', error)
|
||||
return { success: false, error: error.message }
|
||||
}
|
||||
}
|
||||
|
||||
export async function setSessionAction(accessToken: string, refreshToken: string) {
|
||||
try {
|
||||
const payloadPart = accessToken.split('.')[1]
|
||||
const payload: UserPayload = JSON.parse(Buffer.from(payloadPart, 'base64').toString())
|
||||
|
||||
const cookieStore = await cookies()
|
||||
|
||||
cookieStore.set('access_token', accessToken, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: 60 * 15
|
||||
})
|
||||
|
||||
cookieStore.set('refresh_token', refreshToken, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24 * 30
|
||||
})
|
||||
|
||||
return {
|
||||
success: true,
|
||||
user: {
|
||||
id: payload.sub,
|
||||
email: payload.email || 'user@ciphera.net',
|
||||
totp_enabled: payload.totp_enabled || false
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
return { success: false, error: 'Invalid token' }
|
||||
}
|
||||
}
|
||||
|
||||
export async function logoutAction() {
|
||||
const cookieStore = await cookies()
|
||||
cookieStore.delete('access_token')
|
||||
cookieStore.delete('refresh_token')
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
export async function getSessionAction() {
|
||||
const cookieStore = await cookies()
|
||||
const token = cookieStore.get('access_token')
|
||||
|
||||
if (!token) return null
|
||||
|
||||
try {
|
||||
const payloadPart = token.value.split('.')[1]
|
||||
const payload: UserPayload = JSON.parse(Buffer.from(payloadPart, 'base64').toString())
|
||||
return {
|
||||
id: payload.sub,
|
||||
email: payload.email || 'user@ciphera.net',
|
||||
totp_enabled: payload.totp_enabled || false
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
50
app/api/auth/refresh/route.ts
Normal file
50
app/api/auth/refresh/route.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { cookies } from 'next/headers'
|
||||
import { NextResponse } from 'next/server'
|
||||
|
||||
const AUTH_API_URL = process.env.NEXT_PUBLIC_AUTH_API_URL || process.env.NEXT_PUBLIC_AUTH_URL || 'http://localhost:8081'
|
||||
|
||||
export async function POST() {
|
||||
const cookieStore = await cookies()
|
||||
const refreshToken = cookieStore.get('refresh_token')?.value
|
||||
|
||||
if (!refreshToken) {
|
||||
return NextResponse.json({ error: 'No refresh token' }, { status: 401 })
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`${AUTH_API_URL}/api/v1/auth/refresh`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ refresh_token: refreshToken }),
|
||||
})
|
||||
|
||||
if (!res.ok) {
|
||||
// * If refresh fails, clear cookies
|
||||
cookieStore.delete('access_token')
|
||||
cookieStore.delete('refresh_token')
|
||||
return NextResponse.json({ error: 'Refresh failed' }, { status: 401 })
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
|
||||
cookieStore.set('access_token', data.access_token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: 60 * 15
|
||||
})
|
||||
|
||||
cookieStore.set('refresh_token', data.refresh_token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 24 * 30
|
||||
})
|
||||
|
||||
return NextResponse.json({ success: true, access_token: data.access_token })
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Internal error' }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { useEffect, useState, Suspense, useRef } from 'react'
|
||||
import { useRouter, useSearchParams } from 'next/navigation'
|
||||
import { useAuth } from '@/lib/auth/context'
|
||||
import { AUTH_URL } from '@/lib/api/client'
|
||||
import { exchangeAuthCode, setSessionAction } from '@/app/actions/auth'
|
||||
|
||||
function AuthCallbackContent() {
|
||||
const router = useRouter()
|
||||
@@ -17,23 +18,24 @@ function AuthCallbackContent() {
|
||||
if (processedRef.current) return
|
||||
|
||||
// * Check for direct token passing (from auth-frontend direct login)
|
||||
// * TODO: This flow exposes tokens in URL, should be deprecated in favor of Authorization Code flow
|
||||
const token = searchParams.get('token')
|
||||
const refreshToken = searchParams.get('refresh_token')
|
||||
|
||||
if (token && refreshToken) {
|
||||
processedRef.current = true
|
||||
try {
|
||||
const payload = JSON.parse(atob(token.split('.')[1]))
|
||||
login(token, refreshToken, {
|
||||
id: payload.sub,
|
||||
email: payload.email || 'user@ciphera.net',
|
||||
totp_enabled: payload.totp_enabled || false
|
||||
})
|
||||
const returnTo = searchParams.get('returnTo') || '/'
|
||||
router.push(returnTo)
|
||||
} catch (e) {
|
||||
setError('Invalid token received')
|
||||
|
||||
const handleDirectTokens = async () => {
|
||||
const result = await setSessionAction(token, refreshToken)
|
||||
if (result.success && result.user) {
|
||||
login(result.user)
|
||||
const returnTo = searchParams.get('returnTo') || '/'
|
||||
router.push(returnTo)
|
||||
} else {
|
||||
setError('Invalid token received')
|
||||
}
|
||||
}
|
||||
handleDirectTokens()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -54,43 +56,26 @@ function AuthCallbackContent() {
|
||||
}
|
||||
|
||||
if (state !== storedState) {
|
||||
// * Debugging: Log state mismatch to help user diagnose
|
||||
console.error('State mismatch', { received: state, stored: storedState })
|
||||
setError('Invalid state')
|
||||
return
|
||||
}
|
||||
|
||||
if (!codeVerifier) {
|
||||
setError('Missing code verifier')
|
||||
return
|
||||
}
|
||||
|
||||
const exchangeCode = async () => {
|
||||
try {
|
||||
const authApiUrl = process.env.NEXT_PUBLIC_AUTH_API_URL || process.env.NEXT_PUBLIC_AUTH_URL || 'http://localhost:8081'
|
||||
const res = await fetch(`${authApiUrl}/oauth/token`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
grant_type: 'authorization_code',
|
||||
code,
|
||||
client_id: 'analytics-app',
|
||||
redirect_uri: window.location.origin + '/auth/callback',
|
||||
code_verifier: codeVerifier,
|
||||
}),
|
||||
})
|
||||
const redirectUri = window.location.origin + '/auth/callback'
|
||||
const result = await exchangeAuthCode(code, codeVerifier, redirectUri)
|
||||
|
||||
if (!res.ok) {
|
||||
const data = await res.json()
|
||||
throw new Error(data.error || 'Failed to exchange token')
|
||||
if (!result.success || !result.user) {
|
||||
throw new Error(result.error || 'Failed to exchange token')
|
||||
}
|
||||
|
||||
const data = await res.json()
|
||||
|
||||
const payload = JSON.parse(atob(data.access_token.split('.')[1]))
|
||||
|
||||
login(data.access_token, data.refresh_token, {
|
||||
id: payload.sub,
|
||||
email: payload.email || 'user@ciphera.net', // Fallback if email claim missing
|
||||
totp_enabled: payload.totp_enabled || false
|
||||
})
|
||||
login(result.user)
|
||||
|
||||
// * Cleanup
|
||||
localStorage.removeItem('oauth_state')
|
||||
|
||||
Reference in New Issue
Block a user