Docs
Admin Tools

Admin Tools

Admin Tools

This section documents all administrative tools available in the YouTube Analyzer application, with a focus on the Prompt Management System. It consolidates all technical details, UI, API, backend logic, and workflow for prompt management and other admin features.

Overview

Admin tools provide advanced management capabilities for system administrators, including prompt template management, versioning, and other backend controls. These tools are accessible only to users with admin privileges.


Prompt Management System

The Prompt Management System in YouTube Analyzer is a comprehensive solution for managing the LLM prompt templates used in video analysis. It features a versioned approach to prompt templates with careful tracking of changes and active versions.

1. Admin UI

Location: /app/(protected)/dashboard/admin/prompts/PromptsAdmin/

  • Tabbed interface for managing different prompt types (e.g., "Standard Summary", "Channel Deep Dive").
  • View, edit, and create new prompt versions.
  • Version history with editor and timestamp.
  • All changes are made via API calls (no direct DB access).

Key Components

ComponentPurposeFunctionality
index.tsxMain containerManages global state, API fetching, version selection, and overall layout
PromptEditor.tsxTemplate editorText editor for prompt templates with variable insertion
VersionDropdown.tsxVersion selectorDisplays and selects between different prompt versions
SaveAsModal.tsxVersion creationModal for creating new prompt versions with descriptions
TestResults.tsxTest displayShows results from testing prompt templates
VariablesList.tsxTemplate variablesShows available variables that can be inserted into templates
AnalysisRecordDropdown.tsxTest selectionSelects analysis records for testing prompts

UI Workflow

  1. Tab Navigation: Admin selects a prompt type (e.g., "Standard Summary", "Executive Summary").
  2. Version Selection: Admin selects a version from the dropdown to view or edit.
  3. Editing: Admin modifies the template in the text editor.
  4. Variable Insertion: Admin can insert template variables using the variables list.
  5. Version Creation: Admin saves changes as a new version with an optional description.
  6. Version Activation: Admin can set any version as the active one for production use.
  7. Testing: Admin can test the prompt against real data before activating.

2. Database Schema

Tables:

  1. Prompt Model:

    • id: Unique identifier (CUID)
    • name: Display name of the prompt
    • description: Optional description
    • analysisTypeKey: Key that maps to analysis types in config (e.g., "standard-summary")
    • createdById: User ID of creator (audit trail)
    • createdAt: Creation timestamp
    • updatedAt: Last update timestamp
    • status: ACTIVE or ARCHIVED
  2. PromptVersion Model:

    • id: Unique identifier (CUID)
    • promptId: Foreign key to parent prompt
    • content: The actual prompt template text
    • variables: JSON field for variable metadata
    • version: Integer version number (auto-incrementing)
    • createdById: User ID of creator (audit trail)
    • createdAt: Creation timestamp
    • isActive: Boolean flag for active version

Relationships:

  • One Prompt has many PromptVersions (one-to-many)
  • Only one PromptVersion per Prompt can be active (isActive = true)

Important Constraints:

  • Each prompt-version pair must be unique (@@unique([promptId, version]))
  • Foreign key relationships ensure data integrity

3. API Endpoints

Location: /app/api/prompts/

Main Endpoints

  • GET /api/prompts/: List all prompt types and latest versions.

    • Optional filter by analysisTypeKey
    • Returns prompts with their most recent version
    • Admin authentication required
  • POST /api/prompts/: Create a new prompt type with initial version.

    • Required fields: name, analysisTypeKey, content
    • Optional fields: description, variables
    • Creates both the prompt and its first version in one transaction
    • Admin authentication required

ID-based Operations (/api/prompts/[id])

  • GET /api/prompts/[id]: Get a single prompt with all its versions.

    • Returns prompt with all versions sorted by version number (descending)
    • Admin authentication required
  • PATCH /api/prompts/[id]: Three different operations:

    1. Update prompt metadata (name, description, status)
    2. Add a new version (newVersion object with content and variables)
    3. Set active version (setActiveVersion with version ID)
    • Each operation can be performed independently
    • Admin authentication required
  • DELETE /api/prompts/[id]: Soft delete (archive) a prompt.

    • Updates status to ARCHIVED instead of removing from database
    • Admin authentication required

