Skip to content

Open source personal finance application

feat(auth): supabase email/password auth, session gate, and powersync connection driver

Ilya Komichev21798680d98f
diff --git a/app/app/composables/useAuthSession.ts b/app/app/composables/useAuthSession.ts
new file mode 100644
index 00000000..8d6e716a
--- /dev/null
+++ b/app/app/composables/useAuthSession.ts
@@ -0,0 +1,57 @@
+// The persisted Supabase session in localStorage is the synchronous "is logged in" gate:
+// readable the instant route middleware runs (before async getSession resolves), so an
+// already-logged-in user never flashes /login -> /dashboard on a cold start.
+
+// The localStorage key supabase-js persists the session under (pinned via `auth.storageKey`
+// in useSupabase) so the synchronous route gate can read it directly.
+export const AUTH_STORAGE_KEY = 'finapp.auth'
+
+type PersistedSession = {
+ // Unix seconds; null when absent. Optimistic gate: an almost-expired token still passes
+ // (autoRefreshToken + useGuard correct it later).
+ expiresAt: number | null
+ uid: string
+}
+
+/**
+ * Parse the stored token. supabase-js v2 serialises the Session directly; older gotrue shapes
+ * wrapped it in `{ currentSession }`/`{ session }`. Probe all three so a format change degrades
+ * to "logged out" rather than throwing in middleware.
+ */
+function parsePersisted(raw: string): PersistedSession | null {
+ try {
+ const data = JSON.parse(raw) as Record<string, any>
+ const s = data?.user ? data : (data?.currentSession ?? data?.session)
+ const uid = s?.user?.id
+ if (typeof uid !== 'string' || !uid)
+ return null
+ return {
+ expiresAt: typeof s?.expires_at === 'number' ? s.expires_at : null,
+ uid,
+ }
+ }
+ catch {
+ return null
+ }
+}
+
+export function getPersistedSession(): PersistedSession | null {
+ let raw: string | null = null
+ try {
+ raw = globalThis.localStorage?.getItem(AUTH_STORAGE_KEY) ?? null
+ }
+ catch {
+ return null // localStorage blocked (private mode / SSR) - treat as logged out
+ }
+ return raw ? parsePersisted(raw) : null
+}
+
+/** Optimistic synchronous gate: a stored session with a uid exists. */
+export function hasPersistedSession(): boolean {
+ return getPersistedSession() !== null
+}
+
+/** The persisted uid, available synchronously before the async session resolves. */
+export function getPersistedUid(): string | null {
+ return getPersistedSession()?.uid ?? null
+}
diff --git a/app/app/composables/useSupabase.ts b/app/app/composables/useSupabase.ts
new file mode 100644
index 00000000..09f0d64b
--- /dev/null
+++ b/app/app/composables/useSupabase.ts
@@ -0,0 +1,64 @@
+import type { AuthChangeEvent, Session, SupabaseClient } from '@supabase/supabase-js'
+
+import { createClient } from '@supabase/supabase-js'
+
+import { AUTH_STORAGE_KEY } from '~/composables/useAuthSession'
+
+// Singleton Supabase client. Sessions persist in localStorage and auto-refresh;
+// `detectSessionInUrl` is off since we use email/password (no OAuth redirect to parse).
+let _client: SupabaseClient | null = null
+
+export function useSupabase(): SupabaseClient {
+ if (_client)
+ return _client
+
+ const config = useRuntimeConfig()
+ _client = createClient(
+ config.public.supabaseUrl as string,
+ config.public.supabaseAnonKey as string,
+ {
+ auth: {
+ autoRefreshToken: true,
+ detectSessionInUrl: false,
+ persistSession: true,
+ // Fixed key the synchronous route gate (useAuthSession) reads directly.
+ storageKey: AUTH_STORAGE_KEY,
+ },
+ },
+ )
+ return _client
+}
+
+// Reactive auth state, backed by a module-level ref kept in sync via
+// onAuthStateChange. Initialized once on the client.
+const session = shallowRef<Session | null>(null)
+const isAuthReady = ref(false)
+let _authInitialized = false
+
+export function useSupabaseAuth() {
+ const client = useSupabase()
+
+ if (!_authInitialized && import.meta.client) {
+ _authInitialized = true
+ client.auth.getSession().then(({ data }) => {
+ session.value = data.session
+ isAuthReady.value = true
+ })
+ client.auth.onAuthStateChange((_event: AuthChangeEvent, next: Session | null) => {
+ session.value = next
+ isAuthReady.value = true
+ })
+ }
+
+ return {
+ isAuthReady,
+ session,
+ signInWithPassword: (email: string, password: string) =>
+ client.auth.signInWithPassword({ email, password }),
+ signOut: () => client.auth.signOut(),
+ signUp: (email: string, password: string) =>
+ client.auth.signUp({ email, password }),
+ uid: computed<string | null>(() => session.value?.user?.id ?? null),
+ user: computed(() => session.value?.user ?? null),
+ }
+}
diff --git a/app/app/middleware/auth.global.ts b/app/app/middleware/auth.global.ts
index 68b051d5..464470f5 100644
--- a/app/app/middleware/auth.global.ts
+++ b/app/app/middleware/auth.global.ts
@@ -1,84 +1,28 @@
import { useDemo } from '~/components/demo/useDemo'
-import { clearAuthCookie, hasAuthCookie, isSessionInitialized, setAuthCookie, setSessionInitialized } from '~/composables/useAuthCookie'
-import { createLogger } from '~/utils/logger'
-
-const logger = createLogger('auth/middleware')
-
-export default defineNuxtRouteMiddleware(async (to) => {
- if (to.query.ott && to.path !== '/auth/callback') {
- return navigateTo({
- path: '/auth/callback',
- query: { ott: to.query.ott },
- }, { replace: true })
- }
-
- if (to.path === '/auth/callback')
- return
+import { hasPersistedSession } from '~/composables/useAuthSession'
+// The persisted Supabase session (localStorage) is the synchronous "is logged in" gate.
+// Validity is verified asynchronously (autoRefreshToken + useGuard), so the middleware
+// only needs this optimistic check.
+export default defineNuxtRouteMiddleware((to) => {
const { isDemo } = useDemo()
+ const isLoginPage = to.path === '/login'
if (isDemo.value) {
- if (to.path === '/login') {
+ if (isLoginPage)
return navigateTo(getSafeRedirectPath(to.query.redirect))
- }
return
}
- const authClient = useAuth()
- const isLoginPage = to.path === '/login'
-
- if (hasAuthCookie()) {
- if (!isSessionInitialized() && navigator.onLine) {
- setSessionInitialized(true)
- authClient.getSession()
- .then((session) => {
- const user = session.data?.user || null
- if (!user) {
- logger.error('Background getSession: session expired, redirecting to login')
- setSessionInitialized(false)
- clearAuthCookie()
- navigateTo('/login')
- }
- })
- .catch((error) => {
- logger.error('Background getSession failed:', error)
- setSessionInitialized(false)
- })
- }
-
- if (isLoginPage) {
+ if (hasPersistedSession()) {
+ if (isLoginPage)
return navigateTo('/dashboard')
- }
return
}
if (isLoginPage)
return
- if (!navigator.onLine) {
- const redirect = to.fullPath === '/' ? undefined : { redirect: to.fullPath }
- return navigateTo({
- path: '/login',
- query: redirect,
- })
- }
-
- try {
- const session = await authClient.getSession()
- const user = session.data?.user || null
-
- if (user) {
- setAuthCookie(user.id)
- return
- }
- }
- catch (error) {
- logger.error('getSession failed (no cached auth):', error)
- }
-
const redirect = to.fullPath === '/' ? undefined : { redirect: to.fullPath }
- return navigateTo({
- path: '/login',
- query: redirect,
- })
+ return navigateTo({ path: '/login', query: redirect })
})
diff --git a/app/app/pages/login.vue b/app/app/pages/login.vue
index e12d67b7..ee3d161a 100644
--- a/app/app/pages/login.vue
+++ b/app/app/pages/login.vue
@@ -3,8 +3,9 @@ import pkg from '~~/package.json'
import { useDemo } from '~/components/demo/useDemo'
import { showErrorToast } from '~/composables/useStoreSync'
+import { useSupabaseAuth } from '~/composables/useSupabase'
-const { signIn } = useAuth()
+const { signInWithPassword, signUp } = useSupabaseAuth()
const logger = createLogger('login')
definePageMeta({
@@ -23,30 +24,32 @@ const route = useRoute()
const router = useRouter()
const isLoading = ref(false)
+const isSignUp = ref(false)
+const email = ref('')
+const password = ref('')
+
+async function submit() {
+ if (!email.value || !password.value)
+ return
-async function signInWithGoogle() {
isDemo.value = null
isLoading.value = true
- const redirectTo = getSafeRedirectPath(route.query.redirect)
- localStorage.setItem('finapp.authRedirect', redirectTo)
+ try {
+ const { error } = isSignUp.value
+ ? await signUp(email.value, password.value)
+ : await signInWithPassword(email.value, password.value)
- localStorage.removeItem('better-auth_cookie')
- localStorage.removeItem('better-auth_session_data')
+ if (error)
+ throw error
- try {
- const result = await signIn.social({
- callbackURL: `${window.location.origin}/auth/callback`,
- errorCallbackURL: `${window.location.origin}/login`,
- provider: 'google',
- })
-
- if (result.data?.url) {
- window.location.href = result.data.url
- }
+ // supabase-js has already persisted the session to localStorage by the time
+ // signIn/signUp resolves, so the synchronous route gate (hasPersistedSession)
+ // passes immediately - no need to mirror the uid anywhere before navigating.
+ router.push(getSafeRedirectPath(route.query.redirect))
}
catch (e: unknown) {
- logger.error('signIn.social error:', e)
+ logger.error('auth error:', e)
showErrorToast('login.error')
isLoading.value = false
}
@@ -89,16 +92,42 @@ async function openDemo() {
{{ t('login.description') }}
</div>
- <div class="grid min-w-[320px] items-center gap-2 py-14">
+ <form class="grid min-w-[320px] items-center gap-3 py-14" @submit.prevent="submit">
+ <UInput
+ v-model="email"
+ autocomplete="email"
+ :placeholder="t('login.email')"
+ size="xl"
+ type="email"
+ />
+ <UInput
+ v-model="password"
+ :autocomplete="isSignUp ? 'new-password' : 'current-password'"
+ :placeholder="t('login.password')"
+ size="xl"
+ type="password"
+ />
+
<UiButtonAccent
:loading="isLoading"
rounded
size="xl"
- @click="signInWithGoogle"
+ type="submit"
>
- {{ t('loginWithGoogle') }}
+ {{ isSignUp ? t('login.signUp') : t('login.signIn') }}
</UiButtonAccent>
+ <UButton
+ block
+ color="neutral"
+ size="md"
+ type="button"
+ variant="ghost"
+ @click="isSignUp = !isSignUp"
+ >
+ {{ isSignUp ? t('login.haveAccount') : t('login.noAccount') }}
+ </UButton>
+
<USeparator
:label="t('login.or')"
class="!text-muted px-3 pt-3"
@@ -107,12 +136,13 @@ async function openDemo() {
<UiButtonAccent
rounded
size="xl"
+ type="button"
variant="ghost"
@click="openDemo"
>
{{ t('login.openDemo') }}
</UiButtonAccent>
- </div>
+ </form>
</div>
</div>
diff --git a/app/app/plugins/powersync.client.ts b/app/app/plugins/powersync.client.ts
new file mode 100644
index 00000000..cdc296a0
--- /dev/null
+++ b/app/app/plugins/powersync.client.ts
@@ -0,0 +1,71 @@
+import { setUploadErrorHandler } from '~~/services/powersync/connector'
+import { connectPowerSync, disconnectPowerSync, forceResync, usePowerSyncDb } from '~~/services/powersync/db'
+import { deleteRow } from '~~/services/powersync/mutations'
+import { planDivergence } from '~~/services/powersync/uploadReconcile'
+
+import { useDemo } from '~/components/demo/useDemo'
+import { hasPersistedSession } from '~/composables/useAuthSession'
+import { showActionToast, showErrorToast } from '~/composables/useStoreSync'
+import { useSupabase, useSupabaseAuth } from '~/composables/useSupabase'
+import { createLogger } from '~/utils/logger'
+
+const logger = createLogger('powersync-plugin')
+
+export default defineNuxtPlugin(() => {
+ // Protect IndexedDB (PowerSync's local store) from eviction on low storage.
+ navigator.storage?.persist?.()
+
+ const config = useRuntimeConfig()
+ const powerSyncUrl = config.public.powersyncUrl as string
+ const client = useSupabase()
+ const { isDemo } = useDemo()
+ const { isAuthReady, uid } = useSupabaseAuth()
+
+ // Open local SQLite immediately for an already-logged-in user so the cold-start DB
+ // init overlaps app boot instead of waiting for the async session to resolve.
+ if (!isDemo.value && hasPersistedSession())
+ usePowerSyncDb().init().catch(e => logger.error('eager db init failed', e))
+
+ // Reconcile local rows after a write was fatally rejected by the server and discarded.
+ setUploadErrorHandler((_error, divergedOps) => {
+ const plan = planDivergence(divergedOps)
+ if (plan.needsReload) {
+ // Rejected UPDATE/DELETE: offer a full reload (wipe + re-pull server truth). Destructive.
+ showActionToast(
+ 'error',
+ 'sync.errors.uploadDiverged',
+ 'sync.actions.reloadFromServer',
+ () => {
+ if (uid.value)
+ void forceResync(client, powerSyncUrl, uid.value)
+ },
+ )
+ }
+ else if (plan.toRevert.length) {
+ // Rejected INSERT(s): delete the local rows to converge. Defer out of the uploadData
+ // call stack (setTimeout 0) so the new write transaction doesn't contend for the lock.
+ for (const { id, table } of plan.toRevert)
+ setTimeout(() => { void deleteRow(table, id) }, 0)
+ showErrorToast('sync.errors.uploadReverted')
+ }
+ })
+
+ // Drive the PowerSync connection from the auth session.
+ watch(
+ uid,
+ (userId) => {
+ if (isDemo.value)
+ return
+
+ if (userId) {
+ connectPowerSync(client, powerSyncUrl, userId).catch(e => logger.error('connect failed', e))
+ }
+ // Only disconnect+wipe on a genuine sign-out (auth resolved, no user). The initial
+ // null on cold start (session not resolved yet) must NOT wipe a returning user's data.
+ else if (isAuthReady.value) {
+ disconnectPowerSync().catch(e => logger.error('disconnect failed', e))
+ }
+ },
+ { immediate: true },
+ )
+})