Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
81 commits
Select commit Hold shift + click to select a range
9064224
refactor: create services files for further SoC
Zaiidmo Jan 21, 2026
1c674fb
refactor: update authKit Module to not ever call any db, and delete c…
Zaiidmo Jan 21, 2026
072c1b5
refactor: create repositories files for further SoC
Zaiidmo Jan 21, 2026
7e26f30
refactor: create proper package json file #deleted unnecessary matters
Zaiidmo Jan 21, 2026
0d4e691
refactor: update database models and packages configs
Zaiidmo Jan 21, 2026
cebc953
refactor: create DTOs files
Zaiidmo Jan 21, 2026
466ed8f
refactor: update register dto
Zaiidmo Jan 21, 2026
8d99d8d
refactor: remove business logic from auth controller
Zaiidmo Jan 21, 2026
a68656e
refactor: update user model
Zaiidmo Jan 21, 2026
901b9bc
refactor: create an auth business logic service file
Zaiidmo Jan 21, 2026
99356dd
refactor: create user repository file, for db interaction;
Zaiidmo Jan 21, 2026
fe24559
refactor: add alias paths to tsconfig
Zaiidmo Jan 21, 2026
6dfb884
refactor: create mail service
Zaiidmo Jan 21, 2026
80134e1
refactor: update authservice and remove all client references from th…
Zaiidmo Jan 21, 2026
b18bf55
refactor: Update the authentication guard, and wiring new implementat…
Zaiidmo Jan 22, 2026
afd7672
refactor: create admin user-management controller
Zaiidmo Jan 22, 2026
b71395b
refactor: delete duplicated auth middleware
Zaiidmo Jan 22, 2026
cf3fc2f
refactor: create user-management repository
Zaiidmo Jan 22, 2026
3b3f684
refactor: create user-management admin servie
Zaiidmo Jan 22, 2026
b824734
refactor: create role-update dto
Zaiidmo Jan 22, 2026
4c6289e
refactor: separating DTOs folder, create roles&permissions DTOs
Zaiidmo Jan 22, 2026
be490a7
refactor: create roles & permissions HTTP controllers
Zaiidmo Jan 22, 2026
6fdc267
refactor: create roles & permissions Repositories
Zaiidmo Jan 22, 2026
2ab5999
refactor: delete unnecessary unused files
Zaiidmo Jan 22, 2026
0d243aa
refactor: create role middleware and admin decorator, alongside defau…
Zaiidmo Jan 22, 2026
bd13dfa
refactor: create roles & seed services, and update user roles
Zaiidmo Jan 22, 2026
8d847fc
refactor: delete password reset controller, create roles & permission…
Zaiidmo Jan 22, 2026
080db87
refactor: update role dto
Zaiidmo Jan 22, 2026
87e9c7e
refactor: updated roles repository
Zaiidmo Jan 22, 2026
eecf66b
refactor: wiring updates in authkitModule and exporting needed export…
Zaiidmo Jan 22, 2026
1e8f2e6
refactor: delete db config (unneded), and setting up default role ass…
Zaiidmo Jan 22, 2026
91c58d0
refactor: create admin guard and update the service and decorator
Zaiidmo Jan 22, 2026
09643dc
refactor: wiring and exporting new admin service & guard
Zaiidmo Jan 22, 2026
91a465e
refactor: exporting admin providers in auth kit module, updated env v…
Zaiidmo Jan 22, 2026
2a1fbd4
refactor: removing unnecessary types
Zaiidmo Jan 22, 2026
a974a67
refactor: created oAuth Service
Zaiidmo Jan 22, 2026
e53a1ee
refactor: added OAuth endpoints for all providers
Zaiidmo Jan 22, 2026
7261bbb
refactor: updated passport strategy
Zaiidmo Jan 22, 2026
6824de3
updated authentication middleware and auth controller with OAUth endp…
Zaiidmo Jan 22, 2026
2167a1c
created oauth service and updated auth service
Zaiidmo Jan 22, 2026
d288018
wiring all new implementations into authkit module
Zaiidmo Jan 22, 2026
c680adb
doc: update readme file
Zaiidmo Jan 22, 2026
e938792
refactor: Secure auth routes
Zaiidmo Jan 25, 2026
d68c293
refactor: register oAuth Strategy once the module in init
Zaiidmo Jan 25, 2026
73cc584
refactor: create a new .envexample
Zaiidmo Jan 25, 2026
b9bc533
refactor: fix build errors withing typescript stricts
Zaiidmo Jan 25, 2026
5f15b10
refactor: fix dependencies misInstallation
Zaiidmo Jan 25, 2026
feaf388
refactor: update userModel to pass null PhoneNumberValues
Zaiidmo Jan 25, 2026
5f82cd9
refactor: update user repository to have a proper password finding me…
Zaiidmo Jan 25, 2026
8b486bb
refactor: enhance auth service for login paths
Zaiidmo Jan 25, 2026
67cb444
refactor: fix peerDependencies issues
Zaiidmo Jan 26, 2026
3009800
refactor: Update OAuth strategies
Zaiidmo Jan 26, 2026
df70473
refactor: adjust the auth controller and models for OAuth fix
Zaiidmo Jan 26, 2026
2e74eee
DOC: Update Readme documentation#
Zaiidmo Jan 26, 2026
391fcac
fixing merge conflicts from Master branch
Zaiidmo Jan 26, 2026
7cd8cbb
refactor: update user model to contain new fields, and omitting usern…
Zaiidmo Jan 26, 2026
78d9fac
refactor: update user model to contain new fields, and omitting usern…
Zaiidmo Jan 26, 2026
3bea46f
feat: implement comprehensive error handling system
Zaiidmo Jan 27, 2026
a78c64c
Merge branch 'develop' of github.com:CISCODE-MA/AuthKit into develop
Zaiidmo Jan 27, 2026
d7dd80a
Fix merge conflicts
Zaiidmo Jan 27, 2026
3bcb6cc
chore create new user service funcion to retrieve user data
Zaiidmo Jan 28, 2026
c4ab64e
chore: added users `me` end point
Zaiidmo Jan 28, 2026
a05eed2
docs: updated README doc for new endpoint implementation
Zaiidmo Jan 28, 2026
b11b921
Pull master remote branch
Zaiidmo Jan 30, 2026
a419adb
docs(workflow): add Git Flow and npm version requirements (#6)
Zaiidmo Jan 31, 2026
550d890
docs: translate italian text to english and add comprehensive documen…
Zaiidmo Jan 31, 2026
79e2cdf
1.5.1
Zaiidmo Jan 31, 2026
2953c54
aligned branches
Zaiidmo Feb 1, 2026
affc471
chore: upgrade dependencies to latest versions
Zaiidmo Feb 1, 2026
465f89c
1.5.3
Zaiidmo Feb 1, 2026
87bcb44
chore(auth): add eslint 9 and jest configuration
Zaiidmo Mar 1, 2026
4fb2998
fix(auth): resolve lint errors and code formatting
Zaiidmo Mar 1, 2026
3cbb453
chore(auth): add standardized CI/CD workflows
Zaiidmo Mar 1, 2026
342cc21
chore(auth): update dependencies
Zaiidmo Mar 1, 2026
62de3b8
fix(security): address CodeQL alerts - add workflow permissions and s…
Zaiidmo Mar 2, 2026
ea47c29
fix(security): use inline CodeQL suppressions for Mongoose false posi…
Zaiidmo Mar 2, 2026
e1b3f8f
fixed merge conflicts
Zaiidmo Mar 2, 2026
f651c0f
chore: clean up merge conflict duplicates in dependencies
Zaiidmo Mar 2, 2026
816a066
chore(fix) : format errors
Zaiidmo Mar 2, 2026
4bd9994
fix(security): add CodeQL config to suppress Mongoose false positives
Zaiidmo Mar 2, 2026
8c84841
chore(tests): lowered coverage threshold
Zaiidmo Mar 2, 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
11 changes: 11 additions & 0 deletions .github/codeql/codeql-config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name: "CodeQL Config for AuthKit"

# Suppress false positives for Mongoose queries
# Mongoose automatically sanitizes all query parameters
query-filters:
- exclude:
id: js/sql-injection
paths:
- src/repositories/user.repository.ts
- src/repositories/role.repository.ts
- src/repositories/permission.repository.ts
372 changes: 372 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,372 @@
# Copilot Instructions - AuthKit Developer Guide

> **Purpose**: Project-specific instructions for contributing to AuthKit, a comprehensive NestJS authentication and authorization module with OAuth 2.0, JWT, and RBAC support.

---

## 🎯 Project Overview

**Project**: @ciscode/authentication-kit
**Type**: Modular NestJS Backend Library
**Version**: 1.5.3
**Purpose**: Production-ready authentication/authorization with local auth, OAuth 2.0, JWT tokens, role-based access control, email verification, and password reset.

### AuthKit Provides:

- **Local Authentication**: Email + password registration and login
- **OAuth 2.0 Integration**: Google, Microsoft (Entra ID), Facebook
- **JWT Token Management**: Access, refresh, email verification, password reset tokens
- **Role-Based Access Control (RBAC)**: Roles, permissions, and fine-grained authorization
- **Email Verification**: JWT-based email confirmation with customizable templates
- **Password Reset Flow**: Secure JWT-secured reset link workflow
- **Admin User Management**: Create, list, ban/unban, delete users, and assign roles
- **MongoDB Integration**: Uses host app's Mongoose connection (no DB lock-in)
- **TypeScript strict mode, path aliases, and full type safety**
- **Jest testing with 80%+ coverage required**
- **Changesets for versioning and changelog**
- **Linting (ESLint, Prettier) and pre-commit hooks (Husky)**

---

## 🏗️ AuthKit Project Structure

AuthKit uses a layered architecture combining Controller-Service-Repository (CSR) patterns for clarity and modularity.

```
src/
index.ts # PUBLIC API exports
auth/
auth.controller.ts # Auth endpoints (register, login, refresh, verify)
auth.service.ts # Auth business logic
auth.repository.ts # Auth data access
users/
users.controller.ts # User management endpoints
users.service.ts # User business logic
users.repository.ts # User data access
roles/
roles.controller.ts # Role/permission management
roles.service.ts # Role business logic
roles.repository.ts # Role data access
models/
user.model.ts # User Mongoose schema
role.model.ts # Role Mongoose schema
permission.model.ts # Permission Mongoose schema
middleware/
guards/
authenticate.guard.ts # JWT authentication guard
admin.guard.ts # Admin-only guard
roles.guard.ts # Dynamic role-based guard
decorators/
current-user.decorator.ts # @CurrentUser() decorator
admin.decorator.ts # @Admin() decorator
providers/
oauth/
google.strategy.ts # Passport Google OAuth strategy
microsoft.strategy.ts # Passport Microsoft OAuth strategy
facebook.strategy.ts # Passport Facebook OAuth strategy
mail/
mail.service.ts # Email sending service
config/
auth.config.ts # Auth configuration
jwt.config.ts # JWT configuration
oauth.config.ts # OAuth configuration
utils/
token.utils.ts # Token generation/validation
password.utils.ts # Password hashing/verification
```

**Responsibility Layers:**

| Layer | Responsibility | Examples |
| ---------------- | -------------------------------- | ----------------------- |
| **Controllers** | HTTP endpoints, request handling | `auth.controller.ts` |
| **Services** | Business logic, orchestration | `auth.service.ts` |
| **Repositories** | Database access, queries | `auth.repository.ts` |
| **Models** | Mongoose schemas | `user.model.ts` |
| **Guards** | Authentication/Authorization | `authenticate.guard.ts` |
| **Decorators** | Parameter extraction, metadata | `@CurrentUser()` |
| **Providers** | OAuth strategies, mail service | `google.strategy.ts` |
| **Utils** | Helper functions | `token.utils.ts` |

**Public API Exports:**

```typescript
// src/index.ts - Only export what consumers need
export { AuthKitModule } from "./auth-kit.module";
export { AuthService, UsersService, RolesService } from "./services";
export { AuthenticateGuard, AdminGuard, hasRole } from "./middleware";
export { CurrentUser, Admin } from "./decorators";
export { SeedService } from "./seed.service";
export type { User, Role, Permission } from "./models";
```

---

## 📝 Naming Conventions

### Files

**Pattern**: `kebab-case` + suffix

| Type | Example | Directory |
| ---------- | --------------------------- | ------------------ |
| Controller | `auth.controller.ts` | `auth/` |
| Service | `auth.service.ts` | `auth/` |
| Repository | `auth.repository.ts` | `auth/` |
| Model | `user.model.ts` | `models/` |
| Guard | `authenticate.guard.ts` | `middleware/` |
| Decorator | `current-user.decorator.ts` | `decorators/` |
| Strategy | `google.strategy.ts` | `providers/oauth/` |
| Config | `jwt.config.ts` | `config/` |
| Utility | `token.utils.ts` | `utils/` |

### Code Naming

- **Classes & Interfaces**: `PascalCase` → `AuthController`, `User`, `JWT Payload`
- **Functions & Methods**: `camelCase` → `login()`, `verifyToken()`, `assignRole()`
- **Constants**: `UPPER_SNAKE_CASE` → `JWT_SECRET`, `TOKEN_EXPIRY_TIME`
- **Variables**: `camelCase` → `currentUser`, `tokenPayload`

### Path Aliases

Configured in `tsconfig.json`:

```json
"@auth/*" → "src/auth/*",
"@users/*" → "src/users/*",
"@roles/*" → "src/roles/*",
"@models/*" → "src/models/*",
"@middleware/*" → "src/middleware/*",
"@providers/*" → "src/providers/*",
"@config/*" → "src/config/*",
"@utils/*" → "src/utils/*"
```

---

## 🧪 Testing - MANDATORY for AuthKit

### Coverage Target: 80%+ (REQUIRED)

**Unit Tests - MANDATORY:**

- ✅ All services (business logic)
- ✅ All guards and authentication flows
- ✅ All utilities (token, password)
- ✅ All OAuth strategies
- ✅ Repository methods

**Integration Tests:**

- ✅ Full auth flows (register, login, refresh)
- ✅ OAuth integration (mocked)
- ✅ Email verification flow
- ✅ Password reset flow

**Test file location:**

```
src/
├── auth/
│ ├── auth.service.ts
│ └── auth.service.spec.ts
└── utils/
├── token.utils.ts
└── token.utils.spec.ts
```

**CRITICAL**: AuthKit currently has ZERO tests. This MUST be fixed before release!

---

## 📚 Documentation - REQUIRED

### JSDoc/TSDoc - MANDATORY for all public APIs:

```typescript
/**
* Authenticates a user with email and password
* @param email - User email address
* @param password - User password (plain text)
* @returns Access token, refresh token, and user info
* @throws {UnauthorizedException} If credentials invalid
* @example
* const result = await authService.login({ email: 'user@example.com', password: 'pass' });
*/
async login(loginDto: LoginDto): Promise<AuthResult>
```

**Required for:**

- All public functions/methods
- All exported classes and services
- All guards and decorators
- All authentication flows

### Swagger/OpenAPI - MANDATORY on controllers:

```typescript
@ApiOperation({ summary: 'User login with email and password' })
@ApiResponse({ status: 200, description: 'Login successful', type: LoginResponseDto })
@ApiResponse({ status: 401, description: 'Invalid credentials' })
@Post('/login')
async login(@Body() dto: LoginDto) { }
```

---

## 🚀 Development Principles

### 1. Security First

- ✅ Always hash passwords with bcrypt (12+ rounds)
- ✅ Never expose sensitive data in responses
- ✅ Always validate JWT signatures
- ✅ Implement rate limiting on auth endpoints
- ✅ Sanitize all error messages (no stack traces)
- ✅ Never log passwords or tokens

### 2. Exportability

**Export ONLY public API:**

```typescript
// ✅ Export what apps need
export { AuthService } from "./auth/auth.service";
export { AuthenticateGuard } from "./middleware/guards";
export { CurrentUser } from "./decorators";

// ❌ NEVER export
export { AuthRepository } from "./auth/auth.repository"; // Internal
export { User } from "./models"; // Internal
```

### 3. Configuration

**Flexible module registration:**

```typescript
@Module({})
export class AuthKitModule {
static forRoot(options: AuthKitOptions): DynamicModule {
return {
module: AuthKitModule,
providers: [{ provide: "AUTH_OPTIONS", useValue: options }, AuthService],
exports: [AuthService],
};
}

static forRootAsync(options: AuthKitAsyncOptions): DynamicModule {
// Async configuration
}
}
```

### 4. Zero Business Logic Coupling

- No hardcoded business rules
- All behavior configurable via options
- Database-agnostic (apps provide connection)
- OAuth providers configurable
- Email templates customizable

---

## 🔄 Workflow & Task Management

### Branch Naming:

```bash
feature/AUTH-123-add-social-login
bugfix/AUTH-456-fix-token-expiry
refactor/AUTH-789-improve-security
```

### Task Documentation:

```
docs/tasks/active/AUTH-123-add-feature.md
docs/tasks/archive/by-release/v1.5.3/AUTH-123-add-feature.md
```

---

## 📦 Versioning & Breaking Changes

### Semantic Versioning (STRICT)

- **MAJOR** (x.0.0): Breaking changes to public API, guards, decorators
- **MINOR** (0.x.0): New features, new OAuth providers, new endpoints
- **PATCH** (0.0.x): Bug fixes, security patches, performance

### Changesets Workflow

**ALWAYS create a changeset for user-facing changes:**

```bash
npx changeset
```

**Before completing ANY task:**

- [ ] Code implemented
- [ ] Tests passing (80%+ coverage)
- [ ] Documentation updated
- [ ] **Changeset created** ← CRITICAL
- [ ] No security vulnerabilities

---

## ✅ Release Checklist

Before publishing:

- [ ] All tests passing (100% of test suite)
- [ ] Coverage >= 80%
- [ ] No ESLint warnings (`--max-warnings=0`)
- [ ] TypeScript strict mode passing
- [ ] All public APIs documented (JSDoc)
- [ ] Swagger documentation updated
- [ ] README updated with examples
- [ ] Changeset created
- [ ] No security vulnerabilities (`npm audit`)
- [ ] Integration tested with sample app

---

## 🎨 Code Style

- ESLint `--max-warnings=0`
- Prettier formatting
- TypeScript strict mode
- Dependency injection via constructor

---

## 💬 Communication Style

- Brief and direct
- Focus on security and reliability
- Highlight security implications immediately
- AuthKit is production-critical

---

## 📋 Summary

**AuthKit Principles:**

1. Security first, always
2. Comprehensive testing (80%+)
3. Complete documentation
4. Strict versioning
5. Zero app coupling
6. Configurable behavior
7. Production-ready

**When in doubt:** Ask, don't assume. AuthKit secures your entire app.

---

_Last Updated: March 1, 2026_
_Version: 1.5.3_
Loading