Skip to content

Conversation

@arjunkomath
Copy link
Member

@arjunkomath arjunkomath commented Jul 27, 2025

Summary by CodeRabbit

  • New Features

    • Introduced an API endpoint to clean up pages linked to inactive subscriptions, automatically removing old pages and their audit logs.
    • Added a new database function to identify pages associated with inactive subscriptions for improved account management.
    • Added handling for deleting custom domains from Vercel when page settings are deleted.
    • Added a scheduled job to run daily for cleaning up inactive pages.
    • Updated type definitions and constants for improved consistency and easier integration with page and subscription features.
  • Bug Fixes

    • Ensured audit logs are automatically deleted when their associated pages are removed.

@vercel
Copy link

vercel bot commented Jul 27, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
changes-page ✅ Ready (Inspect) Visit Preview Jul 27, 2025 5:01am
changes-page-docs ✅ Ready (Inspect) Visit Preview Jul 27, 2025 5:01am
1 Skipped Deployment
Name Status Preview Updated (UTC)
user-changes-page ⬜️ Skipped (Inspect) Jul 27, 2025 5:01am

@coderabbitai
Copy link

coderabbitai bot commented Jul 27, 2025

Walkthrough

A new API endpoint for cleaning up pages tied to inactive subscriptions was added, leveraging a new Supabase function and updated type definitions. The database migration introduces a function to fetch such pages and modifies a foreign key constraint for cascading deletes. The webhook handler was enhanced to delete custom domains on page deletion. Type utilities and enums in the Supabase types package were refactored and extended. Additionally, a new scheduled job was added to the Vercel configuration for running the cleanup daily.

Changes

File(s) Change Summary
apps/web/pages/api/billing/jobs/cleanup-inactive-pages.ts Added an API handler to delete pages associated with inactive subscriptions, using a new Supabase function, with logging and error handling.
apps/web/pages/api/pages/settings/webhook.ts Extended webhook handler to delete custom domains from Vercel when a page is deleted, with error handling and logging.
apps/web/vercel.json Added a new scheduled cron job at 1:00 AM daily for the cleanup inactive pages API endpoint.
packages/supabase/migrations/17_handle_inactive_pages.sql Added a migration: updates foreign key on page_audit_logs to use ON DELETE CASCADE and introduces the get_pages_with_inactive_subscriptions() function for identifying pages to delete.
packages/supabase/types/index.ts Extended the Database type for internal metadata, added/updated function types, refactored type utilities to use new schema aliases, and introduced a Constants object for enums.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API (cleanupInactivePagesJob)
    participant Supabase

    Client->>API (cleanupInactivePagesJob): POST /api/billing/jobs/cleanup-inactive-pages
    API->>Supabase: Call get_pages_with_inactive_subscriptions()
    Supabase-->>API: Return list of inactive pages
    alt Pages found
        API->>Supabase: Delete pages by IDs
        Supabase-->>API: Deletion result
        API-->>Client: Respond with job ID, status, deleted count
    else No pages found
        API-->>Client: Respond with job ID, status, zero deleted
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

In the warren of code, a cleanup begins,
Old pages retire as a new job spins.
With Supabase magic and types that align,
Inactive subscriptions are pruned just fine.
The logs are all tidy, the enums in place—
A rabbit’s delight for a cleaner workspace! 🐇✨

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/handle-inactive-pages

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
apps/web/pages/api/billing/jobs/cleanup-inactive-pages.ts (1)

64-91: Excellent audit logging implementation

The comprehensive logging with unique job IDs provides a good audit trail for tracking deletions. The structured logging approach makes it easy to trace operations.

One minor improvement for error handling:

     res.status(500).json({
       error: {
         statusCode: 500,
-        message: err.message || "Internal server error",
+        message: process.env.NODE_ENV === "production" 
+          ? "Internal server error" 
+          : (err.message || "Internal server error"),
       },
     });

This prevents leaking potentially sensitive error details in production.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 03c61c2 and e1ff8a5.

📒 Files selected for processing (3)
  • apps/web/pages/api/billing/jobs/cleanup-inactive-pages.ts (1 hunks)
  • packages/supabase/migrations/17_handle_inactive_pages.sql (1 hunks)
  • packages/supabase/types/index.ts (3 hunks)
🔇 Additional comments (4)
packages/supabase/migrations/17_handle_inactive_pages.sql (1)

1-10: Good approach for maintaining referential integrity

Adding CASCADE DELETE to the foreign key constraint ensures audit logs are automatically cleaned up when pages are deleted. This prevents orphaned records and simplifies the cleanup process.

packages/supabase/types/index.ts (3)

9-14: Good addition for Supabase client configuration

The __InternalSupabase property enables automatic client instantiation with the correct Postgrest version, improving developer experience.


561-570: Type definition correctly matches the SQL function

The function type accurately reflects the SQL function signature and return type from the migration file.


744-753: Useful addition for runtime enum access

The Constants export provides runtime access to enum values, which is helpful for validation and UI components.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
apps/web/pages/api/pages/settings/webhook.ts (1)

24-41: LGTM with suggestions for enhanced security and error handling.

The DELETE event handler correctly integrates with Vercel's API to clean up custom domains. The static analysis SSRF warning is likely a false positive since custom_domain comes from the database record, not direct user input.

