security: migrate auth tokens to httpOnly cookies (hybrid bearer token approach)

Backend:
- CookieBearerToken middleware reads httpOnly cookie and injects Authorization
  header before Sanctum validates (prepended to API middleware group)
- SetAuthCookie trait provides cookie creation/expiry helpers with per-app
  cookie names (crewli_admin_token, crewli_app_token, crewli_portal_token)
- LoginController sets token via Set-Cookie, removes it from JSON body
- LogoutController expires the auth cookie on logout
- AuthRefreshController (POST /auth/refresh) rotates tokens with new cookie
- InvitationController accept also sets token via cookie, not JSON body
- All cookies: httpOnly, SameSite=Strict, Secure (in production)

Frontend (all three SPAs):
- Removed all localStorage token storage (apps/app, apps/portal)
- Removed all JS-readable cookie token storage (apps/admin)
- Removed Authorization: Bearer header interceptors from axios
- Auth stores now rely on GET /auth/me to validate httpOnly cookie
- Admin app: new Pinia auth store replaces useCookie-based auth pattern
- withCredentials: true ensures browser sends cookies automatically

Fixes security findings A13-1 (localStorage tokens) and A13-2 (admin
cookie flags). Tokens are now invisible to JavaScript.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-14 16:06:44 +02:00
parent 836cffa232
commit 513ca519b2
32 changed files with 826 additions and 227 deletions

View File

@@ -13,7 +13,7 @@ export function useLogin() {
return data
},
onSuccess: (data) => {
authStore.setToken(data.data.token)
// Token is set automatically via httpOnly Set-Cookie header
authStore.setUser(data.data.user)
queryClient.setQueryData(['auth', 'me'], data.data.user)
},

View File

@@ -1,6 +1,5 @@
import axios from 'axios'
import type { AxiosInstance, InternalAxiosRequestConfig } from 'axios'
import { useAuthStore } from '@/stores/useAuthStore'
import { useNotificationStore } from '@/stores/useNotificationStore'
import { useOrganisationStore } from '@/stores/useOrganisationStore'
@@ -16,13 +15,8 @@ const apiClient: AxiosInstance = axios.create({
apiClient.interceptors.request.use(
(config: InternalAxiosRequestConfig) => {
const authStore = useAuthStore()
const orgStore = useOrganisationStore()
if (authStore.token) {
config.headers.Authorization = `Bearer ${authStore.token}`
}
if (orgStore.activeOrganisationId) {
config.headers['X-Organisation-Id'] = orgStore.activeOrganisationId
}
@@ -53,16 +47,13 @@ apiClient.interceptors.response.use(
const notificationStore = useNotificationStore()
if (status === 401) {
const authStore = useAuthStore()
// During initialization, let initialize() handle the 401 — skip redirect
if (authStore.isInitialized) {
authStore.logout()
if (typeof window !== 'undefined' && window.location.pathname !== '/login') {
window.location.href = '/login'
// Lazy import to avoid circular dependency
import('@/stores/useAuthStore').then(({ useAuthStore }) => {
const authStore = useAuthStore()
if (authStore.isInitialized) {
authStore.handleUnauthorized()
}
}
})
}
else if (status === 403) {
notificationStore.show('You don\'t have permission for this action.', 'error')

View File

@@ -64,7 +64,7 @@ function onSubmit() {
{ token: token.value, ...payload },
{
onSuccess: (response) => {
authStore.setToken(response.data.token)
// Token is set automatically via httpOnly Set-Cookie header
authStore.setUser(response.data.user)
router.replace('/dashboard')
},

View File

@@ -4,18 +4,14 @@ import { apiClient } from '@/lib/axios'
import { useOrganisationStore } from '@/stores/useOrganisationStore'
import type { MeResponse, Organisation, User } from '@/types/auth'
const TOKEN_KEY = 'crewli_token'
export const useAuthStore = defineStore('auth', () => {
const token = ref<string | null>(localStorage.getItem(TOKEN_KEY))
const user = ref<User | null>(null)
const organisations = ref<Organisation[]>([])
const appRoles = ref<string[]>([])
const permissions = ref<string[]>([])
const isInitialized = ref(false)
// Requires both a token AND a validated user — token alone is not enough
const isAuthenticated = computed(() => !!token.value && !!user.value)
const isAuthenticated = computed(() => !!user.value)
const isSuperAdmin = computed(() => appRoles.value?.includes('super_admin') ?? false)
const currentOrganisation = computed(() => {
@@ -25,11 +21,6 @@ export const useAuthStore = defineStore('auth', () => {
?? null
})
function setToken(newToken: string) {
token.value = newToken
localStorage.setItem(TOKEN_KEY, newToken)
}
function setUser(me: MeResponse) {
user.value = {
id: me.id,
@@ -57,21 +48,40 @@ export const useAuthStore = defineStore('auth', () => {
orgStore.setActiveOrganisation(id)
}
function logout() {
token.value = null
function clearState() {
user.value = null
organisations.value = []
appRoles.value = []
permissions.value = []
localStorage.removeItem(TOKEN_KEY)
const orgStore = useOrganisationStore()
orgStore.clear()
}
function handleUnauthorized() {
clearState()
isInitialized.value = false
if (typeof window !== 'undefined' && window.location.pathname !== '/login') {
window.location.href = '/login'
}
}
async function logout() {
try {
await apiClient.post('/auth/logout')
}
catch {
// Ignore network errors; still clear local state
}
finally {
clearState()
}
}
/**
* Called once on app startup. If a token exists in localStorage,
* validates it by calling GET /auth/me. On 401, clears everything.
* Called once on app startup. Validates the httpOnly cookie by calling
* GET /auth/me. On 401, clears everything.
* Safe to call multiple times — subsequent calls return the same promise.
*/
let initializePromise: Promise<void> | null = null
@@ -85,18 +95,13 @@ export const useAuthStore = defineStore('auth', () => {
}
async function doInitialize(): Promise<void> {
if (!token.value) {
isInitialized.value = true
return
}
try {
const { data } = await apiClient.get<{ success: boolean; data: MeResponse }>('/auth/me')
setUser(data.data)
}
catch {
// Token invalid/expired — clear everything
logout()
// Cookie invalid/expired or not present — clear everything
clearState()
}
finally {
isInitialized.value = true
@@ -104,7 +109,6 @@ export const useAuthStore = defineStore('auth', () => {
}
return {
token,
user,
organisations,
appRoles,
@@ -113,10 +117,10 @@ export const useAuthStore = defineStore('auth', () => {
isInitialized,
isSuperAdmin,
currentOrganisation,
setToken,
setUser,
setActiveOrganisation,
logout,
handleUnauthorized,
initialize,
}
})

View File

@@ -39,7 +39,6 @@ export interface LoginResponse {
success: boolean
data: {
user: MeResponse
token: string
}
message: string
}

View File

@@ -83,7 +83,6 @@ export interface AcceptInvitationResponse {
app_roles: string[]
permissions: string[]
}
token: string
}
message: string
}