Open source personal finance application
feat(auth): add google oauth sign-in
Ilya Komichev2ed468e53f8b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7159c6ea..fa5eb0b8 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,6 +1,6 @@# Finapp-Personal finance app. Nuxt 4, Vue 3, Pinia, @nuxt/ui v4 (Tailwind CSS v4), Supabase (Postgres) backend, PowerSync offline-first sync, Supabase Auth (email/password). Repo is a pnpm monorepo: `app/` (`@finapp/app`, Nuxt source under `app/app/`, Supabase config under `app/supabase/`, self-hosted PowerSync under `app/powersync/`) and `docs/` (`@finapp/docs`).+Personal finance app. Nuxt 4, Vue 3, Pinia, @nuxt/ui v4 (Tailwind CSS v4), Supabase (Postgres) backend, PowerSync offline-first sync, Supabase Auth (email/password + Google OAuth). Repo is a pnpm monorepo: `app/` (`@finapp/app`, Nuxt source under `app/app/`, Supabase config under `app/supabase/`, self-hosted PowerSync under `app/powersync/`) and `docs/` (`@finapp/docs`).- Node.js >= v24.12.0- Package manager: pnpm@@ -38,8 +38,8 @@ Personal finance app. Nuxt 4, Vue 3, Pinia, @nuxt/ui v4 (Tailwind CSS v4), Supab### Client data layer- `app/services/powersync/` - `AppSchema.ts` (client SQLite schema), `db.ts` (the `PowerSyncDatabase` singleton + `connectPowerSync` / `watchTable` / `waitForFirstSync`), `connector.ts` (`SupabaseConnector`: `fetchCredentials` + `uploadData`), `transforms.ts` (row↔item: booleans 0/1, `parentId` null↔0, `rates` JSON), `mutations.ts` (`upsertRow` / `deleteRow` - INSERT/UPDATE, never `ON CONFLICT`, since PowerSync tables are views).-- `app/app/composables/useSupabase.ts` - the supabase-js client + `useSupabaseAuth()` (reactive session, sign in/up/out).-- `app/app/plugins/powersync.client.ts` - connects PowerSync when a session resolves; sets the `finapp.localAuthUid` cookie (the synchronous route-guard gate).+- `app/app/composables/useSupabase.ts` - the supabase-js client + `useSupabaseAuth()` (reactive session, `signInWithPassword` / `signUp` / `signInWithGoogle` / `signOut`). `detectSessionInUrl: true` so the Google OAuth PKCE `?code=` is exchanged on return to `/login` (handled in `login.vue`).+- `app/app/plugins/powersync.client.ts` - eagerly opens local SQLite for an already-logged-in user, then connects/disconnects PowerSync as the auth session (`uid`) resolves. The synchronous route-guard gate is `hasPersistedSession()` (`app/app/composables/useAuthSession.ts`), which reads the persisted Supabase session from localStorage directly - no cookie.- Stores hydrate via `db.watch('SELECT * FROM ...')` (one subscription handles both initial load and realtime, local + synced) and write via `upsertRow`/`deleteRow`. Demo mode bypasses PowerSync and uses in-memory + localforage.## Documentationdiff --git a/README.md b/README.mdindex 0b31d813..d5ff7015 100644--- a/README.md+++ b/README.md@@ -134,7 +134,28 @@ docker exec -i supabase_db_app psql -U postgres -d postgres < supabase/powersyncdocker compose -f powersync/docker-compose.yaml up -d```-Auth is Supabase email/password. Sign up a new account from the login screen, or create one with the Supabase CLI.+Auth supports **email/password** and **Sign in with Google**. Email/password works out of the box - sign up from the login screen, or create an account with the Supabase CLI.++### Google sign-in (optional, local)++The login screen shows a **Sign in with Google** button. To make it work against the local stack:++1. In the [Google Cloud Console](https://console.cloud.google.com/apis/credentials), create an **OAuth 2.0 Client ID** (Web application) and add the local Supabase callback as an authorized redirect URI:++ ```text+ http://127.0.0.1:54321/auth/v1/callback+ ```++2. Put the client id/secret in `app/.env` (the Supabase CLI loads `.env` from the directory you run it in; these feed `env()` in `app/supabase/config.toml` and are **not** shipped to the client):++ ```bash+ SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID=your_google_client_id+ SUPABASE_AUTH_EXTERNAL_GOOGLE_SECRET=your_google_client_secret+ ```++3. Restart Supabase so it re-reads the config and env (`supabase stop && supabase start`).++The Google provider is already enabled in `app/supabase/config.toml` (`[auth.external.google]`, `skip_nonce_check = true` for local). Leaving the env vars empty just keeps the button non-functional - email/password still works. For **production**, configure Google in the hosted Supabase dashboard instead (see [Deployment](docs/content/en/2.development/05.deployment.md)).### Environment filesdiff --git a/app/.env.example b/app/.env.exampleindex 52d35d36..cf0296e7 100644--- a/app/.env.example+++ b/app/.env.example@@ -3,3 +3,10 @@ VITE_SUPABASE_URL=VITE_SUPABASE_ANON_KEY=# PowerSync service URL.VITE_POWERSYNC_URL=++# Google OAuth client (Google Cloud Console). Consumed by the local Supabase Auth server via+# env() substitution in supabase/config.toml - NOT shipped to the client. Leave empty to keep+# the Google button disabled locally (email/password still works). For prod, set the provider in+# the Supabase dashboard instead.+SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID=+SUPABASE_AUTH_EXTERNAL_GOOGLE_SECRET=diff --git a/app/app/composables/useSupabase.ts b/app/app/composables/useSupabase.tsindex 09f0d64b..5a2999c8 100644--- a/app/app/composables/useSupabase.ts+++ b/app/app/composables/useSupabase.ts@@ -4,8 +4,9 @@ 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).+// Singleton Supabase client. Sessions persist in localStorage and auto-refresh.+// `detectSessionInUrl` is on so the PKCE `?code=` from the Google OAuth redirect is+// exchanged for a session on return; it's a no-op on normal loads (no code param).let _client: SupabaseClient | null = nullexport function useSupabase(): SupabaseClient {@@ -19,7 +20,7 @@ export function useSupabase(): SupabaseClient {{auth: {autoRefreshToken: true,- detectSessionInUrl: false,+ detectSessionInUrl: true,persistSession: true,// Fixed key the synchronous route gate (useAuthSession) reads directly.storageKey: AUTH_STORAGE_KEY,@@ -53,6 +54,11 @@ export function useSupabaseAuth() {return {isAuthReady,session,+ // OAuth redirect flow: supabase-js stores a PKCE verifier and navigates to Google.+ // On return, `detectSessionInUrl` exchanges the code (see login.vue). `redirectTo` must+ // be allow-listed in Supabase auth config (config.toml additional_redirect_urls / dashboard).+ signInWithGoogle: (redirectTo: string) =>+ client.auth.signInWithOAuth({ options: { redirectTo }, provider: 'google' }),signInWithPassword: (email: string, password: string) =>client.auth.signInWithPassword({ email, password }),signOut: () => client.auth.signOut(),diff --git a/app/app/pages/login.vue b/app/app/pages/login.vueindex ee3d161a..1afc1062 100644--- a/app/app/pages/login.vue+++ b/app/app/pages/login.vue@@ -5,7 +5,7 @@ import { useDemo } from '~/components/demo/useDemo'import { showErrorToast } from '~/composables/useStoreSync'import { useSupabaseAuth } from '~/composables/useSupabase'-const { signInWithPassword, signUp } = useSupabaseAuth()+const { session, signInWithGoogle, signInWithPassword, signUp } = useSupabaseAuth()const logger = createLogger('login')definePageMeta({@@ -28,6 +28,10 @@ const isSignUp = ref(false)const email = ref('')const password = ref('')+// Set right before redirecting to Google, read on return: marks this load as the OAuth callback.+const OAUTH_PENDING_KEY = 'finapp.oauthPending'+const isOauthReturn = ref(false)+async function submit() {if (!email.value || !password.value)return@@ -55,11 +59,64 @@ async function submit() {}}+async function onGoogle() {+ isDemo.value = null+ isLoading.value = true++ try {+ const redirect = getSafeRedirectPath(route.query.redirect)+ const base = `${window.location.origin}/login`+ const redirectTo = redirect === '/dashboard'+ ? base+ : `${base}?redirect=${encodeURIComponent(redirect)}`++ // Survives the full-page redirect to Google and back (detectSessionInUrl can strip ?code= before we read it).+ sessionStorage.setItem(OAUTH_PENDING_KEY, '1')++ const { error } = await signInWithGoogle(redirectTo)+ if (error)+ throw error+ // Success: the browser is already navigating to Google; keep the spinner.+ }+ catch (e: unknown) {+ sessionStorage.removeItem(OAUTH_PENDING_KEY)+ logger.error('google auth error:', e)+ showErrorToast('login.error')+ isLoading.value = false+ }+}+async function openDemo() {isDemo.value = 'true'await generateDemoData(locale.value)router.push(getSafeRedirectPath(route.query.redirect))}++// Returning from Google: detectSessionInUrl exchanges the ?code= asynchronously; hold the spinner,+// then navigate once the session lands. Denied consent / provider errors come back as ?error=.+onMounted(() => {+ const params = new URLSearchParams(window.location.search)+ const pending = sessionStorage.getItem(OAUTH_PENDING_KEY) === '1'++ if (params.has('error')) {+ sessionStorage.removeItem(OAUTH_PENDING_KEY)+ logger.error('google auth error:', params.get('error_description') ?? params.get('error'))+ showErrorToast('login.error')+ return+ }++ if (pending || params.has('code')) {+ isOauthReturn.value = true+ isLoading.value = true+ }+})++watch(session, (next) => {+ if (next && isOauthReturn.value) {+ sessionStorage.removeItem(OAUTH_PENDING_KEY)+ router.replace(getSafeRedirectPath(route.query.redirect))+ }+}, { immediate: true })</script><template>@@ -93,6 +150,24 @@ async function openDemo() {</div><form class="grid min-w-[320px] items-center gap-3 py-14" @submit.prevent="submit">+ <UButton+ block+ color="neutral"+ icon="mdi:google"+ :loading="isLoading"+ size="xl"+ type="button"+ variant="subtle"+ @click="onGoogle"+ >+ {{ t('login.signInWithGoogle') }}+ </UButton>++ <USeparator+ :label="t('login.or')"+ class="!text-muted px-3 pb-3"+ />+<UInputv-model="email"autocomplete="email"diff --git a/app/i18n/locales/en-US.js b/app/i18n/locales/en-US.jsindex 8d632665..0c286ec9 100644--- a/app/i18n/locales/en-US.js+++ b/app/i18n/locales/en-US.js@@ -244,6 +244,7 @@ export default {or: 'or',password: 'Password',signIn: 'Sign in',+ signInWithGoogle: 'Sign in with Google',signUp: 'Sign up',title: 'Login',},diff --git a/app/i18n/locales/ru-RU.js b/app/i18n/locales/ru-RU.jsindex 6eace90e..fd6693ee 100644--- a/app/i18n/locales/ru-RU.js+++ b/app/i18n/locales/ru-RU.js@@ -244,6 +244,7 @@ export default {or: 'или',password: 'Пароль',signIn: 'Войти',+ signInWithGoogle: 'Войти через Google',signUp: 'Регистрация',title: 'Вход',},diff --git a/app/supabase/config.toml b/app/supabase/config.tomlindex 6a14357e..0fc540d4 100644--- a/app/supabase/config.toml+++ b/app/supabase/config.toml@@ -151,11 +151,12 @@ max_indexes = 5enabled = true# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used# in emails.-site_url = "http://127.0.0.1:3000"+site_url = "http://localhost:3050"# The public URL that Auth serves on. Defaults to the API external URL with `/auth/v1` appended.# external_url = ""# A list of *exact* URLs that auth providers are permitted to redirect to post authentication.-additional_redirect_urls = ["https://127.0.0.1:3000"]+# `/**` wildcards cover the OAuth return at /login?redirect=... (the dev server runs on :3050).+additional_redirect_urls = ["http://localhost:3050", "http://localhost:3050/**", "http://127.0.0.1:3050", "http://127.0.0.1:3050/**"]# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week).jwt_expiry = 3600# JWT issuer URL. If not set, defaults to auth.external_url.@@ -329,6 +330,14 @@ skip_nonce_check = false# If enabled, it will allow the user to successfully authenticate when the provider does not return an email address.email_optional = false+[auth.external.google]+enabled = true+client_id = "env(SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID)"+# DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead:+secret = "env(SUPABASE_AUTH_EXTERNAL_GOOGLE_SECRET)"+# Required for local sign in with Google auth.+skip_nonce_check = true+# Allow Solana wallet holders to sign in to your project via the Sign in with Solana (SIWS, EIP-4361) standard.# You can configure "web3" rate limit in the [auth.rate_limit] section and set up [auth.captcha] if self-hosting.[auth.web3.solana]diff --git a/docs/content/en/1.guide/03.auth.md b/docs/content/en/1.guide/03.auth.mdindex dba52b88..cbbddb1f 100644--- a/docs/content/en/1.guide/03.auth.md+++ b/docs/content/en/1.guide/03.auth.md@@ -5,7 +5,7 @@ navigation:icon: i-lucide-lockseo:title: Authentication- description: Sign in to Finapp with Google OAuth to sync data across devices. Offline mode, demo without registration, and account management.+ description: Sign in to Finapp with Google or email and password to sync data across devices. Offline mode, demo without registration, and account management.---::app-media@@ -16,7 +16,7 @@ name: login## Google Sign-In-Finapp uses Google OAuth for authentication. Sign in with your Google account to:+**Sign in with Google** is the quickest way in (you can also use [email and password](#email--password)). Sign in with your Google account to:- Sync data across all your devices- Keep your financial data backed up on the server@@ -31,6 +31,15 @@ Finapp uses Google OAuth for authentication. Sign in with your Google account toOn first sign-in, Finapp walks you through an onboarding flow: create your first wallet and category to get started.+## Email & Password++Prefer not to use Google? Sign in with an email and password instead:++1. On the login screen, tap **Sign up** and enter an email and password to create an account (skip this if you already have one).+2. Enter your credentials and tap **Sign in**.++Email/password accounts sync exactly like Google ones - the sign-in method only changes how you log in, not how your data is stored or synced.+## Demo ModeDon't want to create an account? Use demo mode to explore Finapp with pre-generated data:diff --git a/docs/content/en/2.development/01.installation.md b/docs/content/en/2.development/01.installation.mdindex 574ad48d..98e7f401 100644--- a/docs/content/en/2.development/01.installation.md+++ b/docs/content/en/2.development/01.installation.md@@ -82,6 +82,37 @@ The app will be available at [http://localhost:3050](http://localhost:3050).A design system playground is available at [http://localhost:3050/dev](http://localhost:3050/dev) during development (hidden in production).::+## Google sign-in (optional)++The login screen has a **Sign in with Google** button. Email/password works without any of this - set up Google only to test that flow locally.++::steps+### Create a Google OAuth client++In the [Google Cloud Console](https://console.cloud.google.com/apis/credentials), create an **OAuth 2.0 Client ID** (Web application) and add the local Supabase callback as an authorized redirect URI:++```text+http://127.0.0.1:54321/auth/v1/callback+```++### Add the credentials to `app/.env`++```bash [app/.env]+SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID=<client id>+SUPABASE_AUTH_EXTERNAL_GOOGLE_SECRET=<client secret>+```++The Supabase CLI loads `.env` from the directory you run it in. These feed `env()` in `app/supabase/config.toml` and are **not** exposed to the client (no `VITE_` prefix).++### Restart Supabase++```bash [Terminal - from app/]+supabase stop && supabase start+```++The Google provider is already enabled in `config.toml` (`[auth.external.google]`, `skip_nonce_check = true` for local), with the dev origin `http://localhost:3050` in `additional_redirect_urls`.+::+## Production Build::code-groupdiff --git a/docs/content/en/2.development/05.deployment.md b/docs/content/en/2.development/05.deployment.mdindex a9864301..b0d3cc21 100644--- a/docs/content/en/2.development/05.deployment.md+++ b/docs/content/en/2.development/05.deployment.md@@ -79,6 +79,21 @@ The Nuxt SPA is statically hosted on Vercel. The backend services are separate:Set the three `VITE_*` env vars in Vercel to point at your production Supabase project and PowerSync instance. See [Installation](/en/development/installation#env-variables) for the variable descriptions.+## Google Sign-In (Production)++In production the Google provider is configured in the **hosted Supabase dashboard**, not in `config.toml` (that file only drives the local stack).++1. In the [Google Cloud Console](https://console.cloud.google.com/apis/credentials), create (or reuse) an **OAuth 2.0 Client ID** and add your project's auth callback as an authorized redirect URI:++ ```text+ https://<your-supabase-project>.supabase.co/auth/v1/callback+ ```++2. In the Supabase dashboard: **Authentication -> Providers -> Google**, enable it and paste the client id/secret.+3. In **Authentication -> URL Configuration**, set **Site URL** to your deployed app origin (e.g. `https://finapp.ilko.me`) and add it (with a `/**` wildcard) to **Redirect URLs**, so the OAuth return to `/login` is allowed.++Google needs no extra app env vars - it reuses `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY`. Supabase issues its own JWT regardless of the sign-in provider, so PowerSync keeps validating it via JWKS unchanged.+## Premium (Finapp Premium)Finapp Premium lives in a separate repository ([finapp-premium](https://github.com/ilkome/finapp-premium)) and extends the base app as a **Nuxt layer**.diff --git a/docs/content/en/3.reference/01.architecture.md b/docs/content/en/3.reference/01.architecture.mdindex 38c52b46..66f6f9e9 100644--- a/docs/content/en/3.reference/01.architecture.md+++ b/docs/content/en/3.reference/01.architecture.md@@ -102,18 +102,18 @@ Demo mode bypasses PowerSync entirely. Stores check `isDemo` and skip all PowerS### Supabase Auth`app/app/composables/useSupabase.ts` provides:-- A singleton `supabase-js` client (`autoRefreshToken`, `persistSession`, `detectSessionInUrl: false`).-- `useSupabaseAuth()` composable exposing reactive `session`, `uid`, `user`, `isAuthReady`, plus `signInWithPassword` / `signUp` / `signOut`.+- A singleton `supabase-js` client (`autoRefreshToken`, `persistSession`, `detectSessionInUrl: true`).+- `useSupabaseAuth()` composable exposing reactive `session`, `uid`, `user`, `isAuthReady`, plus `signInWithPassword` / `signUp` / `signInWithGoogle` / `signOut`.- Session persists in localStorage and auto-refreshes. `onAuthStateChange` keeps a module-level reactive `session` ref in sync.-Auth method: **email/password only** (no OAuth for the MVP).+Auth methods: **email/password** and **Sign in with Google** (`signInWithOAuth`, PKCE). `detectSessionInUrl: true` lets supabase-js exchange the `?code=` on the OAuth return: `login.vue` sends Google back to `/login`, then navigates to the original destination once the session lands. Google sessions are ordinary Supabase JWTs, so PowerSync (JWKS validation) and the rest of the auth wiring are unchanged.### Auth GuardAuth uses two layers:-1. **Route middleware** (`app/app/middleware/auth.global.ts`): synchronous gate on the `finapp.localAuthUid` cookie (`hasAuthCookie()`), no network call, works offline. Redirects to `/login` (preserving `?redirect=`) when absent; bounces `/login` → `/dashboard` when the cookie is present. Demo mode bypasses this check.-2. **PowerSync plugin** (`app/app/plugins/powersync.client.ts`): watches the Supabase `uid`. Sets the `finapp.localAuthUid` cookie when a session resolves; clears it on sign-out. This is the only place the cookie is written.+1. **Route middleware** (`app/app/middleware/auth.global.ts`): synchronous gate on the persisted Supabase session in localStorage (`hasPersistedSession()`, `app/app/composables/useAuthSession.ts`), no network call, works offline. Redirects to `/login` (preserving `?redirect=`) when absent; bounces `/login` → `/dashboard` when a session is present. Demo mode bypasses this check. On the Google OAuth return the session is not persisted yet, so `/login?...&code=` is left in place (no bounce) while the code is exchanged.+2. **PowerSync plugin** (`app/app/plugins/powersync.client.ts`): watches the Supabase `uid` and connects/disconnects PowerSync as the session resolves or clears. The gate reads localStorage directly, so there is no auth cookie to write.### Redirect Protection@@ -137,11 +137,10 @@ signOut()→ isSigningOut = true (prevents auth guard redirect loop)→ supabase.auth.signOut()→ disconnectPowerSync() - disconnectAndClear() wipes local SQLite + clears owner marker- → clearAuthCookie()→ window.location.href = '/login' (hard navigation, destroys all JS state)```-Hard navigation instead of Vue Router - see [Technical Decisions](/en/development/tech-decisions).+Hard navigation instead of Vue Router - see [Technical Decisions](/en/reference/tech-decisions).## Exchange Rates@@ -204,5 +203,5 @@ The mobile transaction form uses a custom `BottomSheet` component with `useBotto## Next Steps-- [Sync](/en/development/sync) - how PowerSync syncs data between server and local SQLite-- [Offline-first](/en/development/offline-queue) - offline writes, upload queue, and error handling+- [Sync](/en/reference/sync) - how PowerSync syncs data between server and local SQLite+- [Offline-first](/en/reference/offline-queue) - offline writes, upload queue, and error handlingdiff --git a/docs/content/ru/1.guide/03.auth.md b/docs/content/ru/1.guide/03.auth.mdindex 47342e78..9fedec30 100644--- a/docs/content/ru/1.guide/03.auth.md+++ b/docs/content/ru/1.guide/03.auth.md@@ -5,7 +5,7 @@ navigation:icon: i-lucide-lockseo:title: Авторизация- description: Войдите в Финапку через Google для синхронизации данных между устройствами. Офлайн-режим, демо без регистрации и управление аккаунтом.+ description: Войдите в Финапку через Google или по почте и паролю для синхронизации данных между устройствами. Офлайн-режим, демо без регистрации и управление аккаунтом.---::app-media@@ -16,7 +16,7 @@ name: login## Вход через Google-Войдите с помощью Google-аккаунта, чтобы:+**Вход через Google** - самый быстрый способ (также можно использовать [почту и пароль](#вход-по-почте-и-паролю)). Войдите с помощью Google-аккаунта, чтобы:- Синхронизировать данные между устройствами- Хранить резервную копию на сервере@@ -31,6 +31,15 @@ name: loginПри первом входе Финапка проведёт по онбордингу: создайте первый кошелёк и категорию.+## Вход по почте и паролю++Не хотите использовать Google? Войдите по почте и паролю:++1. На экране входа нажмите **Регистрация** и введите почту и пароль, чтобы создать аккаунт (пропустите, если он уже есть).+2. Введите данные и нажмите **Войти**.++Аккаунты с почтой и паролем синхронизируются так же, как Google - способ входа влияет только на то, как вы авторизуетесь, а не на то, как хранятся и синхронизируются данные.+## Демо-режимНе хотите регистрироваться? Попробуйте демо-режим с готовыми данными:diff --git a/docs/content/ru/2.development/01.installation.md b/docs/content/ru/2.development/01.installation.mdindex 11160049..f00f14ab 100644--- a/docs/content/ru/2.development/01.installation.md+++ b/docs/content/ru/2.development/01.installation.md@@ -82,6 +82,37 @@ pnpm devPlayground дизайн-системы доступен на [http://localhost:3050/dev](http://localhost:3050/dev) в режиме разработки (скрыт в продакшене).::+## Вход через Google (опционально)++На экране входа есть кнопка **Войти через Google**. Вход по почте и паролю работает без этой настройки - настраивайте Google, только если хотите протестировать этот флоу локально.++::steps+### Создайте OAuth-клиент Google++В [Google Cloud Console](https://console.cloud.google.com/apis/credentials) создайте **OAuth 2.0 Client ID** (Web application) и добавьте локальный callback Supabase как разрешённый redirect URI:++```text+http://127.0.0.1:54321/auth/v1/callback+```++### Добавьте ключи в `app/.env`++```bash [app/.env]+SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID=<client id>+SUPABASE_AUTH_EXTERNAL_GOOGLE_SECRET=<client secret>+```++CLI Supabase загружает `.env` из директории запуска. Эти переменные подставляются в `env()` в `app/supabase/config.toml` и **не** попадают в клиент (без префикса `VITE_`).++### Перезапустите Supabase++```bash [Terminal - из app/]+supabase stop && supabase start+```++Провайдер Google уже включён в `config.toml` (`[auth.external.google]`, `skip_nonce_check = true` для локали), а dev-origin `http://localhost:3050` добавлен в `additional_redirect_urls`.+::+## Сборка::code-groupdiff --git a/docs/content/ru/2.development/05.deployment.md b/docs/content/ru/2.development/05.deployment.mdindex 4f3722c0..df1a16c3 100644--- a/docs/content/ru/2.development/05.deployment.md+++ b/docs/content/ru/2.development/05.deployment.md@@ -79,6 +79,21 @@ Nuxt SPA статически хостится на Vercel. Бэкенд-серУстановите три `VITE_*` переменные в Vercel, указывающие на продакшен-проект Supabase и экземпляр PowerSync. Описание переменных - в разделе [Установка](/ru/development/installation#переменные-окружения).+## Вход через Google (продакшен)++В продакшене провайдер Google настраивается в **дашборде хостируемого Supabase**, а не в `config.toml` (этот файл управляет только локальным стеком).++1. В [Google Cloud Console](https://console.cloud.google.com/apis/credentials) создайте (или используйте существующий) **OAuth 2.0 Client ID** и добавьте callback вашего проекта как разрешённый redirect URI:++ ```text+ https://<ваш-проект-supabase>.supabase.co/auth/v1/callback+ ```++2. В дашборде Supabase: **Authentication -> Providers -> Google**, включите провайдер и вставьте client id/secret.+3. В **Authentication -> URL Configuration** задайте **Site URL** = origin вашего приложения (например, `https://finapp.ilko.me`) и добавьте его (с шаблоном `/**`) в **Redirect URLs**, чтобы возврат после OAuth на `/login` был разрешён.++Дополнительные env-переменные для Google не нужны - используются те же `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY`. Supabase выдаёт собственный JWT независимо от провайдера входа, поэтому PowerSync продолжает проверять его через JWKS без изменений.+## Premium (Finapp Premium)Finapp Premium живёт в отдельном репозитории ([finapp-premium](https://github.com/ilkome/finapp-premium)) и расширяет базовое приложение как **Nuxt layer**.diff --git a/docs/content/ru/3.reference/01.architecture.md b/docs/content/ru/3.reference/01.architecture.mdindex 0b2a8ef2..292042f8 100644--- a/docs/content/ru/3.reference/01.architecture.md+++ b/docs/content/ru/3.reference/01.architecture.md@@ -102,18 +102,18 @@ watchTable('SELECT * FROM trns', [], onRows, throttleMs)### Supabase Auth`app/app/composables/useSupabase.ts` предоставляет:-- Синглтон-клиент `supabase-js` (`autoRefreshToken`, `persistSession`, `detectSessionInUrl: false`).-- Composable `useSupabaseAuth()` с реактивными `session`, `uid`, `user`, `isAuthReady`, а также `signInWithPassword` / `signUp` / `signOut`.+- Синглтон-клиент `supabase-js` (`autoRefreshToken`, `persistSession`, `detectSessionInUrl: true`).+- Composable `useSupabaseAuth()` с реактивными `session`, `uid`, `user`, `isAuthReady`, а также `signInWithPassword` / `signUp` / `signInWithGoogle` / `signOut`.- Сессия сохраняется в localStorage и автоматически обновляется. `onAuthStateChange` поддерживает модульный реактивный ref `session` в актуальном состоянии.-Метод авторизации: **только email/password** (OAuth в MVP не предусмотрен).+Методы авторизации: **email/password** и **вход через Google** (`signInWithOAuth`, PKCE). `detectSessionInUrl: true` позволяет supabase-js обменять `?code=` при возврате после OAuth: `login.vue` возвращает Google на `/login`, а после появления сессии переходит к исходному пункту назначения. Сессии Google - это обычные JWT Supabase, поэтому PowerSync (проверка через JWKS) и остальная auth-обвязка не меняются.### Защита авторизацииАвторизация использует два слоя:-1. **Route middleware** (`app/app/middleware/auth.global.ts`): синхронная проверка cookie `finapp.localAuthUid` (`hasAuthCookie()`), без сетевых запросов, работает офлайн. Перенаправляет на `/login` (сохраняя `?redirect=`) при отсутствии; перенаправляет `/login` → `/dashboard` при наличии cookie. Демо-режим обходит эту проверку.-2. **Плагин PowerSync** (`app/app/plugins/powersync.client.ts`): следит за Supabase `uid`. Устанавливает cookie `finapp.localAuthUid` при разрешении сессии; очищает при выходе. Это единственное место, где записывается cookie.+1. **Route middleware** (`app/app/middleware/auth.global.ts`): синхронная проверка сохранённой сессии Supabase в localStorage (`hasPersistedSession()`, `app/app/composables/useAuthSession.ts`), без сетевых запросов, работает офлайн. Перенаправляет на `/login` (сохраняя `?redirect=`) при отсутствии; перенаправляет `/login` → `/dashboard` при наличии сессии. Демо-режим обходит эту проверку. При возврате после Google OAuth сессия ещё не сохранена, поэтому `/login?...&code=` остаётся без редиректа, пока код обменивается на месте.+2. **Плагин PowerSync** (`app/app/plugins/powersync.client.ts`): следит за Supabase `uid` и подключает/отключает PowerSync по мере появления или сброса сессии. Проверка читает localStorage напрямую, поэтому auth-cookie не записывается.### Защита от редиректов@@ -137,11 +137,10 @@ signOut()→ isSigningOut = true (предотвращение цикла редиректов)→ supabase.auth.signOut()→ disconnectPowerSync() - disconnectAndClear() стирает локальную SQLite + очищает маркер владельца- → clearAuthCookie()→ window.location.href = '/login' (жёсткая навигация, уничтожение всего JS-состояния)```-Жёсткая навигация вместо Vue Router - см. [Технические решения](/ru/development/tech-decisions).+Жёсткая навигация вместо Vue Router - см. [Технические решения](/ru/reference/tech-decisions).## Курсы валют@@ -204,5 +203,5 @@ signOut()## Следующие шаги-- [Синхронизация](/ru/development/sync) - как PowerSync синхронизирует данные между сервером и локальной SQLite-- [Офлайн-first](/ru/development/offline-queue) - офлайн-записи, очередь загрузки и обработка ошибок+- [Синхронизация](/ru/reference/sync) - как PowerSync синхронизирует данные между сервером и локальной SQLite+- [Офлайн-first](/ru/reference/offline-queue) - офлайн-записи, очередь загрузки и обработка ошибок