Cross-Cutting Concerns & Shared Infrastructure
3.1 Auth, Sessions, MFA & RBAC/Permissions
- Five Distinct Edge Function Auth Patterns (No Unified Middleware):
- Strict Staff RBAC (
_shared/auth.ts::requireUser+requireStaff+ 5 inline copies): Verifies GoTrue JWT (auth.getUser), checks activecompany_members, bypasses foradmin/owner(drifted from DB owner-only bypass), then checksuser_overrides(revoke > grant) ->user_roles -> role_permissionsforteam_declarations|VIEWorOTHERS. - Billing Manager Guard (
canManageBilling, duplicated across 6 Stripe functions): Activeowner, OR activeadminwithcan_manage_billing = true, OR activeadminin a company with 0 active owners. - Platform Operator Guard (
operator-coupons,is_platform_operator()): Activeowner/adminof a company registered inpublic.platform_operators. - Shared
validateAuth(req)(_shared/auth.ts:113-176): Acceptsx-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 restrictallowUser: false, leaving cron/admin endpoints callable by any authenticated member. - 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-telemetrypreview mode).
- Strict Staff RBAC (
- Database RBAC Authority (Final State as of
20261118180000):has_permission(p_company, p_module, p_action)evaluates:auth.uid() IS NOT NULL-> activecompany_members->company_has_module(p_company, p_module)(enforcesapp_modules.min_plan1..4 even onowners) ->rbac_is_owner(p_company)(owner-only bypass) ->user_overridesrevoke ->user_overridesgrant ->user_roles -> role_permissions.- Anti-escalation
RESTRICTIVEpolicies guardroles,role_permissions,user_roles, anduser_overrides. company_settings.enforce_2fa(20261118180000) stores tenant-wide 2FA enforcement (enforcement of TOTP enrollment/challenge itself occurs inplanovi-flutter-app/ GoTrue, not in Edge Functions).- Live permission updates stream via
supabase_realtimeonrole_permissions,user_overrides,user_roles,company_members(20261117100000).
3.2 Multi-Tenancy & Data Isolation
- Primary Tenant Key:
company_id(UUID referencingpublic.companies(id)). Legacy pre-July 2026 functions still query removed/renamedcoop_id,cooperatives,user_cooperatives,telemetry_logs, anddevice_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 buildingbilling_records, and ownmember_wallet_transactions. Company-wide visibility is granted via RBACOTHERS/full_scope(20261117120000/130000) AND (still during rollout) legacy additiveplanovi_coop_staff_company_ids()(owner/admin/technician/auditor). - Edge Functions: Almost all Edge Functions instantiate a
service_roleclient (bypassing RLS completely) and must re-enforce tenant scoping manually in TypeScript. Confirmed tenant-isolation gaps exist ingenerate-invoice-pdf,generate-resolution-document,ingest-telemetry(preview mode),ai-energy-balancer,billing-calculator,generate-monthly-invoices,docx-to-html,get_15min_energy(reverted toSECURITY DEFINERin20261118140000), anduser_overrides(nocompany_idcolumn).
- PostgreSQL RLS: Plain members (
- 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_roleonly),documents(signed URLs; CRM offer/agreement paths omit${companyId}/and bypass storage quota tracking),governance_documents(signed URLs),invoices,coop_reports(60s signed URLs).
- Public:
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
#09090Bheader with3px solid #32CA42accent,#F4F4F5backdrop,#FFFFFFcard,#32CA42CTA button with#09090Bbold text,#22A830green links, hosted PNG logo (logo-white.png). - Zone 2 (Tenant Co-Branded PDFs, DOCX & Widgets): White A4 background (
18mm/16mmmargins), 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).
- Zone 1 (Platform Emails & Unconfigured Fallbacks): Graphite
- 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 embedshttps://dev-webpage.planovi.app/assets/logo-white.pnginstead ofhttps://planovi.app/assets/logo-white.png. - Non-Compliant:
send-subscription-updated&send-subscription-cancelled(white/light text#F1F5F9/#CBD5E0on#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).
- Compliant (Zone 1):
- i18n (
pl/en):- User-facing Polish error messages, emails, and documents are hardcoded inline across functions (no central i18n dictionary).
generate-offersupportspl-PL,en-GB,en-US,de-DEfor number/currency formatting, yet leaves table headers, seller labels, and email body in Polish.reminder-scheduleremits English HTML emails (en-UStime formatting);jarvisdynamically 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), causingpdf-libWinAnsi 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 } }, usingerr.status ?? 500). Older functions throw plainError(causing HTTP500for 400/401/403/404 validation errors), or return HTTP400for every failure (export-csv,generate-report), or always return HTTP200(fetch-energy-news). - Logging: Only
ingest-telemetryemits structured JSON logs (request_id,event,latency_ms). All other functions use plaintextconsole.log/console.error(generate-reporthas zero logging).process-declaration-ocrlogs up to 1,500 chars of raw document text + full Gemini output. - Timeouts & Retries:
- Router worker limits (
main/index.ts):150 MBRAM,300swall clock,10ssoft /20shard CPU. - Explicit
15_000 msAbortSignal.timeouton: Resend (_shared/email.ts), DealFlow form writer (_shared/form_link.ts), andconverters-api-devdual-write (ingest-telemetry). - Explicit
4_500 mstimeout on QuickChart.io (generate-report);8_000 mson 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), andrun-scheduler(DB-configured inline sleep retries) implement retry logic.
- Router worker limits (
- Maintenance Gates:
app_modules+app_modules_maintenance(20240101000000) store per-module maintenance flags (bypass_for_admins = true), read by client apps — zero Edge Functions checkapp_modules_maintenance. - SQL Security Guards:
trg_guard_company_license_tier,trg_guard_company_licenses,trg_guard_user_license_assignments,trg_company_members_billing_guard, andRESTRICTIVERBAC policies enforce integrity wheneverauth.uid() IS NOT NULL.