kim-auth
v2.0.0
Published
Production-ready Authentication & Authorization (JWT, API Key, OAuth2)
Maintainers
Readme
kim-auth
Production-Ready Authentication & Authorization System
Version: 2.0.0
Features
Core
- ✅ JWT Authentication - Access + Refresh tokens
- ✅ API Key Management - Create, list, revoke
- ✅ Scope-based Authorization - Fine-grained permissions
- ✅ bcrypt Password Hashing - Industry standard (12 rounds)
- ✅ SQLite Database - Zero-config persistence
- ✅ Redis Session Store - Optional distributed support
- ✅ Audit Logging - Full authentication trail
- ✅ Rate Limiting - IP-based protection
- ✅ Helmet Security - Security headers
- ✅ Winston Logging - Structured logs
Production-Ready
- Token blacklisting (logout support)
- Refresh token rotation
- API key expiration
- User role management
- Internal validation API (for microservices)
- Graceful shutdown
- Health check endpoint
Quick Start
1. Install Dependencies
npm install2. Environment Setup
cp .env.example .envEdit .env:
JWT_SECRET=your-very-secure-secret-min-64-characters-recommended
PORT=503003. Initialize Database
npm run migrate4. Start Server
npm startServer runs on http://localhost:50300
Default admin: admin / admin123
API Documentation
Authentication
Login
POST /auth/login
Content-Type: application/json
{
"userId": "admin",
"password": "admin123"
}
# Response
{
"accessToken": "eyJhbGc...",
"refreshToken": "a1b2c3...",
"expiresIn": "24h",
"tokenType": "Bearer",
"user": {
"id": "admin",
"name": "Administrator",
"role": "admin"
}
}Refresh Token
POST /auth/refresh
Content-Type: application/json
{
"refreshToken": "a1b2c3..."
}
# Response
{
"accessToken": "eyJhbGc...",
"expiresIn": "24h",
"tokenType": "Bearer"
}Logout
POST /auth/logout
Authorization: Bearer eyJhbGc...
Content-Type: application/json
{
"refreshToken": "a1b2c3..."
}Verify Token
POST /auth/verify
Content-Type: application/json
{
"token": "eyJhbGc..."
}
# Response
{
"valid": true,
"payload": {
"userId": "admin",
"name": "Administrator",
"role": "admin"
},
"expiresAt": "2026-01-05T12:00:00Z"
}API Keys
Create API Key
POST /api-keys
Authorization: Bearer eyJhbGc...
Content-Type: application/json
{
"name": "Production API",
"scopes": ["read", "write"],
"expiresInDays": 90
}
# Response
{
"apiKey": "kim_a1b2c3d4e5f6...",
"prefix": "kim_a1b2c3d4...",
"name": "Production API",
"scopes": ["read", "write"],
"expiresAt": "2026-04-05T00:00:00Z"
}⚠️ Save the full API key - it's only shown once!
List API Keys
GET /api-keys
Authorization: Bearer eyJhbGc...
# Response
{
"keys": [
{
"prefix": "kim_a1b2c3d4...",
"name": "Production API",
"scopes": ["read", "write"],
"createdAt": "2026-01-04T00:00:00Z",
"lastUsed": "2026-01-04T12:00:00Z",
"expiresAt": "2026-04-05T00:00:00Z"
}
],
"count": 1
}Delete API Key
DELETE /api-keys/kim_a1b2c3d4
Authorization: Bearer eyJhbGc...User Management
Create User (Admin Only)
POST /users
Authorization: Bearer eyJhbGc...
Content-Type: application/json
{
"userId": "john",
"name": "John Doe",
"email": "[email protected]",
"password": "secure123",
"role": "user"
}Get Current User
GET /users/me
Authorization: Bearer eyJhbGc...
# or
X-API-Key: kim_a1b2c3d4...
# Response
{
"id": "admin",
"name": "Administrator",
"email": "[email protected]",
"role": "admin",
"apiKeyCount": 2,
"lastLogin": "2026-01-04T12:00:00Z"
}Internal Validation
For microservices to validate tokens/keys:
POST /internal/validate
Content-Type: application/json
{
"token": "eyJhbGc...",
"requiredScopes": ["read"]
}
# Response
{
"valid": true,
"type": "jwt",
"user": {
"userId": "admin",
"name": "Administrator",
"role": "admin",
"scopes": ["*"]
}
}Health Check
GET /health
# Response
{
"status": "ok",
"service": "kim-auth",
"version": "2.0.0",
"users": 5,
"redis": "connected"
}Using API Keys
Header Method (Recommended)
GET /users/me
X-API-Key: kim_a1b2c3d4e5f6...Query Parameter
GET /users/me?api_key=kim_a1b2c3d4e5f6...Authorization Scopes
*- Full access (admin)read- Read-only accesswrite- Write accessdelete- Delete accessadmin- Admin operationsuser:create- Create users- Custom scopes supported
Environment Variables
| Variable | Default | Description |
|----------|---------|-------------|
| NODE_ENV | development | Environment |
| PORT | 50300 | Server port |
| HOST | 0.0.0.0 | Bind address |
| JWT_SECRET | Required | JWT signing secret (min 32 chars) |
| JWT_EXPIRES_IN | 24h | Access token lifetime |
| REFRESH_TOKEN_EXPIRES_DAYS | 7 | Refresh token days |
| BCRYPT_ROUNDS | 12 | Password hash rounds |
| DB_PATH | ./data/auth.db | SQLite database path |
| REDIS_URL | redis://localhost:6379 | Redis connection |
| REDIS_ENABLED | false | Enable Redis |
| RATE_LIMIT_WINDOW_MS | 900000 | Rate limit window (15min) |
| RATE_LIMIT_MAX_REQUESTS | 100 | Max requests per window |
| LOG_LEVEL | info | Logging level |
| LOG_FILE | ./logs/auth.log | Log file path |
Database Schema
Tables
- users - User accounts
- api_keys - API key management
- refresh_tokens - Refresh token store
- audit_logs - Authentication audit trail
Migrations
npm run migrateRedis (Optional)
Enable for:
- Distributed deployments
- Token blacklisting
- Session sharing
- Rate limiting across instances
REDIS_ENABLED=true
REDIS_URL=redis://localhost:6379Security Best Practices
JWT Secret: Use a strong random string (64+ characters)
openssl rand -hex 32HTTPS Only: Always use HTTPS in production
Environment Variables: Never commit
.envto gitRate Limiting: Adjust limits based on your needs
Password Policy: Enforce strong passwords at application level
API Key Rotation: Regularly rotate keys
Audit Logs: Monitor authentication failures
Monitoring
Logs
tail -f logs/auth.log
tail -f logs/auth-error.logMetrics
- Authentication success/failure rates
- Token refresh patterns
- API key usage
- Rate limit hits
Check audit logs:
sqlite3 data/auth.db
SELECT * FROM audit_logs ORDER BY created_at DESC LIMIT 10;Testing
Test Coverage (Phase 4 npm Upgrade)
- 5 Jest Test Suites (70%+ coverage)
- 60+ test cases
- 100% pass rate ✅
Test Suites
| Test File | Suites | Focus | |-----------|--------|-------| | jwt.test.js | 5 | Token generation, verification, refresh | | auth.test.js | 5 | Login, registration, logout, password management | | oauth.test.js | 5 | OAuth2 flows, scopes, PKCE, refresh tokens | | security.test.js | 7 | API keys, RBAC, permissions, sessions, CSRF | | rate-limit.test.js | 7 | Rate limiting, DDoS protection, quotas |
Run Tests
# Full test suite with coverage
npm run test
# Watch mode
npm run test:watch
# Specific test file
npm run test -- tests/jwt.test.js
npm run test -- tests/auth.test.js
npm run test -- tests/security.test.jsTest Coverage Targets
- Branches: 70%+
- Functions: 70%+
- Lines: 70%+
- Statements: 70%+
Development
# Watch mode
npm run dev
# Check logs
tail -f logs/auth.logProduction Deployment
PM2
pm2 start server-v2.js --name kim-auth
pm2 logs kim-auth
pm2 monitDocker (coming soon)
docker build -t kim-auth .
docker run -p 50300:50300 --env-file .env kim-authTroubleshooting
JWT_SECRET Error
JWT_SECRET must be set and at least 32 charactersSolution: Set a secure JWT_SECRET in .env
Database Lock
database is lockedSolution: SQLite WAL mode enabled automatically. Check file permissions.
Redis Connection Failed
Logs show:
Redis errorSolution: Set REDIS_ENABLED=false or start Redis server
Architecture
kim-auth/
├── server-v2.js # Main application
├── lib/
│ ├── db.js # Database layer
│ ├── logger.js # Winston logger
│ └── redis.js # Redis client
├── migrations/
│ └── init.js # Database schema
├── config/
├── data/ # SQLite database
├── logs/ # Application logs
└── .env # Environment configLicense
MIT
Version History
v2.0.0 (2026-01-04)
- ✅ Production-ready rewrite
- ✅ SQLite + bcrypt + Redis
- ✅ Audit logging
- ✅ Rate limiting
- ✅ Token blacklisting
- ✅ Comprehensive error handling
v1.0.0 (2026-01-01)
- Basic JWT + API Key auth
- In-memory storage
- Proof of concept
Built by Kim | Powered by Node.js
