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→ writesrefresh_tokentoFlutterSecureStorage→ checksmfa.getAuthenticatorAssuranceLevel()(nextLevel == aal2 && currentLevel == aal1pushesMfaVerifyScreen). Errors translateinvalid login credentialstolblInvalidEmailOrPasswordand 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'. _upsertGoogleTokenruns onsignedIn/tokenRefreshed: calls RPCget_my_google_tokensto preserve priorrefresh_tokenif Google omitted it, then upsertsuser_google_tokens(onConflict: 'user_id').
- Sign-In (
- Registration (
register_screen.dart:44-137): Validates first/last name, email (@), password>= 8chars, match, and Turnstile token →signUp→ non-dismissible success dialog → pops toLoginScreen. 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 callresetPassword()with Turnstile (neither resets Turnstile on error!).AuthChangeEvent.passwordRecoveryflipsAuthProvider.isPasswordRecoveryMode = true→AuthWrappermountsResetPasswordScreen(>= 8chars) →completePasswordRecovery(). - Deep Auth Links (
auth_link.dart,auth_link_gate.dart,url_cleaner*.dart):PendingAuthLink.captureFromUrl()runs inmain()beforeSupabaseService.initialize().tokenHashflow: 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()→ ifinvite/recovery, enforces password set (>= 8chars) → clears URL viawindow.history.replaceState.legacySessionflow (#access_token=...&refresh_token=...): auto-callssetSession(refreshToken)→ password set if needed.- Expired/error flow: lets user resend
resetPasswordForEmail(without Turnstile CAPTCHA!), surfaces429rate limit, hides other errors (anti-enumeration).
- MFA TOTP (
mfa_setup_screen.dart,profile_settings_dialog.dart:744-890,mfa_verify_screen.dart): Enrollment unenrolls allunverifiedghost factors, callsmfa.enroll(issuer: 'Planovi', friendlyName: 'PlanoviAuth_<ms>'), renders SVG QR + secret, auto-verifies at 6 digits (challenge+verify). Management dialog lists verified factors and supportsunenroll. 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
CompanyGateinsideAuthWrapper. Monitors globalpointerRouter+HardwareKeyboard(1000msthrottle), primary timer (Nmin),15swall-clock watchdog, andAppLifecycleState.resumed. Always checks_hasTimedOut()before resetting_lastActivityAt. On expiry: setsSessionEndNotice.inactivity, pops root navigator to first route, callsauth.signOut(). SessionEndNoticetracks_lastExpiresAton auth events; ifsignedOutfires while_lastExpiresAt <= now + 60and no reason is set, classifies asexpired→AuthWrappershowsSessionEndedScreen.isPermanentAuthFailureexcludesAuthRetryableFetchException,AuthUnknownException, HTTP429, and>= 500so offline users are never falsely signed out.
- Wraps
- Profile & Account Lifecycle Edge Functions (
profile_settings_dialog.dart,user_usage_card.dart, 4 Edge Functions):- Profile edits check
user_profiles.phoneuniqueness, updateuser_profiles, and syncfirst_name/last_name/avatar_urltoauth.usersmetadata. - 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 toSharedPreferences(session_timeout+session_timeout_<uid>), syncsuserMetadata.session_timeout, and broadcastsSessionTimeoutWrapper.updateTimeout(val). - Danger Zone invokes
send-account-deletion-notice(setsdeletion_scheduled_at = now + 30 daysidempotently; sends Resend email bypassingemail_opt_outwith link tocancel-account-deletion?token=<user_profile_id>). Publiccancel-account-deletionclearsdeletion_scheduled_at = null. Publicunsubscribe?token=<onboarding_token>setsemail_opt_out = true.send-account-updated-noticeis unused/orphaned.
- Profile edits check
3. Hard Business Rules (BR-AUTH-01..22)
- BR-AUTH-01:
PendingAuthLink.captureFromUrl()MUST run beforeSupabaseService.initialize(), andSessionEndNotice.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'); fragmentrefresh_token+access_token→AuthLinkKind.legacySession.needsPasswordifftype in {'invite', 'recovery'}. - BR-AUTH-03:
tokenHashlinks require manual user click beforeverifyOTP(anti-scanner), and sign out any existing browser session withSignOutScope.localfirst (auth_link_gate.dart:70-83). - BR-AUTH-04: Client-side password policy across Register, Reset, Profile, and
AuthLinkGateis>= 8characters + exact confirmation match (register_screen.dart:243,reset_password_screen.dart:152,profile_settings_dialog.dart:192,auth_link_gate.dart:117). Localsupabase/config.toml:171hasminimum_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._sendNewLinksurfaces HTTP429('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 viawindow.history.replaceState(url_cleaner_web.dart:4-7). - BR-AUTH-08:
SessionEndNotice.isPermanentAuthFailure(session_end_notice.dart:35-45) returnstrueONLY forAuthExceptionexcludingAuthRetryableFetchException,AuthUnknownException, HTTP429, and HTTP>= 500.isExpiringSoonuses a60smargin (line 48). - BR-AUTH-09: On
signedOut, ifreason == null && _lastExpiresAt != null && _lastExpiresAt <= nowSec + 60,SessionEndNoticesets'expired'; anysignedInclearsreason(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,SessionTimeoutWrapperruns primary timer +15swall-clock watchdog +1000msactivity throttle + lifecycle resume check; when0, zero timers run (session_timeout_wrapper.dart:173-246). - BR-AUTH-12:
MfaSetupDialogunenrolls allunverifiedfactors beforemfa.enroll(), and auto-submits atcode.length == 6(mfa_setup_screen.dart:39-57,75-107).MfaVerifyScreenstrictly selectsFactorType.totp && FactorStatus.verified(mfa_verify_screen.dart:32-103). - BR-AUTH-13: Profile phone updates must be unique across
user_profilesexcluding 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 passsignInWithPassword(profile_settings_dialog.dart:89-95,182-224). - BR-AUTH-15:
UserUsageCard(user_usage_card.dart:142-198) defaults fallbacks to10,000AI tokens and5 GiB(5,368,709,120B) storage; bar color:< 75%teal,>= 75%orange,>= 90%red. - BR-AUTH-16:
send-account-deletion-notice(index.ts:57-142) enforcesuser.id === user_profile_id, idempotently setsdeletion_scheduled_at = now + 30 days, ALWAYS sends email even ifemail_opt_out === true, and omits unsubscribe footer. Returns HTTP500on all errors (including 401/403). - BR-AUTH-17:
cancel-account-deletion(index.ts:32-127) is public GET?token=<user_profile_id>:400missing token,404unknown profile,200idempotent HTML clearingdeletion_scheduled_at = null,500DB error. - BR-AUTH-18:
send-account-updated-notice(index.ts:60-130) enforcesuser.id === user_profile_id, requires non-emptychanged_fields[], respectsemail_opt_out, returns500on all errors. - BR-AUTH-19:
unsubscribe(index.ts:39-129) is public GET?token=<onboarding_token>:400missing token,404not inonboarding_tokens.token,200idempotent HTML settinguser_profiles.email_opt_out = true(does NOT checkexpires_at!). - BR-AUTH-20:
AuthService.signInbacks uprefresh_tokenintoFlutterSecureStorage(deleted onsignOut, never read anywhere) (auth_service.dart:43-58). - BR-AUTH-21:
AuthWrapperevaluation 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.idon 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 onuser_id),onboarding_tokens(SELECT inunsubscribe). - 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 -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
Flutter -> Supabase GoTrue | HTTPS / Anon Key + Turnstile | signInWithPassword, signUp, signInWithOAuth, verifyOTP, resetPasswordForEmail, mfa.* (requires panel origins in GoTrue additional_redirect_urls) |
Edge Functions (4) -> Energy Supabase Project | HTTPS / ENERGY_SUPABASE_SERVICE_ROLE_KEY | Uses ENERGY_SUPABASE_URL (NOT standard SUPABASE_URL) |
Edge Functions -> Resend | HTTPS / Bearer RESEND_API_KEY | POST https://api.resend.com/emails from FROM_EMAIL (noreply@planovi.app) |
cancel-account-deletion -> External Portal | HTML CTA Link | PORTAL_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 becausesupabase_flutterstrips#access_tokenduringSupabase.initialize()(auth_link.dart:3).AuthLinkGaterequires a manual button click beforeverifyOTPso corporate Safe Links email scanners do not burn one-time tokens (auth_link_gate.dart:4).LoginScreenhidesTurnstileWidgetviaOffstage(offstage: _isDialogOpen)because Flutter Web platform-view iframes render above CanvasKit dialogs (login_screen.dart:459-461).SessionTimeoutWrappercombines globalpointerRouter+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 checksgetAuthenticatorAssuranceLevel(), andLoginScreen._handleLoginraces withAuthWrapperunmountingLoginScreenonsignedIn-> move AAL2 check directly intoAuthWrapper. - Expired-link resend silently fails when Turnstile enabled ->
AuthLinkGate._sendNewLink(auth_link_gate.dart:147-151) omitscaptchaTokenand swallows non-429 errors -> add Turnstile widget or inspectdebugPrint. - Unsubscribe link in
send-account-updated-noticealways 404s -> passesuser_profile_idas?token=whileunsubscribe/index.ts:58only queriesonboarding_tokens.token-> align token lookup or mint signed opt-out token. - Turnstile fails on retry on
ForgotPasswordScreen->forgot_password_screen.dart:139does not passresetSignalor clear_captchaTokenon error. - Unexpected
"Zostałeś wylogowany"-> checkuserMetadata['session_timeout']synced from another device or refresh-token rotation collisions (> 10sreuse interval).