Testing Endpoint

  • POST /api/prompts/test: Test a prompt version against an analysis.
    • Takes promptId, version number, and analysisId
    • Returns rendered HTML result
    • Provides a safe testing environment without affecting production data
    • Aids in verifying prompt effectiveness before activation
    • Admin authentication required
    • Implementation details:
      • Fetches the specified prompt version from the database
      • Retrieves the complete analysis record with all video data
      • Processes templates using the same core logic as production
      • Returns test results immediately without storing to database
      • Catches and reports detailed error information for debugging
    • Testing workflow:
      1. Admin selects a prompt version to test
      2. Admin chooses an analysis record for test data
      3. System runs the prompt against the analysis data
      4. Results are displayed but not saved as a new analysis

Support Endpoints for Testing

  • GET /api/prompts/sample-analyses: Returns a list of recent analyses for prompt testing.

    • Returns simplified analysis data including ID, channel name, video count, transcript length, and a preview of the analysis summary
    • Processes and formats data to be immediately usable in the testing UI
    • Used by the prompt testing UI to select real data for test runs
    • Admin authentication required
    • Internally queries the Analysis and Video tables, limiting to 20 recent analyses
    • Returns data normalized with consistent structure for prompt variable substitution
  • GET /api/prompts/sample-transcripts: Returns sample video transcripts for prompt testing.

    • Returns up to 10 recent video transcripts with metadata (id, title, language, content)
    • Used for testing template variables with real content
    • Admin authentication required
    • Provides raw transcripts that can be used to simulate the analysis process
    • Used by the transcript selection modal in the prompt testing interface
  • GET /api/prompts/env: Exposes limited environment configuration for testing.

    • Returns only the streaming server URL (without any API keys or sensitive data)
    • Used to configure the test environment in the prompt admin UI
    • Admin authentication required
    • Security note: This endpoint only exposes the STREAMING_SERVER_URL environment variable
    • Current implementation strips any endpoint paths (like /analyze-channel) to ensure only the base URL is exposed
    • Risk assessment: Low risk as the endpoint only returns a publicly accessible URL, not credentials
    • Future improvement: Consider refactoring to avoid exposing environment variables via API endpoints
    • Better approaches include:
      • Injecting necessary configurations at build time using Next.js environment variables
      • Using secure server-side configuration with appropriate access controls
      • Moving the configuration into a dedicated configuration service with proper authentication
      • Using feature flags or a dedicated config management system

4. Shared Backend Logic

Location: /lib/prompts.ts

Key Functions

  • loadPromptTemplate: Loads prompt files from the filesystem.

    • Reads from file paths like prompts/${analysisType}.txt
    • Falls back to default type if specified one isn't found
  • fillPromptTemplate: Template engine for replacing variables.

    • Replaces {{variableName}} placeholders with actual values
    • Handles missing variables by replacing with empty string
  • buildPrompt: Constructs complete prompts for analysis.

    • Combines template with data for LLM processing
    • Formats complex data structures like arrays and objects
    • Converts structured data to strings for template insertion

Integration with Analysis Workflow

  • LLM analysis code uses these functions to get the current active prompt
  • Variables from video/channel data are injected into templates
  • Results are processed and stored in analysis records

5. Version Management Workflow

Version States

  • Draft: New version being edited (not saved)
  • Saved: Version that exists in the database but is not active
  • Active: The current production version used for analysis (only one active version per prompt type)

Version Creation Process

  1. Admin selects an existing prompt version to use as starting point
  2. Admin edits the template content
  3. Admin clicks "Save as New Version"
  4. Admin provides an optional description
  5. System:
    • Determines the next version number (latest + 1)
    • Creates a new record in PromptVersion
    • Sets isActive = false by default
    • Returns updated prompt with all versions

