This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
- Scalability: Write code that handles growth in data, users, and complexity
- Best Practices: Follow industry standards and proven patterns
- Performance: Optimize for speed and efficiency; consider database query performance, caching, and algorithmic complexity
- Modern Standards: Use current TypeScript/JavaScript features, latest framework patterns, and contemporary architecture
IMPORTANT: Always stage, commit, push, and open PRs directly — do not provide commands for the user to run manually. Use the Bash tool to execute all git operations.
Format requirements:
- First line: conventional commit type (feat/fix/docs/test/refactor/perf/chore)
- Add blank lines between sections for readability
- Group related changes with bullet points
- No attribution or AI-generated notices
- Never include AI attribution in code, comments, or commit messages
- Never add "Generated by Claude" or similar notices
- Code should appear as if written by a human developer
Station is a pnpm workspace monorepo for gaming guild/organization management with a NestJS backend and React frontend. The architecture uses role-based access control (RBAC) with flexible JSONB permissions, JWT authentication with refresh token rotation, and Redis caching with graceful in-memory fallback.
# Start both frontend and backend (from root)
pnpm dev
# Start individual services (from root)
pnpm dev:backend # NestJS on http://localhost:3001
pnpm dev:frontend # React on http://localhost:5173
# Start infrastructure
docker-compose up -d # PostgreSQL (5433) + Redis (6379)# From backend/ directory
pnpm migration:create src/migrations/YourMigrationName
pnpm migration:run # Run pending migrations
pnpm migration:revert # Rollback last migration
pnpm db:backup # Create timestamped backup
pnpm db:health-check # Validate database state
pnpm seed # Seed database with test dataCritical: Always create backup before production migrations. See backend/docs/database/migrations.md for complete migration safety procedures including rollback decision tree and pre-migration checklist.
# Backend tests (from backend/)
pnpm test # Unit tests
pnpm test:e2e # E2E tests (requires database)
pnpm test:watch # Watch mode
pnpm test:cov # Coverage report
# From root (all packages)
pnpm testNote: E2E tests require PostgreSQL running. Use docker-compose up -d database first.
pnpm lint # Lint all packages
pnpm format # Format with Prettier
pnpm typecheck # TypeScript type checking
pnpm build # Build all packagesNestJS follows modular architecture where each feature is self-contained:
auth- JWT authentication, refresh tokens, password resetusers- User management with extended profilesorganizations- Guild/organization CRUDroles- Role definitions with JSONB permissionsuser-organization-roles- Many-to-many user ↔ org ↔ role relationshipspermissions- Permission aggregation with Redis cachingaudit-logs- Activity tracking and audit trails
Key Pattern: Each module contains:
*.module.ts- Module definition with imports/providers*.controller.ts- HTTP endpoints (REST API)*.service.ts- Business logic*.entity.ts- TypeORM database entitiesdto/- Data transfer objects withclass-validator*.guard.ts- Route protection (JWT, permissions)
TypeORM with PostgreSQL using manual migrations (not synchronize in production):
users ─┐
├─ user_organization_role ─┬─ organizations
roles ─┘ │
└─ audit_log
refresh_tokens ── users
password_resets ── users
Critical Details:
- Test environment uses
synchronize: trueanddropSchema: true(auto-recreates schema) - Production uses migrations only:
migrationsRun: false(manual execution required) - Composite indexes on
user_organization_rolefor query performance - JSONB
permissionsfield onroleenables flexible permission structures
Redis with automatic fallback:
- Default: Redis connection at
REDIS_HOST:6379 - Fallback: In-memory cache if Redis unavailable
- Test env: Forced in-memory via
USE_REDIS_CACHE=false - TTL: 5 minutes (300000ms)
Cached entities: Organization members, aggregated permissions
- Register:
POST /auth/register→ Creates user with hashed password - Login:
POST /auth/login→ Returnsaccess_token(15min) +refresh_token(7 days) - Protected Routes: Add header
Authorization: Bearer <access_token> - Refresh:
POST /auth/refreshwith refresh token → New token pair - Logout:
POST /auth/logout→ Revokes refresh token
Security:
- Passwords hashed with bcrypt (10 rounds)
- Refresh token rotation (old tokens revoked)
- JWT signed with
JWT_SECRETfrom environment - Guards:
JwtAuthGuard,LocalAuthGuard,RefreshTokenAuthGuard
Required variables:
DATABASE_HOST=localhost
DATABASE_PORT=5433
DATABASE_USER=stationDbUser
DATABASE_PASSWORD=stationDbPassword1
DATABASE_NAME=stationDb
JWT_SECRET=your-secret-key
REDIS_HOST=localhost
REDIS_PORT=6379
PORT=3001
APP_NAME=STATION BACKEND
USE_REDIS_CACHE=true # Set false for testsSame as .env but with USE_REDIS_CACHE=false to avoid Redis dependency in CI/CD.
Every production migration must:
- Have working
up()anddown()methods - Be tested with
migration:revertin development - Include pre-migration backup:
pnpm db:backup - Run post-migration health check:
pnpm db:health-check - Follow checklist in
backend/src/migrations/templates/PRE_MIGRATION_CHECKLIST.md
Templates: Use backend/src/migrations/templates/migration-template.ts for structure and examples.
Rollback decision tree available in backend/docs/database/migrations.md - includes 5-step process for handling failures.
- E2E tests drop and recreate schema on every run (via
dropSchema: true) - Tests run serially (
--runInBand) to avoid race conditions - Database must be running:
docker-compose up -d database - Some tests skip in CI/CD if PostgreSQL tools (
pg_dump,psql) unavailable
lint-staged runs on commit:
- Backend: ESLint + Prettier
- Root: Prettier on JSON/MD files
If hooks fail, fix issues and re-commit. To bypass (not recommended): git commit --no-verify
Turbo manages builds/tests across packages:
- Parallel execution where possible
- Caching for faster rebuilds
- Run from root to execute across all packages
- Use
pnpm --filter <package>for specific packages
Swagger UI auto-generated at http://localhost:3001/api/docs when backend running.
Includes:
- All endpoints with request/response schemas
- Bearer token authentication
- Try-it-out functionality
- Database not running: Start with
docker-compose up -d databasebefore running app or tests - Migration errors: Always test rollback in dev:
pnpm migration:revert - Test failures in CI: Check if test requires PostgreSQL tools (backup/health-check tests skip in CI)
- Redis connection warnings: Expected in test environment - app falls back to memory cache
- Port conflicts: Backend default is 3001, frontend is 5173, PostgreSQL is 5433 (not 5432)
- pnpm version: Requires pnpm 8+ (specified in package.json engines)
- Node version: Requires Node 18+ (specified in package.json engines)
Controllers use NestJS built-in exceptions:
throw new NotFoundException('User not found');
throw new BadRequestException('Invalid input');
throw new UnauthorizedException('Invalid credentials');All DTOs use class-validator decorators:
@IsString()
@IsNotEmpty()
username: string;
@IsEmail()
email: string;Global ValidationPipe in main.ts auto-validates incoming requests.
Use PermissionsService.getUserPermissions(userId, orgId) to get aggregated permissions from all user's roles in an organization. Results are cached in Redis.
AuditLogsService tracks important actions. Log via:
await this.auditLogsService.log({
userId,
action: 'USER_UPDATED',
resource: 'User',
resourceId: user.id,
metadata: { changes: ... }
});