Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
2202175
refactor(architecture): align with CSR pattern [MODULE-001]
RedaChannaCiscode Feb 2, 2026
0df1e5b
test(auth-service): implement testing infrastructure and AuthService …
RedaChannaCiscode Feb 2, 2026
81fd471
test(auth-controller): add integration tests (WIP - 13/25 passing)
RedaChannaCiscode Feb 2, 2026
eb46daf
test(services): add LoggerService & MailService tests
RedaChannaCiscode Feb 2, 2026
54265c7
test(services): add AdminRoleService & SeedService tests
RedaChannaCiscode Feb 2, 2026
23b8b75
test(services): add UsersService tests - 22 tests, 100% coverage
RedaChannaCiscode Feb 2, 2026
7b6aa69
test(services): add RolesService tests - 18 tests, 100% coverage
RedaChannaCiscode Feb 2, 2026
3f728b2
test(services): add PermissionsService tests - 14 tests, 100% coverage
RedaChannaCiscode Feb 2, 2026
c4bde5e
refactor(oauth): restructure OAuthService into modular architecture
RedaChannaCiscode Feb 2, 2026
af5bfeb
test(oauth): add comprehensive tests for refactored OAuth architecture
RedaChannaCiscode Feb 2, 2026
651952b
test(controllers): add unit tests for 4 controllers (Health, Permissi…
RedaChannaCiscode Feb 2, 2026
79c7a15
test(guards): add unit tests for 3 guards + fix configuration error h…
RedaChannaCiscode Feb 2, 2026
204c9a0
refactor(auth-kit): complete code quality refactoring and test organi…
RedaChannaCiscode Feb 2, 2026
d8d72fd
refactor(module): align architecture to CSR pattern [MODULE-001]
RedaChannaCiscode Feb 4, 2026
e450460
docs: complete API documentation with Swagger and structured error co…
RedaChannaCiscode Feb 4, 2026
671efe4
docs(copilot): update Copilot instructions to align with current arch…
RedaChannaCiscode Feb 4, 2026
9d0e9c7
feat(rbac): implement manual permission query and fix role/permission…
RedaChannaCiscode Feb 5, 2026
5750ade
test(oauth): stabilize FacebookOAuthProvider spec and fix mongoose ch…
RedaChannaCiscode Feb 5, 2026
ef635d1
Merge origin/develop into refactor/MODULE-001-align-architecture-csr …
Zaiidmo Mar 4, 2026
4d8a212
refactor: fix build, tests, and linting after merge
Zaiidmo Mar 4, 2026
99bdba3
chore: remove scripts directory to fix SonarQube quality gate
Zaiidmo Mar 4, 2026
543e21e
chore: add npm scripts and apply code formatting
Zaiidmo Mar 4, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 144 additions & 0 deletions .env.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
# =============================================================================
# Auth Kit - Environment Configuration Template
# Generated: 2026-02-04
#
# ISTRUZIONI:
# 1. Copia questo file in .env
# 2. Compila i valori necessari
# 3. Vedi docs/CREDENTIALS_NEEDED.md per dettagli
# =============================================================================

# -----------------------------------------------------------------------------
# DATABASE (OBBLIGATORIO)
# -----------------------------------------------------------------------------
# Opzione 1: MongoDB locale (per development/testing)
MONGO_URI=mongodb://127.0.0.1:27017/auth_kit_test

# Opzione 2: MongoDB Atlas (per staging/production)
# MONGO_URI=mongodb+srv://<username>:<password>@cluster0.xxxxx.mongodb.net/<database>?retryWrites=true&w=majority

# -----------------------------------------------------------------------------
# JWT SECRETS (OBBLIGATORIO)
#
# GENERA AUTOMATICAMENTE CON:
# .\scripts\setup-env.ps1 -GenerateSecrets
#
# O MANUALMENTE (min 32 caratteri casuali ciascuno):
# -----------------------------------------------------------------------------
JWT_SECRET=GENERA_CON_SCRIPT_O_FORNISCI_SECRET_SICURO_MIN_32_CHAR
JWT_ACCESS_TOKEN_EXPIRES_IN=15m

JWT_REFRESH_SECRET=GENERA_CON_SCRIPT_O_FORNISCI_SECRET_SICURO_MIN_32_CHAR
JWT_REFRESH_TOKEN_EXPIRES_IN=7d

JWT_EMAIL_SECRET=GENERA_CON_SCRIPT_O_FORNISCI_SECRET_SICURO_MIN_32_CHAR
JWT_EMAIL_TOKEN_EXPIRES_IN=1d

JWT_RESET_SECRET=GENERA_CON_SCRIPT_O_FORNISCI_SECRET_SICURO_MIN_32_CHAR
JWT_RESET_TOKEN_EXPIRES_IN=1h

# -----------------------------------------------------------------------------
# EMAIL / SMTP (OBBLIGATORIO per email verification e password reset)
#
# RACCOMANDATO: Mailtrap (gratis per testing)
# https://mailtrap.io/
#
# Copia credentials da: Dashboard → My Inbox → SMTP Settings
# -----------------------------------------------------------------------------
SMTP_HOST=sandbox.smtp.mailtrap.io
SMTP_PORT=2525
SMTP_USER=YOUR_MAILTRAP_USERNAME_HERE
SMTP_PASS=YOUR_MAILTRAP_PASSWORD_HERE
SMTP_SECURE=false
FROM_EMAIL=no-reply@test.com

# -----------------------------------------------------------------------------
# Alternativa: Gmail (SCONSIGLIATO per testing, più complicato)
# Richiede: 2FA enabled + App Password generata
# -----------------------------------------------------------------------------
# SMTP_HOST=smtp.gmail.com
# SMTP_PORT=587
# SMTP_USER=your.email@gmail.com
# SMTP_PASS=your_16_char_app_password
# SMTP_SECURE=false
# FROM_EMAIL=your.email@gmail.com

# -----------------------------------------------------------------------------
# APPLICATION URLS
# -----------------------------------------------------------------------------
FRONTEND_URL=http://localhost:3000
BACKEND_URL=http://localhost:3000

# -----------------------------------------------------------------------------
# GOOGLE OAUTH (OPZIONALE - per Google login)
#
# Setup: https://console.cloud.google.com/
# Guida: docs/CREDENTIALS_NEEDED.md → Google OAuth
#
# Required:
# - Create project
# - Enable Google+ API
# - Create OAuth 2.0 Client ID (Web application)
# - Add redirect URI: http://localhost:3000/api/auth/google/callback
# -----------------------------------------------------------------------------
GOOGLE_CLIENT_ID=
GOOGLE_CLIENT_SECRET=
GOOGLE_CALLBACK_URL=http://localhost:3000/api/auth/google/callback

# -----------------------------------------------------------------------------
# MICROSOFT OAUTH (OPZIONALE - per Microsoft/Azure AD login)
#
# Setup: https://portal.azure.com/
# Guida: docs/CREDENTIALS_NEEDED.md → Microsoft OAuth
#
# Required:
# - App registration (Entra ID)
# - Redirect URI: http://localhost:3000/api/auth/microsoft/callback
# - Client secret generato
# - API permissions: User.Read, openid, profile, email
# -----------------------------------------------------------------------------
MICROSOFT_CLIENT_ID=
MICROSOFT_CLIENT_SECRET=
MICROSOFT_CALLBACK_URL=http://localhost:3000/api/auth/microsoft/callback
MICROSOFT_TENANT_ID=common

# -----------------------------------------------------------------------------
# FACEBOOK OAUTH (OPZIONALE - per Facebook login)
#
# Setup: https://developers.facebook.com/
# Guida: docs/CREDENTIALS_NEEDED.md → Facebook OAuth
#
# Required:
# - Create app (Consumer type)
# - Add Facebook Login product
# - Valid OAuth Redirect: http://localhost:3000/api/auth/facebook/callback
# -----------------------------------------------------------------------------
FB_CLIENT_ID=
FB_CLIENT_SECRET=
FB_CALLBACK_URL=http://localhost:3000/api/auth/facebook/callback

# -----------------------------------------------------------------------------
# ENVIRONMENT
# -----------------------------------------------------------------------------
NODE_ENV=development

# =============================================================================
# CHECKLIST:
#
# OBBLIGATORIO (per funzionare):
# [ ] JWT secrets generati (4 secrets) - usa script automatico
# [ ] MongoDB running e MONGO_URI configurato
# [ ] SMTP credentials (Mailtrap) - serve per email verification
#
# OPZIONALE (per OAuth providers):
# [ ] Google OAuth credentials (se vuoi Google login)
# [ ] Microsoft OAuth credentials (se vuoi Microsoft login)
# [ ] Facebook OAuth credentials (se vuoi Facebook login)
#
# NEXT STEPS:
# 1. Compila valori necessari
# 2. Rinomina in .env
# 3. Verifica con: .\scripts\setup-env.ps1 -Validate
# 4. Avvia backend: npm run start:dev
# 5. Test endpoints: docs/TESTING_GUIDE.md
# =============================================================================
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@ yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Development tools (download separately)
tools/mailhog.exe
tools/mailhog

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

Expand Down
207 changes: 54 additions & 153 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,185 +1,86 @@
# Changelog

All notable changes to the AuthKit authentication library will be documented in this file.
All notable changes to the Authentication Kit will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

---

## [1.5.0] - 2026-01-31

### Added

- Full API documentation in README with request/response examples
- Complete Copilot development instructions for module maintainers
- Contribution guidelines with module-specific setup instructions
- Enhanced SECURITY.md with vulnerability reporting procedures
- Troubleshooting and FAQ sections in documentation
- TypeScript type definitions for all public APIs

### Changed

- Improved error handling and error message consistency
- Enhanced JWT payload structure documentation
- Optimized admin route filtering capabilities
- Updated CONTRIBUTING.md with module-specific requirements

### Fixed

- Translation of Italian text in Copilot instructions to English
- JWT refresh token validation edge cases
- Admin decorator permission checking

### Security

- Added security best practices section to documentation
- Documented JWT secret rotation procedures
- Enhanced password reset token expiration guidelines

---

## [1.4.0] - 2026-01-15

### Added

- Support for Facebook OAuth provider
- Microsoft Entra ID OAuth with JWKS verification
- Role-based permission management system
- Admin routes for user, role, and permission management
- User banning/unbanning functionality

### Changed

- Refresh token implementation now uses JWT instead of database storage
- Password change now invalidates all existing refresh tokens
- User model now supports optional jobTitle and company fields

### Fixed

- OAuth provider token validation improvements
- Email verification token expiration handling
- Microsoft tenant ID configuration flexibility

---

## [1.3.0] - 2025-12-20

### Added

- Email verification requirement before login
- Password reset functionality with JWT-secured reset links
- Resend verification email feature
- User profile endpoint (`GET /api/auth/me`)
- Account deletion endpoint (`DELETE /api/auth/account`)
- Auto-generated usernames when not provided (fname-lname format)

### Changed

- Authentication flow now requires email verification
- User model schema restructuring for better organization
- Improved password hashing with bcryptjs

### Security

- Implemented httpOnly cookies for refresh token storage
- Added password change tracking with `passwordChangedAt` timestamp
- Enhanced input validation on all auth endpoints

---
## [2.0.0] - 2026-02-02

## [1.2.0] - 2025-11-10
### 🏗️ Architecture Refactoring

### Added

- JWT refresh token implementation
- Token refresh endpoint (`POST /api/auth/refresh-token`)
- Automatic token refresh via cookies
- Configurable token expiration times
This release refactors the module architecture to align with the **Controller-Service-Repository (CSR)** pattern, making it simpler and more intuitive for consumers while maintaining all functionality.

### Changed

- Access token now shorter-lived (15 minutes by default)
- Refresh token implementation for better security posture
- JWT payload structure refined

### Fixed

- Token expiration validation during refresh

---

## [1.1.0] - 2025-10-05
- **BREAKING**: Renamed `models/` directory to `entities/`
Comment on lines +8 to +16
Copy link

Copilot AI Mar 4, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The CHANGELOG states this is version [2.0.0] - 2026-02-02 with multiple BREAKING changes, yet the package.json version is downgraded from 1.5.4 to 1.5.0. The docs/tasks/archive/2026-02/MODULE-001-align-architecture-csr.md also says "MAJOR version bump required: v1.5.0 → v2.0.0". The version should be 2.0.0 to reflect the breaking changes documented in the CHANGELOG.

Copilot uses AI. Check for mistakes.
- **BREAKING**: Renamed all `*.model.ts` files to `*.entity.ts`
- `user.model.ts` → `user.entity.ts`
- `role.model.ts` → `role.entity.ts`
- `permission.model.ts` → `permission.entity.ts`
- **BREAKING**: Moved guards from `middleware/` to dedicated `guards/` directory
- `middleware/authenticate.guard.ts` → `guards/authenticate.guard.ts`
- `middleware/admin.guard.ts` → `guards/admin.guard.ts`
- `middleware/role.guard.ts` → `guards/role.guard.ts`
- **BREAKING**: Moved decorators from `middleware/` to dedicated `decorators/` directory
- `middleware/admin.decorator.ts` → `decorators/admin.decorator.ts`
- **BREAKING**: Renamed `dtos/` directory to `dto/` (singular form, following NestJS conventions)
- **BREAKING**: Updated TypeScript path aliases:
- `@models/*` → `@entities/*`
- `@dtos/*` → `@dto/*`
- Added `@guards/*` → `src/guards/*`
- Added `@decorators/*` → `src/decorators/*`

### Added

- Google OAuth provider integration
- OAuth mobile exchange endpoints (ID Token and Authorization Code)
- OAuth web redirect flow with Passport.js
- Automatic user registration for OAuth providers

### Changed
- ✨ **Public API Exports**: All DTOs are now exported from the main package entry point
- Authentication DTOs: `LoginDto`, `RegisterDto`, `RefreshTokenDto`, `ForgotPasswordDto`, `ResetPasswordDto`, `VerifyEmailDto`, `ResendVerificationDto`, `UpdateUserRolesDto`
- Role DTOs: `CreateRoleDto`, `UpdateRoleDto`
- Permission DTOs: `CreatePermissionDto`, `UpdatePermissionDto`

- Authentication controller refactored for OAuth support
- Module configuration to support multiple OAuth providers
### Removed

### Security
- Removed empty `application/` directory (use-cases not needed for library simplicity)
- Removed `middleware/` directory (contents moved to `guards/` and `decorators/`)

- Google ID Token validation implementation
- Authorization Code exchange with PKCE support
### Migration Guide for Consumers

---
**If you were using the public API correctly (importing from package root), NO CHANGES NEEDED:**

## [1.0.0] - 2025-09-01
```typescript
// ✅ This continues to work (recommended usage)
import { AuthKitModule, AuthService, LoginDto, AuthenticateGuard } from '@ciscode/authentication-kit';
```

### Added
**If you were importing from internal paths (NOT recommended), update imports:**

- Initial release of AuthKit authentication library
- Local authentication (email + password)
- User registration and login
- JWT access token generation and validation
- Role-Based Access Control (RBAC) system
- Admin user management routes
- Email service integration (SMTP)
- Host app independent - uses host app's Mongoose connection
- Seed service for default roles and permissions
- Admin decorator and authenticate guard

### Features

- Local auth strategy with password hashing
- JWT-based authentication
- Role and permission models
- Default admin, user roles with configurable permissions
- Email sending capability for future notifications
- Clean Architecture implementation
- Production-ready error handling
```typescript
// ❌ OLD (internal imports - should never have been used)
import { User } from '@ciscode/authentication-kit/dist/models/user.model';
import { AuthenticateGuard } from '@ciscode/authentication-kit/dist/middleware/authenticate.guard';

---
// ✅ NEW (if you really need internal imports - but use public API instead)
import { User } from '@ciscode/authentication-kit/dist/entities/user.entity';
import { AuthenticateGuard } from '@ciscode/authentication-kit/dist/guards/authenticate.guard';

## Future Roadmap
// ✅ BEST (use public API)
import { AuthenticateGuard } from '@ciscode/authentication-kit';
```

### Planned for v2.0.0
### Why This Change?

- [ ] Two-factor authentication (2FA) support
- [ ] API key authentication for service-to-service communication
- [ ] Audit logging for security-critical operations
- [ ] Session management with concurrent login limits
- [ ] OpenID Connect (OIDC) provider support
- [ ] Breaking change: Restructure module exports for better tree-shaking
- [ ] Migration guide for v1.x → v2.0.0
This refactoring aligns the module with industry-standard **Controller-Service-Repository (CSR)** pattern for NestJS libraries:

### Planned for v1.6.0
- **Simpler structure**: Easier to understand and navigate
- **Clear separation**: Guards, decorators, and entities in dedicated folders
- **Better discoverability**: All DTOs exported for consumer use
- **Industry standard**: Follows common NestJS library patterns

- [ ] Rate limiting built-in helpers
- [ ] Request signing and verification for webhooks
- [ ] Enhanced logging with structured JSON output
- [ ] Support for more OAuth providers (LinkedIn, GitHub)
The 4-layer Clean Architecture is now reserved for complex business applications (like ComptAlEyes), while reusable modules like Authentication Kit use the simpler CSR pattern.

---

## Support
## [1.5.0] - Previous Release

For version support timeline and security updates, please refer to the [SECURITY.md](SECURITY) policy.
(Previous changelog entries...)

For issues, questions, or contributions, please visit: https://github.com/CISCODE-MA/AuthKit
Loading
Loading