Version Activation Process

  1. Admin selects the desired version
  2. Admin clicks "Make Active"
  3. System:
    • Updates all versions for that prompt to isActive = false
    • Sets the selected version to isActive = true
    • Frontend optimistically updates UI
    • All new analyses will use this version

6. Prompt Template Format

Template Structure

Prompt templates use a simple {{variable}} syntax for dynamic content:

Create a comprehensive summary for the YouTube channel {{channelName}}.
This channel has {{videoCount}} videos analyzed.

Video data:
{{videoLinksWithData}}

Performance metrics:
{{performanceData}}

Combined transcript data:
{{combinedTranscripts}}

Chart data:
{{chartData}}

Available Variables

  • channelName: Name of the YouTube channel
  • videoCount: Number of videos analyzed
  • performanceData: Channel statistics and metrics
  • combinedTranscripts: Processed transcript text
  • videoLinksWithData: Video metadata and links
  • videosString: Simplified video list
  • chartData: Structured data for visualizations
  • videos: Raw video data array (JSON)

7. Testing Workflow

Test Process

  1. Admin selects a prompt version to test
  2. Admin selects an existing analysis record as test data
  3. Admin clicks "Run Test"
  4. System:
    • Renders the prompt with the selected analysis data
    • Sends to LLM for processing
    • Returns the generated HTML result
    • Displays side-by-side comparison of prompt and result

Test Data Sources

  • Real analysis records from the database
  • Sample data for new prompt types
  • Admin can select different analyses to test edge cases

8. Error Handling and Validation

  • Form Validation: Required fields are checked before submission
  • API Validation: Additional validation at API level with clear error messages
  • Version Conflicts: System prevents duplicate version numbers
  • Permission Checks: All endpoints verify admin role

9. Security Considerations

  • Authentication: All prompt management endpoints require admin authentication
  • No Direct DB Access: All changes go through validated API endpoints
  • Limited Environment Variable Exposure:
    • The /api/prompts/env endpoint exposes only the streaming server URL but no API keys or other sensitive data
    • Current implementation strips any endpoint paths (like /analyze-channel) to ensure only the base URL is exposed
    • Risk assessment: Low risk as the endpoint only returns a publicly accessible URL, not credentials
    • Future improvement: Consider refactoring to avoid exposing environment variables via API endpoints
    • Better approaches include:
      • Injecting necessary configurations at build time using Next.js environment variables
      • Using secure server-side configuration with appropriate access controls
      • Moving the configuration into a dedicated configuration service with proper authentication
      • Using feature flags or a dedicated config management system
  • Validation: Input validation at both client and server levels
  • Audit Trail: Version history provides an audit trail of prompt changes
  • No Raw SQL: All database access uses Prisma ORM with parameterized queries

Beta Mode Invite Code Management System

The Beta Mode Invite Code Management System allows administrators to control registration during beta periods by requiring valid invite codes for new user signups.

1. Overview

When BETA_MODE=true is set in environment variables, the application requires invite codes for new user registration. Administrators can create, manage, and track invite codes through a dedicated admin interface.

2. Admin UI

Location: /app/(protected)/dashboard/admin/invite-codes/

Features

  • Create invite codes: Generate unique codes with custom descriptions and usage limits
  • Track usage: Monitor how many times each code has been used
  • Manage status: Activate/deactivate codes as needed
  • Usage analytics: View which email addresses used specific codes
  • Bulk management: Create codes for different purposes (sponsors, early access, etc.)

UI Components

ComponentPurposeFunctionality
InviteCodeManagerMain management interfaceCreate, list, and manage all invite codes
Code creation dialogGenerate new codesForm for description and usage limits
Usage tracking tableMonitor code usageDisplay usage stats and user emails
Status toggleActivate/deactivate codesControl code availability

3. Database Schema

InviteCode Model:

model InviteCode {
  id            String    @id @default(cuid())
  code          String    @unique      // Generated unique code
  description   String?                // Optional description for tracking
  createdAt     DateTime  @default(now())
  createdById   String?                // Admin who created it
  usedAt        DateTime?              // When it was used
  usedByEmail   String?                // Email of user who used it
  isActive      Boolean   @default(true)
  maxUses       Int       @default(1)  // How many times it can be used
  currentUses   Int       @default(0)  // How many times it's been used
 
  createdBy     User?     @relation(fields: [createdById], references: [id])
}

Key Features:

  • Unique codes: Each invite code is automatically generated using nanoid
  • Usage tracking: Tracks both maximum allowed uses and current usage count
  • Audit trail: Records who created the code and who used it
  • Flexible limits: Supports single-use or multi-use codes

4. API Endpoints

Location: /app/api/admin/invite-codes/

Main Endpoints

  • GET /api/admin/invite-codes: List all invite codes with usage statistics

    • Returns array of invite codes with creator information
    • Sorted by creation date (newest first)
    • Admin authentication required
  • POST /api/admin/invite-codes: Create a new invite code

    • Required: Admin authentication
    • Optional fields: description, maxUses (defaults to 1)
    • Automatically generates unique code using nanoid(10).toUpperCase()
    • Returns created code with all metadata

Individual Code Management

  • PATCH /api/admin/invite-codes/[id]: Update invite code status

    • Toggle isActive status to enable/disable codes
    • Used for temporarily deactivating codes without deletion
    • Admin authentication required
  • DELETE /api/admin/invite-codes/[id]: Permanently delete invite code

    • Hard delete from database
    • Admin authentication required
    • Use with caution as this removes audit trail

5. Beta Mode Integration

Environment Configuration

# Enable beta mode
BETA_MODE=true

When beta mode is enabled:

  • Registration form shows invite code field
  • /api/auth/validate-invite-code endpoint validates codes before registration
  • /api/auth/use-invite-code endpoint consumes codes during registration
  • Invalid or exhausted codes prevent registration

Registration Flow

  1. User visits registration page: Form includes invite code field when beta mode is active
  2. Client-side validation: Code is validated before form submission
  3. Server-side processing: Code usage is tracked and incremented
  4. Registration completion: User account is created and code usage is recorded

Validation Logic

// Code validation checks:
- Code exists in database
- Code is active (isActive = true)
- Code has remaining uses (currentUses < maxUses)
- Code usage is incremented atomically

6. Command Line Tools

Create Invite Codes via Script

Location: scripts/create-invite-code.js

# Create single-use code with description
node scripts/create-invite-code.js "For podcast sponsors" 1
 
# Create multi-use code
node scripts/create-invite-code.js "Early access users" 5
 
# Create code with default settings
node scripts/create-invite-code.js

Features:

  • Generates unique codes automatically
  • Supports custom descriptions and usage limits
  • Provides immediate feedback with code details
  • Checks beta mode status and provides guidance

7. Security Considerations

  • Admin-only access: All invite code management requires ADMIN role
  • Atomic operations: Code usage updates use database transactions
  • Usage limits: Strict enforcement of usage quotas prevents abuse
  • Audit trail: Complete tracking of code creation and usage
  • Unique constraints: Database ensures no duplicate codes

8. Monitoring and Analytics

Usage Tracking

  • Track which codes are most popular
  • Monitor usage patterns over time
  • Identify unused or expired codes
  • Analyze registration conversion rates

Admin Dashboard Features

  • Real-time usage statistics
  • Code performance metrics
  • User registration tracking
  • Bulk code management tools

Additional Admin Tools

This section can be expanded as new admin features are added.

We've created a more secure alternative to the current /api/prompts/env endpoint approach. The new endpoint (/api/prompts/config) implements these security best practices:

import { NextResponse } from 'next/server';
import { auth } from '@/auth';
 
