Skip to content

Identity Service

@nx/identityJWKS 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ínhGiá trị
Package@nx/identity
CodeSVC-00010-IDENTITY
LoạiMicroservice (JWKS issuer)
RuntimeBun
Base ClassIssuerApplication
Vị trípackages/identity
Base Path/v1/api/identity
Dev Port31010
Container Port3000 (external 31010)
Snowflake ID1
DB Schemaidentity (User, UserCredential, UserIdentifier, UserProfile, Role, Permission, PolicyDefinition, Customer, Employee + Configuration)
JWKS endpointGET /jw-certs
Thuật toán JWTES256
Binding Namespace@nx/identity

2. Mục đích & Phạm vi

Bao gồmLoạ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 / refreshABAC 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 merchantLưu trữ session (chỉ JWT stateless)
Profile chuyên biệt cho Customer + EmployeeIdentity provider chaining
Mail templates + SMS templates (EN/VI)

3. Tech Stack

External:

LibraryMục đích
@venizia/ignisIoC + DI + base classes
@venizia/ignis-helpersLogger, Redis helper, password hashing
hono + @hono/zod-openapiHTTP + sinh OpenAPI
@scalar/hono-api-referenceScalar viewer tại /doc
drizzle-orm + pgDB
casbinRBAC engine
nodemailerEmail transport
bullmq + ioredisMail/OTP queue (khi đã cấu hình Redis)

Internal:

PackageMục đích
@nx/coreSchema, 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.json

5. 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):

ControllerBase pathGhi chú
IdentityAuthController/authsign-in/up, change-password, refresh, OTP flows (verify email/phone, forgot password, link account)
UserController/usersCRUD theo phạm vi merchant
RoleController/rolesCRUD có ưu tiên; system role bất biến
PermissionController/permissionsđọc catalogue; ghi qua migration seed
PolicyDefinitionController/policy-definitionsRBAC 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/customersprofile khách hàng
EmployeeController/employeesprofile nhân viên + ánh xạ tổ chức
UserIdentifierController/user-identifiersCRUD email/phone/username
UserConfigurationController/user-configurationsthiết lập theo từng user

Async surface — tham chiếu đầy đủ tại API Events:

HướngChannelGhi chú
OutboundWebSocketbroadcast sự kiện identity (auth state, role/policy changes)
OutboundMail (Nodemailer)verification, forgot-password, welcome, password-changed
OutboundSMS (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

ComponentFileMục đích
NodemailerComponentsrc/components/mail/component.tsSMTP transport + template registry
ApplicationSMSComponentsrc/components/sms/sms.component.tsVN Pay SMS qua MQSMSComponent; nạp config từ DB lúc khởi động
ApplicationWebSocketComponentsrc/components/websocket/component.tsEmitter dùng Redis (single/cluster)

9. Services (tổng 15)

Top-level (8) + OTP sub-services (3 + base) + policy-definition sub-services (4 + base).

ServiceFileMô tả ngắn
AuthenticationServiceauthentication.service.ts (369 dòng)Sign-in, sign-up, change-password, refresh, generate-token (JWT ES256)
UserServiceuser.service.ts (535 dòng)CRUD aggregate User: identifier + credential + profile + gán role
RoleServicerole.service.ts (409 dòng)CRUD Role với validate priority + giải quyết scope
PermissionServicepermission.service.tsQuản lý catalogue permission
ConfigurationServiceconfiguration.service.tsĐọc/ghi config hệ thống (mail, SMS, OTP)
CustomerServicecustomer.service.tsCRUD profile khách hàng
EmployeeServiceemployee.service.tsProfile nhân viên + ánh xạ org
UserConfigurationServiceuser-configuration.service.tsMặc định cài đặt theo từng user
OTPservices/otp/
BaseOTPBasedMFAServicebaseAbstract: hash + TTL + giới hạn lần thử + cooldown + quota theo ngày
EmailOtpServiceemail-otp.service.tsGửi + xác minh Email OTP
PhoneOtpServicephone-otp.service.tsGửi + xác minh SMS OTP
VerifyEmailServiceverify-email.service.tsLuồng xác minh email (code → token)
VerifyPhoneServiceverify-phone.service.tsLuồng xác minh SĐT
ForgotPasswordServiceforgot-password.service.tsOTP → reset-token → mật khẩu mới
LinkAccountServicelink-account.service.tsThêm phone/email vào tài khoản đã đăng nhập
Policyservices/policy-definition/
BasePolicyDefinitionServicebaseCRUD policy abstract theo subject type
UserPolicyDefinitionServiceconcreteUser → cạnh Role/Permission/Organizer/Merchant
RolePolicyDefinitionServiceconcreteRole → cạnh Permission/User
OrganizerPolicyDefinitionServiceconcreteCạnh theo phạm vi Organizer
PermissionPolicyDefinitionServiceconcreteCạnh theo phạm vi Permission

10. Repositories (12)

RepositoryNguồnGhi chú
UserRepositoryidentity-localAggregate-aware (tạo identifier + credential nguyên tử)
UserIdentifierRepositoryidentity-localTra cứu theo (scheme, value) — entry point sign-in
UserCredentialRepository@nx/coreLưu credential đã hash (Bun.password)
UserProfileRepository@nx/core1:1 với User
UserConfigurationRepository@nx/coreCài đặt theo user
RoleRepository@nx/coreNgữ nghĩa priority + scope
PermissionRepository@nx/coreCatalogue
PolicyDefinitionRepository@nx/coreCạnh RBAC (variant: GROUP/PERMISSION)
CustomerRepository@nx/core
MerchantRepository@nx/coreĐọc liên package
OrganizerRepository@nx/coreĐọc liên package
ConfigurationRepository@nx/coreCấu hình hệ thống Mail/SMS/OTP

11. Điểm vào

FileMục đích
src/index.tsService entry → bootstrapApplication()
src/migrate.tsMigration entry → bootstrapMigration()
src/application.tsApplication 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:

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:

Decisions:

Proprietary and Confidential. Unauthorized copying, distribution, or use of this software is strictly prohibited.