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, localglobal_crm_sync, calendar shares, Jarvis settings,TenderProfileWidget, ANDWhitelistedDomainsScreen(not admin-gated in UI or RLS!). - Company Admin /
settings:UPDATEHolder (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-newswhen openingEnergyDashboardScreen. - External Cron Runner: Invokes
tender-cronwithX-Cron-Secret.
- Any Authenticated Company Member: Views
2. All Features & End-to-End Flows (Happy Path + Error Paths)
- Settings Hub (
settings_screen.dart): WatchesAuthProvider.user?.id(loadsSharedPreferences.getBool('global_crm_sync')defaulttrue, checks Google token insession.providerTokenthenuser_google_tokens) andCompanyProvider.currentCompany?.id(loadscompany_settings).- Edit Company Profile: Updates
companiesviaCompanyProvider.updateCurrentCompanyDetails; if logo picked (ImagePicker maxWidth/maxHeight: 500), uploads logo AND mirrorslogo_urltocompany_settings(onConflict: 'company_id'). - Company Branding Colors: Sets/clears
primary_colorandsecondary_colorincompany_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}intouser_google_tokens; disconnect deletes user’s row. (DuplicateGoogleCalendarConnectButtonalso rendered in adjacent section.) - Calendar Sharing / Admin Delegations: Loads all
company_members+user_profiles!inner(bug: omitsis_active = truefilter!) and opensCalendarSettingsDialogorAdminCalendarDelegationsDialog.
- Edit Company Profile: Updates
- 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'.', generatesplanovi-verification=pv_<companyId[0..8]>_<16HexChars>usingRandom.secure(), inserts intowhitelisted_domains(status: 'pending'). Unique violationuq_company_domainsurfaces 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 updateswhitelisted_domainsto{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.
- Register: Sanitizes input (lowercase, strips
- Tender Profile (
tender_profile_widget.dart): Loads/saves 1 row percompany_idintender_profiles(is_active, comma-separatedindustry_keywords,employee_count,annual_revenue). - Tender Matching Cron (
supabase/functions/tender-cron/index.ts): ValidatesX-Cron-Secret === CRON_SECRET(401 on mismatch), queries all activetender_profilesviaservice_role, evaluates 2 hardcoded mock 2026 tenders (TND-2026-001,TND-2026-002) serially per company via Geminigemini-2.5-flash(temperature: 0.1, JSON output), deduplicates intender_matchesby(company_id, title), inserts new rows withstatus: '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 120User-Agent), checks for HTML/WAF block, regex-parses up to 6 items, truncates descriptions to 300 chars, classifieswarningvsinfovia 14 Polish keywords, returns HTTP 200 withCache-Control: public, max-age=900. All error/WAF paths still return HTTP 200 with a static 1-itemSystem Planovifallback.
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 requireisAdmin || canUpdate('schedules'); all other cards (includingWhitelistedDomainsScreenandTenderProfileWidget) 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 at500×500px and mirrorslogo_urltocompany_settings(settings_screen.dart:288,348-352,432). - BR-SET-03 (CRM Sync Local Default):
SharedPreferenceskey'global_crm_sync'defaults totrue(dead preference: never read outsidesettings_screen.dart:128,134). - BR-SET-04 (Domain Sanitization & Format):
WhitelistedDomain.sanitizeDomainlowercases 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>; tokenplanovi-verification=pv_<8charCompanyId>_<16charSecureHex>; unique DB constraintuq_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_domainsRLS — SECURITY DEFECT): All 4 policies (SELECT/INSERT/UPDATE/DELETE) grant access to any row incompany_membersmatchingauth.uid()with NOis_active = truecheck and NO admin role check (20261013120000_create_whitelisted_domains_table.sql:29-73). - BR-SET-08 (Tender Profile Coercion): Non-numeric
employee_count/annual_revenuesilently coerce to0; missingcompanyIdthrows'Brak wybranej przestrzeni roboczej (Company ID).'(tender_profile_widget.dart:72-85). - BR-SET-09 (
tender-cronAuth & Config Conflict): Requires headerX-Cron-Secret === CRON_SECRET(else HTTP 401{"error":"Unauthorized"}), whilesupabase/config.toml:399simultaneously setsverify_jwt = true(tender-cron/index.ts:6-12). - BR-SET-10 (
tender-cronAI & Deduplication): Usesgemini-2.5-flash(temperature: 0.1,response_mime_type: 'application/json'); only evaluatesis_active = trueprofiles; deduplicates on(company_id, title)before insertingstatus: '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 max300chars;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) setsseverity = '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-itemSystem Planovifallback (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'bytender-cron; no further transitions or UI consumers exist in this repo.
5. Technical Contract (Inputs → Processing → Side Effects)
- Tables:
company_settings(upsertcompany_id),user_google_tokens(upsert/deleteuser_id),whitelisted_domains(migration20261013120000),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:
SharedPreferenceskey'global_crm_sync'.
6. Cross-Repository Dependencies
| Caller -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
DomainVerificationService -> Google DoH | HTTPS / Public | GET https://dns.google/resolve?name=<host>&type=TXT |
DomainVerificationService -> Customer Origin | HTTPS / Public | GET https://<domain>/.well-known/planovi-verify.txt |
tender-cron -> Google Gemini API | HTTPS / Query GEMINI_API_KEY | POST .../v1beta/models/gemini-2.5-flash:generateContent |
fetch-energy-news -> RSS Feeds | HTTPS / Public (spoofed UA) | wysokienapiecie.pl/feed/, cire.pl/rss.xml, news.google.com/rss/... |
External Embed Microservices -> whitelisted_domains | DB Read (external repo) | Enforces CSP frame-ancestors for embedded Dealflow/Scheduler/Agreement iframes |
External Cron -> tender-cron | HTTPS / 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-newsspoofs a Chrome 120 User-Agent, detects HTML WAF pages, and always returns HTTP 200 soEnergyDashboardScreennever crashes when Polish portals enable Cloudflare challenges.tender-cronexplicitly marks its 2 tenders asSIMULATED API RESPONSE FOR DEMO PURPOSESpending 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 directlyPATCH /rest/v1/whitelisted_domainssettingstatus = 'verified'via PostgREST RLS without owning DNS (20261013120000_create_whitelisted_domains_table.sql:52-61). Additionally,list_of_schedulers_screen.dart:224unlocks iframe embed code wheneverdomains.isNotEmpty, ignoringisVerified! fetch-energy-newsWAF block short-circuits fallback chain: If primarywysokienapiecie.plreturns HTTP 200 with a Cloudflare HTML challenge page,fetchRssresolves without throwing, so Secondary (cire.pl) and Tertiary (Google News) are never attempted (fetch-energy-news/index.ts:178-215).tender-cron401 from Supabase gateway:supabase/config.toml:399setsverify_jwt = true, blocking external crons that send onlyX-Cron-Secret. Also crashes the whole company loop ifindustry_keywordsis 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-knownfallback:http.get('https://<domain>/.well-known/planovi-verify.txt')fails on Web without customer CORS headers (silently swallowed atdomain_verification_service.dart:140). - Deactivated users shown in Calendar sharing/delegations:
settings_screen.dart:779-782,810-813omit.eq('is_active', true). - Log grep:
Checking DNS TXT records,DNS verification error,🚀 [CRON],[WAF BLOCK DETECTED],company_settings load error.