export async function GET() {
  // Require admin authentication
  const session = await auth();
  if (!session || session.user.role !== 'ADMIN') {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }
  
  // Get base streaming URL (without exposing the full environment variable)
  let streamingUrl = process.env.STREAMING_SERVER_URL || '';
  if (streamingUrl.endsWith('/analyze-channel')) {
    streamingUrl = streamingUrl.replace(/\/analyze-channel$/, '');
  }
  
  // Return a configuration object with only the necessary non-sensitive settings
  return NextResponse.json({
    promptTesting: {
      streamingServiceUrl: streamingUrl,
      defaultTimeout: 120000, // 2 minutes
      maxResponseTokens: 4000,
    },
    // Add feature flags or other configuration categories as needed
  });
}

Advantages:

  1. Explicit admin authentication check
  2. Returns a structured configuration object instead of direct environment variables
  3. Makes it clear what configuration is being exposed (no accidental exposure)
  4. Can be extended with feature flags and other settings
  5. Provides a more consistent API structure

Implementation steps:

  1. Create the new endpoint at /api/prompts/config/route.ts
  2. Update the PromptEditor component to use this new endpoint
  3. Deprecate and eventually remove the old /api/prompts/env endpoint

Prompt Management System

The Prompt Management System in YouTube Analyzer is a comprehensive solution for managing the LLM prompt templates used in video analysis. It features a versioned approach to prompt templates with careful tracking of changes and active versions.

1. Admin UI

Location: /app/(protected)/dashboard/admin/prompts/PromptsAdmin/

  • Tabbed interface for managing different prompt types (e.g., "Standard Summary", "Channel Deep Dive").
  • View, edit, and create new prompt versions.
  • Version history with editor and timestamp.
  • All changes are made via API calls (no direct DB access).

Key Components

ComponentPurposeFunctionality
index.tsxMain containerManages global state, API fetching, version selection, and overall layout
PromptEditor.tsxTemplate editorText editor for prompt templates with variable insertion
VersionDropdown.tsxVersion selectorDisplays and selects between different prompt versions
SaveAsModal.tsxVersion creationModal for creating new prompt versions with descriptions
TestResults.tsxTest displayShows results from testing prompt templates
VariablesList.tsxTemplate variablesShows available variables that can be inserted into templates
AnalysisRecordDropdown.tsxTest selectionSelects analysis records for testing prompts

UI Workflow

  1. Tab Navigation: Admin selects a prompt type (e.g., "Standard Summary", "Executive Summary").
  2. Version Selection: Admin selects a version from the dropdown to view or edit.
  3. Editing: Admin modifies the template in the text editor.
  4. Variable Insertion: Admin can insert template variables using the variables list.
  5. Version Creation: Admin saves changes as a new version with an optional description.
  6. Version Activation: Admin can set any version as the active one for production use.
  7. Testing: Admin can test the prompt against real data before activating.

2. Database Schema

Tables:

  1. Prompt Model:

    • id: Unique identifier (CUID)
    • name: Display name of the prompt
    • description: Optional description
    • analysisTypeKey: Key that maps to analysis types in config (e.g., "standard-summary")
    • createdById: User ID of creator (audit trail)
    • createdAt: Creation timestamp
    • updatedAt: Last update timestamp
    • status: ACTIVE or ARCHIVED
  2. PromptVersion Model:

    • id: Unique identifier (CUID)
    • promptId: Foreign key to parent prompt
    • content: The actual prompt template text
    • variables: JSON field for variable metadata
    • version: Integer version number (auto-incrementing)
    • createdById: User ID of creator (audit trail)
    • createdAt: Creation timestamp
    • isActive: Boolean flag for active version

Relationships:

  • One Prompt has many PromptVersions (one-to-many)
  • Only one PromptVersion per Prompt can be active (isActive = true)

Important Constraints:

  • Each prompt-version pair must be unique (@@unique([promptId, version]))
  • Foreign key relationships ensure data integrity

3. API Endpoints

Location: /app/api/prompts/

Main Endpoints

  • GET /api/prompts/: List all prompt types and latest versions.

    • Optional filter by analysisTypeKey
    • Returns prompts with their most recent version
    • Admin authentication required
  • POST /api/prompts/: Create a new prompt type with initial version.

    • Required fields: name, analysisTypeKey, content
    • Optional fields: description, variables
    • Creates both the prompt and its first version in one transaction
    • Admin authentication required

