Identity Service
@nx/identity là JWKS issuer của nền tảng BANA — ký JWT (ES256) và phơi bày khóa công khai tại /jw-certs. Tất cả các service khác đóng vai trò VerifierApplication và tin tưởng các token được phát hành tại đây. Package này sở hữu định danh user, credential, employee, customer, role, permission và policy definition.
1. Tham chiếu nhanh
| Thuộc tính | Giá trị |
|---|---|
| Package | @nx/identity |
| Code | SVC-00010-IDENTITY |
| Loại | Microservice (JWKS issuer) |
| Runtime | Bun |
| Base Class | IssuerApplication |
| Vị trí | packages/identity |
| Base Path | /v1/api/identity |
| Dev Port | 31010 |
| Container Port | 3000 (external 31010) |
| Snowflake ID | 1 |
| DB Schema | identity (User, UserCredential, UserIdentifier, UserProfile, Role, Permission, PolicyDefinition, Customer, Employee + Configuration) |
| JWKS endpoint | GET /jw-certs |
| Thuật toán JWT | ES256 |
| Binding Namespace | @nx/identity |
2. Mục đích & Phạm vi
| Bao gồm | Loại trừ |
|---|---|
| User CRUD + identifier (email/phone/username) + credential (BASIC/OAuth) | OAuth2 federation (đã khai báo scheme; chưa có provider) |
| Phát hành JWT (ES256) — sign-in / sign-up / change-password / refresh | ABAC theo từng resource (chỉ có Casbin RBAC) |
| Email OTP + SMS OTP (verify email, verify phone, forgot password, link account) | Cô lập key đa tenant (chỉ một signing key) |
| RBAC dựa trên Casbin (Role × Permission × PolicyDefinition) | Revocation list / token blocklist |
| Role hệ thống cố định + role tùy biến theo merchant | Lưu trữ session (chỉ JWT stateless) |
| Profile chuyên biệt cho Customer + Employee | Identity provider chaining |
| Mail templates + SMS templates (EN/VI) |
3. Tech Stack
External:
| Library | Mục đích |
|---|---|
@venizia/ignis | IoC + DI + base classes |
@venizia/ignis-helpers | Logger, Redis helper, password hashing |
hono + @hono/zod-openapi | HTTP + sinh OpenAPI |
@scalar/hono-api-reference | Scalar viewer tại /doc |
drizzle-orm + pg | DB |
casbin | RBAC engine |
nodemailer | Email transport |
bullmq + ioredis | Mail/OTP queue (khi đã cấu hình Redis) |
Internal:
| Package | Mục đích |
|---|---|
@nx/core | Schema, repository, IssuerApplication, JWKSIssuerTokenService, MQSMSComponent, MailComponent |
4. Cấu trúc Dự án
packages/identity/
├── src/
│ ├── application.ts # IssuerApplication subclass
│ ├── index.ts # bootstrapApplication()
│ ├── migrate.ts # bootstrapMigration()
│ ├── common/
│ │ ├── constants.ts # 15+ enums (UserIdentifierSchemes, OTPDefaults, MailValidationFields, …)
│ │ ├── keys.ts # BindingKeys (Redis/BullMQ, OTP_SENDER, SMS_TEMPLATE_ENGINE)
│ │ ├── rest-paths.ts # 12 REST paths
│ │ └── … # mail/sms/otp helpers
│ ├── components/
│ │ ├── mail/ # NodemailerComponent (SMTP)
│ │ ├── sms/ # ApplicationSMSComponent (VN Pay SMS)
│ │ └── websocket/ # ApplicationWebSocketComponent (Redis-backed)
│ ├── controllers/ # 8 thư mục → 12 controllers
│ ├── datasources/ # PostgresCoreDataSource
│ ├── migrations/processes/ # 7 seed processes
│ ├── models/ # zod request/response schemas
│ ├── repositories/ # re-exports + identity-local repos
│ └── services/ # 15 services (top-level + otp/ + policy-definition/)
├── package.json
└── tsconfig.json5. Kiến trúc
Chi tiết: xem Architecture.
6. Tổng quan miền
ERD đầy đủ + bảng theo entity: xem Domain Model.
7. Tóm tắt Bề mặt
REST controllers — tham chiếu đầy đủ render trực tiếp từ /v1/api/identity/doc/openapi.json (live spec — Scalar viewer tại /doc, gateway portal):
| Controller | Base path | Ghi chú |
|---|---|---|
IdentityAuthController | /auth | sign-in/up, change-password, refresh, OTP flows (verify email/phone, forgot password, link account) |
UserController | /users | CRUD theo phạm vi merchant |
RoleController | /roles | CRUD có ưu tiên; system role bất biến |
PermissionController | /permissions | đọc catalogue; ghi qua migration seed |
PolicyDefinitionController | /policy-definitions | RBAC edges cấp thấp |
OrganizerPolicyDefinitionController | /policy-definitions/... | nhắm policy theo phạm vi organizer |
RolePolicyDefinitionController | /policy-definitions/... | nhắm policy theo phạm vi role |
UserPolicyDefinitionController | /policy-definitions/... | nhắm policy theo phạm vi user |
CustomerController | /customers | profile khách hàng |
EmployeeController | /employees | profile nhân viên + ánh xạ tổ chức |
UserIdentifierController | /user-identifiers | CRUD email/phone/username |
UserConfigurationController | /user-configurations | thiết lập theo từng user |
Async surface — tham chiếu đầy đủ tại API Events:
| Hướng | Channel | Ghi chú |
|---|---|---|
| Outbound | WebSocket | broadcast sự kiện identity (auth state, role/policy changes) |
| Outbound | Mail (Nodemailer) | verification, forgot-password, welcome, password-changed |
| Outbound | SMS (MQ-SMS) | phone-auth, add-phone OTP |
Identity không phải Kafka producer hay consumer — đây là biên xác thực; sister service kéo JWKS qua HTTP.
8. Components
| Component | File | Mục đích |
|---|---|---|
NodemailerComponent | src/components/mail/component.ts | SMTP transport + template registry |
ApplicationSMSComponent | src/components/sms/sms.component.ts | VN Pay SMS qua MQSMSComponent; nạp config từ DB lúc khởi động |
ApplicationWebSocketComponent | src/components/websocket/component.ts | Emitter dùng Redis (single/cluster) |
9. Services (tổng 15)
Top-level (8) + OTP sub-services (3 + base) + policy-definition sub-services (4 + base).
| Service | File | Mô tả ngắn |
|---|---|---|
AuthenticationService | authentication.service.ts (369 dòng) | Sign-in, sign-up, change-password, refresh, generate-token (JWT ES256) |
UserService | user.service.ts (535 dòng) | CRUD aggregate User: identifier + credential + profile + gán role |
RoleService | role.service.ts (409 dòng) | CRUD Role với validate priority + giải quyết scope |
PermissionService | permission.service.ts | Quản lý catalogue permission |
ConfigurationService | configuration.service.ts | Đọc/ghi config hệ thống (mail, SMS, OTP) |
CustomerService | customer.service.ts | CRUD profile khách hàng |
EmployeeService | employee.service.ts | Profile nhân viên + ánh xạ org |
UserConfigurationService | user-configuration.service.ts | Mặc định cài đặt theo từng user |
| OTP | services/otp/ | |
BaseOTPBasedMFAService | base | Abstract: hash + TTL + giới hạn lần thử + cooldown + quota theo ngày |
EmailOtpService | email-otp.service.ts | Gửi + xác minh Email OTP |
PhoneOtpService | phone-otp.service.ts | Gửi + xác minh SMS OTP |
VerifyEmailService | verify-email.service.ts | Luồng xác minh email (code → token) |
VerifyPhoneService | verify-phone.service.ts | Luồng xác minh SĐT |
ForgotPasswordService | forgot-password.service.ts | OTP → reset-token → mật khẩu mới |
LinkAccountService | link-account.service.ts | Thêm phone/email vào tài khoản đã đăng nhập |
| Policy | services/policy-definition/ | |
BasePolicyDefinitionService | base | CRUD policy abstract theo subject type |
UserPolicyDefinitionService | concrete | User → cạnh Role/Permission/Organizer/Merchant |
RolePolicyDefinitionService | concrete | Role → cạnh Permission/User |
OrganizerPolicyDefinitionService | concrete | Cạnh theo phạm vi Organizer |
PermissionPolicyDefinitionService | concrete | Cạnh theo phạm vi Permission |
10. Repositories (12)
| Repository | Nguồn | Ghi chú |
|---|---|---|
UserRepository | identity-local | Aggregate-aware (tạo identifier + credential nguyên tử) |
UserIdentifierRepository | identity-local | Tra cứu theo (scheme, value) — entry point sign-in |
UserCredentialRepository | @nx/core | Lưu credential đã hash (Bun.password) |
UserProfileRepository | @nx/core | 1:1 với User |
UserConfigurationRepository | @nx/core | Cài đặt theo user |
RoleRepository | @nx/core | Ngữ nghĩa priority + scope |
PermissionRepository | @nx/core | Catalogue |
PolicyDefinitionRepository | @nx/core | Cạnh RBAC (variant: GROUP/PERMISSION) |
CustomerRepository | @nx/core | — |
MerchantRepository | @nx/core | Đọc liên package |
OrganizerRepository | @nx/core | Đọc liên package |
ConfigurationRepository | @nx/core | Cấu hình hệ thống Mail/SMS/OTP |
11. Điểm vào
| File | Mục đích |
|---|---|
src/index.ts | Service entry → bootstrapApplication() |
src/migrate.ts | Migration entry → bootstrapMigration() |
src/application.ts | Application extends IssuerApplication |
12. Cấu hình
Env vars + dữ liệu seed: xem Configuration.
13. Vận hành
Triển khai + observability + bảo mật + runbook: xem Operations.
14. Trang liên quan
Concepts — vì sao/cách thức:
- Architecture
- Domain Model
- Integration — sister service kéo JWKS, yêu cầu permission
Reference — tra cứu:
- API Events — bề mặt mail/SMS/WS
- Configuration
- Operations
- REST endpoints — live OpenAPI tại
/v1/api/identity/doc/openapi.json(live spec — Scalar viewer tại/doc, gateway portal)
Features — đào sâu:
- Authentication — sign-in / sign-up / change-password / refresh
- User Management — User aggregate + Employee
- Customer Management
- RBAC — Role + Permission + PolicyDefinition + Casbin
- MFA & OTP — luồng Email/SMS OTP
Decisions: