Examples of the documentation extraction workflow.
Extract documentation for a JWT-based authentication system, including login, token refresh, and RBAC.
Discover feature
authentication JWT login logout token refresh auth middleware
]]>
- Auth controllers, services, middleware, models, and routes.
Analyze structure
src/auth
]]>
- Identify main classes/functions.
- Map auth flow.
- Find token generation/validation logic.
Read core files
src/auth/auth.controller.ts
src/auth/auth.service.ts
src/auth/jwt.strategy.ts
src/auth/auth.guard.ts
src/models/user.model.ts
]]>
Extract API endpoints
src/auth
@(Post|Get)\(['"]\/auth\/[^'"]+['"]|router\.(post|get)\(['"]\/auth\/[^'"]+['"]
]]>
- POST /auth/login, POST /auth/logout, POST /auth/refresh, GET /auth/profile, POST /auth/register
Extract configuration
src
JWT_SECRET|JWT_EXPIRATION|AUTH_.*|process\.env\.\w*AUTH\w*
]]>
Analyze security
src/auth
bcrypt|hash|salt|encrypt|sanitize|validate|@IsEmail|@MinLength
]]>
Generate docs
DOCS-TEMP-authentication-system.md
# Authentication System Documentation
## Table of Contents
1. [Overview](#overview)
2. [Quick Start](#quick-start)
3. [Architecture](#architecture)
4. [API Reference](#api-reference)
5. [Configuration](#configuration)
6. [Security](#security)
7. [User Guide](#user-guide)
8. [Developer Guide](#developer-guide)
9. [Troubleshooting](#troubleshooting)
---
## Overview
### Purpose
The authentication system provides secure user authentication using JWT (JSON Web Tokens) with support for:
- User registration and login
- Token-based authentication
- Refresh token rotation
- Role-based access control (RBAC)
- Session management
- Password reset functionality
### Key Features
- **JWT Authentication**: Stateless authentication using signed tokens
- **Refresh Tokens**: Long-lived tokens for seamless user experience
- **Role-Based Access**: Fine-grained permission control
- **Security**: bcrypt password hashing, rate limiting, CSRF protection
- **Multi-device Support**: Token management across devices
### Version Information
- **Current Version**: 2.1.0
- **Minimum Node.js**: 14.0.0
- **Dependencies**:
- jsonwebtoken: ^9.0.0
- bcrypt: ^5.1.0
- passport: ^0.6.0
---
## Quick Start
### For Users
1. Register a new account:
```bash
POST /api/auth/register
{
"email": "user@example.com",
"password": "SecurePassword123!",
"name": "John Doe"
}
```
2. Login to receive tokens:
```bash
POST /api/auth/login
{
"email": "user@example.com",
"password": "SecurePassword123!"
}
```
3. Use the access token in subsequent requests:
```bash
Authorization: Bearer
```
### For Developers
```typescript
// Import authentication module
import { AuthModule } from './auth/auth.module';
// Configure in app module
@Module({
imports: [
AuthModule.forRoot({
jwtSecret: process.env.JWT_SECRET,
jwtExpiration: '15m',
refreshExpiration: '7d'
})
]
})
export class AppModule {}
```
---
## Architecture
### System Overview
```
┌─────────────┐ ┌──────────────┐ ┌─────────────┐
│ Client │────▶│ Auth Guard │────▶│ Service │
└─────────────┘ └──────────────┘ └─────────────┘
│ │
▼ ▼
┌──────────────┐ ┌─────────────┐
│ JWT Strategy │ │ Database │
└──────────────┘ └─────────────┘
```
### Components
- **AuthController**: Handles HTTP requests for authentication endpoints
- **AuthService**: Core authentication logic and token management
- **JwtStrategy**: Passport strategy for JWT validation
- **AuthGuard**: Route protection middleware
- **UserService**: User management and database operations
### Token Flow
1. User provides credentials
2. System validates credentials against database
3. Generate access token (short-lived) and refresh token (long-lived)
4. Client stores tokens securely
5. Access token used for API requests
6. Refresh token used to obtain new access token
---
## API Reference
### Authentication Endpoints
#### `POST /api/auth/register`
Register a new user account.
**Request Body**:
```json
{
"email": "string (required)",
"password": "string (required, min 8 chars)",
"name": "string (required)",
"role": "string (optional, default: 'user')"
}
```
**Response** (201 Created):
```json
{
"user": {
"id": "uuid",
"email": "user@example.com",
"name": "John Doe",
"role": "user",
"createdAt": "2024-01-01T00:00:00Z"
},
"tokens": {
"accessToken": "jwt_token",
"refreshToken": "refresh_token",
"expiresIn": 900
}
}
```
**Error Responses**:
- `400 Bad Request`: Invalid input data
- `409 Conflict`: Email already exists
#### `POST /api/auth/login`
Authenticate user and receive tokens.
**Request Body**:
```json
{
"email": "string (required)",
"password": "string (required)"
}
```
**Response** (200 OK):
```json
{
"user": {
"id": "uuid",
"email": "user@example.com",
"name": "John Doe",
"role": "user"
},
"tokens": {
"accessToken": "jwt_token",
"refreshToken": "refresh_token",
"expiresIn": 900
}
}
```
**Error Responses**:
- `401 Unauthorized`: Invalid credentials
- `429 Too Many Requests`: Rate limit exceeded
#### `POST /api/auth/refresh`
Refresh access token using refresh token.
**Request Body**:
```json
{
"refreshToken": "string (required)"
}
```
**Response** (200 OK):
```json
{
"accessToken": "new_jwt_token",
"expiresIn": 900
}
```
#### `POST /api/auth/logout`
Invalidate refresh token.
**Headers**:
- `Authorization: Bearer `
**Request Body**:
```json
{
"refreshToken": "string (required)"
}
```
**Response** (200 OK):
```json
{
"message": "Logged out successfully"
}
```
---
## Configuration
### Environment Variables
| Variable | Type | Default | Description |
|----------|------|---------|-------------|
| `JWT_SECRET` | string | - | Secret key for signing JWT tokens (required) |
| `JWT_EXPIRATION` | string | '15m' | Access token expiration time |
| `REFRESH_TOKEN_EXPIRATION` | string | '7d' | Refresh token expiration time |
| `BCRYPT_ROUNDS` | number | 10 | Number of bcrypt hashing rounds |
| `AUTH_RATE_LIMIT` | number | 5 | Max login attempts per minute |
| `ENABLE_2FA` | boolean | false | Enable two-factor authentication |
### Configuration File (auth.config.ts)
```typescript
export const authConfig = {
jwt: {
secret: process.env.JWT_SECRET,
signOptions: {
expiresIn: process.env.JWT_EXPIRATION || '15m',
issuer: 'your-app-name',
audience: 'your-app-users'
}
},
bcrypt: {
rounds: parseInt(process.env.BCRYPT_ROUNDS || '10')
},
session: {
maxDevices: 5,
inactivityTimeout: '30d'
}
};
```
---
## Security
### Authentication Flow
1. **Password Storage**: Passwords hashed using bcrypt with configurable rounds
2. **Token Security**: JWT tokens signed with RS256 algorithm
3. **Refresh Token Rotation**: New refresh token issued on each refresh
4. **Rate Limiting**: Prevents brute force attacks on login endpoint
### Security Best Practices
- Store tokens securely (httpOnly cookies recommended)
- Implement CSRF protection for cookie-based auth
- Use HTTPS in production
- Rotate JWT secrets periodically
- Implement account lockout after failed attempts
- Enable 2FA for sensitive accounts
### Common Vulnerabilities Addressed
- **SQL Injection**: Parameterized queries
- **XSS**: Input sanitization and validation
- **CSRF**: Token validation
- **Brute Force**: Rate limiting and account lockout
- **Token Hijacking**: Short expiration times and refresh rotation
---
## User Guide
### Registration Process
1. Navigate to registration page
2. Enter email, password, and name
3. Verify email (if enabled)
4. Login with credentials
### Managing Sessions
- View active sessions in account settings
- Revoke sessions from other devices
- Set session timeout preferences
### Password Management
- Change password from profile settings
- Reset forgotten password via email
- Password requirements:
- Minimum 8 characters
- At least one uppercase letter
- At least one number
- At least one special character
---
## Developer Guide
### Protecting Routes
```typescript
// Use AuthGuard decorator
@UseGuards(AuthGuard('jwt'))
@Get('protected')
async getProtectedData() {
return { data: 'This is protected' };
}
// Role-based protection
@UseGuards(AuthGuard('jwt'), RolesGuard)
@Roles('admin')
@Get('admin')
async getAdminData() {
return { data: 'Admin only' };
}
```
### Custom Authentication Logic
```typescript
// Extend AuthService
export class CustomAuthService extends AuthService {
async validateUser(email: string, password: string): Promise {
// Add custom validation logic
const user = await super.validateUser(email, password);
// Additional checks
if (user.suspended) {
throw new UnauthorizedException('Account suspended');
}
return user;
}
}
```
### Testing Authentication
```typescript
describe('AuthController', () => {
it('should login user', async () => {
const response = await request(app.getHttpServer())
.post('/auth/login')
.send({
email: 'test@example.com',
password: 'TestPass123!'
})
.expect(200);
expect(response.body).toHaveProperty('tokens.accessToken');
});
});
```
---
## Troubleshooting
### Common Issues
#### Invalid Token Error
**Problem**: "JsonWebTokenError: invalid token"
**Solutions**:
- Verify token format (Bearer prefix)
- Check token expiration
- Ensure JWT_SECRET matches
#### Login Rate Limit
**Problem**: "429 Too Many Requests"
**Solutions**:
- Wait for rate limit window to reset
- Check AUTH_RATE_LIMIT configuration
- Implement exponential backoff
#### CORS Issues
**Problem**: "Access blocked by CORS policy"
**Solutions**:
- Configure CORS middleware
- Add origin to allowed list
- Check preflight requests
### Debug Mode
Enable debug logging:
```bash
DEBUG=auth:* npm start
```
### Support
- GitHub Issues: [github.com/yourapp/issues](https://github.com/yourapp/issues)
- Documentation: [docs.yourapp.com/auth](https://docs.yourapp.com/auth)
- Email: support@yourapp.com
---
## Changelog
### v2.1.0 (2024-01-15)
- Added refresh token rotation
- Improved rate limiting
- Fixed security vulnerability in password reset
### v2.0.0 (2023-12-01)
- Breaking: Changed token format
- Added 2FA support
- Improved session management
### Migration Guide (v1.x to v2.x)
1. Update JWT_SECRET format
2. Run token migration script
3. Update client-side token handling
---
## References
- [JWT.io](https://jwt.io) - JWT Documentation
- [OWASP Authentication Guide](https://owasp.org/www-project-cheat-sheets/cheatsheets/Authentication_Cheat_Sheet)
- [Passport.js Documentation](http://www.passportjs.org/docs/)
450
]]>
Use semantic search to find related files.
Read multiple files for context.
Extract API docs from route definitions.
Use tests to understand behavior.
Document security measures.
Include troubleshooting for common errors.
Extract documentation for database models, relationships, and migrations.
Find DB files
database schema model entity migration table column relationship
]]>
Analyze models
src/models
@(Entity|Table|Model)|class\s+\w+\s+extends\s+(Model|BaseEntity)
]]>
Extract relationships
src/models
@(OneToMany|ManyToOne|OneToOne|ManyToMany|BelongsTo|HasMany)
]]>
Document migrations
migrations
true
]]>
Generate schema documentation
Extract comprehensive API documentation including all endpoints,
request/response formats, authentication, and examples.
Find all API routes
src
(app|router)\.(get|post|put|patch|delete|all)\s*\(\s*['"`]([^'"`]+)['"`]
]]>
Extract request validation
src
@(Body|Query|Param|Headers)\(|joi\.object|yup\.object|zod\.object
]]>
Find response schemas
src
@ApiResponse|swagger|openapi|response\.json\(|res\.send\(
]]>
Document authentication requirements
src
@(UseGuards|Authorized|Public)|passport\.authenticate|requireAuth
]]>
Generate OpenAPI/Swagger documentation
- OpenAPI 3.0 specification
- Postman collection
- API client examples
- cURL commands
- SDK usage examples
Document React/Vue/Angular components including props, events,
slots, styling, and usage examples.
Find component files
src/components
export\s+(default\s+)?(function|class|const)\s+\w+|@Component
*.tsx
]]>
Extract component props/inputs
src/components
interface\s+\w+Props|type\s+\w+Props|@Input\(\)|props:\s*{
]]>
Find component usage examples
src
]]>
Document styling and themes
src/components
styled\.|makeStyles|@apply|className=|style=
]]>
Extract Storybook stories
src
export\s+default\s+{.*title:|\.stories\.
*.stories.tsx
]]>
Generate component documentation
Document all configuration options, environment variables,
feature flags, and their impacts on system behavior.
Find configuration files
.
false
]]>
- .env.example
- config/
- settings.json
- app.config.ts
Extract environment variables
.
process\.env\.(\w+)|getenv\(['"](\w+)['"]\)
]]>
Find feature flags
src
feature\.|featureFlag|isEnabled\(['"]|flags\.
]]>
Document configuration impacts
- How each config affects behavior
- Dependencies between configs
- Performance implications
- Security considerations
- Default values and overrides
Generate configuration guide
Review a user-provided documentation section for accuracy against the codebase
and provide recommendations for improvement in the chat.
User provides documentation for review
"Here's our current draft for the JWT_SECRET setting. Can you check it for accuracy? 'The `JWT_SECRET` is an optional key for enhancing security.'"
Analyze relevant code
JWT_SECRET configuration implementation
]]>
- Code where `JWT_SECRET` is read (e.g., `process.env.JWT_SECRET`)
- Logic that fails if the secret is missing
- Default values or error handling related to the secret
Formulate and provide feedback in chat
I have reviewed the documentation section provided for the `JWT_SECRET` setting. Here are my recommendations for improvement:
**Overall Assessment**: The current draft is critically inaccurate and could lead to security vulnerabilities if followed.
**Recommendations for Improvement**:
* **Critical Inaccuracy**:
* The documentation states that `JWT_SECRET` is optional. However, the application will fail to start if it is not provided. It is a **required** setting for the application to function securely.
* **Suggestion**: "The `JWT_SECRET` is a **required** environment variable used to sign and verify JSON Web Tokens. The application will not run without it."
This feedback can be copied and pasted for your documentation team.
]]>
No file is written. The feedback is provided directly to the user in the chat interface.
Ensure all aspects are documented
- Technical implementation details
- Business logic and rules
- User workflows and journeys
- API specifications
- Configuration options
- Security measures
- Performance characteristics
- Error handling
- Testing strategies
- Deployment procedures
Tailor content for different readers
Focus on how-to guides and troubleshooting
Include code examples and technical details
Emphasize configuration and maintenance
Highlight business value and metrics
Create documentation that's easy to update
Use clear section headers
Include version information
Add last-updated timestamps
Cross-reference related sections
Provide migration guides
Include practical examples throughout
Code snippets with syntax highlighting
API request/response pairs
Configuration examples
Command-line usage
Error scenarios and solutions
- Table of contents with working links
- All sections properly formatted
- Code examples are syntactically correct
- No placeholder text remaining
- Version information included
- Cross-references are valid
- Metadata is complete
- File follows naming convention