Skip to content

Cross-Cutting Concerns & Shared Infrastructure

3.1 Auth, Sessions, MFA & RBAC/Permissions

  • Five Distinct Edge Function Auth Patterns (No Unified Middleware):
    1. Strict Staff RBAC (_shared/auth.ts::requireUser + requireStaff + 5 inline copies): Verifies GoTrue JWT (auth.getUser), checks active company_members, bypasses for admin/owner (drifted from DB owner-only bypass), then checks user_overrides (revoke > grant) -> user_roles -> role_permissions for team_declarations|VIEW or OTHERS.
    2. Billing Manager Guard (canManageBilling, duplicated across 6 Stripe functions): Active owner, OR active admin with can_manage_billing = true, OR active admin in a company with 0 active owners.
    3. Platform Operator Guard (operator-coupons, is_platform_operator()): Active owner/admin of a company registered in public.platform_operators.
    4. Shared validateAuth(req) (_shared/auth.ts:113-176): Accepts x-cron-secret, Bearer <SUPABASE_SERVICE_ROLE_KEY>, Bearer <CRON_SECRET>, OR any valid Supabase user JWT by default (allowUser: true). Used by 15 functions (aggregate-hourly, aggregate-daily, ai-energy-balancer, billing-calculator, cleanup-telemetry, docx-to-html, generate-invoice-pdf, generate-monthly-invoices, generate-report, generate-resolution-document, process-alerts, process-tauron-csv, reminder-scheduler, run-scheduler, tender-cron) — none restrict allowUser: false, leaving cron/admin endpoints callable by any authenticated member.
    5. Public / Cryptographic Token Endpoints: Stripe HMAC (handle-stripe-webhook, stripe-webhook), e-signing HMAC (signing-api), single-use DB tokens (submit-member-declaration, update-member-declaration), unauthenticated raw-UUID GETs (cancel-account-deletion, unsubscribe), mTLS reverse-proxy headers (ingest-telemetry), and completely unauthenticated endpoints (submit-inquiry, fetch-energy-news, refresh-live-state, ingest-telemetry-old, ingest-telemetry preview mode).
  • Database RBAC Authority (Final State as of 20261118180000):
    • has_permission(p_company, p_module, p_action) evaluates: auth.uid() IS NOT NULL -> active company_members -> company_has_module(p_company, p_module) (enforces app_modules.min_plan 1..4 even on owners) -> rbac_is_owner(p_company) (owner-only bypass) -> user_overrides revoke -> user_overrides grant -> user_roles -> role_permissions.
    • Anti-escalation RESTRICTIVE policies guard roles, role_permissions, user_roles, and user_overrides.
    • company_settings.enforce_2fa (20261118180000) stores tenant-wide 2FA enforcement (enforcement of TOTP enrollment/challenge itself occurs in planovi-flutter-app / GoTrue, not in Edge Functions).
    • Live permission updates stream via supabase_realtime on role_permissions, user_overrides, user_roles, company_members (20261117100000).

