Skip to content

2. RBAC, Licensing, Quotas, Operator Panel & Team Access

Repository: Backend (planovi-backend) • Rule Prefix: BR-RBAC • Documented Rules: 17 • Open [TEAM_WHY_NEEDED] Questions: 3

1. Business Purpose & Actors

Controls multi-tenant authorization, plan/module gating, license seat allocation, billing manager delegation, platform operator governance (company inspection & Stripe discount grants), company storage & per-user monthly AI token quotas, team invitations, cooperative member portal onboarding, 2FA policy enforcement, and self-service GDPR account deletion/update notifications.

  • Actors:
    • Platform Operator (public.platform_operators active owner/admin): Views all tenants/licenses (operator_companies, operator_company_detail, operator_grants) and creates/revokes Stripe coupons (operator-coupons).
    • Company Owner (company_members.role = 'owner', is_active = true): Only role bypassing RBAC role/override checks inside their company (still bounded by company_has_module). Manages billing, delegates can_manage_billing (set_billing_manager), invites/modifies owners, and edits any RBAC role/override.
    • Company Admin (role = 'admin', is_active = true): Bound by their auto-seeded 'Admin' RBAC role (20261116150000), cannot edit their own role or manage admins/owners, cannot manage billing unless can_manage_billing = true or company has 0 active owners.
    • RBAC-Delegated Staff / Coop Staff (technician, auditor, or custom RBAC roles): Access governed by has_permission() and OTHERS/full_scope.
    • Plain Member (role = 'member'): Scoped to own buildings, own telemetry/devices, own invoices/wallet transactions; requires an active seat in user_license_assignments.
    • Unauthenticated User: Can cancel scheduled deletion via GET /functions/v1/cancel-account-deletion?token=<user_profile_id>.