ID-based Operations (/api/prompts/[id])

  • GET /api/prompts/[id]: Get a single prompt with all its versions.

    • Returns prompt with all versions sorted by version number (descending)
    • Admin authentication required
  • PATCH /api/prompts/[id]: Three different operations:

    1. Update prompt metadata (name, description, status)
    2. Add a new version (newVersion object with content and variables)
    3. Set active version (setActiveVersion with version ID)
    • Each operation can be performed independently
    • Admin authentication required
  • DELETE /api/prompts/[id]: Soft delete (archive) a prompt.

    • Updates status to ARCHIVED instead of removing from database
    • Admin authentication required

Testing Endpoint

  • POST /api/prompts/test: Test a prompt version against an analysis.
    • Takes promptId, version number, and analysisId
    • Returns rendered HTML result
    • Provides a safe testing environment without affecting production data
    • Aids in verifying prompt effectiveness before activation
    • Admin authentication required
    • Implementation details:
      • Fetches the specified prompt version from the database
      • Retrieves the complete analysis record with all video data
      • Processes templates using the same core logic as production
      • Returns test results immediately without storing to database
      • Catches and reports detailed error information for debugging
    • Testing workflow:
      1. Admin selects a prompt version to test
      2. Admin chooses an analysis record for test data
      3. System runs the prompt against the analysis data
      4. Results are displayed but not saved as a new analysis

Support Endpoints for Testing

  • GET /api/prompts/sample-analyses: Returns a list of recent analyses for prompt testing.

    • Returns simplified analysis data including ID, channel name, video count, transcript length, and a preview of the analysis summary
    • Processes and formats data to be immediately usable in the testing UI
    • Used by the prompt testing UI to select real data for test runs
    • Admin authentication required
    • Internally queries the Analysis and Video tables, limiting to 20 recent analyses
    • Returns data normalized with consistent structure for prompt variable substitution
  • GET /api/prompts/sample-transcripts: Returns sample video transcripts for prompt testing.

    • Returns up to 10 recent video transcripts with metadata (id, title, language, content)
    • Used for testing template variables with real content
    • Admin authentication required
    • Provides raw transcripts that can be used to simulate the analysis process
    • Used by the transcript selection modal in the prompt testing interface
  • GET /api/prompts/env: Exposes limited environment configuration for testing.

    • Returns only the streaming server URL (without any API keys or sensitive data)
    • Used to configure the test environment in the prompt admin UI
    • Admin authentication required
    • Security note: This endpoint only exposes the STREAMING_SERVER_URL environment variable
    • Current implementation strips any endpoint paths (like /analyze-channel) to ensure only the base URL is exposed
    • Risk assessment: Low risk as the endpoint only returns a publicly accessible URL, not credentials
    • Future improvement: Consider refactoring to avoid exposing environment variables via API endpoints
    • Better approaches include:
      • Injecting necessary configurations at build time using Next.js environment variables
      • Using secure server-side configuration with appropriate access controls
      • Moving the configuration into a dedicated configuration service with proper authentication
      • Using feature flags or a dedicated config management system

4. Shared Backend Logic

Location: /lib/prompts.ts

Key Functions

  • loadPromptTemplate: Loads prompt files from the filesystem.

    • Reads from file paths like prompts/${analysisType}.txt
    • Falls back to default type if specified one isn't found
  • fillPromptTemplate: Template engine for replacing variables.

    • Replaces {{variableName}} placeholders with actual values
    • Handles missing variables by replacing with empty string
  • buildPrompt: Constructs complete prompts for analysis.

    • Combines template with data for LLM processing
    • Formats complex data structures like arrays and objects
    • Converts structured data to strings for template insertion

Integration with Analysis Workflow

  • LLM analysis code uses these functions to get the current active prompt
  • Variables from video/channel data are injected into templates
  • Results are processed and stored in analysis records

