Skip to content

Monetization Integrations

jumalaw98 edited this page May 28, 2026 · 1 revision

Monetization & Integrations

Subscription Tiers & Feature Gating

Relevant source files

The following files were used as context for generating this wiki page:

Subscription Tiers & Feature Gating

The Subscription Tiers & Feature Gating system in Colabs is a centralized architecture designed to manage user access levels across three primary plans: Starter, Pro, and Pro+. This system ensures that premium functionalities—such as private repository syncing, team management, and advanced analytics—are reserved for paying users while maintaining a functional free tier for the community. The system is built on a foundation of Supabase-backed data fetching and client-side hooks to enforce limits and provide real-time feedback on plan status.

Sources: README.md:104-104, src/hooks/useSubscription.tsx:28-40

Subscription Architecture

The architecture relies on a "Security Definer" pattern within Supabase to handle subscription verification and automatic demotion. The frontend consumes this state via the useSubscription hook, which centralizes the logic for plan identification and feature availability.

Data Flow & Verification

Subscription data is fetched from the user_subscriptions table via a specialized RPC call. This call, check_and_demote_subscription, acts as a server-side gatekeeper that evaluates the user's current status and expires-at timestamps before returning the active plan details to the client.

flowchart TD
    User[User Session] --> Hook[useSubscription Hook]
    Hook --> RPC{check_and_demote_subscription}
    RPC -- Valid --> Cache[React Query Cache]
    RPC -- Expired --> Demote[Demote to Starter]
    Demote --> Cache
    Cache --> UI[Feature Gating Logic]
    UI --> UI_Elements[Buttons/Tabs/API Access]
Loading

The flow ensures that if a user's subscription has lapsed, the system automatically demotes them to the "Starter" tier during the initial data fetch. Sources: src/hooks/useSubscription.tsx:84-106

Plan Tiers & Resource Limits

Colabs defines specific resource quotas and feature access for each tier. These limits are defined in a central PLAN_LIMITS configuration object.

Defined Limits Table

Feature Starter (Free) Pro ($20/mo) Pro+ ($30/mo)
Project Limit 3 25 Unlimited
Team Management No (0) Yes (3) Unlimited
Gig Marketplace No Yes Yes
Advanced Analytics No Yes Yes
API Access No No Yes
Repository Access Public Only Private & Public Private & Public

Sources: src/hooks/useSubscription.tsx:28-33, src/pages/Settings.tsx:220-252

Implementation Components

useSubscription Hook

This custom hook serves as the primary interface for components to determine user capabilities. It returns a SubscriptionState object containing boolean flags and metadata.

Key Data Structure:

export interface SubscriptionState {
  plan: 'starter' | 'pro' | 'pro_plus';
  status: 'active' | 'expired' | 'cancelled';
  expiresAt: string | null;
  isPro: boolean;
  isProPlus: boolean;
  canCreateProject: boolean;
  canCreateGig: boolean;
  canCreateTeam: boolean;
  canAccessAdvancedAnalytics: boolean;
  canAccessApi: boolean;
  daysRemaining: number | null;
}

Sources: src/hooks/useSubscription.tsx:10-26

Billing Management

Billing is handled via an integration with the Stripe Customer Portal. Users access this via the Settings page, which triggers an Edge Function to generate a secure portal session.

sequenceDiagram
    participant U as User (Settings UI)
    participant E as Supabase Edge Function
    participant S as Stripe API
    U->>E: invoke('create-portal-session')
    alt Stripe Configured
        E->>S: Create Session
        S-->>E: return url
        E-->>U: Redirect to Stripe Portal
    else Stripe Not Configured
        E-->>U: Error: stripe_not_configured
        U-->>U: Show Info Toast
    end
Loading

Sources: src/pages/Settings.tsx:50-84

Feature Gating Logic

Feature gating is enforced throughout the application using conditional rendering and disabled states based on the flags returned by useSubscription.

  1. UI Feedback: In the Settings billing section, the UI displays badges (e.g., "Active" or "Free") and a summary of current features based on the plan ID.
  2. Access Blocking: Features like "Manage Billing" are only enabled if the user has a pro or pro_plus plan; otherwise, an "Upgrade Plan" or "View Plans" button is presented.
  3. Automatic Demotion: If expires_at is in the past, the isExpired flag is set to true, and the UI provides visual feedback to the user regarding the loss of premium access.

Sources: src/pages/Settings.tsx:215-275, src/hooks/useSubscription.tsx:126-130

Conclusion

The subscription and feature gating system provides a robust framework for monetizing the Colabs platform while ensuring data integrity via server-side checks. By centralizing limits in a single hook and using Supabase RPCs for state management, the project maintains a clear separation between business logic and presentational components. Developers should reference the PLAN_LIMITS object in useSubscription.tsx when adding new features that require access control.

Sources: src/hooks/useSubscription.tsx:28-33, CLAUDE.md:214-214

Stripe Checkout & Portal Integration

Relevant source files

The following files were used as context for generating this wiki page:

Stripe Checkout & Portal Integration

The Stripe Checkout and Portal Integration provides the financial infrastructure for the Colabs platform, enabling marketplace transactions for digital projects and subscription management for users. The system leverages Supabase Edge Functions to securely interact with the Stripe API, facilitating payment processing and a self-service billing portal.

This integration is critical for supporting the platform's tiered subscription models (Starter, Pro, Pro+) and the freelance marketplace where developers can monetize their work. Sources: README.md:92-94, CLAUDE.md:278-281

Architecture Overview

The integration follows a serverless architecture where the frontend communicates with Stripe via Supabase Edge Functions. This ensures that sensitive operations, such as creating checkout sessions or accessing the billing portal, are performed in a secure environment using the STRIPE_SECRET_KEY.

Integration Components

Component Description Location
Marketplace Checkout Handles one-time payments for project purchases. src/pages/Checkout.tsx
Billing Portal Allows users to manage subscriptions and payment methods. supabase/functions/create-portal-session/
Session Verification Post-purchase logic to verify Stripe sessions. src/pages/PurchaseSuccess.tsx
Webhook Handler (Planned) Processes asynchronous events from Stripe. CLAUDE.md:434-436

Sources: src/pages/Checkout.tsx:47-64, supabase/functions/create-portal-session/index.ts:1-15, src/pages/PurchaseSuccess.tsx:32-41

Marketplace Checkout Flow

The marketplace payment flow is initiated when a user attempts to purchase a project. The application transitions from a localized checkout form to a Stripe-hosted checkout page.

flowchart TD
    A[Checkout Page] --> B{Payment Method}
    B -- Card --> C[Invoke 'create-marketplace-checkout']
    C --> D[Redirect to Stripe URL]
    D --> E[Stripe Hosted Payment]
    E --> F[Redirect to /purchase-success]
    F --> G[Invoke 'verify-checkout-session']
    G -- Valid --> H[Show Download Link]
Loading

The checkout process utilizes the create-marketplace-checkout Edge Function to generate a secure session URL. This function requires parameters such as projectId, projectName, amount, and email. Sources: src/pages/Checkout.tsx:50-58, src/pages/PurchaseSuccess.tsx:32-41

Checkout Logic Implementation

The frontend triggers the Stripe session by invoking a Supabase function. Upon successful payment, the user is redirected to a success page where the session_id is extracted from the URL parameters for verification.

// Proposed implementation for Marketplace Checkout
const { data, error } = await supabase.functions.invoke('create-marketplace-checkout', {
  body: {
    projectId: project.id,
    projectName: project.name,
    amount: total,
    userId: user.id,
    email: formData.email
  }
});

if (data?.url) window.location.href = data.url;

Sources: src/pages/Checkout.tsx:50-58

Customer Billing Portal