2. All Features & End-to-End Flows

  1. Invite Team Member (supabase/functions/invite-team-member/index.ts):
    • POST -> Bearer JWT + active company_members (admin/owner) -> validates email regex, first_name/last_name (max 80), phone (max 30), license_ids (deduped with legacy license_id, max 5, max 1 non-addon main plan, active & assigned < seat_count), optional role_id belonging to company_id (only owner may assign/re-invite owner role -> 403).
    • Reuses existing user_profiles by exact lowercase email (sets actionUrl = PANEL_URL) OR creates new user via auth.admin.generateLink({ type: "invite", ... }) (actionUrl = ${PANEL_URL}/?token_hash=...&type=invite).
    • Rejects active existing members (400), updates user_profiles, upserts company_members (is_active: true), replaces user_roles if role_id provided, inserts user_license_assignments, emails invite via Resend ("Planovi – zaproszenie do zespołu ${companyName}", non-fatal on failure), returns 200 { success: true, is_new_user, user_id, license_assigned, licenses_assigned }.
  2. Grant Portal Access (supabase/functions/grant-portal-access/index.ts):
    • POST -> Bearer JWT + requireStaff(company_id, "OTHERS") -> verifies target belongs to company (onboarding_sessions matching session_id, or row in company_members/onboarding_sessions) -> inserts company_members (role: "member", ignoring Postgres 23505) -> updates user_profiles (onboarding_status: "approved", is_energy_coop_member: true) -> sends Resend welcome email unless email_opt_out === true (non-fatal warning on failure).
  3. Schedule Account Deletion Notice (supabase/functions/send-account-deletion-notice/index.ts):
    • POST -> Bearer JWT -> verifies user.id === user_profile_id -> idempotently sets user_profiles.deletion_scheduled_at = now() + 30 days (if null) -> sends Polish notice email with ?token=${user_profile_id} cancellation link, ignoring email_opt_out. All errors return HTTP 500.
  4. Cancel Account Deletion (supabase/functions/cancel-account-deletion/index.ts):
    • Public GET ?token=<user_profile_id> -> looks up user_profiles -> if deletion_scheduled_at is null returns 200 HTML "Usunięcie już anulowane", else clears to null and returns 200 HTML "Usunięcie anulowane" with CTA to PORTAL_URL. Missing token -> 400 HTML; not found -> 404 HTML; DB error -> 500 HTML.
  5. Account Updated Notice (supabase/functions/send-account-updated-notice/index.ts):
    • POST -> Bearer JWT -> verifies user.id === user_profile_id and non-empty changed_fields[] -> maps keys (first_name, last_name, email, phone, avatar_url, password, "2fa") to Polish labels -> emails user via Resend unless email_opt_out === true. All errors return HTTP 500.
  6. Operator Coupons (supabase/functions/operator-coupons/index.ts):
    • POST (405 otherwise) -> Bearer JWT verified against active owner/admin in platform_operators (403 "Brak dostępu: tylko operator platformy").
    • action: "create": validates code (auto-generates PLANOVI-XXXXXXXX if omitted), percent_off (0.01..100), duration (once|repeating [1..36 mo]|forever), redeem_by (> now + 60s), max_redemptions (1..10000), company_id, allowed_tiers, seat_limits (1..1000/tier), max_total_seats (1..10000), note (>= 3 chars), unique code -> creates Stripe POST /v1/coupons (resolving product IDs from GET /v1/prices/{id}) -> creates Stripe POST /v1/promotion_codes (dual-payload fallback coupon= -> promotion[type]=coupon) -> inserts license_grants (deactivates Stripe promo code on DB failure).
    • action: "revoke": idempotently deactivates Stripe promo code (active=false) and sets license_grants.revoked_at, revoked_by.
  7. Database RBAC, License, Billing & Quota RPCs/Triggers:
    • trg_guard_company_license_tier, trg_guard_company_licenses, trg_guard_user_license_assignments, trg_sync_seats_used, trg_company_members_billing_guard, trg_access_levels_grant_admin, trg_sync_company_storage_usage.
    • RPCs: has_permission, company_has_module, planovi_has_module_full_scope, planovi_has_full_scope_any, my_license_access, my_billing_access, billing_admins, set_billing_manager, company_admin_contacts, company_storage_status, can_upload, recalculate_company_storage, my_token_status, get_user_token_status, record_ai_token_usage, is_platform_operator, operator_companies, operator_company_detail, operator_grants.