5. Version Management Workflow

Version States

  • Draft: New version being edited (not saved)
  • Saved: Version that exists in the database but is not active
  • Active: The current production version used for analysis (only one active version per prompt type)

Version Creation Process

  1. Admin selects an existing prompt version to use as starting point
  2. Admin edits the template content
  3. Admin clicks "Save as New Version"
  4. Admin provides an optional description
  5. System:
    • Determines the next version number (latest + 1)
    • Creates a new record in PromptVersion
    • Sets isActive = false by default
    • Returns updated prompt with all versions

Version Activation Process

  1. Admin selects the desired version
  2. Admin clicks "Make Active"
  3. System:
    • Updates all versions for that prompt to isActive = false
    • Sets the selected version to isActive = true
    • Frontend optimistically updates UI
    • All new analyses will use this version

6. Prompt Template Format

Template Structure

Prompt templates use a simple {{variable}} syntax for dynamic content:

Create a comprehensive summary for the YouTube channel {{channelName}}.
This channel has {{videoCount}} videos analyzed.

Video data:
{{videoLinksWithData}}

Performance metrics:
{{performanceData}}

Combined transcript data:
{{combinedTranscripts}}

Chart data:
{{chartData}}

Available Variables

  • channelName: Name of the YouTube channel
  • videoCount: Number of videos analyzed
  • performanceData: Channel statistics and metrics
  • combinedTranscripts: Processed transcript text
  • videoLinksWithData: Video metadata and links
  • videosString: Simplified video list
  • chartData: Structured data for visualizations
  • videos: Raw video data array (JSON)

7. Testing Workflow

Test Process

  1. Admin selects a prompt version to test
  2. Admin selects an existing analysis record as test data
  3. Admin clicks "Run Test"
  4. System:
    • Renders the prompt with the selected analysis data
    • Sends to LLM for processing
    • Returns the generated HTML result
    • Displays side-by-side comparison of prompt and result

Test Data Sources

  • Real analysis records from the database
  • Sample data for new prompt types
  • Admin can select different analyses to test edge cases

8. Error Handling and Validation

  • Form Validation: Required fields are checked before submission
  • API Validation: Additional validation at API level with clear error messages
  • Version Conflicts: System prevents duplicate version numbers
  • Permission Checks: All endpoints verify admin role

9. Security Considerations

  • Authentication: All prompt management endpoints require admin authentication
  • No Direct DB Access: All changes go through validated API endpoints
  • Limited Environment Variable Exposure:
    • The /api/prompts/env endpoint exposes only the streaming server URL but no API keys or other sensitive data
    • Current implementation strips any endpoint paths (like /analyze-channel) to ensure only the base URL is exposed
    • Risk assessment: Low risk as the endpoint only returns a publicly accessible URL, not credentials
    • Future improvement: Consider refactoring to avoid exposing environment variables via API endpoints
    • Better approaches include:
      • Injecting necessary configurations at build time using Next.js environment variables
      • Using secure server-side configuration with appropriate access controls
      • Moving the configuration into a dedicated configuration service with proper authentication
      • Using feature flags or a dedicated config management system
  • Validation: Input validation at both client and server levels
  • Audit Trail: Version history provides an audit trail of prompt changes
  • No Raw SQL: All database access uses Prisma ORM with parameterized queries

Beta Mode Invite Code Management System

The Beta Mode Invite Code Management System allows administrators to control registration during beta periods by requiring valid invite codes for new user signups.

1. Overview

When BETA_MODE=true is set in environment variables, the application requires invite codes for new user registration. Administrators can create, manage, and track invite codes through a dedicated admin interface.

2. Admin UI

Location: /app/(protected)/dashboard/admin/invite-codes/

Features

  • Create invite codes: Generate unique codes with custom descriptions and usage limits
  • Track usage: Monitor how many times each code has been used
  • Manage status: Activate/deactivate codes as needed
  • Usage analytics: View which email addresses used specific codes
  • Bulk management: Create codes for different purposes (sponsors, early access, etc.)

UI Components

ComponentPurposeFunctionality
InviteCodeManagerMain management interfaceCreate, list, and manage all invite codes
Code creation dialogGenerate new codesForm for description and usage limits
Usage tracking tableMonitor code usageDisplay usage stats and user emails
Status toggleActivate/deactivate codesControl code availability

3. Database Schema

InviteCode Model:

model InviteCode {
  id            String    @id @default(cuid())
  code          String    @unique      // Generated unique code
  description   String?                // Optional description for tracking
  createdAt     DateTime  @default(now())
  createdById   String?                // Admin who created it
  usedAt        DateTime?              // When it was used
  usedByEmail   String?                // Email of user who used it
  isActive      Boolean   @default(true)
  maxUses       Int       @default(1)  // How many times it can be used
  currentUses   Int       @default(0)  // How many times it's been used
 
  createdBy     User?     @relation(fields: [createdById], references: [id])
}

Key Features:

  • Unique codes: Each invite code is automatically generated using nanoid
  • Usage tracking: Tracks both maximum allowed uses and current usage count
  • Audit trail: Records who created the code and who used it
  • Flexible limits: Supports single-use or multi-use codes

4. API Endpoints

Location: /app/api/admin/invite-codes/

Main Endpoints

  • GET /api/admin/invite-codes: List all invite codes with usage statistics

    • Returns array of invite codes with creator information
    • Sorted by creation date (newest first)
    • Admin authentication required
  • POST /api/admin/invite-codes: Create a new invite code

    • Required: Admin authentication
    • Optional fields: description, maxUses (defaults to 1)
    • Automatically generates unique code using nanoid(10).toUpperCase()
    • Returns created code with all metadata

Individual Code Management

  • PATCH /api/admin/invite-codes/[id]: Update invite code status

    • Toggle isActive status to enable/disable codes
    • Used for temporarily deactivating codes without deletion
    • Admin authentication required
  • DELETE /api/admin/invite-codes/[id]: Permanently delete invite code

    • Hard delete from database
    • Admin authentication required
    • Use with caution as this removes audit trail

5. Beta Mode Integration

Environment Configuration

# Enable beta mode
BETA_MODE=true

When beta mode is enabled:

  • Registration form shows invite code field
  • /api/auth/validate-invite-code endpoint validates codes before registration
  • /api/auth/use-invite-code endpoint consumes codes during registration
  • Invalid or exhausted codes prevent registration

Registration Flow

  1. User visits registration page: Form includes invite code field when beta mode is active
  2. Client-side validation: Code is validated before form submission
  3. Server-side processing: Code usage is tracked and incremented
  4. Registration completion: User account is created and code usage is recorded

Validation Logic

// Code validation checks:
- Code exists in database
- Code is active (isActive = true)
- Code has remaining uses (currentUses < maxUses)
- Code usage is incremented atomically

6. Command Line Tools

Create Invite Codes via Script

Location: scripts/create-invite-code.js

# Create single-use code with description
node scripts/create-invite-code.js "For podcast sponsors" 1
 
# Create multi-use code
node scripts/create-invite-code.js "Early access users" 5
 
# Create code with default settings
node scripts/create-invite-code.js

Features:

  • Generates unique codes automatically
  • Supports custom descriptions and usage limits
  • Provides immediate feedback with code details
  • Checks beta mode status and provides guidance

7. Security Considerations

  • Admin-only access: All invite code management requires ADMIN role
  • Atomic operations: Code usage updates use database transactions
  • Usage limits: Strict enforcement of usage quotas prevents abuse
  • Audit trail: Complete tracking of code creation and usage
  • Unique constraints: Database ensures no duplicate codes

8. Monitoring and Analytics

Usage Tracking

  • Track which codes are most popular
  • Monitor usage patterns over time
  • Identify unused or expired codes
  • Analyze registration conversion rates

Admin Dashboard Features

  • Real-time usage statistics
  • Code performance metrics
  • User registration tracking
  • Bulk code management tools