The Customer Billing Portal is a self-service interface where authenticated users can manage their financial relationship with the platform. This is primarily used for subscription-based features like the Pro and Pro+ tiers.

Portal Functionality

The create-portal-session Edge Function performs the following operations:

  1. Identity Verification: Validates the user's JWT via supabase.auth.getClaims.
  2. Customer Lookup: Retrieves the stripe_customer_id from the public.user_subscriptions table.
  3. Session Creation: Uses the Stripe SDK to create a portal session.
  4. Redirection: Returns a secure URL for the frontend to redirect the user.
sequenceDiagram
    participant User as User Interface
    participant EF as Edge Function
    participant DB as Supabase DB
    participant Stripe as Stripe API
    
    User->>EF: POST /create-portal-session
    EF->>EF: Verify JWT Claims
    EF->>DB: SELECT stripe_customer_id
    DB-->>EF: ID: cus_12345
    EF->>Stripe: stripe.billingPortal.sessions.create()
    Stripe-->>EF: URL: https://billing.stripe.com/...
    EF-->>User: { "url": "..." }
    User->>Stripe: Redirect to Portal
Loading

Sources: supabase/functions/create-portal-session/index.ts:1-25, supabase/functions/create-portal-session/index.ts:77-101

Security and Configuration

Environment Secrets

Stripe integration requires specific secrets to be configured within the Supabase environment. These secrets must never be exposed to the client-side (prefixed with VITE_).

Secret Name Purpose
STRIPE_SECRET_KEY Authenticating requests to the Stripe API from Edge Functions.
STRIPE_WEBHOOK_SECRET Verifying the signature of incoming Stripe webhooks.

Sources: CLAUDE.md:434-436, supabase/functions/create-portal-session/index.ts:16-20

Database Requirements

To support Stripe Customer mapping, the database requires a specific column in the subscription tracking table:

ALTER TABLE public.user_subscriptions ADD COLUMN stripe_customer_id TEXT;

Sources: supabase/functions/create-portal-session/index.ts:22-23

Summary

The Stripe Checkout and Portal integration provides a robust, serverless solution for handling both one-time marketplace transactions and recurring subscriptions. By offloading sensitive payment data to Stripe's hosted UI and securing API interactions within Supabase Edge Functions, the platform maintains high security standards while offering a seamless user experience for billing management and project purchases. Sources: CLAUDE.md:278-281, src/pages/Checkout.tsx:47-64

Webhook Processing

Relevant source files

The following files were used as context for generating this wiki page:

Webhook Processing

Webhook processing in Colabs is a critical component of the platform's integration strategy, primarily used to handle asynchronous events from external services like GitHub and Stripe. These webhooks are processed using Supabase Edge Functions, which run on the Deno runtime, providing a serverless environment for handling external triggers without a persistent custom backend server.

The system is designed to maintain high reliability and security, ensuring that external signals—such as repository updates or payment confirmations—are accurately reflected within the application's PostgreSQL database.

Sources: CLAUDE.md:16-20, CLAUDE.md:330-333

Architecture and Infrastructure

Colabs utilizes Supabase Edge Functions for all server-side logic, including webhook ingestion. Unlike the frontend, which uses Node.js tooling during development, these functions run on Deno. This architectural choice necessitates specific patterns for environment variable access and module imports.

Edge Function Environment