3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-RBAC)

  • BR-RBAC-01 (Payment-System-Only License Mutation): 20261029120000_license_guard.sql: Authenticated callers (auth.uid() IS NOT NULL) cannot update companies.license_tier, insert/delete company_licenses, or update any company_licenses column other than seats_used and updated_at (42501).
  • BR-RBAC-02 (Tier Quota Matrix): 20261102110000 & 20261102130000:
    • starter (1, is_addon=false): 5 GiB (5,368,709,120 B), 10,000 AI tokens/mo, margin 1.50, GA4 false.
    • pro (2, is_addon=false): 10 GiB (10,737,418,240 B), 100,000 AI tokens/mo, margin 1.50, GA4 true.
    • enterprise (3, is_addon=false): 25 GiB (26,843,545,600 B), 100,000 AI tokens/mo, margin 1.50, GA4 true.
    • energy_coop (4, is_addon=true): 10 GiB (10,737,418,240 B), 0 AI tokens/mo, margin 1.50, GA4 false.
  • BR-RBAC-03 (Quota Aggregation & Legacy Fallback): fn_company_tier_limits (20261102130000) reads active/trialing company_licenses; ONLY if 0 exist, falls back to companies.license_tier::int[]. Computes disk_limit_bytes = MAX(base) + SUM(addon) (+ purchased_storage_addon_bytes), token_limit = MAX(user_token_monthly_limit) (+ purchased_token_addon), margin = MAX(token_margin_multiplier) (default 1.50).
  • BR-RBAC-04 (Storage Quota Scope): trg_sync_company_storage_usage (20261102120000) tracks ONLY 6 buckets (documents, invoices, governance_documents, buildings, company-media, coop_reports) when split_part(name, '/', 1) is a valid companies.id UUID. Exceptions downgrade to WARNING (never blocks uploads); enforcement relies on callers invoking can_upload(company_id, bytes).
  • BR-RBAC-05 (AI Token Billing & Monthly Rollover): fn_token_quota_locked (20261102120000) locks user_token_quotas FOR UPDATE, resets current_tokens_used = 0 lazily when now() >= token_cycle_reset_at (advancing by elapsed whole months + 1), checks remaining > 0, bills ceil((max(prompt,0) + max(completion,0)) * margin), and logs ai_token_logs (p_feature max 50 chars).
  • BR-RBAC-06 (Serialized Seat Allocation): trg_guard_user_license_assignments (20261103100000) locks company_licenses FOR UPDATE, requires status = 'active', same-company active company_member_id, unique (company_license_id, company_member_id) (23505), and count < seat_count (42501). No UPDATE RLS policy exists on user_license_assignments so trg_sync_seats_used (SECURITY DEFINER) cannot drift.
  • BR-RBAC-07 (Multi-License Invite Constraints): invite-team-member/index.ts caps requests at <= 5 license IDs, max 1 non-addon main plan (!is_addon), and blocks non-owners from inviting or reactivating role = 'owner' (403).
  • BR-RBAC-08 (Owner-Only Billing Delegation + Ownerless Fallback): 20261110190000: Only active owners may call billing_admins, set_billing_manager (targeting active admins only, 22023 otherwise), or mutate company_members.can_manage_billing (42501). If a company has 0 active owners, any active admin receives can_manage_billing = true.
  • BR-RBAC-09 (Blocked-Seat Admin Contacts): company_admin_contacts(p_company_id) (20261110210000) returns up to 5 active admins (excluding owners and auth.uid()).
  • BR-RBAC-10 (Canonical RBAC Precedence): has_permission(p_company, p_module, p_action) (20261116160000) checks strictly in order: (1) auth.uid() IS NOT NULL; (2) active company_members; (3) company_has_module(p_company, p_module) (gates owners too); (4) rbac_is_owner(p_company) (only owner bypasses; admin does NOT); (5) user_overrides is_granted = false (deny wins); (6) user_overrides is_granted = true; (7) user_roles -> role_permissions -> access_levels.
  • BR-RBAC-11 (Module min_plan Matrix): 20261116160000, 20261117090000, 20261117130000:
    • min_plan = 1 (Starter): dashboard, documents.*, sales, clients.*, dealflow*, schedules*, calendar, scheduler_bookings, settings, config, team, custom_enums, offer_templates, agreement_templates, offers, agreements, team_calendars (and unknown modules).
    • min_plan = 2 (Pro): jarvis, operations.
    • min_plan = 3 (Enterprise): strategy.
    • min_plan = 4 (Energy add-on / is_cooperative = true): energy_devices, energy_balance, knowledge_base.*, team_declarations.*, governance.*, wallet, technician_queue, ledger.*, coop_settings.
  • BR-RBAC-12 (Anti-Privilege-Escalation RESTRICTIVE RLS): 20261116150000: roles/role_permissions writes require rbac_may_edit_role (owner OR caller doesn’t hold that role); user_roles writes require rbac_may_manage_member (owner OR target != self AND target not admin/owner); user_overrides writes require rbac_may_manage_overrides_of (target != self AND owner in every shared company where target is admin/owner). trg_access_levels_grant_admin auto-grants every new access_levels row to all roles named 'Admin'.
  • BR-RBAC-13 (Full-Scope Visibility & Member Data Isolation): 20261105120000, 20261105130000, 20261117120000, 20261117130000, 20261117140000: Plain members (role = 'member') without OTHERS/full_scope see ONLY own buildings (buildings.client_id = auth.uid()), own converters/gateways/telemetry/live-state, own building billing_records (not coop-level building_id IS NULL), and own member_wallet_transactions. full_scope applies to 5 modules (dashboard, energy_devices, energy_balance, wallet, ledger).
  • BR-RBAC-14 (Pilot Declarations Write RLS): 20261116100000 & 20261116150000 drop legacy admin write policies and enforce has_permission() on declaration_templates, declaration_fields, declaration_steps, onboarding_sessions, member_declaration_reviews, onboarding_tokens, and company_members DELETE (blocks deleting owner, admin, or self).
  • BR-RBAC-15 (2FA Enforcement Setting): 20261118180000: company_settings.enforce_2fa (default false) readable by active members; writable by rbac_is_owner OR has_permission(company_id, 'coop_settings', 'UPDATE').
  • BR-RBAC-16 (Operator & Grant Constraints): platform_operators, license_grants, license_grant_redemptions have RLS enabled with ZERO policies + REVOKE ALL from anon, authenticated. license_grants checks: code ~ '^[A-Z0-9][A-Z0-9_-]{2,39}$', percent_off ∈ (0, 100], duration_months ∈ [1, 36] iff 'repeating', max_redemptions ∈ [1, 10000], max_total_seats ∈ [1, 10000].
  • BR-RBAC-17 (Self-Only Account Notices & Opt-Out Override): send-account-deletion-notice & send-account-updated-notice enforce user.id === user_profile_id. Deletion notice ALWAYS ignores email_opt_out; update & welcome emails honor email_opt_out === true.

