This file provides guidance to WARP (warp.dev) when working with code in this repository.
This is a Robotics-themed Capture the Flag (CTF) platform built with Next.js 15, React 19, TypeScript 5.9, and Tailwind CSS 4. The platform serves as both a functional robotics company website and a foundation for CTF challenges. The application features secure foundations with intentionally vulnerable endpoints for educational purposes.
# Start development server
npm run dev
# Build for production
npm run build
# Start production server
npm start
# Lint code
npm run lint# Run all tests
npm test
# Run tests in watch mode (for continuous development)
npm run test:watch
# Run tests with coverage report
npm test -- --coverage
# Run a single test file
npm test __tests__/api.test.ts# Install dependencies
npm install
# Add new dependency
npm install <package-name>
# Add development dependency
npm install -D <package-name>- Framework: Next.js 15.5.2 with App Router
- Frontend: React 19.1.1
- Language: TypeScript 5.9.2
- Styling: Tailwind CSS 4.1.12 (Major version upgrade)
- Testing: Jest 30.1.2 with jsdom environment
- Linting: ESLint 9.34.0
- Database: Supabase with latest client libraries
- Security: Custom middleware + built-in Next.js security headers
- Node.js: Version 20.19.4 (locked)
- npm: Version 10.0.0 (locked)
The application uses Next.js App Router with a clear separation of concerns:
app/- Main application directory with co-located componentsapp/api/- API routes with server-side validationapp/components/- Reusable React componentsapp/contexts/- React context providers for state management
Multi-layered security approach:
- Middleware: Global request logging and security headers (
middleware.ts) - API Security: Server-side validation, XSS prevention, input sanitization
- Headers: CSP, HSTS, X-Frame-Options configured in
next.config.mjs - Authentication: Context-based auth with localStorage persistence
The codebase is structured to support CTF challenges:
- Secure baseline with documented security measures
- Example vulnerable endpoints for educational purposes
- Comprehensive test coverage for security scenarios
- Clear separation between secure and potentially vulnerable code
- Responsive navigation with mobile menu
- Authentication-aware UI (login/logout states)
- Centralized navigation logic for all pages
- Client-side authentication context
- Supabase-based authentication with secure session management
- Password reset flow with email-based recovery
- React hooks for authentication state including:
requestPasswordReset(email)- Request password reset via emailupdatePassword(newPassword)- Update user password securely
- Demonstrates secure API patterns
- Input validation and sanitization
- XSS payload filtering
- Proper error handling without information leakage
- Homepage (
/) - Company landing page - About (
/about) - Company information - Projects (
/projects) - Project showcase - Assembly Line (
/assembly-line) - Interactive robotics demo - Login (
/login) - Authentication interface - Forgot Password (
/forgot-password) - Password reset request form - Reset Password (
/reset-password) - Password update form with token validation
The project has been recently upgraded to Next.js 15.5.2 and React 19.1.1 with several breaking changes handled:
- Route Parameters: Route
paramsare now Promises and must be awaited - Cookies API:
cookies()now returns a Promise, requiring async handling - TailwindCSS v4: Major version upgrade with new PostCSS plugin structure
- Created
createClientSyncwrapper for Supabase client to maintain backward compatibility - Updated all route handlers to properly await
params - Migrated PostCSS configuration to use
@tailwindcss/postcss - Updated all
@typespackages to match React 19 compatibility
- Test Type Errors: 89 TypeScript errors in test files due to
RequestvsNextRequesttype changes - Tailwind Warnings: Some deprecated utility classes need updating for v4 compatibility
- CI/CD Pipeline: May need updates to accommodate new Node.js/npm version locks
- Node.js: Locked to v20.19.4 for Next.js 15 compatibility
- npm: Locked to v10.0.0 for consistent package resolution
- Browser Support: Maintained compatibility with modern browsers
- Security: All security features and headers remain functional
The project includes comprehensive security tests in __tests__/api.test.ts:
- Valid request handling
- Input validation testing
- XSS payload sanitization
- Error handling verification
- Follow the existing TypeScript patterns
- Add corresponding tests for security-sensitive code
- Update navigation if adding new pages
- Maintain security headers and middleware protection
- Run tests after making changes:
npm run test - Verify application launches:
npm run dev
When adding CTF challenges:
- Document any intentional vulnerabilities clearly
- Maintain the secure baseline for production pages
- Add test coverage for both secure and vulnerable endpoints
- Keep challenges isolated from core application logic
- Use TypeScript for type safety
- Follow the established component patterns
- Implement proper error boundaries
- Maintain responsive design with Tailwind CSS
- Ensure all new API routes have corresponding tests
next.config.mjs- Next.js config with security headersjest.config.js- Test configuration with TypeScript supporttailwind.config.ts- Styling configuration (TailwindCSS v4)tsconfig.json- TypeScript compiler settings
middleware.ts- Global security middleware and request loggingapp/api/hello/route.ts- Example of secure API patterns__tests__/api.test.ts- Security-focused test examples
README.md- Comprehensive project documentationcursor.md- Development principles and practicesCHANGELOG.md- Detailed upgrade history and breaking changes documentation
.nvmrc- Node.js version lock for consistencypackage.json- npm version lock and dependency specifications
This platform is specifically designed for a robotics-themed CTF competition. The baseline provides:
- Secure foundation demonstrating best practices
- Educational examples of common vulnerabilities
- Test-driven security validation
- Professional-grade development environment
Always verify that tests pass and the application launches correctly after making changes, especially when working with security-sensitive code or adding new CTF challenges.
The platform includes a real-time notification system that alerts dev users to important events like AI activations and user promotions. This system uses Supabase Realtime for instant delivery.
- Database Table:
public.notificationsstores all notification events - RLS Security: Only dev users can read notifications (admin/user roles cannot see them)
- Realtime Delivery: Supabase automatically broadcasts INSERT events to subscribed clients
- Client Filtering: Only dev users subscribe to notifications, ensuring security
- Toast UI: Uses
react-hot-toastfor non-intrusive notification display
- AI_ACTIVATION: When a user activates the AI system
- USER_PROMOTED: When someone completes the final challenge and becomes admin
- SYSTEM_ALERT: For system maintenance and important alerts
- CHALLENGE_COMPLETED: For significant challenge completions (future use)
-- Notifications table with RLS policies
CREATE TABLE public.notifications (
id UUID DEFAULT uuid_generate_v4() PRIMARY KEY,
type TEXT NOT NULL CHECK (type IN ('AI_ACTIVATION', 'CHALLENGE_COMPLETED', 'SYSTEM_ALERT', 'USER_PROMOTED')),
message TEXT NOT NULL,
data JSONB DEFAULT '{}',
created_by UUID REFERENCES auth.users(id),
created_at TIMESTAMP WITH TIME ZONE DEFAULT timezone('utc'::text, now())
);
-- Only dev users can read notifications
CREATE POLICY "Dev users can read notifications" ON public.notifications
FOR SELECT USING (EXISTS (SELECT 1 FROM public.profiles WHERE id = auth.uid() AND role = 'dev'));// lib/notifications/dispatch.ts
import { dispatchAIActivationNotification } from '@/lib/notifications/dispatch';
// In API routes:
await dispatchAIActivationNotification(userEmail, userName, userId);// app/contexts/NotificationsContext.tsx
// Automatically subscribes dev users to real-time notifications
// Displays toast notifications for incoming events- Unit Tests: Run
npm test __tests__/notifications.test.ts - Integration Test:
- Log in as a dev user in two browser tabs
- Activate AI in one tab
- Verify toast appears in both tabs instantly
- Role Testing: Verify non-dev users don't receive notifications
- Update Database: Add new type to the CHECK constraint in
schema.sql - Update Dispatch: Add helper function in
lib/notifications/dispatch.ts - Update Types: Add to TypeScript interfaces in
NotificationsContext.tsx - Update Icons: Add icon mapping in
getNotificationIcon()function
- RLS Protection: Database-level security prevents unauthorized access
- Client Filtering: Only dev users subscribe to notifications
- Server-Side Dispatch: All notifications originate from secure API routes
- No Client Inserts: RLS policies prevent client-side notification creation
The CTF platform implements a strict role-based access control (RBAC) system with three distinct roles. Each role has carefully defined permissions to ensure proper separation of concerns and maintain security boundaries.
dev (Super Admin)
├── Full system access
├── All admin capabilities
└── Challenge management
admin (Limited Admin)
└── AI activation only
user (CTF Participant)
├── Challenge submission
├── Project management
└── Basic features
| Permission Function | dev |
admin |
user |
|---|---|---|---|
canActivateAI() |
✅ | ✅ | ❌ |
canViewAdminData() |
✅ | ❌ | ❌ |
canManageSystem() |
✅ | ❌ | ❌ |
canManageChallenges() |
✅ | ❌ | ❌ |
canAccessGraphQL() |
✅ | ❌ | ❌ |
canResetChallenges() |
✅ | ❌ | ❌ |
canManageRateLimit() |
✅ | ❌ | ❌ |
canViewAllProjects() |
✅ | ❌ | ❌ |
| Receive Notifications | ✅ | ❌ | ❌ |
- Purpose: Full system administration and challenge creation
- Access Level: Unrestricted
- Key Responsibilities:
- System configuration and maintenance
- Challenge creation and management
- User promotion and role assignment
- Real-time monitoring via notifications
- Database administration
- Security incident response
- Purpose: CTF players who complete the final challenge
- Access Level: Restricted to essential functions only
- Key Responsibilities:
- AI system activation (primary function)
- Switch between user projects (read-only)
- Restrictions:
- Cannot modify system settings
- Cannot create or edit challenges
- Cannot access GraphQL admin endpoints
- Cannot view admin dashboard data
- Cannot access rate limiting statistics
- Cannot receive system notifications
- Cannot reset challenge cutoffs
- Purpose: Standard CTF participants
- Access Level: Basic platform features
- Key Responsibilities:
- Submit challenge flags
- Manage personal projects
- View leaderboard
- Update profile information
All permission checks are enforced server-side using the centralized permission system:
// Example usage in API routes
import { createPermissionContext, canActivateAI } from '@/lib/auth/permissions';
const permissionContext = createPermissionContext(authUser, userProfile);
if (!canActivateAI(permissionContext)) {
return NextResponse.json({ error: 'Admin access required' }, { status: 403 });
}Row Level Security (RLS) policies enforce permissions at the database level:
-- Example: Only dev users can read notifications
CREATE POLICY "Dev users can read notifications" ON public.notifications
FOR SELECT USING (EXISTS (SELECT 1 FROM public.profiles WHERE id = auth.uid() AND role = 'dev'));// Frontend check - for UI display only
const isAdmin = profile?.role === 'admin' || profile?.role === 'dev';
// This check can be bypassed by CTF participants (intentionally)
const isAdminFrontend = localStorage.getItem('admin_access') === 'true' || isAdmin;- Never trust frontend: All critical operations validate permissions server-side
- Use permission helpers: Always use the centralized permission functions from
@/lib/auth/permissions - Database enforcement: RLS policies provide defense in depth
- Audit trail: All admin actions are logged with user identification
- Principle of least privilege: Admin role has minimal necessary permissions
Several intentional vulnerabilities exist for educational purposes:
- Frontend Admin Bypass: Participants can manipulate localStorage to bypass frontend admin checks, but backend validation prevents actual privilege escalation
- Admin Terminal: Accessible via URL parameter with XSS vulnerability for challenge purposes
- GraphQL Endpoint: Exposed without authentication as a security challenge
These vulnerabilities are contained and do not compromise the actual security model.
- Notifications are delivered in <100ms via WebSocket connection
- Client maintains last 50 notifications in memory
- Automatic cleanup of realtime subscriptions on component unmount
- Graceful degradation if Supabase Realtime is unavailable