Skip to content
📦 ARCHIVED SNAPSHOT (v1.0) You are viewing historical business logic and documentation for Flutter App v1.0 (frozen on 2026-11-23, commit 92290cf7). Switch to Latest →

2. Authentication, Deep Auth Links, Session Timeout, MFA & User Profile

Repository: Flutter App (planovi-flutter-app) • Rule Prefix: BR-AUTH • Documented Rules: 22 • Open [TEAM_WHY_NEEDED] Questions: 2

1. Business Purpose & Actors

Manages user authentication (email/password + Cloudflare Turnstile, Google OAuth, Google Workspace offline token vault), scanner-safe email deep links (invite, recovery, signup, magiclink, email_change), TOTP 2FA enrollment & verification, cross-device inactivity auto-logout with wall-clock recovery, user profile/password management, 30-day GDPR deletion requests, and email opt-out.

  • Actors: Anonymous/Unauthenticated visitors, Invited Team/Coop members activating accounts, Authenticated users (Email or Google OAuth), Unauthenticated email link clickers (cancel-account-deletion, unsubscribe), Supabase GoTrue, Cloudflare Turnstile, Google OAuth, Resend API.

2. All Features & End-to-End Flows (Happy Path + Error Paths)

  • Email/Password Login (login_screen.dart:65-122): Validates email (@), password, and non-null Turnstile _captchaToken → AuthProvider.signIn → writes refresh_token to FlutterSecureStorage → checks mfa.getAuthenticatorAssuranceLevel() (nextLevel == aal2 && currentLevel == aal1 pushes MfaVerifyScreen). Errors translate invalid login credentials to lblInvalidEmailOrPassword and reset Turnstile (_captchaToken = null, _captchaResetKey++).
  • Google OAuth Sign-In & Workspace Connect (auth_provider.dart:114-248):
    • Sign-In (signInWithGoogle): scopes 'email profile', access_type: 'offline', prompt: 'select_account', no CAPTCHA.
    • Workspace Connect (connectWithGoogle): scopes 'email profile calendar calendar.events gmail.send documents', access_type: 'offline', prompt: 'consent', include_granted_scopes: 'true'.
    • _upsertGoogleToken runs on signedIn/tokenRefreshed: calls RPC get_my_google_tokens to preserve prior refresh_token if Google omitted it, then upserts user_google_tokens (onConflict: 'user_id').
  • Registration (register_screen.dart:44-137): Validates first/last name, email (@), password >= 8 chars, match, and Turnstile token → signUp → non-dismissible success dialog → pops to LoginScreen. Translates duplicate email (already registered/already exists); resets Turnstile on error.
  • Forgot Password, Invite Activation & Reset Password (forgot_password_screen.dart, login_screen.dart:137-277, reset_password_screen.dart): Forgot screen and LoginScreen’s “Activate Account” modal both call resetPassword() with Turnstile (neither resets Turnstile on error!). AuthChangeEvent.passwordRecovery flips AuthProvider.isPasswordRecoveryMode = true → AuthWrapper mounts ResetPasswordScreen (>= 8 chars) → completePasswordRecovery().
  • Deep Auth Links (auth_link.dart, auth_link_gate.dart, url_cleaner*.dart):
    • PendingAuthLink.captureFromUrl() runs in main() before SupabaseService.initialize().
    • tokenHash flow: waits on manual CTA (_Step.confirm, preventing corporate email scanners from burning one-time tokens) → signs out any existing local session (SignOutScope.local) → auth.verifyOTP() → if invite/recovery, enforces password set (>= 8 chars) → clears URL via window.history.replaceState.
    • legacySession flow (#access_token=...&refresh_token=...): auto-calls setSession(refreshToken) → password set if needed.
    • Expired/error flow: lets user resend resetPasswordForEmail (without Turnstile CAPTCHA!), surfaces 429 rate limit, hides other errors (anti-enumeration).
  • MFA TOTP (mfa_setup_screen.dart, profile_settings_dialog.dart:744-890, mfa_verify_screen.dart): Enrollment unenrolls all unverified ghost factors, calls mfa.enroll(issuer: 'Planovi', friendlyName: 'PlanoviAuth_<ms>'), renders SVG QR + secret, auto-verifies at 6 digits (challenge + verify). Management dialog lists verified factors and supports unenroll. Login verification picks first verified TOTP factor (MfaVerifyScreen), auto-verifies at 6 digits, resets route to '/'.
  • Inactivity Timeout & Session Expiry (session_timeout_wrapper.dart, session_end_notice.dart, session_ended_screen.dart):
    • Wraps CompanyGate inside AuthWrapper. Monitors global pointerRouter + HardwareKeyboard (1000ms throttle), primary timer (N min), 15s wall-clock watchdog, and AppLifecycleState.resumed. Always checks _hasTimedOut() before resetting _lastActivityAt. On expiry: sets SessionEndNotice.inactivity, pops root navigator to first route, calls auth.signOut().
    • SessionEndNotice tracks _lastExpiresAt on auth events; if signedOut fires while _lastExpiresAt <= now + 60 and no reason is set, classifies as expired → AuthWrapper shows SessionEndedScreen. isPermanentAuthFailure excludes AuthRetryableFetchException, AuthUnknownException, HTTP 429, and >= 500 so offline users are never falsely signed out.
  • Profile & Account Lifecycle Edge Functions (profile_settings_dialog.dart, user_usage_card.dart, 4 Edge Functions):
    • Profile edits check user_profiles.phone uniqueness, update user_profiles, and sync first_name/last_name/avatar_url to auth.users metadata.
    • Password change requires current-password re-auth (signInWithPassword) for non-Google users; Google OAuth users skip current password.
    • Auto-logout dropdown [0, 5, 10, 15, 30, 45, 60, 120, 180, 240, 300] saves to SharedPreferences (session_timeout + session_timeout_<uid>), syncs userMetadata.session_timeout, and broadcasts SessionTimeoutWrapper.updateTimeout(val).
    • Danger Zone invokes send-account-deletion-notice (sets deletion_scheduled_at = now + 30 days idempotently; sends Resend email bypassing email_opt_out with link to cancel-account-deletion?token=<user_profile_id>). Public cancel-account-deletion clears deletion_scheduled_at = null. Public unsubscribe?token=<onboarding_token> sets email_opt_out = true. send-account-updated-notice is unused/orphaned.

3. Hard Business Rules (BR-AUTH-01..22)

  • BR-AUTH-01: PendingAuthLink.captureFromUrl() MUST run before SupabaseService.initialize(), and SessionEndNotice.init() immediately after (lib/main.dart:127-129).
  • BR-AUTH-02: Deep-link parse precedence (auth_link.dart:30-63): error_code/error → AuthLinkKind.error; token_hash → AuthLinkKind.tokenHash (default type 'invite'); fragment refresh_token + access_token → AuthLinkKind.legacySession. needsPassword iff type in {'invite', 'recovery'}.
  • BR-AUTH-03: tokenHash links require manual user click before verifyOTP (anti-scanner), and sign out any existing browser session with SignOutScope.local first (auth_link_gate.dart:70-83).
  • BR-AUTH-04: Client-side password policy across Register, Reset, Profile, and AuthLinkGate is >= 8 characters + exact confirmation match (register_screen.dart:243, reset_password_screen.dart:152, profile_settings_dialog.dart:192, auth_link_gate.dart:117). Local supabase/config.toml:171 has minimum_password_length = 6.
  • BR-AUTH-05: Turnstile CAPTCHA is mandatory for email/password Login, Registration, Forgot Password, and Activation Link resend (login_screen.dart:69,165, register_screen.dart:49, forgot_password_screen.dart:34), bypassed for Google OAuth and (erroneously) AuthLinkGate._sendNewLink.
  • BR-AUTH-06: AuthLinkGate._sendNewLink surfaces HTTP 429 ('Za dużo prób. Spróbuj ponownie za chwilę.') and suppresses all other errors to prevent email enumeration (auth_link_gate.dart:139-162).
  • BR-AUTH-07: On Web, cleanAuthParamsFromUrl() strips query/fragment auth params via window.history.replaceState (url_cleaner_web.dart:4-7).
  • BR-AUTH-08: SessionEndNotice.isPermanentAuthFailure (session_end_notice.dart:35-45) returns true ONLY for AuthException excluding AuthRetryableFetchException, AuthUnknownException, HTTP 429, and HTTP >= 500. isExpiringSoon uses a 60s margin (line 48).
  • BR-AUTH-09: On signedOut, if reason == null && _lastExpiresAt != null && _lastExpiresAt <= nowSec + 60, SessionEndNotice sets 'expired'; any signedIn clears reason (session_end_notice.dart:63-80).
  • BR-AUTH-10: Auto-logout timeout resolution order (session_timeout_wrapper.dart:42-64): userMetadata['session_timeout'] (int/num/numeric string >= 0) > prefs['session_timeout_<userId>'] > prefs['session_timeout'] > 0 (Never).
  • BR-AUTH-11: When _timeoutMinutes > 0, SessionTimeoutWrapper runs primary timer + 15s wall-clock watchdog + 1000ms activity throttle + lifecycle resume check; when 0, zero timers run (session_timeout_wrapper.dart:173-246).
  • BR-AUTH-12: MfaSetupDialog unenrolls all unverified factors before mfa.enroll(), and auto-submits at code.length == 6 (mfa_setup_screen.dart:39-57,75-107). MfaVerifyScreen strictly selects FactorType.totp && FactorStatus.verified (mfa_verify_screen.dart:32-103).
  • BR-AUTH-13: Profile phone updates must be unique across user_profiles excluding current user (lblPhoneAlreadyInUse) (profile_settings_dialog.dart:152-168).
  • BR-AUTH-14: Google OAuth users (appMetadata.providers.contains('google') || provider == 'google') skip current-password verification when setting a password; non-Google users must pass signInWithPassword (profile_settings_dialog.dart:89-95,182-224).
  • BR-AUTH-15: UserUsageCard (user_usage_card.dart:142-198) defaults fallbacks to 10,000 AI tokens and 5 GiB (5,368,709,120 B) storage; bar color: < 75% teal, >= 75% orange, >= 90% red.
  • BR-AUTH-16: send-account-deletion-notice (index.ts:57-142) enforces user.id === user_profile_id, idempotently sets deletion_scheduled_at = now + 30 days, ALWAYS sends email even if email_opt_out === true, and omits unsubscribe footer. Returns HTTP 500 on all errors (including 401/403).
  • BR-AUTH-17: cancel-account-deletion (index.ts:32-127) is public GET ?token=<user_profile_id>: 400 missing token, 404 unknown profile, 200 idempotent HTML clearing deletion_scheduled_at = null, 500 DB error.
  • BR-AUTH-18: send-account-updated-notice (index.ts:60-130) enforces user.id === user_profile_id, requires non-empty changed_fields[], respects email_opt_out, returns 500 on all errors.
  • BR-AUTH-19: unsubscribe (index.ts:39-129) is public GET ?token=<onboarding_token>: 400 missing token, 404 not in onboarding_tokens.token, 200 idempotent HTML setting user_profiles.email_opt_out = true (does NOT check expires_at!).
  • BR-AUTH-20: AuthService.signIn backs up refresh_token into FlutterSecureStorage (deleted on signOut, never read anywhere) (auth_service.dart:43-58).
  • BR-AUTH-21: AuthWrapper evaluation order (auth_wrapper.dart:26-61): !isInitialized → PlanoviLoadingScreen → !isAuthenticated → (SessionEndNotice.reason != null ? SessionEndedScreen : LoginScreen) → isPasswordRecoveryMode → ResetPasswordScreen → SessionTimeoutWrapper(CompanyGate).
  • BR-AUTH-22: Crashlytics user ID is bound to user.id on non-web platforms and cleared ('') on sign-out (auth_provider.dart:305-315).

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> CapturingLink: main() PendingAuthLink.captureFromUrl
    CapturingLink --> LinkConfirm: tokenHash
    CapturingLink --> LinkWorking: legacySession
    CapturingLink --> LinkExpired: error param
    CapturingLink --> AuthWrapperInit: no auth link
    LinkConfirm --> LinkWorking: user clicks CTA (local signOut + verifyOTP)
    LinkWorking --> SetPassword: ok & (invite | recovery)
    LinkWorking --> AuthWrapperInit: ok & other type (+clean URL)
    LinkWorking --> LinkExpired: AuthException
    SetPassword --> AuthWrapperInit: completePasswordRecovery (+clean URL)
    LinkExpired --> AuthWrapperInit: skip to login (+clean URL)
    AuthWrapperInit --> SessionEnded: !authenticated & notice != null
    AuthWrapperInit --> Login: !authenticated & notice == null
    AuthWrapperInit --> ResetPassword: isPasswordRecoveryMode
    AuthWrapperInit --> ActiveSession: authenticated (SessionTimeoutWrapper -> CompanyGate)
    ActiveSession --> SessionEnded: inactivity timeout | expired refresh
    ActiveSession --> Login: manual signOut (valid token)
  • GDPR Deletion Lifecycle: Active (deletion_scheduled_at = null) → Scheduled (+30d via send-account-deletion-notice) → Cancelled (cancel-account-deletion sets null) | [Permanent Deletion Cron NOT present in this repo].

5. Technical Contract (Inputs → Processing → Side Effects)

  • Tables: user_profiles (first_name, last_name, phone, email, email_opt_out, deletion_scheduled_at), company_members (company_id), user_google_tokens (UPSERT on user_id), onboarding_tokens (SELECT in unsubscribe).
  • RPCs: get_my_google_tokens(), my_token_status(p_company), company_storage_status(p_company).
  • Edge Functions: POST send-account-deletion-notice ({user_profile_id}), GET cancel-account-deletion?token=<uuid>, POST send-account-updated-notice ({user_profile_id, changed_fields[]}), GET unsubscribe?token=<onboarding_token>.
  • External APIs: Supabase GoTrue Auth/MFA, Cloudflare Turnstile, Google OAuth, Resend (POST https://api.resend.com/emails), Firebase Crashlytics.

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
Flutter -> Supabase GoTrueHTTPS / Anon Key + TurnstilesignInWithPassword, signUp, signInWithOAuth, verifyOTP, resetPasswordForEmail, mfa.* (requires panel origins in GoTrue additional_redirect_urls)
Edge Functions (4) -> Energy Supabase ProjectHTTPS / ENERGY_SUPABASE_SERVICE_ROLE_KEYUses ENERGY_SUPABASE_URL (NOT standard SUPABASE_URL)
Edge Functions -> ResendHTTPS / Bearer RESEND_API_KEYPOST https://api.resend.com/emails from FROM_EMAIL (noreply@planovi.app)
cancel-account-deletion -> External PortalHTML CTA LinkPORTAL_URL (defaults https://app.planovi.app vs panel.planovi.app vs portal.planovi.app)

7. Why It Works This Way

  • PendingAuthLink.captureFromUrl() runs pre-init because supabase_flutter strips #access_token during Supabase.initialize() (auth_link.dart:3).
  • AuthLinkGate requires a manual button click before verifyOTP so corporate Safe Links email scanners do not burn one-time tokens (auth_link_gate.dart:4).
  • LoginScreen hides TurnstileWidget via Offstage(offstage: _isDialogOpen) because Flutter Web platform-view iframes render above CanvasKit dialogs (login_screen.dart:459-461).
  • SessionTimeoutWrapper combines global pointerRouter + HardwareKeyboard + 15s wall-clock watchdog + lifecycle resume to cover pushed routes and throttled background browser tabs (session_timeout_wrapper.dart:5-8,181-185).
  • [TEAM_WHY_NEEDED: Confirm whether the 30-day GDPR encryption & permanent account deletion cron promised in ProfileScreen and send-account-deletion-notice exists in an external backend repo or is unimplemented.]
  • [TEAM_WHY_NEEDED: Why do all 4 auth/account Edge Functions use ENERGY_SUPABASE_URL instead of standard SUPABASE_URL, and is send-account-updated-notice meant to be wired to Flutter?]

8. Debugging, Logs & Common Failure Modes

  • 2FA completely bypassed on login / refresh / Google OAuth -> AuthWrapper (auth_wrapper.dart) never checks getAuthenticatorAssuranceLevel(), and LoginScreen._handleLogin races with AuthWrapper unmounting LoginScreen on signedIn -> move AAL2 check directly into AuthWrapper.
  • Expired-link resend silently fails when Turnstile enabled -> AuthLinkGate._sendNewLink (auth_link_gate.dart:147-151) omits captchaToken and swallows non-429 errors -> add Turnstile widget or inspect debugPrint.
  • Unsubscribe link in send-account-updated-notice always 404s -> passes user_profile_id as ?token= while unsubscribe/index.ts:58 only queries onboarding_tokens.token -> align token lookup or mint signed opt-out token.
  • Turnstile fails on retry on ForgotPasswordScreen -> forgot_password_screen.dart:139 does not pass resetSignal or clear _captchaToken on error.
  • Unexpected "Zostałeś wylogowany" -> check userMetadata['session_timeout'] synced from another device or refresh-token rotation collisions (> 10s reuse interval).