Cross-Cutting Concerns & Shared Infrastructure
3.1 Authentication, Sessions, MFA & RBAC
- Supabase Auth & Session Lifecycle:
lib/main.dartinitializesSplashVideoGate -> AuthLinkGate -> AuthWrapper, runsPendingAuthLink.captureFromUrl()beforeSupabaseService.initialize()(AuthFlowType.pkce), and startsSessionEndNotice.init().AuthWrapper(lib/core/widgets/auth_wrapper.dart) watchesAuthProvider: showsPlanoviLoadingScreenwhile initializing; if unauthenticated, showsSessionEndedScreen(whenSessionEndNotice.reason != null) orLoginScreen; ifisPasswordRecoveryMode, showsResetPasswordScreen; otherwise mountsSessionTimeoutWrapper -> CompanyGate -> (CreateCompanyScreen | CompanySelectionScreen | PermissionGate -> LicenseGate -> PlanoviAppHome).- MFA (2FA) Bypass Defect:
MfaVerifyScreenis only pushed byLoginScreen._handleLoginafter password sign-in, racing againstAuthWrapperunmountingLoginScreen.AuthWrappernever callsgetAuthenticatorAssuranceLevel(), so page refresh, session restore, or Google OAuth bypasses TOTP MFA atAAL1. - Google OAuth Token Vault:
AuthProvider.connectWithGoogle()requests 6 scopes (email,profile,calendar,calendar.events,gmail.send,documents) withaccess_type=offline,prompt=consent,include_granted_scopes=trueand persists tokens intouser_google_tokens(preservingrefresh_tokenvia RPCget_my_google_tokens). However,jarvisEdge Function never refreshes expired tokens,reminder-schedulerrefreshes without updatingexpires_at, and Scheduler editors read ephemeralsession.providerTokeninstead ofuser_google_tokens.
- Dual RBAC & Permission Resolution:
PermissionProvider(lib/features/admin/providers/permission_provider.dart) caches permissions per${companyId}_${userId}and evaluates strictly:isAdmin (true)→_overrideRevokeKeys (false)(fail-closed) →_overrideGrantKeys (true)→_roleKeys, synced via Realtimerbac_sync_${userId}(300ms debounce, monotonic_currentReloadId).- Effective role precedence:
user_roles -> roles.nameoverrides legacycompany_members.role(TenantSessionProvider,RbacUnifiedScreen), exceptUsersLicensesService.updateMemberRoleAndDetailsonly updatescompany_members.role(creating RBAC drift). - Billing Two-Tier Access: Financial actions are gated separately from
PermissionProvider.isAdminvia server RPCmy_billing_access(p_company_id)(is_owner,can_manage_billing), used in bothBillingScreenandLicenseGate. - Platform Operator Gate: Sidebar
"Panel operatora"is gated by RPCis_platform_operatorand enforced server-side inoperator_*RPCs (42501on denial).
- Edge Function Authentication Matrix (44 Functions in
supabase/functions/):- Manual Bearer JWT + Active Tenant Membership (6):
send-onboarding-invitation,send-correction-request-notice,send-rejection-notice,grant-portal-access,generate-report,export-csv(all 6 omit role checks likeadmin/owner!). - Manual Bearer JWT +
role === "admin"(2):send-subscription-updated,send-subscription-cancelled(bug: rejects"owner"!). - Manual Bearer JWT, ZERO Tenant Membership Check (12 — IDOR):
upload-declaration,process-declaration-ocr,approve-declaration-schema,get-company-declaration-schema,get-member-declaration,update-member-declaration,review-member-declaration,member-onboarding-status,generate-prefilled-docx,generate-invoice-pdf,generate-resolution-document,jarvis(QUERY_DB& mutations lack tenant/owner checks). - Zero Auth Check in Code (5):
generate-offer,generate-agreement,docx-to-html,fetch-energy-news,ingest-telemetry-new(relies solely on Nginx mTLS injectingX-Device-Serial). - Shared Cron / Webhook Secret (13):
X-Cron-Secret === CRON_SECRET(tender-cron,reminder-scheduler,ingest-telemetry,aggregate-hourly,aggregate-daily,refresh-live-state,cleanup-telemetry,process-alerts,run-scheduler,ai-energy-balancer,billing-calculator,generate-monthly-invoices);X-Webhook-Secret === STORAGE_WEBHOOK_SECRET(process-tauron-csv). All use non-constant-time!==;tender-cronandprocess-tauron-csvconflict withverify_jwt = trueinsupabase/config.toml. - Stripe HMAC Signature (1):
stripe-webhook(constructEventAsync; missingverify_jwt = falseinconfig.toml). - Public Tokenized Endpoints (4):
submit-member-declaration(72honboarding_tokens, 10 req/15m IP rate limit),unsubscribe(onboarding_tokens.token),cancel-account-deletion(raw predictableuser_profile_idUUID!),send-account-updated-notice(JWT + self-check).
- Manual Bearer JWT + Active Tenant Membership (6):
3.2 Multi-Tenancy, Workspace Isolation & Dual-Supabase Split
- Dual Workspace Providers (
CompanyProvidervsTenantSessionProvider):- Standard CRM/Sales screens (
ClientsListScreen,ListOfDealflowsScreen,DealflowEntriesScreen,OffersListScreen,AgreementsListScreen,ListOfSchedulersScreen,UnifiedCalendarScreen,SettingsScreen,BillingScreen) watchCompanyProvider.currentCompany?.id. - Energy Cooperative screens +
CreateDealflowScreen+MainLayoutwatchTenantSessionProvider.activeWorkspaceIdandworkspaceMode(standardvscooperative). - Workspace switching clears tenant caches via
didChangeDependencieschecks (_lastKnownCompanyId/_loadedWorkspaceId), resetscoop_modetostandardfor standard tier-4 companies, and resetsPlanoviAppHome._currentIndex = 0(which aliases to_cachedScreens[99]EnergyDashboardScreenin cooperative mode).
- Standard CRM/Sales screens (
- RLS Silent-Block Mitigation Pattern: Because PostgREST returns HTTP
200with[]when RLS blocks anUPDATE/DELETE, newer code (BillingScreen._unassignSeat,OffersListScreennote delete,CoopSettingsScreen,TeamDeclarationsScreen,BuildingAgreementService,FinancialProvider,WorkOrderProvider,KnowledgeBaseProvider) appends.select('id')and treats empty results as permission denial. - Unscoped / Cross-Tenant Leak Vectors:
user_overrides(rbac_service.dart:76-97) andcalendar_delegations(calendar_settings_dialog.dart:39-42,unified_calendar_screen.dart:133-136) query withoutcompany_id.GovernanceProvidersubscribes toresolution_votesRealtime withoutcompany_idfilter.archiveOnboardingSession(team_coop_provider.dart:1241-1246) andupdateVotingDeadline(governance_provider.dart:784-786) omit.eq('company_id', companyId).- Service-role cross-tenant bugs in
jarvis(QUERY_DB),ai-energy-balancer(allGateways),billing-calculator&generate-monthly-invoices(gateway_registry.limit(1)), and 14+ IDOR Edge Functions.
ENERGY_SUPABASE_URLvsSUPABASE_URL&coop_idvscompany_idSplit:- 27 Edge Functions connect via custom
ENERGY_SUPABASE_URL/ENERGY_SUPABASE_SERVICE_ROLE_KEY; 16 use standardSUPABASE_URL/SUPABASE_SERVICE_ROLE_KEY(orANON_KEY);run-schedulerusesENERGY_SUPABASE_URLfor DB reads andSUPABASE_URLfor HTTP job dispatch. - Legacy schema columns (
cooperatives,user_cooperatives,coop_documents,devices.coop_id,invoices.coop_id,system_settings.coop_id) persist across 10+ Edge Functions even though Flutter has migrated tocompaniesandcompany_id.
- 27 Edge Functions connect via custom
3.3 Branding Architecture (Zone 1 vs. Zone 2) & Internationalization (i18n)
- Zone 1 (Platform UI) vs. Zone 2 (Tenant White-Label):
- Source of truth:
BRANDING_GUIDE.md+lib/core/theme/app_colors.dart+scripts/sync-brand.sh(syncs logos fromassets/brand/toweb/icons/, Android mipmaps, and iOSAppIcon.appiconset). - Zone 1 Target: Neutral graphite (
#09090B/#121215dark) & zinc (#FAFAFA/#FFFFFFlight) surfaces with Planovi green#32CA42(#09090Btext on solid#32CA42buttons;#22A830links/text on light surfaces). - Observed Zone 1 Drift: Legacy teal/navy tokens (
AppColors.teal400#2DD4BF,#14B8A6,AppColors.navy800/900,#0F172A,#1E293B) remain widely used across Billing, Operator, Settings, CRM, Dealflow, Offers/Agreements editors, Jarvis emails, and all Energy Cooperative screens & Edge Function HTML emails. - Zone 2 Compliance:
lib/features/templates/data/template_styles.dartpreserves all 7 presets (planovi_modern,modern_blue,minimal_white,dark_premium,green_energy,teal_planowi,commercial_offer);KonfiguracjeBrandinguScreenbinds previews to tenant colors and computes CTA foreground dynamically viaAppColors.contrastOn(color)(luminance > 0.42 ? #09090B : white).
- Source of truth:
- Internationalization (
pl_PL/en_US):- Driven by GetX
LocalString(lib/core/constants/local_string.dart, 9,344 LOC) andAppString(lib/core/constants/strings.dart), persisted inSharedPreferenceskeys'locale_lang_code'&'locale_country_code'(defaultpl_PL). - Verified i18n Defects:
LocalStringcontains 157 duplicate keys inpl_PL, 106 duplicate keys inen_US, and 8 value collisions where later definitions silently overwrite earlier ones;OperatorPanelScreen,OperatorCouponsView, and multiple strings inBillingScreen,SettingsScreen,Jarvis, andEnergyCoopremain hardcoded in Polish (or mixed English/Polish).
- Driven by GetX
3.4 Global Error Handling, Logging, Timeouts, Maintenance Gates & Security Guards
- Global Error Capture (
lib/main.dart,lib/core/services/app_error_logger.dart,lib/core/utils/app_error_handler.dart):FlutterError.onErrorandPlatformDispatcher.instance.onErrorforward uncaught errors toAppErrorLogger.logError()(fire-and-forget POST to Google Chat webhook with 60s per-fingerprint deduplication — CRITICAL: contains hardcoded fallback webhook URL with embeddedkey&tokeninapp_error_logger.dart:20-21!).AppErrorHandler.getMessage(e)maps SupabaseAuthException,PostgrestException(23505,42501,PGRST116),SocketException, andTimeoutExceptionto localized Polish/English messages.
- Maintenance Gate (
lib/core/providers/maintenance_provider.dart,supabase/migrations/20240101000000_create_maintenance_table.sql):- Subscribes to Realtime on
app_modules_maintenance(channelmaintenance_sync_channel); blocks per-module tabs withModuleMaintenanceDialog/ModuleMaintenanceScreen(bypasses admins viabypass_for_admins). Bug:getModuleNameForIndex()maps tabs0–13and20–29, omitting tabs14–18(Offers,Agreements,Templates).
- Subscribes to Realtime on
- Turnstile Bot Protection (
lib/core/widgets/turnstile_widget*.dart):- Cloudflare Turnstile widget on Login/Signup/Reset; Web uses
turnstile.html, Mobile WebView loads broken URIio.supabase.planovi:///turnstile.html.
- Cloudflare Turnstile widget on Login/Signup/Reset; Web uses
- Timeout & Retry Policies:
JarvisApiService:60srequest timeout,10sweb blob fetch.DomainVerificationService:10sprimary DoH,8sfallback DoH /.well-known.DealflowBlanksService:8sHostinger JSON fetch.fetch-energy-news:8sper RSS feed (AbortController), 15-minCache-Control.generate-report:4.5sQuickChart PNG timeout.TelemetryProvider:5smetadata/health timeout.run-scheduler: per-jobretry_attempts+retry_backoff_secondsfromsystem_jobs.invokeEdgeFunction(lib/core/utils/edge_functions.dart): requires HTTP 2xx AND{'success': true}.