4. State Machines & Data Lifecycle

stateDiagram-v2
    [*] --> Pending : invite / onboarding created
    Pending --> Filled : member submits declaration
    Pending --> Expired : token expires on submit
    Filled --> CorrectionRequired : board requests fixes
    CorrectionRequired --> Filled : member resubmits
    Filled --> Approved : grant-portal-access
    Filled --> Rejected : send-rejection-notice
    Approved --> [*]
    Rejected --> [*]
  • license_grants: Active (revoked_at IS NULL, bounded by redeem_by & max_redemptions) -> Revoked (revoked_at, revoked_by via operator-coupons).
  • license_grant_redemptions.outcome: 'ok' | 'cancelled_over_limit' | 'over_limit_update'.
  • user_profiles.deletion_scheduled_at: NULL (active) <-> now() + 30 days (send-account-deletion-notice / cancel-account-deletion).
  • RBAC Realtime Tables (20261117100000): role_permissions, user_overrides, user_roles, company_members stream live changes via supabase_realtime.

5. Technical Contract

  • Endpoints: POST invite-team-member, POST grant-portal-access, POST send-account-deletion-notice, GET cancel-account-deletion?token=, POST send-account-updated-notice, POST operator-coupons.
  • Tables Created/Altered: company_storage_quotas, user_token_quotas, ai_token_logs, platform_operators, license_grants, license_grant_redemptions, company_settings (+enforce_2fa), license_tiers (+company_disk_limit_bytes, +user_token_monthly_limit, +token_margin_multiplier, +allow_ga4_integration, +is_addon), company_members (+can_manage_billing), app_modules (+parent_module_name, +sort_order, +min_plan).
  • External APIs: Resend API (invite-team-member, grant-portal-access, send-account-deletion-notice, send-account-updated-notice), Stripe REST API (GET prices/{id}, POST coupons, POST promotion_codes, POST promotion_codes/{id} in operator-coupons).

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
planovi-flutter-app (LicenseGate, PermissionProvider, OperatorPanel, Settings) -> PostgreSQL RPCs & RealtimePostgREST + Supabase Realtime / User JWTmy_license_access, company_admin_contacts, my_billing_access, billing_admins, set_billing_manager, company_storage_status, can_upload, my_token_status, is_platform_operator, operator_companies, operator_company_detail, operator_grants, Realtime on 4 RBAC tables
planovi-flutter-app -> Module 2 Edge FunctionsHTTPS POST / User JWTinvite-team-member, grant-portal-access, send-account-deletion-notice, send-account-updated-notice, operator-coupons
operator-coupons -> Stripe APIHTTPS form-urlencoded / STRIPE_SECRET_KEY/v1/prices/{id}, /v1/coupons, /v1/promotion_codes
handle-stripe-webhook, change-plan -> license_grants / license_grant_redemptionsPostgREST / Service RoleEnforces grant limits created by operator-coupons
jarvis/index.ts -> get_user_token_status / record_ai_token_usagePostgREST RPC / Service RolePre-check & post-LLM token billing

