Skip to content

Implement backend payment and pricing model#60

Closed
Jackson57279 wants to merge 1 commit intomainfrom
cursor/implement-backend-payment-and-pricing-model-2165
Closed

Implement backend payment and pricing model#60
Jackson57279 wants to merge 1 commit intomainfrom
cursor/implement-backend-payment-and-pricing-model-2165

Conversation

@Jackson57279
Copy link
Owner

@Jackson57279 Jackson57279 commented Aug 12, 2025

Integrate Autumn for backend-only payments and pricing, including server-side feature checks and usage tracking for chat messages.


Open in Cursor Open in Web

Summary by CodeRabbit

  • New Features
    • Integrated Autumn billing: authenticated checkout, product attachment, feature checks, usage tracking, and customer info retrieval.
    • Server-enforced message limits based on plan with automatic usage recording.
    • Pricing page now falls back to the new checkout flow if the primary provider fails.
  • Documentation
    • Added deployment docs for Autumn billing and required environment variables.
  • Chores
    • Updated environment templates and local setup script to include Autumn configuration.

Co-authored-by: dogesman098 <dogesman098@gmail.com>
@cursor
Copy link

cursor bot commented Aug 12, 2025

Cursor Agent can help with this pull request. Just @cursor in comments and I'll start working on changes in this branch.
Learn more about Cursor Agents

@vercel
Copy link

vercel bot commented Aug 12, 2025

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

Project Deployment Preview Comments Updated (UTC)
zapdev Failed Aug 12, 2025 10:02pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 12, 2025

Walkthrough

Adds Autumn billing integration: new serverless API routes (checkout, attach, check, customer, track) with Clerk-auth and CORS; backend message creation checks/records usage via Autumn; frontend checkout adds an Autumn fallback; introduces Autumn config (features/products); updates README and environment templates/scripts.

Changes

Cohort / File(s) Summary of changes
Autumn serverless API routes
api/autumn-attach.ts, api/autumn-check.ts, api/autumn-checkout.ts, api/autumn-customer.ts, api/autumn-track.ts
Add POST/GET endpoints calling Autumn (/v1/attach, /v1/check, /v1/checkout, /v1/customers/:id, /v1/track). Implement Clerk token auth, dynamic CORS with preflight, upstream error propagation, and AUTUMN_SECRET_KEY/AUTUMN_API_BASE usage.
Backend message gating and tracking
convex/messages.ts
On user message creation, check allowance via Autumn; block when disallowed; after success, record usage via Autumn. Introduces two internal helpers for check/track.
Frontend checkout fallback
src/components/pricing/CustomPricingTable.tsx
In Pro monthly checkout error path, attempt POST to /api/autumn-checkout; redirect on returned URL; adjust error handling and Sentry reporting.
Client-side usage hook
src/lib/ai.ts
Export recordAutumnMessageUsage to POST to /api/autumn-track; ignore errors.
Autumn billing configuration
autumn.config.ts
Define feature messages and products free and pro with included usage and price (static config).
Environment templates
env-template.txt, scripts/create-env-local.js
Add AUTUMN_SECRET_KEY and optional AUTUMN_API_BASE placeholders; insert Autumn section in templates.
Documentation
README.md
Document Autumn (backend-only) billing, env var, endpoints, and server-side access control/usage recording.

Sequence Diagram(s)

sequenceDiagram
  participant FE as Frontend (PricingTable)
  participant API as /api/autumn-checkout
  participant Clerk as Clerk Verify
  participant Autumn as Autumn API

  FE->>API: POST /api/autumn-checkout {product_id}
  API->>Clerk: Verify token (issuer,audience)
  alt Auth OK
    API->>Autumn: POST /v1/checkout {customer_id, product_id}
    alt Autumn OK
      Autumn-->>API: {data|payload}
      API-->>FE: 200 {url or data}
      FE->>FE: Redirect if url present
    else Autumn Error
      Autumn-->>API: error
      API-->>FE: Upstream status + error
    end
  else Auth Fail
    API-->>FE: 401 Unauthorized
  end
Loading
sequenceDiagram
  participant Client as Client (App)
  participant Convex as convex/messages.createMessage
  participant Autumn as Autumn API

  Client->>Convex: createMessage(role, content)
  alt role == 'user'
    Convex->>Autumn: POST /v1/check {customer_id, feature_id:'messages'}
    alt Allowed == true
      Convex->>Convex: Insert message, update chat
      Convex->>Autumn: POST /v1/track {customer_id, feature_id:'messages'}
      Convex-->>Client: success
    else Disallowed/Null
      Convex-->>Client: error "No more messages..."
    end
  else non-user
    Convex->>Convex: Insert message
    Convex-->>Client: success
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Poem

a hare taps keys with autumn grace,
new routes crisp as fallen lace—
check, track, attach, and swiftly go,
a secret key beneath the snow.
messages counted, limits clear,
I thump approval: ship it here!
hop-hop to checkout— onward, dear.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cursor/implement-backend-payment-and-pricing-model-2165

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@claude
Copy link

claude bot commented Aug 12, 2025

Claude finished @otdoges's task —— View job


PR Review: Backend Payment and Pricing Model Implementation

Reviewing the Autumn payment integration implementation for code quality, security, performance, and best practices.

Review Tasks:

  • Analyze new API endpoints and configuration
  • Review security implementation for payment handling
  • Check error handling and validation
  • Evaluate integration with existing codebase
  • Assess performance considerations
  • Review test coverage needs
  • Provide comprehensive feedback

🔍 Code Review Summary

This PR implements a comprehensive Autumn billing integration with solid security practices and good error handling. The implementation follows the project's patterns well and includes proper authentication and validation.

Strengths

Security Implementation

  • Robust Authentication: All API endpoints properly verify Clerk JWT tokens with comprehensive error handling
  • CORS Configuration: Proper CORS setup with domain validation for zapdev.link, localhost, and 127.0.0.1
  • Input Validation: Server-side validation of request parameters with default values
  • Environment Variable Security: Sensitive keys properly managed via environment variables
  • Error Sanitization: Errors are properly logged server-side while returning safe messages to clients

Code Quality

  • Consistent Architecture: All 5 Autumn API endpoints follow identical patterns for maintainability
  • Proper Error Handling: Comprehensive try-catch blocks with fallback error responses
  • Type Safety: Good TypeScript usage with proper typing for Vercel request/response
  • Clean Separation: Configuration properly separated in autumn.config.ts

Integration Quality

  • Backend Integration: Smart server-side calls to Autumn API from Convex functions (autumnCheckMessagesAllowedDirect, autumnTrackMessageDirect)
  • Usage Tracking: Integrated with message creation workflow with proper conditional checks
  • Fallback Strategy: Frontend pricing component includes Autumn checkout as fallback when Stripe fails
  • Environment Setup: Updated environment templates and setup scripts

⚠️ Issues & Recommendations

🚨 Critical Security Issues

1. JWT Audience Validation Missing - api/_utils/auth.ts:41

const options: { jwtKey?: string; audience?: string } = { jwtKey: issuer };
if (audience) options.audience = audience;

Issue: The audience parameter is optional, but JWT validation should always verify the audience to prevent token reuse attacks.

Recommendation:

const options = { 
  jwtKey: issuer,
  audience: audience || process.env.CLERK_JWT_AUDIENCE || 'https://zapdev.link'
};

2. Missing Rate Limiting - All API endpoints

Issue: Payment-related APIs lack rate limiting, making them vulnerable to abuse.

Recommendation: Implement rate limiting similar to the existing Convex functions:

// Add to each API endpoint
const rateLimitKey = `autumn_api_${authenticatedUserId}`;
// Implement rate limiting logic

🔧 Code Quality Issues

3. Duplicate CORS Logic - All 5 API files

Issue: Identical CORS handling duplicated across all files (40+ lines each).

Recommendation: Extract to shared utility:

// api/_utils/cors.ts
export function withCors(res: VercelResponse, allowOrigin?: string) { /* ... */ }
export function handleCors(req: VercelRequest, res: VercelResponse) { /* ... */ }

4. Inconsistent Error Response Format - Multiple files

Issue: Error responses use different structures (error/message vs details).

Recommendation: Standardize error response format:

interface StandardErrorResponse {
  error: string;
  message: string;
  code?: string;
  details?: unknown;
}

5. Magic Values - convex/messages.ts:260-264

Issue: Hard-coded feature ID 'messages' appears in multiple places.

Recommendation:

const AUTUMN_FEATURE_IDS = {
  MESSAGES: 'messages'
} as const;

🔧 Enhancement Opportunities

6. Missing Request Validation

Issue: API endpoints don't validate request body structure.

Recommendation: Add Zod validation:

import { z } from 'zod';

const autumnCheckSchema = z.object({
  featureId: z.string().default('messages')
});

7. No Timeout Configuration - All fetch calls

Issue: Fetch calls to Autumn API lack timeout configuration.

Recommendation:

const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);
const upstream = await fetch(url, { 
  ...options, 
  signal: controller.signal 
});

8. Missing Observability

Issue: No metrics or monitoring for Autumn API calls.

Recommendation: Add structured logging and metrics collection for billing operations.

🧪 Test Coverage

9. No Tests Provided

Issue: No unit tests or integration tests for the new API endpoints.

Recommendations:

  • Unit tests for each API endpoint with mocked Autumn responses
  • Integration tests for the Convex message flow with Autumn checks
  • End-to-end tests for the complete billing workflow
  • Mock Autumn API responses for testing scenarios

📊 Performance Considerations

Good Performance Practices:

  • Efficient server-side API calls without client round-trips
  • Proper error handling that doesn't block user flow
  • Smart fallback from Stripe to Autumn in pricing component

Potential Optimizations:

  • Consider caching Autumn check responses for repeated calls within short timeframes
  • Implement circuit breaker pattern for Autumn API calls
  • Add request deduplication for concurrent identical requests

🔒 Security Assessment

Well Implemented:

  • ✅ Proper authentication on all endpoints
  • ✅ CORS configuration with domain allowlisting
  • ✅ Environment variable usage for secrets
  • ✅ Error message sanitization

Needs Attention:

  • ⚠️ JWT audience validation should be mandatory
  • ⚠️ Rate limiting missing on payment endpoints
  • ⚠️ Request validation could be more comprehensive

📝 Documentation & Maintainability

Strengths:

  • Clear environment variable documentation
  • Consistent code patterns across endpoints
  • Good separation of concerns

Improvements Needed:

  • API endpoint documentation
  • Error code documentation
  • Integration flow documentation

🎯 Overall Assessment

This is a solid implementation that follows good security practices and integrates well with the existing codebase. The main concerns are around rate limiting for payment endpoints and some code duplication that could be refactored.

Recommendation: ✅ APPROVE with minor fixes - Address the critical security issues (JWT audience validation, rate limiting) before merging.


@Jackson57279 Jackson57279 marked this pull request as ready for review August 12, 2025 21:38
Copy link
Contributor

@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: 28

🔭 Outside diff range comments (3)
src/components/pricing/CustomPricingTable.tsx (3)

93-96: Auth check contradicts the comment. Fix condition or comment.

Comment says “authenticated if signed in even if Convex sync is in progress,” but code requires !authLoading. Align to intent.

Apply this diff to match the comment:

-// Better authentication check: user is considered authenticated if signed in to Clerk
-// even if Convex sync is still in progress
-const isUserAuthenticated = isSignedIn && !authLoading;
+// Consider the user authenticated if signed in to Clerk (ignore Convex sync state)
+const isUserAuthenticated = !!isSignedIn;

171-181: Remove the any type and add minimal typing for error payload parsing.

Violates strict TS guideline to never use any. Use unknown with a narrow cast.

Apply this diff:

-        let errorData: any = null;
+        let errorData: unknown = null;
@@
-          errorData = await response.json();
-          errorMessage = errorData.message || errorMessage;
+          errorData = await response.json();
+          const maybe = errorData as { message?: string };
+          if (typeof maybe?.message === 'string') {
+            errorMessage = maybe.message;
+          }

Add this helper type near the top of the file (outside the changed range):

type ApiErrorPayload = { message?: string; [key: string]: unknown };

23-86: UI copy conflicts with Autumn config (Free: 10 vs 5; Pro: Unlimited vs 100; Price: $29 vs $20).

Presently, the UI advertises:

  • Free: 10 AI conversations/month (Autumn config: 5)
  • Pro: “Unlimited AI conversations” (Autumn config: 100)
  • Pro price: $29 (Autumn config: $20)

Aligning these is critical to avoid user-facing inconsistency and billing disputes.

I can either: (a) update UI copy to match current config, or (b) adjust Autumn config and restrict fallback to supported products. Which direction should we take?

🧹 Nitpick comments (8)
scripts/create-env-local.js (1)

67-70: Mirror env template guidance and add a helpful placeholder for AUTUMN_SECRET_KEY

To keep developer onboarding consistent with env-template.txt and reduce setup friction, include a placeholder and a link to Autumn’s dashboard.

Apply this diff:

-# Autumn Billing Integration (optional)
-AUTUMN_SECRET_KEY=
-# AUTUMN_API_BASE=https://api.useautumn.com
+# Autumn Billing Integration (optional)
+# Get from: https://dashboard.useautumn.com
+AUTUMN_SECRET_KEY=am_sk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+# AUTUMN_API_BASE=https://api.useautumn.com
api/autumn-attach.ts (2)

60-73: Add a timeout to upstream fetch to avoid hanging function invocations

Network hiccups can stall the function. Use AbortController to bound latency.

Apply this diff:

-    const apiBase = process.env.AUTUMN_API_BASE || 'https://api.useautumn.com';
-
-    const upstream = await fetch(`${apiBase}/v1/attach`, {
+    const apiBase = process.env.AUTUMN_API_BASE || 'https://api.useautumn.com';
+    const controller = new AbortController();
+    const timeoutId = setTimeout(() => controller.abort(), 10_000);
+    const upstream = await fetch(`${apiBase}/v1/attach`, {
       method: 'POST',
       headers: {
         'Authorization': `Bearer ${autumnSecret}`,
         'Content-Type': 'application/json',
       },
       body: JSON.stringify({
         customer_id: authenticatedUserId,
         product_id: productId,
-      }),
-    });
+      }),
+      signal: controller.signal,
+    }).finally(() => clearTimeout(timeoutId));

76-79: Avoid leaking upstream error details to clients

Return a generic message and omit raw payload details. Keep specifics in server logs.

Apply this diff:

-    if (!upstream.ok) {
-      console.error('Autumn attach error:', upstream.status, payload);
-      return withCors(res, allowedOrigin).status(upstream.status).json({ error: 'Attach Error', message: payload?.message || 'Failed to attach Autumn product', details: payload });
-    }
+    if (!upstream.ok) {
+      console.error('Autumn attach error:', upstream.status, payload);
+      const safeMessage = typeof payload?.message === 'string' ? payload.message : 'Failed to attach Autumn product';
+      return withCors(res, allowedOrigin).status(upstream.status).json({ error: 'Attach Error', message: safeMessage });
+    }
README.md (1)

155-160: Document all new Autumn endpoints for completeness

List check and track endpoints alongside checkout/attach, so integrators understand the full flow.

Apply this diff:

 ## Autumn (backend-only) billing

-- Add `AUTUMN_SECRET_KEY` to your environment (see `env-template.txt` or `scripts/create-env-local.js`).
-- Use `/api/autumn-checkout` to initiate checkout and `/api/autumn-attach` to attach if payment method exists.
-- Server enforces feature access for chat messages via Autumn and records usage automatically.
+- Add `AUTUMN_SECRET_KEY` to your environment (see `env-template.txt` or `scripts/create-env-local.js`).
+- Endpoints:
+  - `POST /api/autumn-checkout` — initiate checkout
+  - `POST /api/autumn-attach` — attach if a payment method exists
+  - `POST /api/autumn-check` — server-side feature gate check
+  - `POST /api/autumn-track` — record feature usage (e.g., messages)
+- Server enforces feature access for chat messages via Autumn and records usage automatically.
src/components/pricing/CustomPricingTable.tsx (2)

166-169: Avoid logging full response headers in the browser.

This can inadvertently expose sensitive info in devtools. Log only in development or remove.

Apply this diff to guard logs:

-console.log('Response headers:', Object.fromEntries(response.headers.entries()));
+if (import.meta.env.DEV) {
+  console.log('Response headers:', Object.fromEntries(response.headers.entries()));
+}

88-91: Prefer React.FC typing for components per guidelines.

Add proper component typings for clarity and consistency.

Example:

-const PricingCard = ({ plan, index }: { plan: PricingPlan; index: number }) => {
+type PricingCardProps = { plan: PricingPlan; index: number };
+const PricingCard: React.FC<PricingCardProps> = ({ plan, index }) => {

And:

-export const CustomPricingTable = () => {
+export const CustomPricingTable: React.FC = () => {
api/autumn-customer.ts (2)

27-29: Set Allow header on 405 responses

Return the supported methods to be explicit and spec-compliant.

-  if (req.method !== 'GET') {
-    return withCors(res, allowedOrigin).status(405).json({ error: 'Method Not Allowed', message: 'Only GET requests are allowed' });
-  }
+  if (req.method !== 'GET') {
+    res.setHeader('Allow', 'GET, OPTIONS');
+    return withCors(res, allowedOrigin).status(405).json({ error: 'Method Not Allowed', message: 'Only GET requests are allowed' });
+  }

14-14: Explicit return type for handler

Add an explicit return type for this public API handler to conform to strict TS guidelines.

-export default async function handler(req: VercelRequest, res: VercelResponse) {
+export default async function handler(req: VercelRequest, res: VercelResponse): Promise<void> {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 875dde0 and 79d9f2b.

📒 Files selected for processing (12)
  • README.md (1 hunks)
  • api/autumn-attach.ts (1 hunks)
  • api/autumn-check.ts (1 hunks)
  • api/autumn-checkout.ts (1 hunks)
  • api/autumn-customer.ts (1 hunks)
  • api/autumn-track.ts (1 hunks)
  • autumn.config.ts (1 hunks)
  • convex/messages.ts (4 hunks)
  • env-template.txt (1 hunks)
  • scripts/create-env-local.js (1 hunks)
  • src/components/pricing/CustomPricingTable.tsx (1 hunks)
  • src/lib/ai.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/convex-security.mdc)

**/*.{ts,tsx}: All Convex queries and mutations MUST use proper authentication. Never accept user IDs from client parameters.
Always verify user owns the data before allowing access.
Use the authenticated user's identity.subject for user references.
Implement proper error messages that don't leak information.
Authentication verification in every function.
Authorization checks for data ownership.
Input validation and sanitization.
Error handling without information leakage.

**/*.{ts,tsx}: Use Sonner for toast notifications to provide consistent user feedback, including success, error, and loading states.
Always handle errors gracefully using try-catch blocks in asynchronous functions, providing user feedback and logging errors.
Provide specific, actionable error messages for form validation errors using toast notifications.
Handle common network error scenarios in catch blocks, providing appropriate toast messages for network errors, authentication errors, and unexpected errors.

If using TypeScript, use an enum to store flag names.

Strict TypeScript must be used with no 'any' types allowed

**/*.{ts,tsx}: NEVER use any type - use proper TypeScript types
Use unknown for truly unknown data types
Implement proper interface definitions
Do not use empty interfaces; use a type alias instead (e.g., type InputProps = ... instead of interface InputProps {})
All function parameters must be typed
All return types should be explicit for public APIs
Use proper generic constraints
Implement discriminated unions for state management
Use proper interface definitions for error handling types (e.g., interface ValidationResult { isValid: boolean; error?: string; })

**/*.{ts,tsx}: Always sanitize user input before storing or displaying using a sanitization function like sanitizeText.
Implement comprehensive input validation, including length checks and detection of malicious patterns, as shown in the validateInput function.
Define and use security constants suc...

Files:

  • src/lib/ai.ts
  • api/autumn-track.ts
  • api/autumn-attach.ts
  • autumn.config.ts
  • api/autumn-checkout.ts
  • api/autumn-check.ts
  • api/autumn-customer.ts
  • convex/messages.ts
  • src/components/pricing/CustomPricingTable.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/posthog-integration.mdc)

**/*.{js,jsx,ts,tsx}: Use a consistent naming convention for this storage. enum/const object members should be written UPPERCASE_WITH_UNDERSCORE.
If a custom property for a person or event is at any point referenced in two or more files or two or more callsites in the same file, use an enum or const object, as above in feature flags.

Files:

  • src/lib/ai.ts
  • api/autumn-track.ts
  • api/autumn-attach.ts
  • autumn.config.ts
  • scripts/create-env-local.js
  • api/autumn-checkout.ts
  • api/autumn-check.ts
  • api/autumn-customer.ts
  • convex/messages.ts
  • src/components/pricing/CustomPricingTable.tsx
**/*.{js,jsx}

📄 CodeRabbit Inference Engine (.cursor/rules/posthog-integration.mdc)

If using JavaScript, store flag names as strings to an object declared as a constant, to simulate an enum.

Files:

  • scripts/create-env-local.js
convex/**/*.ts

📄 CodeRabbit Inference Engine (.cursor/rules/project-overview.mdc)

convex/**/*.ts: All Convex functions must use proper authentication verification
User data access must be controlled with ownership verification for authorization

convex/**/*.ts: All Convex functions must verify authentication
Enforce ownership-based access control (userId checks) for user data in Convex functions
Validate all inputs to Convex functions using Zod schemas

Files:

  • convex/messages.ts
**/{pages,components}/**/*.tsx

📄 CodeRabbit Inference Engine (.cursor/rules/authentication-patterns.mdc)

Handle all authentication states in components by showing a loading spinner when loading, a sign-in prompt when unauthenticated, and protected content when authenticated.

Files:

  • src/components/pricing/CustomPricingTable.tsx
**/*.tsx

📄 CodeRabbit Inference Engine (.cursor/rules/error-handling.mdc)

**/*.tsx: Always provide loading feedback to users during asynchronous operations.
Use proper error boundaries to handle component crashes and display user-friendly error UI.

Use proper React component typing (e.g., const MyComponent: React.FC<Props> = ...)

**/*.tsx: Use the SafeText React component for all user-generated content to ensure safe text display.
NEVER use dangerouslySetInnerHTML with user content.
NEVER use direct string interpolation in HTML with user content.

Files:

  • src/components/pricing/CustomPricingTable.tsx
src/components/**/*.tsx

📄 CodeRabbit Inference Engine (.cursor/rules/project-overview.mdc)

Input sanitization and validation must be implemented throughout the codebase to provide XSS protection

Files:

  • src/components/pricing/CustomPricingTable.tsx
src/**/*.tsx

📄 CodeRabbit Inference Engine (CLAUDE.md)

src/**/*.tsx: Use React Hook Form with Zod validation for client-side forms
Prevent XSS by sanitizing any user-generated content before rendering (avoid unsafe HTML, or sanitize it)
Implement proper error handling with typed error boundaries in React

Files:

  • src/components/pricing/CustomPricingTable.tsx
🧠 Learnings (1)
📚 Learning: 2025-08-09T23:03:47.108Z
Learnt from: CR
PR: otdoges/zapdev#0
File: .cursor/rules/xss-protection.mdc:0-0
Timestamp: 2025-08-09T23:03:47.108Z
Learning: Applies to **/*.{ts,tsx} : Define and use security constants such as `MAX_MESSAGE_LENGTH`, `MAX_TITLE_LENGTH`, and `MAX_CODE_BLOCK_LENGTH` to enforce input size limits.

Applied to files:

  • convex/messages.ts
🧬 Code Graph Analysis (5)
api/autumn-track.ts (1)
api/_utils/auth.ts (2)
  • getBearerOrSessionToken (6-33)
  • verifyClerkToken (35-45)
api/autumn-attach.ts (1)
api/_utils/auth.ts (2)
  • getBearerOrSessionToken (6-33)
  • verifyClerkToken (35-45)
api/autumn-checkout.ts (1)
api/_utils/auth.ts (2)
  • getBearerOrSessionToken (6-33)
  • verifyClerkToken (35-45)
api/autumn-check.ts (5)
api/autumn-attach.ts (1)
  • handler (14-86)
api/autumn-checkout.ts (1)
  • handler (14-86)
api/autumn-customer.ts (1)
  • handler (14-79)
api/autumn-track.ts (1)
  • handler (14-87)
api/_utils/auth.ts (2)
  • getBearerOrSessionToken (6-33)
  • verifyClerkToken (35-45)
api/autumn-customer.ts (2)
api/autumn-attach.ts (1)
  • handler (14-86)
api/_utils/auth.ts (2)
  • getBearerOrSessionToken (6-33)
  • verifyClerkToken (35-45)
🔇 Additional comments (3)
env-template.txt (1)

41-45: LGTM: Server-only Autumn secrets are introduced correctly

Using AUTUMN_SECRET_KEY (without a VITE_ prefix) and documenting an optional AUTUMN_API_BASE override is the right approach for backend-only billing. Placement and comments look good.

convex/messages.ts (2)

9-9: Non-functional whitespace change

No action needed.


996-996: Non-functional whitespace change

No action needed.

@Jackson57279 Jackson57279 deleted the cursor/implement-backend-payment-and-pricing-model-2165 branch August 12, 2025 22: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.

2 participants