3.2 Multi-Tenancy & Data Isolation

  • Primary Tenant Key: company_id (UUID referencing public.companies(id)). Legacy pre-July 2026 functions still query removed/renamed coop_id, cooperatives, user_cooperatives, telemetry_logs, and device_telemetry.
  • Two-Layer Isolation Model:
    • PostgreSQL RLS: Plain members (role = 'member') are restricted to own buildings (buildings.client_id = auth.uid()), own converters/gateways/logical points/telemetry, own building billing_records, and own member_wallet_transactions. Company-wide visibility is granted via RBAC OTHERS/full_scope (20261117120000/130000) AND (still during rollout) legacy additive planovi_coop_staff_company_ids() (owner/admin/technician/auditor).
    • Edge Functions: Almost all Edge Functions instantiate a service_role client (bypassing RLS completely) and must re-enforce tenant scoping manually in TypeScript. Confirmed tenant-isolation gaps exist in generate-invoice-pdf, generate-resolution-document, ingest-telemetry (preview mode), ai-energy-balancer, billing-calculator, generate-monthly-invoices, docx-to-html, get_15min_energy (reverted to SECURITY DEFINER in 20261118140000), and user_overrides (no company_id column).
  • Storage Bucket Isolation:
    • Public: declaration-templates (${companyId}/${uuid}.${ext}), client_files (jarvis_audio/*.mp3 — no company prefix).
    • Private: declaration-documents (no RLS, service-role only, ${companyId}/${userProfileId}/${uuid}.docx, 1h signed URLs), tauron_csvs (50 MB, service_role only), documents (signed URLs; CRM offer/agreement paths omit ${companyId}/ and bypass storage quota tracking), governance_documents (signed URLs), invoices, coop_reports (60s signed URLs).

3.3 Branding Rules (Zone 1 vs. Zone 2) & i18n (pl / en)

  • Canonical Spec (BRANDING_GUIDE.md & AGENTS.md):
    • Zone 1 (Platform Emails & Unconfigured Fallbacks): Graphite #09090B header with 3px solid #32CA42 accent, #F4F4F5 backdrop, #FFFFFF card, #32CA42 CTA button with #09090B bold text, #22A830 green links, hosted PNG logo (logo-white.png).
    • Zone 2 (Tenant Co-Branded PDFs, DOCX & Widgets): White A4 background (18mm/16mm margins), tenant logo top-left + tenant accent color (auto-darkened if WCAG luminance > 0.45), discrete Planovi footer stamp ("Wygenerowano w systemie" + logo-black.png), UTF-8 fonts (Poppins + Inter/Roboto).
  • Actual Code Compliance Audit:
    • Compliant (Zone 1): _shared/email.ts, _shared/form_link.ts (BRANDING), send-invoice-email, send-agreement-email, send-event-invitation, send-onboarding-invitation, send-correction-request-notice, update-member-declaration, invite-team-member, handle-stripe-webhook — except every single email still embeds https://dev-webpage.planovi.app/assets/logo-white.png instead of https://planovi.app/assets/logo-white.png.
    • Non-Compliant: send-subscription-updated & send-subscription-cancelled (white/light text #F1F5F9/#CBD5E0 on #FFFFFF + "noreply@planowi.app" typo); generate-agreement & finalize-agreement (legacy #0F172A/#2DD4BF + "Planowi" typo + hardcoded placeholder seller); generate-invoice-pdf & generate-report (legacy navy/teal dark headers, WinAnsi Helvetica, zero Zone 2 tenant branding); create-form-preview & create-admin-edit-link (hardcoded Planovi dark theme instead of tenant branding); generate-resolution-document ("Planowi" + mojibake).
  • i18n (pl / en):
    • User-facing Polish error messages, emails, and documents are hardcoded inline across functions (no central i18n dictionary).
    • generate-offer supports pl-PL, en-GB, en-US, de-DE for number/currency formatting, yet leaves table headers, seller labels, and email body in Polish.
    • reminder-scheduler emits English HTML emails (en-US time formatting); jarvis dynamically matches the user’s spoken/written language via prompt Rule 7, while system errors and [SILENCE] fallback are hardcoded Polish.
    • 9 files suffer from double-encoded UTF-8 mojibake (billing-calculator, generate-monthly-invoices, generate-invoice-pdf, ai-energy-balancer, generate-report, generate-resolution-document, reminder-scheduler, tender-cron, docx-to-html), causing pdf-lib WinAnsi crashes and corrupted Polish strings in emails/DB.

3.4 Global Error Handling, Logging, Retry/Timeout Policies, Maintenance Gates & Security Guards

  • Error Handling Patterns: Newer functions use _shared/auth.ts::errorResponse(err) ({ success: false, error: { message, details, hint, code } }, using err.status ?? 500). Older functions throw plain Error (causing HTTP 500 for 400/401/403/404 validation errors), or return HTTP 400 for every failure (export-csv, generate-report), or always return HTTP 200 (fetch-energy-news).
  • Logging: Only ingest-telemetry emits structured JSON logs (request_id, event, latency_ms). All other functions use plaintext console.log/console.error (generate-report has zero logging). process-declaration-ocr logs up to 1,500 chars of raw document text + full Gemini output.
  • Timeouts & Retries:
    • Router worker limits (main/index.ts): 150 MB RAM, 300s wall clock, 10s soft / 20s hard CPU.
    • Explicit 15_000 ms AbortSignal.timeout on: Resend (_shared/email.ts), DealFlow form writer (_shared/form_link.ts), and converters-api-dev dual-write (ingest-telemetry).
    • Explicit 4_500 ms timeout on QuickChart.io (generate-report); 8_000 ms on RSS feeds (fetch-energy-news).
    • No fetch timeouts on Stripe REST calls, Google Gemini (process-declaration-ocr, suggest-declaration-steps, submit-member-declaration, tender-cron, jarvis), ElevenLabs (jarvis), or Google Calendar/Gmail/Docs APIs.
    • Only suggest-declaration-steps (1 retry on malformed JSON), operator-coupons (1 Stripe API-shape retry), and run-scheduler (DB-configured inline sleep retries) implement retry logic.
  • Maintenance Gates: app_modules + app_modules_maintenance (20240101000000) store per-module maintenance flags (bypass_for_admins = true), read by client apps — zero Edge Functions check app_modules_maintenance.
  • SQL Security Guards: trg_guard_company_license_tier, trg_guard_company_licenses, trg_guard_user_license_assignments, trg_company_members_billing_guard, and RESTRICTIVE RBAC policies enforce integrity whenever auth.uid() IS NOT NULL.