Consider these improvements for robustness:

 if (type === "DELETE") {
   if (page_settings?.custom_domain) {
+    // Validate domain format for defense in depth
+    const domainRegex = /^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$/;
+    if (!domainRegex.test(page_settings.custom_domain)) {
+      console.error("Invalid domain format:", page_settings.custom_domain);
+      return res.status(200).json({ ok: true });
+    }
+
     try {
       const response = await fetch(
         `https://api.vercel.com/v8/projects/${process.env.VERCEL_PAGES_PROJECT_ID}/domains/${page_settings.custom_domain}?teamId=${process.env.VERCEL_TEAM_ID}`,
         {
           headers: {
             Authorization: `Bearer ${process.env.VERCEL_AUTH_TOKEN}`,
           },
           method: "DELETE",
         }
-      ).then((res) => res.json());
+      );
+      
+      if (!response.ok) {
+        console.error(`Vercel API error: ${response.status} ${response.statusText}`);
+        const errorData = await response.json();
+        console.error("Vercel API error details:", errorData);
+      } else {
+        const data = await response.json();
+        console.log("Response from Vercel API:", data);
+      }
-      console.log("Response from Vercel API:", response);
     } catch (error) {
       console.error("Error deleting custom domain:", error);
     }
   }
 }

These changes add:

  1. Domain format validation to address potential security concerns
  2. Proper HTTP response status checking
  3. Better error logging for debugging
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e1ff8a5 and a86b2cc.

📒 Files selected for processing (1)
  • apps/web/pages/api/pages/settings/webhook.ts (1 hunks)
🧰 Additional context used
🪛 GitHub Check: CodeQL
apps/web/pages/api/pages/settings/webhook.ts

[failure] 27-35: Server-side request forgery
The URL of this request depends on a user-provided value.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
packages/supabase/migrations/17_handle_inactive_pages.sql (1)

13-47: Pagination & indexing were already requested – still unresolved

Previous review highlighted that returning the entire result set with no LIMIT / OFFSET and without supporting indexes can hurt production performance. The function body is unchanged, so the concern remains.

🧹 Nitpick comments (2)
packages/supabase/migrations/17_handle_inactive_pages.sql (2)

2-3: Make the migration idempotent by guarding the drop with IF EXISTS

Running this migration twice (e.g. on a restored staging DB) will fail because the constraint is already gone. Add IF EXISTS to make the script safe to re-run.

-ALTER TABLE page_audit_logs 
-DROP CONSTRAINT page_audit_logs_page_id_fkey;
+ALTER TABLE page_audit_logs 
+DROP CONSTRAINT IF EXISTS page_audit_logs_page_id_fkey;

6-10: Protect the re-creation against name clashes

If a different migration has already introduced a cascade version of this FK, ADD CONSTRAINT will error. Consider the DO-block pattern to check first, or pick a new constraint name.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a86b2cc and 926c487.

📒 Files selected for processing (1)
  • packages/supabase/migrations/17_handle_inactive_pages.sql (1 hunks)

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 213e13d and 068159d.

📒 Files selected for processing (1)
  • apps/web/vercel.json (1 hunks)

Comment on lines +7 to 10
{
"path": "/api/billing/jobs/cleanup-inactive-pages",
"schedule": "0 1 * * *"
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Specify HTTP method to prevent side-effectful cleanup from defaulting to GET

Vercel cron invocations default to a GET request, which is semantically wrong for a mutation-type endpoint and can introduce caching or proxy side-effects. Declare the intended verb explicitly.

       "path": "/api/billing/jobs/cleanup-inactive-pages",
+      "method": "POST",
       "schedule": "0 1 * * *"

Ensure the handler in pages/api/billing/jobs/cleanup-inactive-pages.ts is prepared to accept POST requests before applying the change.


🏁 Script executed:

#!/bin/bash
set -e

# Locate the cleanup-inactive-pages API handler file
handler_file=$(fd cleanup-inactive-pages.ts)

echo "Handler file found at: $handler_file"

# Inspect HTTP method checks in the handler
echo -e "\nChecking for HTTP method conditions (req.method) in the handler:"
grep -n -C2 "req.method" "$handler_file" || echo "No HTTP method checks found"

# Show the handler export signature for context
echo -e "\nHandler export signature:"
grep -n "export default" "$handler_file" | head -n 1

Length of output: 864


Specify HTTP method for the cleanup-inactive-pages cron job

Your handler in apps/web/pages/api/billing/jobs/cleanup-inactive-pages.ts already enforces req.method === "POST" (returning 405 otherwise), so it’s safe—and recommended—to explicitly declare the HTTP verb in vercel.json to avoid a default GET invocation:

• File: apps/web/vercel.json
• Location: the block for /api/billing/jobs/cleanup-inactive-pages

     {
       "path": "/api/billing/jobs/cleanup-inactive-pages",
+      "method": "POST",
       "schedule": "0 1 * * *"
     }

This ensures Vercel’s cron will invoke the endpoint with POST, matching your mutation-style handler.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{
"path": "/api/billing/jobs/cleanup-inactive-pages",
"schedule": "0 1 * * *"
}
{
"path": "/api/billing/jobs/cleanup-inactive-pages",
"method": "POST",
"schedule": "0 1 * * *"
}
🤖 Prompt for AI Agents
In apps/web/vercel.json around lines 7 to 10, the cron job for
/api/billing/jobs/cleanup-inactive-pages does not specify the HTTP method,
causing Vercel to default to GET. Since your handler requires POST, update the
configuration to explicitly include "method": "POST" in the job definition to
ensure the cron triggers a POST request matching your handler's expectations.

@arjunkomath arjunkomath merged commit cbebe2b into develop Jul 27, 2025
6 checks passed
@arjunkomath arjunkomath deleted the feat/handle-inactive-pages branch July 27, 2025 05:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant