Skip to content

feat: Add authentication, payments, and claim flow for detailed reports#2

Merged
sungmanch merged 17 commits intomainfrom
nextjs-migration
Jan 17, 2026
Merged

feat: Add authentication, payments, and claim flow for detailed reports#2
sungmanch merged 17 commits intomainfrom
nextjs-migration

Conversation

@sungmanch
Copy link
Copy Markdown
Collaborator

Summary

This PR introduces a complete monetization and user account system for NoMoreAISlop:

  • Authentication: Supabase OAuth integration with callback handling and middleware
  • Payments: Polar.sh integration for purchasing detailed analysis reports
  • Claim Flow: Users can claim anonymous analysis results to their account
  • App Router Restructure: Migrated to (app) route group for consistent layouts
  • CLI Improvements: Better caching, verbose mode, and cleaner output

Changes

Database

  • Add user_id column to analysis_results table for ownership tracking

API Endpoints

  • POST /api/analysis/claim - Claim anonymous analysis to user account
  • GET /api/analysis/user - Fetch user's claimed analysis history
  • GET /api/analysis/results/[id] - Enhanced with auth and unlock support
  • POST /api/payments/checkout - Initiate Polar checkout session
  • GET /api/payments/success - Handle post-payment redirect

Authentication

  • /auth/callback route for OAuth completion
  • Middleware for session management and protected routes

UI Components

  • UnlockButton component for detailed report purchases
  • Enhanced PublicResultPage with claim/unlock flow
  • Updated PersonalDashboardPage with analysis history
  • Improved navigation and auth context

CLI

  • Simplified cache implementation
  • Added -v/--verbose flag for detailed output
  • Better cost estimation and formatting

Test plan

  • Test OAuth login flow with GitHub/Google
  • Test anonymous analysis → claim flow
  • Test Polar checkout and payment success redirect
  • Test detailed report unlock after payment
  • Test CLI with --verbose flag
  • Verify protected routes redirect to login

🤖 Generated with Claude Code

sungmanch and others added 10 commits January 16, 2026 18:19
Remove placeholder page files that have been migrated to the
(app) route group with proper authentication wrappers.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add migration to support linking analysis results to authenticated
users, enabling the claim/ownership flow for anonymous analyses.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- POST /api/analysis/claim: Claim anonymous analysis to user account
- GET /api/analysis/user: Fetch user's claimed analysis results

Enables users to save their analysis results after authentication.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add support for paid detailed reports with authentication checks.
Users can unlock detailed analysis after claiming their results.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add /auth/callback route for OAuth flow completion
- Add middleware for session management and route protection
- Support redirect back to original page after authentication

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add Polar client wrapper for checkout flow
- Add /api/payments/checkout endpoint to initiate purchases
- Add /api/payments/success endpoint for post-payment handling

Enables monetization of detailed AI collaboration reports.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Migrate pages to (app) route group for consistent layout and
authentication handling across protected routes.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add UnlockButton component for detailed report purchases
- Update PublicResultPage with claim/unlock flow
- Enhance PersonalDashboardPage with analysis history
- Improve Sidebar with conditional navigation
- Update auth context and hooks for better UX

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Simplify cache implementation with cleaner expiration logic
- Add -v/--verbose flag for detailed progress output
- Improve cost estimation accuracy
- Enhance display formatting for better readability

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Update README with new authentication and payment features
- Enhance LLM_FLOW.md with detailed pipeline documentation
- Add @polar-sh/sdk for payment integration
- Minor fix in remote analysis route

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@vercel
Copy link
Copy Markdown

vercel bot commented Jan 16, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
no-more-ai-slop Ready Ready Preview, Comment Jan 17, 2026 6:53am

@sungmanch
Copy link
Copy Markdown
Collaborator Author

Code review

Found 2 issues:

  1. Authorization bypass in payment success handler - The database update at lines 68-75 marks an analysis result as paid using only result_id from checkout metadata, without verifying the result belongs to the authenticated user. An attacker could create a checkout with a victim's resultId in metadata, complete payment, and mark the victim's result as paid.

https://github.com/sungmanch/no-more-AI-slop/blob/d30d4f9d77024e477a611b876a2f29638b0f7964/app/api/payments/success/route.ts#L65-L76

  1. Missing environment variable documentation (CLAUDE.md lists env vars in "Environment Variables" table) - The PR adds POLAR_ACCESS_TOKEN and POLAR_PRODUCT_ID as required environment variables in src/lib/polar/client.ts, but these are not documented in README.md's Environment Variables section.

https://github.com/sungmanch/no-more-AI-slop/blob/d30d4f9d77024e477a611b876a2f29638b0f7964/src/lib/polar/client.ts#L19-L26

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

sungmanch and others added 6 commits January 16, 2026 19:13
Session ordering no longer defaults to ascending token count.
This allows sessions to be displayed in their natural order.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add comprehensive schemas for Premium/Enterprise analysis features:

Analysis Data (Stage 1 extraction):
- ActionablePatternMatchSchema: Expert advice detection with evidence
- DetectedAntiPatternSchema: Sunk cost loops, blind retry patterns
- CriticalThinkingMomentSchema: Verification and questioning behaviors
- PlanningBehaviorSchema: /plan usage, task decomposition detection

Verbose Evaluation (Stage 2 output):
- ActionablePracticesSchema: Practiced vs opportunity categorization
- AntiPatternsAnalysisSchema: Growth opportunities with health score
- CriticalThinkingAnalysisSchema: Strengths and overall score
- PlanningAnalysisSchema: Maturity level and /plan statistics

These schemas enable data-driven feedback grounded in research.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add new research-backed insights to INITIAL_INSIGHTS:
- "The 50% Context Rule": Anthropic research on optimal context utilization
- "Sunk Cost Fallacy in AI Prompting": Reset vs retry guidance
- "Trust but Verify": Critical thinking in AI collaboration

Create knowledge-driven-patterns.ts module:
- Maps INITIAL_INSIGHTS actionableAdvice to detectable RegExp patterns
- Enables evidence-based feedback: "You practiced X (Source: Y)"
- Includes 13 patterns across 4 dimensions:
  - Context Engineering: /compact, task delegation, context awareness
  - AI Collaboration: Planning, acceptance criteria, TodoWrite
  - AI Control: Modifications, challenges, verification
  - Skill Resilience: Pseudocode first, explanation requests

Patterns are injected into Gemini context via buildKnowledgePatternsXML().

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Implement Anthropic's context window research findings:
- Optimal utilization is ~50% (OPTIMAL_MIN=30%, OPTIMAL_MAX=60%)
- Warning threshold at 70%, critical at 85%
- Performance degrades and hallucination risk increases above 70%

New metrics in ContextEngineeringResult:
- contextUtilization.maxUtilization: Peak % of context window
- contextUtilization.avgUtilization: Average % across sessions
- contextUtilization.isOverloaded: True if max > 70%
- contextUtilization.isOptimal: True if avg is 30-60%

Updated COMPRESS score calculation:
- Utilization score: 40% weight (optimal ~50% rewarded, >70% penalized)
- Iteration efficiency: 35% weight
- /compact usage: 25% weight

Enhanced tips generation with context overload warnings.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Extend Stage 1 prompts for Premium/Enterprise behavioral analysis:

Anti-Pattern Detection (frame as "growth opportunities"):
- sunk_cost_loop: Same error + same approach 3+ times
- emotional_escalation: Frustration affecting prompts
- blind_retry: Retry without error analysis
- passive_acceptance: No verification of AI output

Critical Thinking Detection (celebrate as strengths):
- verification_request: "Are you sure?", "Is that correct?"
- output_validation: Running tests, checking results
- assumption_questioning: Challenging AI decisions
- alternative_exploration: Requesting different approaches
- security_check: Performance/security verification

Planning Behavior Detection:
- slash_plan_usage: /plan command (highest signal)
- structure_first: Planning before implementation
- task_decomposition: Breaking tasks into steps
- todowrite_usage: Task list management

Language-independent detection supports Korean, English, etc.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Content Writer Stage enhancements:
- detectKoreanContent(): Auto-detect Korean quotes (≥30% threshold)
- Korean language instruction in prompts when detected
- sanitizePremiumSections(): Post-processing for anti-patterns,
  critical thinking, and planning analysis

Premium/Enterprise output transformation:
- Anti-Patterns: Memorable names ("The Retry Loop Trap"), growth framing
- Critical Thinking: Celebration titles ("The Guardrail"), strengths/opps
- Planning: Maturity levels (reactive→expert), /plan statistics

Content Gateway tier updates:
- Premium now includes: actionablePractices, antiPatternsAnalysis,
  criticalThinkingAnalysis, planningAnalysis
- New preview fields for upsell: antiPatternsPreview,
  criticalThinkingPreview, planningPreview

Knowledge Context integration:
- Inject actionable_patterns XML into Gemini context
- Enable evidence-based feedback grounded in research

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@sungmanch
Copy link
Copy Markdown
Collaborator Author

Code review

Found 4 issues:

  1. Missing Polar environment variables in documentation (CLAUDE.md says "Environment Variables" section should list required variables)

The code in src/lib/polar/client.ts requires POLAR_ACCESS_TOKEN and POLAR_PRODUCT_ID, but these are not documented in CLAUDE.md's Environment Variables section.

https://github.com/sungmanch/no-more-AI-slop/blob/b59ac39f8039670bee9022d378b3b5700d523b7f/CLAUDE.md#L28-L35

  1. Inconsistent environment variable naming in .env.example (CLAUDE.md specifies NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY)

The .env.example file uses SUPABASE_URL and SUPABASE_ANON_KEY instead of the NEXT_PUBLIC_ prefixed versions specified in CLAUDE.md. This would break Next.js client-side Supabase access.

https://github.com/sungmanch/no-more-AI-slop/blob/b59ac39f8039670bee9022d378b3b5700d523b7f/.env.example#L17-L22

  1. Race condition in analysis claim route (TOCTOU vulnerability)

The claim handler has a check-then-update pattern where two concurrent claims can both pass the initial check. Supabase's .update().is('user_id', null) returns no error when 0 rows are affected, so both users receive success despite only one actually claiming. Add .select().single() after update to verify a row was affected.

https://github.com/sungmanch/no-more-AI-slop/blob/b59ac39f8039670bee9022d378b3b5700d523b7f/app/api/analysis/claim/route.ts#L86-L122

  1. No validation of checkout metadata integrity (Authorization bypass)

The payment success handler trusts checkout.metadata?.resultId without verifying the result exists or that the user owns it. A malicious user could potentially unlock any result by manipulating checkout metadata. Verify result ownership before marking as paid.

https://github.com/sungmanch/no-more-AI-slop/blob/b59ac39f8039670bee9022d378b3b5700d523b7f/app/api/payments/success/route.ts#L55-L76

🤖 Generated with Claude Code

- If this code review was useful, please react with 👍. Otherwise, react with 👎.

…m UI

- Add server-side auth check to redirect paid users to personal dashboard
- Enhance PublicResultPageWrapper with DetailButton component
- Improve CSS styling with premium visual enhancements
- Update analyzer prompts for better behavioral detection
- Add verbose evaluation model updates

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
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