Skip to content

Open source personal finance application

refactor(auth): clean up auth chain — remove dead code, fix security, deduplicate origins

Ilya Komichev70635b3afcd3
diff --git a/app/components/user/useUserStore.ts b/app/components/user/useUserStore.ts
index 632cf345..1e803314 100644
--- a/app/components/user/useUserStore.ts
+++ b/app/components/user/useUserStore.ts
@@ -222,10 +222,6 @@ export const useUserStore = defineStore('user', () => {
walletsStore.setWallets(null)
useTrnsFormStore().$reset()
- categoriesStore.cancelPersist()
- trnsStore.cancelPersist()
- walletsStore.cancelPersist()
-
const { clearOfflineQueue, setOfflineQueueUserId } = await import('~/components/offline/helpers')
await clearOfflineQueue()
diff --git a/app/middleware/auth.global.ts b/app/middleware/auth.global.ts
index f0116b8b..e44e4219 100644
--- a/app/middleware/auth.global.ts
+++ b/app/middleware/auth.global.ts
@@ -81,6 +81,10 @@ export default defineNuxtRouteMiddleware(async (to) => {
return
}
+ // No cached auth on login page — nothing to verify, let user through.
+ if (isLoginPage)
+ return
+
// No cached auth: must verify (blocking)
try {
const session = await authClient.getSession()
@@ -88,21 +92,16 @@ export default defineNuxtRouteMiddleware(async (to) => {
if (user) {
setAuthCookie(user.id)
- if (isLoginPage) {
- return navigateTo('/dashboard')
- }
return
}
}
catch (error) {
- logger.error(' getSession failed (no cached auth):', error)
+ logger.error('getSession failed (no cached auth):', error)
}
- if (!isLoginPage) {
- const redirect = to.fullPath === '/' ? undefined : { redirect: to.fullPath }
- return navigateTo({
- path: '/login',
- query: redirect,
- })
- }
+ const redirect = to.fullPath === '/' ? undefined : { redirect: to.fullPath }
+ return navigateTo({
+ path: '/login',
+ query: redirect,
+ })
})
diff --git a/app/pages/auth/callback.vue b/app/pages/auth/callback.vue
index 442fdfbb..060b85bd 100644
--- a/app/pages/auth/callback.vue
+++ b/app/pages/auth/callback.vue
@@ -1,4 +1,5 @@
<script setup lang="ts">
+import { hasAuthCookie } from '~/composables/useAuthCookie'
import { showErrorToast } from '~/composables/useStoreSync'
definePageMeta({
@@ -15,12 +16,17 @@ onMounted(async () => {
return
}
- const authClient = useAuth()
+ // Service worker can replay callback navigation after the first run already
+ // succeeded. If auth cookie is set, the first callback already completed —
+ // skip verify and redirect to the app.
+ if (hasAuthCookie()) {
+ const redirectTo = getSafeRedirectPath(localStorage.getItem('finapp.authRedirect'))
+ localStorage.removeItem('finapp.authRedirect')
+ window.location.href = redirectTo
+ return
+ }
- // Do NOT clear localStorage here — the cross-domain client's onSuccess hook
- // will overwrite stale cookies with fresh ones from the verify response.
- // Clearing here is dangerous because service worker can replay the callback
- // navigation, and the second run would delete cookies written by the first.
+ const authClient = useAuth()
try {
const result = await authClient.$fetch<{
diff --git a/app/pages/login.vue b/app/pages/login.vue
index 5b0bbb99..cfeba542 100644
--- a/app/pages/login.vue
+++ b/app/pages/login.vue
@@ -18,10 +18,9 @@ useSeoMeta({
title: t('login.title'),
})
-const { generateDemoData } = useDemo()
+const { generateDemoData, isDemo } = useDemo()
const route = useRoute()
const router = useRouter()
-const { isDemo } = useDemo()
const isLoading = ref(false)
diff --git a/app/plugins/convex.ts b/app/plugins/convex.ts
index f63aaa0e..88a72f5c 100644
--- a/app/plugins/convex.ts
+++ b/app/plugins/convex.ts
@@ -37,13 +37,22 @@ export default defineNuxtPlugin(() => {
const timeout = setTimeout(() => controller.abort(), 5000)
try {
- // Use raw fetch with explicit cookie forwarding — bypasses
- // authClient.$fetch pipeline to isolate the issue.
+ // Use raw fetch with explicit cookie forwarding — cross-domain
+ // client stores cookies in localStorage, not document.cookie.
const raw = localStorage.getItem('better-auth_cookie')
if (!raw)
return null
- const parsed = JSON.parse(raw) as Record<string, { value?: string }>
+ let parsed: Record<string, { value?: string }>
+ try {
+ parsed = JSON.parse(raw)
+ }
+ catch {
+ return null
+ }
+
+ if (!parsed || typeof parsed !== 'object')
+ return null
const cookieStr = Object.entries(parsed)
.filter(([, val]) => val?.value)
.map(([key, val]) => `${key}=${val!.value}`)
@@ -61,7 +70,7 @@ export default defineNuxtPlugin(() => {
if (forceRefreshToken)
url.searchParams.set('forceRefresh', 'true')
- const res = await fetch(url.toString(), {
+ const res = await fetch(url, {
credentials: 'omit',
headers: {
'Better-Auth-Cookie': cookieStr,
@@ -92,20 +101,7 @@ export default defineNuxtPlugin(() => {
if (!hasAuthCookie())
return null
- try {
- return await fetchConvexToken(forceRefreshToken)
- }
- catch (error) {
- logger.error('fetchToken failed, retrying:', error)
- try {
- await new Promise(r => setTimeout(r, 1000))
- return await fetchConvexToken(forceRefreshToken)
- }
- catch {
- logger.error('fetchToken retry failed')
- return null
- }
- }
+ return fetchConvexToken(forceRefreshToken)
}
// Only set auth when user is logged in to avoid 401 in console
diff --git a/convex/_generated/api.d.ts b/convex/_generated/api.d.ts
index 7391bdce..9192605f 100644
--- a/convex/_generated/api.d.ts
+++ b/convex/_generated/api.d.ts
@@ -13,6 +13,7 @@ import type * as categories from "../categories.js";
import type * as crons from "../crons.js";
import type * as http from "../http.js";
import type * as migrate from "../migrate.js";
+import type * as origins from "../origins.js";
import type * as rates from "../rates.js";
import type * as shared from "../shared.js";
import type * as trns from "../trns.js";
@@ -33,6 +34,7 @@ declare const fullApi: ApiFromModules<{
crons: typeof crons;
http: typeof http;
migrate: typeof migrate;
+ origins: typeof origins;
rates: typeof rates;
shared: typeof shared;
trns: typeof trns;
diff --git a/convex/auth.ts b/convex/auth.ts
index a095b064..a3ed9cae 100644
--- a/convex/auth.ts
+++ b/convex/auth.ts
@@ -10,17 +10,11 @@ import type { DataModel } from './_generated/dataModel'
import { components } from './_generated/api'
import { query } from './_generated/server'
import authConfig from './auth.config'
+import { frontendOrigins } from './origins'
const siteUrl = process.env.SITE_URL!
const frontendUrl = process.env.FRONTEND_URL || 'http://localhost:3050'
-const trustedOrigins = [
- 'https://finapp.ilko.me',
- 'https://finapp-git-convex-ilkome2.vercel.app',
- 'https://main-git-convex-ilkome2.vercel.app',
- 'http://localhost:3050',
-]
-
export const authComponent = createClient<DataModel>(components.betterAuth)
function createAuth(ctx: GenericCtx<DataModel>) {
@@ -57,7 +51,7 @@ function createAuth(ctx: GenericCtx<DataModel>) {
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
},
},
- trustedOrigins,
+ trustedOrigins: frontendOrigins,
})
}
diff --git a/convex/http.ts b/convex/http.ts
index 6415e11a..1c292c41 100644
--- a/convex/http.ts
+++ b/convex/http.ts
@@ -1,22 +1,19 @@
import { httpRouter } from 'convex/server'
import { authComponent, createAuth } from './auth'
+import { frontendOrigins } from './origins'
const http = httpRouter()
authComponent.registerRoutes(http, createAuth, {
cors: {
allowedOrigins: [
- 'https://finapp.ilko.me',
- 'https://finapp-git-convex-ilkome2.vercel.app',
- 'https://main-git-convex-ilkome2.vercel.app',
- 'https://tacit-kingfisher-781.convex.site',
- 'https://tacit-kingfisher-781.convex.cloud',
+ ...frontendOrigins,
+ // Convex deployment origins (needed for CORS on auth HTTP actions)
'https://frugal-hornet-995.eu-west-1.convex.site',
'https://frugal-hornet-995.eu-west-1.convex.cloud',
'https://proficient-elk-135.eu-west-1.convex.site',
'https://proficient-elk-135.eu-west-1.convex.cloud',
- 'http://localhost:3050',
],
},
})
diff --git a/convex/origins.ts b/convex/origins.ts
new file mode 100644
index 00000000..5e554815
--- /dev/null
+++ b/convex/origins.ts
@@ -0,0 +1,6 @@
+export const frontendOrigins = [
+ 'https://finapp.ilko.me',
+ 'https://finapp-git-convex-ilkome2.vercel.app',
+ 'https://main-git-convex-ilkome2.vercel.app',
+ 'http://localhost:3050',
+]