Skip to content

Cross-Cutting Concerns & Shared Infrastructure

3.1 Authentication, Sessions, MFA & RBAC

  • Supabase Auth & Session Lifecycle:
    • lib/main.dart initializes SplashVideoGate -> AuthLinkGate -> AuthWrapper, runs PendingAuthLink.captureFromUrl() before SupabaseService.initialize() (AuthFlowType.pkce), and starts SessionEndNotice.init().
    • AuthWrapper (lib/core/widgets/auth_wrapper.dart) watches AuthProvider: shows PlanoviLoadingScreen while initializing; if unauthenticated, shows SessionEndedScreen (when SessionEndNotice.reason != null) or LoginScreen; if isPasswordRecoveryMode, shows ResetPasswordScreen; otherwise mounts SessionTimeoutWrapper -> CompanyGate -> (CreateCompanyScreen | CompanySelectionScreen | PermissionGate -> LicenseGate -> PlanoviAppHome).
    • MFA (2FA) Bypass Defect: MfaVerifyScreen is only pushed by LoginScreen._handleLogin after password sign-in, racing against AuthWrapper unmounting LoginScreen. AuthWrapper never calls getAuthenticatorAssuranceLevel(), so page refresh, session restore, or Google OAuth bypasses TOTP MFA at AAL1.
    • Google OAuth Token Vault: AuthProvider.connectWithGoogle() requests 6 scopes (email, profile, calendar, calendar.events, gmail.send, documents) with access_type=offline, prompt=consent, include_granted_scopes=true and persists tokens into user_google_tokens (preserving refresh_token via RPC get_my_google_tokens). However, jarvis Edge Function never refreshes expired tokens, reminder-scheduler refreshes without updating expires_at, and Scheduler editors read ephemeral session.providerToken instead of user_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 Realtime rbac_sync_${userId} (300ms debounce, monotonic _currentReloadId).
    • Effective role precedence: user_roles -> roles.name overrides legacy company_members.role (TenantSessionProvider, RbacUnifiedScreen), except UsersLicensesService.updateMemberRoleAndDetails only updates company_members.role (creating RBAC drift).
    • Billing Two-Tier Access: Financial actions are gated separately from PermissionProvider.isAdmin via server RPC my_billing_access(p_company_id) (is_owner, can_manage_billing), used in both BillingScreen and LicenseGate.
    • Platform Operator Gate: Sidebar "Panel operatora" is gated by RPC is_platform_operator and enforced server-side in operator_* RPCs (42501 on 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 like admin/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 injecting X-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-cron and process-tauron-csv conflict with verify_jwt = true in supabase/config.toml.
    • Stripe HMAC Signature (1): stripe-webhook (constructEventAsync; missing verify_jwt = false in config.toml).
    • Public Tokenized Endpoints (4): submit-member-declaration (72h onboarding_tokens, 10 req/15m IP rate limit), unsubscribe (onboarding_tokens.token), cancel-account-deletion (raw predictable user_profile_id UUID!), send-account-updated-notice (JWT + self-check).

3.2 Multi-Tenancy, Workspace Isolation & Dual-Supabase Split

  • Dual Workspace Providers (CompanyProvider vs TenantSessionProvider):
    • Standard CRM/Sales screens (ClientsListScreen, ListOfDealflowsScreen, DealflowEntriesScreen, OffersListScreen, AgreementsListScreen, ListOfSchedulersScreen, UnifiedCalendarScreen, SettingsScreen, BillingScreen) watch CompanyProvider.currentCompany?.id.
    • Energy Cooperative screens + CreateDealflowScreen + MainLayout watch TenantSessionProvider.activeWorkspaceId and workspaceMode (standard vs cooperative).
    • Workspace switching clears tenant caches via didChangeDependencies checks (_lastKnownCompanyId / _loadedWorkspaceId), resets coop_mode to standard for standard tier-4 companies, and resets PlanoviAppHome._currentIndex = 0 (which aliases to _cachedScreens[99] EnergyDashboardScreen in cooperative mode).
  • RLS Silent-Block Mitigation Pattern: Because PostgREST returns HTTP 200 with [] when RLS blocks an UPDATE/DELETE, newer code (BillingScreen._unassignSeat, OffersListScreen note 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) and calendar_delegations (calendar_settings_dialog.dart:39-42, unified_calendar_screen.dart:133-136) query without company_id.
    • GovernanceProvider subscribes to resolution_votes Realtime without company_id filter.
    • archiveOnboardingSession (team_coop_provider.dart:1241-1246) and updateVotingDeadline (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_URL vs SUPABASE_URL & coop_id vs company_id Split:
    • 27 Edge Functions connect via custom ENERGY_SUPABASE_URL / ENERGY_SUPABASE_SERVICE_ROLE_KEY; 16 use standard SUPABASE_URL / SUPABASE_SERVICE_ROLE_KEY (or ANON_KEY); run-scheduler uses ENERGY_SUPABASE_URL for DB reads and SUPABASE_URL for 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 to companies and company_id.

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 from assets/brand/ to web/icons/, Android mipmaps, and iOS AppIcon.appiconset).
    • Zone 1 Target: Neutral graphite (#09090B / #121215 dark) & zinc (#FAFAFA / #FFFFFF light) surfaces with Planovi green #32CA42 (#09090B text on solid #32CA42 buttons; #22A830 links/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.dart preserves all 7 presets (planovi_modern, modern_blue, minimal_white, dark_premium, green_energy, teal_planowi, commercial_offer); KonfiguracjeBrandinguScreen binds previews to tenant colors and computes CTA foreground dynamically via AppColors.contrastOn(color) (luminance > 0.42 ? #09090B : white).
  • Internationalization (pl_PL / en_US):
    • Driven by GetX LocalString (lib/core/constants/local_string.dart, 9,344 LOC) and AppString (lib/core/constants/strings.dart), persisted in SharedPreferences keys 'locale_lang_code' & 'locale_country_code' (default pl_PL).
    • Verified i18n Defects: LocalString contains 157 duplicate keys in pl_PL, 106 duplicate keys in en_US, and 8 value collisions where later definitions silently overwrite earlier ones; OperatorPanelScreen, OperatorCouponsView, and multiple strings in BillingScreen, SettingsScreen, Jarvis, and EnergyCoop remain hardcoded in Polish (or mixed English/Polish).

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.onError and PlatformDispatcher.instance.onError forward uncaught errors to AppErrorLogger.logError() (fire-and-forget POST to Google Chat webhook with 60s per-fingerprint deduplication — CRITICAL: contains hardcoded fallback webhook URL with embedded key & token in app_error_logger.dart:20-21!).
    • AppErrorHandler.getMessage(e) maps Supabase AuthException, PostgrestException (23505, 42501, PGRST116), SocketException, and TimeoutException to 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 (channel maintenance_sync_channel); blocks per-module tabs with ModuleMaintenanceDialog / ModuleMaintenanceScreen (bypasses admins via bypass_for_admins). Bug: getModuleNameForIndex() maps tabs 0–13 and 20–29, omitting tabs 14–18 (Offers, Agreements, Templates).
  • Turnstile Bot Protection (lib/core/widgets/turnstile_widget*.dart):
    • Cloudflare Turnstile widget on Login/Signup/Reset; Web uses turnstile.html, Mobile WebView loads broken URI io.supabase.planovi:///turnstile.html.
  • Timeout & Retry Policies:
    • JarvisApiService: 60s request timeout, 10s web blob fetch.
    • DomainVerificationService: 10s primary DoH, 8s fallback DoH / .well-known.
    • DealflowBlanksService: 8s Hostinger JSON fetch.
    • fetch-energy-news: 8s per RSS feed (AbortController), 15-min Cache-Control.
    • generate-report: 4.5s QuickChart PNG timeout.
    • TelemetryProvider: 5s metadata/health timeout.
    • run-scheduler: per-job retry_attempts + retry_backoff_seconds from system_jobs.
    • invokeEdgeFunction (lib/core/utils/edge_functions.dart): requires HTTP 2xx AND {'success': true}.