Skip to content

5. Settings, Whitelisted Domains, Tender Profile & News/Tender Cron

Repository: Flutter App (planovi-flutter-app) • Rule Prefix: BR-SET • Documented Rules: 13 • Open [TEAM_WHY_NEEDED] Questions: 3

1. Business Purpose & Actors

Central workspace settings hub (profile & billing entrypoints, company profile & white-label PDF branding colors, iframe embed security domain whitelisting with DNS TXT / .well-known verification, Google Calendar & local CRM sync preferences, calendar sharing/delegations, Jarvis settings, and automated Grant/Tender matching profile) plus two backend Edge Functions: an AI grant/tender matcher cron (tender-cron) and a Polish energy-market RSS aggregator (fetch-energy-news).

  • Actors:
    • Any Authenticated Company Member: Views SettingsScreen, manages own profile, Google Calendar OAuth, local global_crm_sync, calendar shares, Jarvis settings, TenderProfileWidget, AND WhitelistedDomainsScreen (not admin-gated in UI or RLS!).
    • Company Admin / settings:UPDATE Holder (permissions.isAdmin || permissions.hasAccess('settings', 'UPDATE')): Edits company profile & white-label PDF branding colors (company_settings).
    • Schedule Manager (permissions.isAdmin || permissions.canUpdate('schedules')): Manages admin calendar delegations (AdminCalendarDelegationsDialog).
    • Energy Dashboard Viewer: Implicitly calls fetch-energy-news when opening EnergyDashboardScreen.
    • External Cron Runner: Invokes tender-cron with X-Cron-Secret.

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

  • Settings Hub (settings_screen.dart): Watches AuthProvider.user?.id (loads SharedPreferences.getBool('global_crm_sync') default true, checks Google token in session.providerToken then user_google_tokens) and CompanyProvider.currentCompany?.id (loads company_settings).
    • Edit Company Profile: Updates companies via CompanyProvider.updateCurrentCompanyDetails; if logo picked (ImagePicker maxWidth/maxHeight: 500), uploads logo AND mirrors logo_url to company_settings (onConflict: 'company_id').
    • Company Branding Colors: Sets/clears primary_color and secondary_color in company_settings (6-digit hex validation; invalid hex silently does nothing on OK).
    • Google Calendar Connect/Disconnect: Calls AuthProvider.connectWithGoogle(), waits 600ms, upserts {user_id, access_token, refresh_token, updated_at} into user_google_tokens; disconnect deletes user’s row. (Duplicate GoogleCalendarConnectButton also rendered in adjacent section.)
    • Calendar Sharing / Admin Delegations: Loads all company_members + user_profiles!inner (bug: omits is_active = true filter!) and opens CalendarSettingsDialog or AdminCalendarDelegationsDialog.
  • Whitelisted Domains (whitelisted_domains_screen.dart, domain_verification_service.dart, whitelisted_domain.dart):
    • Register: Sanitizes input (lowercase, strips http(s)://, www., path, port), validates non-empty + contains '.', generates planovi-verification=pv_<companyId[0..8]>_<16HexChars> using Random.secure(), inserts into whitelisted_domains (status: 'pending'). Unique violation uq_company_domain surfaces as snackbar error.
    • Verify (3-Stage Client-Side Fallback): (1) GET https://dns.google/resolve?name=_planovi-challenge.<domain>&type=TXT (10s timeout) → (2) GET https://dns.google/resolve?name=<domain>&type=TXT (8s timeout) → (3) GET https://<domain>/.well-known/planovi-verify.txt (8s timeout, errors swallowed). If token matches/contained, Flutter client directly updates whitelisted_domains to {status: 'verified', verified_at: nowUtc}; else updates to {status: 'failed'}. Network/timeout exception in Stage 1–2 leaves DB status unchanged.
    • Delete: Confirmation dialog warning of immediate iframe block → hard deletes row by id.
  • Tender Profile (tender_profile_widget.dart): Loads/saves 1 row per company_id in tender_profiles (is_active, comma-separated industry_keywords, employee_count, annual_revenue).
  • Tender Matching Cron (supabase/functions/tender-cron/index.ts): Validates X-Cron-Secret === CRON_SECRET (401 on mismatch), queries all active tender_profiles via service_role, evaluates 2 hardcoded mock 2026 tenders (TND-2026-001, TND-2026-002) serially per company via Gemini gemini-2.5-flash (temperature: 0.1, JSON output), deduplicates in tender_matches by (company_id, title), inserts new rows with status: 'new'.
  • Energy News RSS Aggregator (supabase/functions/fetch-energy-news/index.ts): Public endpoint (no auth, CORS *). Tries 3 RSS feeds in order (wysokienapiecie.pl/feed/ → cire.pl/rss.xml → Google News PL RSS, 8s timeout each, spoofed Chrome 120 User-Agent), checks for HTML/WAF block, regex-parses up to 6 items, truncates descriptions to 300 chars, classifies warning vs info via 14 Polish keywords, returns HTTP 200 with Cache-Control: public, max-age=900. All error/WAF paths still return HTTP 200 with a static 1-item System Planovi fallback.

3. Hard Business Rules (BR-SET-01..13)

  • BR-SET-01 (Settings Visibility Gates): Company Profile & Branding require isAdmin || hasAccess('settings', 'UPDATE'); Admin Calendar Delegations require isAdmin || canUpdate('schedules'); all other cards (including WhitelistedDomainsScreen and TenderProfileWidget) are visible to every authenticated member (settings_screen.dart:546-547,561-854).
  • BR-SET-02 (Branding Color & Logo Constraints): Hex inputs must match ^#([A-Fa-f0-9]{6})$; logo upload caps at 500×500 px and mirrors logo_url to company_settings (settings_screen.dart:288,348-352,432).
  • BR-SET-03 (CRM Sync Local Default): SharedPreferences key 'global_crm_sync' defaults to true (dead preference: never read outside settings_screen.dart:128,134).
  • BR-SET-04 (Domain Sanitization & Format): WhitelistedDomain.sanitizeDomain lowercases and strips protocol, www., path, and port; must be non-empty and contain '.' (whitelisted_domain.dart:55-66, domain_verification_service.dart:52-54). Error: 'Nieprawidłowy adres domeny. Wprowadź domenę w formacie np. twojafirma.pl'.
  • BR-SET-05 (Challenge Token & Uniqueness): DNS host _planovi-challenge.<domain>; token planovi-verification=pv_<8charCompanyId>_<16charSecureHex>; unique DB constraint uq_company_domain (company_id, domain) (whitelisted_domain.dart:52, domain_verification_service.dart:57-59,195-199, 20261013120000_create_whitelisted_domains_table.sql:14).
  • BR-SET-06 (3-Stage Domain Verification): Google DoH TXT on _planovi-challenge.<domain> (10s) → apex <domain> TXT (8s) → HTTPS /.well-known/planovi-verify.txt (8s); matches on exact equality OR .contains(challengeToken) (domain_verification_service.dart:87-143).
  • BR-SET-07 (Permissive whitelisted_domains RLS — SECURITY DEFECT): All 4 policies (SELECT/INSERT/UPDATE/DELETE) grant access to any row in company_members matching auth.uid() with NO is_active = true check and NO admin role check (20261013120000_create_whitelisted_domains_table.sql:29-73).
  • BR-SET-08 (Tender Profile Coercion): Non-numeric employee_count/annual_revenue silently coerce to 0; missing companyId throws 'Brak wybranej przestrzeni roboczej (Company ID).' (tender_profile_widget.dart:72-85).
  • BR-SET-09 (tender-cron Auth & Config Conflict): Requires header X-Cron-Secret === CRON_SECRET (else HTTP 401 {"error":"Unauthorized"}), while supabase/config.toml:399 simultaneously sets verify_jwt = true (tender-cron/index.ts:6-12).
  • BR-SET-10 (tender-cron AI & Deduplication): Uses gemini-2.5-flash (temperature: 0.1, response_mime_type: 'application/json'); only evaluates is_active = true profiles; deduplicates on (company_id, title) before inserting status: 'new' (tender-cron/index.ts:94-135).
  • BR-SET-11 (Energy News Priority, Limits & Caching): Priority: wysokienapiecie.pl/feed/ → cire.pl/rss.xml → Google News PL RSS; MAX_ITEMS = 6; FETCH_TIMEOUT_MS = 8000; description max 300 chars; Cache-Control: public, max-age=900 (fetch-energy-news/index.ts:13-20,107,235).
  • BR-SET-12 (Energy News Severity Keywords): Case-insensitive match against 14 Polish keywords (awaria, przerwa, wzrost cen, kryzys, blackout, odcięcie, wyłączenie, alarm, zagrożenie, embargo, sankcje, deficyt, ograniczenia, podwyżki) sets severity = 'warning', else 'info' (fetch-energy-news/index.ts:32-42).
  • BR-SET-13 (Energy News Guaranteed HTTP 200 & WAF Guard): HTML/Cloudflare responses (<!doctype html / <html) and all errors return HTTP 200 with a static 1-item System Planovi fallback (fetch-energy-news/index.ts:209-254).

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> Pending: registerDomain()
    Pending --> Verified: DNS TXT or .well-known match (verified_at set)
    Pending --> Failed: Token not found
    Failed --> Verified: Retry succeeds
    Failed --> Failed: Retry misses
    Pending --> [*]: deleteDomain (hard delete)
    Verified --> [*]: deleteDomain (hard delete)
    Failed --> [*]: deleteDomain (hard delete)
    note right of Verified: DomainStatus.revoked exists in enum/UI but is never assigned in code
  • tender_matches: Inserted as 'new' by tender-cron; no further transitions or UI consumers exist in this repo.

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

  • Tables: company_settings (upsert company_id), user_google_tokens (upsert/delete user_id), whitelisted_domains (migration 20261013120000), tender_profiles, tender_matches, company_members + user_profiles.
  • Edge Functions: tender-cron (CRON_SECRET, SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY, GEMINI_API_KEY); fetch-energy-news (public, zero env vars).
  • Local Prefs: SharedPreferences key 'global_crm_sync'.

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
DomainVerificationService -> Google DoHHTTPS / PublicGET https://dns.google/resolve?name=<host>&type=TXT
DomainVerificationService -> Customer OriginHTTPS / PublicGET https://<domain>/.well-known/planovi-verify.txt
tender-cron -> Google Gemini APIHTTPS / Query GEMINI_API_KEYPOST .../v1beta/models/gemini-2.5-flash:generateContent
fetch-energy-news -> RSS FeedsHTTPS / Public (spoofed UA)wysokienapiecie.pl/feed/, cire.pl/rss.xml, news.google.com/rss/...
External Embed Microservices -> whitelisted_domainsDB Read (external repo)Enforces CSP frame-ancestors for embedded Dealflow/Scheduler/Agreement iframes
External Cron -> tender-cronHTTPS / X-Cron-Secret (+ JWT per config.toml)POST /functions/v1/tender-cron

7. Why It Works This Way

  • Google DoH (dns.google/resolve) is used because Flutter Web cannot execute raw UDP DNS TXT queries (domain_verification_service.dart).
  • fetch-energy-news spoofs a Chrome 120 User-Agent, detects HTML WAF pages, and always returns HTTP 200 so EnergyDashboardScreen never crashes when Polish portals enable Cloudflare challenges.
  • tender-cron explicitly marks its 2 tenders as SIMULATED API RESPONSE FOR DEMO PURPOSES pending EU TED / Polish e-Zamówienia API integration (tender-cron/index.ts:35-57).
  • [TEAM_WHY_NEEDED: Why is domain DNS verification executed client-side with direct client UPDATE on whitelisted_domains instead of a server-side Edge Function?]
  • [TEAM_WHY_NEEDED: Is the Tender/Grant Matching feature (tender_profiles + tender-cron + tender_matches) paused or consumed by an external app, given tender_matches has zero UI readers in this repo?]
  • [TEAM_WHY_NEEDED: Why does SettingsScreen render two separate Google Calendar connect widgets side-by-side (custom tile at line 704 and GoogleCalendarConnectButton at line 763)?]

8. Debugging, Logs & Common Failure Modes

  • CRITICAL SECURITY — Client-side domain verification bypass: Any company member (even is_active = false, non-admin) can directly PATCH /rest/v1/whitelisted_domains setting status = 'verified' via PostgREST RLS without owning DNS (20261013120000_create_whitelisted_domains_table.sql:52-61). Additionally, list_of_schedulers_screen.dart:224 unlocks iframe embed code whenever domains.isNotEmpty, ignoring isVerified!
  • fetch-energy-news WAF block short-circuits fallback chain: If primary wysokienapiecie.pl returns HTTP 200 with a Cloudflare HTML challenge page, fetchRss resolves without throwing, so Secondary (cire.pl) and Tertiary (Google News) are never attempted (fetch-energy-news/index.ts:178-215).
  • tender-cron 401 from Supabase gateway: supabase/config.toml:399 sets verify_jwt = true, blocking external crons that send only X-Cron-Secret. Also crashes the whole company loop if industry_keywords is null or Gemini returns markdown-wrapped JSON, and triggers a PostgREST 406 on every new tender via .single() instead of .maybeSingle() (tender-cron/index.ts:122).
  • Web CORS blocks .well-known fallback: http.get('https://<domain>/.well-known/planovi-verify.txt') fails on Web without customer CORS headers (silently swallowed at domain_verification_service.dart:140).
  • Deactivated users shown in Calendar sharing/delegations: settings_screen.dart:779-782,810-813 omit .eq('is_active', true).
  • Log grep: Checking DNS TXT records, DNS verification error, 🚀 [CRON], [WAF BLOCK DETECTED], company_settings load error.