Webhook processing functions are located in the supabase/functions/ directory. They differ from standard Node.js applications in several key ways:

  • Runtime: Deno (uses Deno.env.get instead of process.env).
  • Imports: Uses URL-based imports (e.g., from https://esm.sh/).
  • Server: Uses Deno.serve for handling incoming HTTP requests.

Sources: CLAUDE.md:21-23, CLAUDE.md:300-310

Processing Flow

When an external service sends a POST request to a Colabs webhook endpoint, the Edge Function follows a standardized execution path:

flowchart TD
    A[External Service] -->|POST Webhook| B{Method Check}
    B -->|OPTIONS| C[Return CORS Headers]
    B -->|POST| D[Verify Signature/Secret]
    D -->|Invalid| E[Return 401/403]
    D -->|Valid| F[Execute Business Logic]
    F --> G[Database Update via Service Role]
    G --> H[Return 200 OK]
    
    subgraph Edge Function
    B
    D
    F
    end
Loading

The diagram above illustrates the high-level flow of a webhook request through a Supabase Edge Function.

Sources: CLAUDE.md:315-340

Security and Verification

Security is paramount in webhook processing because these endpoints are exposed to the public internet. Colabs implements several layers of protection to ensure the integrity of incoming data.

Signature Verification

Webhook endpoints must always verify the signature of the payload before processing. This prevents unauthorized actors from spoofing events. For services like Stripe or GitHub, specific secrets (e.g., STRIPE_WEBHOOK_SECRET) are stored in Supabase secrets and accessed within the function.

Sources: CLAUDE.md:330-345

Authentication Bypass

Standard Edge Functions in Colabs often require a JWT for user authentication. However, webhooks are called by external servers that do not possess user JWTs. Therefore, webhook endpoints must be configured with verify_jwt = false in the supabase/config.toml file to allow incoming traffic from external services.

Sources: CLAUDE.md:341-342

Service Role Usage

Because webhooks are system-level events, the functions processing them use the SUPABASE_SERVICE_ROLE_KEY. This key bypasses Row Level Security (RLS), allowing the function to update records across the database that might otherwise be restricted to specific users.

Sources: CLAUDE.md:175-179, CLAUDE.md:323-326

Security Element Implementation Purpose
JWT Verification Set to false in config Allows external server-to-server calls
Secrets Management npx supabase secrets set Securely stores provider-specific webhook secrets
Signature Check Manual verification in code Ensures payload was sent by the trusted provider
Database Access Service Role Client Bypasses RLS for system-wide updates

Sources: CLAUDE.md:330-345, CLAUDE.md:355-365

Error Handling and Resilience

Colabs follows specific patterns to handle failures in webhook processing, particularly to avoid "retry storms" from external providers.

Response Requirements

Webhook endpoints are instructed to return a 200 OK status even on non-fatal errors. This is a best practice for integrations like Stripe and GitHub, which may aggressively retry failed deliveries, potentially overwhelming the serverless infrastructure.

Sources: CLAUDE.md:342-343

Logging and Monitoring

While errors may not be exposed to the caller for security reasons (to avoid leaking stack traces), they are logged internally using console.error within the Deno environment for developer debugging.

Sources: CLAUDE.md:334-340

Integration Specifics

GitHub Synchronization

GitHub webhooks are utilized to sync repository data, such as issues and pull requests, to the Colabs dashboard. This allows the "Explore Issues" and "My Issues" features to stay up-to-date with the actual state of the linked GitHub repositories.

Sources: src/pages/Project.tsx:143-157, src/components/dashboard/IssuesTab.tsx:645-660, CLAUDE.md:460-465

sequenceDiagram
    participant GH as GitHub
    participant EF as Edge Function
    participant DB as PostgreSQL
    GH->>EF: Repository Event (e.g., Issue Opened)
    Note over EF: Verify X-Hub-Signature
    EF->>DB: Upsert Issue Record
    DB-->>EF: Success
    EF-->>GH: 200 OK
Loading

The sequence diagram shows how a GitHub event is propagated to the Colabs database.

Sources: CLAUDE.md:330-345, src/pages/Project.tsx:150-155

Conclusion

Webhook processing in Colabs provides a robust bridge between the SPA frontend and external ecosystem events. By leveraging Supabase Edge Functions and strict security protocols, the system ensures that data synchronization—particularly for GitHub issues and payment states—remains consistent, secure, and resilient to external delivery failures.

Sources: CLAUDE.md:16-20, CLAUDE.md:342-343

Clone this wiki locally