7. Why It Works This Way

  • auth.uid() IS NULL trigger bypasses: Enables webhooks/service-role/Studio SQL to manage billing/seats while blocking PostgREST client tampering.
  • sync_seats_used() made SECURITY DEFINER (20261103100000): Previously ran as caller; legacy RLS only allowed admin (not owner), causing seats_used drift whenever an owner removed a seat.
  • fn_company_tier_limits companies.license_tier fallback (20261102130000): 19 legacy DEV companies had no company_licenses rows and would otherwise get 0 storage/token quota.
  • Additive rbac_full_scope_select policies (20261117120000/130000): Intentionally OR-ed with legacy planovi_coop_staff_company_ids() during phased rollout so no existing staff lose access before legacy policies are dropped.
  • Explicit null::uuid for app_modules.created_by/updated_by: Avoids FK violation against non-existent default system user UUID in public.users.
  • [TEAM_WHY_NEEDED: user_overrides lacks a company_id column, so revoking/granting an override for a user in Company A mutates their permissions in Company B. Is a schema migration adding company_id planned?]
  • [TEAM_WHY_NEEDED: user_token_quotas.purchased_token_addon is permanently added to every monthly cycle reset instead of decrementing as a one-time top-up. Is it intended to be a recurring monthly add-on or an unfinished consumption model?]
  • [TEAM_WHY_NEEDED: send-account-deletion-notice comments describe a 30-day permanent purge & encryption cron job, which does not exist in this repository. Where is it implemented?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact Query or LogFix
Operator panel returns 403 / 42501 "Brak dostępu: tylko operator platformy"public.platform_operators is not seeded by migrations (20261110150000:15-17)SELECT * FROM public.platform_operators; (as service_role)INSERT INTO public.platform_operators (company_id) VALUES ('<planovi-company-uuid>') ON CONFLICT DO NOTHING;
Unsubscribe link from grant-portal-access or send-account-updated-notice returns 404Both pass ?token=${user_profile_id} instead of an onboarding_tokens.token, which unsubscribe/index.ts:57 cannot matchInspect grant-portal-access/index.ts:207 & send-account-updated-notice/index.ts:107Update unsubscribe or mint signed/dedicated opt-out tokens
Storage quota numbers drift from actual Storage usagetrg_sync_company_storage_usage swallowed a failure (WARNING) or legacy files predated triggerPostgres logs for storage usage tracking skipped; compare company_storage_quotas vs storage.objectsRun SELECT public.recalculate_company_storage(); as service_role
Deactivated member cannot regain access via grant-portal-accessgrant-portal-access/index.ts:166-173 ignores 23505 on company_members insert without flipping is_active = trueSELECT is_active, role FROM company_members WHERE company_id=... AND user_id=...;Update grant-portal-access to upsert is_active = true
Non-owner admin still bypasses RBAC in Edge Functions or sees full telemetry after full_scope revokeinvite-team-member/grant-portal-access/_shared/auth.ts still bypass for admin, and legacy planovi_coop_staff_company_ids() SELECT policies remain activeCheck pg_policies on raw_telemetry/billing_records and _shared/auth.ts:70Drop legacy staff SELECT policies once RBAC rollout completes; align _shared/auth.ts to owner-only bypass
has_permission(co, mod, 'OTHERS') unexpectedly returns truehas_permission (20261116160000) omits al.granular_action IS NULL, matching full_scope/vote/generateSELECT * FROM access_levels WHERE action_type='OTHERS';Filter al.granular_action IS NULL in has_permission or add p_granular parameter