Skip to content

Identity Service

@nx/identity is the JWKS issuer for the BANA platform — it signs JWTs (ES256) and exposes public keys at /jw-certs. All other services act as VerifierApplication and trust tokens issued here. The package owns user identity, credentials, employees, customers, roles, permissions, and policy definitions.

1. Quick Reference

PropertyValue
Package@nx/identity
CodeSVC-00010-IDENTITY
TypeMicroservice (JWKS issuer)
RuntimeBun
Base ClassIssuerApplication
Locationpackages/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
JWT algorithmES256
Binding Namespace@nx/identity

2. Purpose & Scope

IncludedExcluded
User CRUD + identifier (email/phone/username) + credential (BASIC/OAuth)OAuth2 federation (declared scheme; no provider yet)
JWT issuance (ES256) — sign-in / sign-up / change-password / refreshPer-resource ABAC (only Casbin RBAC)
Email OTP + SMS OTP (verify email, verify phone, forgot password, link account)Multi-tenant key isolation (single signing key)
Casbin-based RBAC (Role × Permission × PolicyDefinition)Revocation list / token blocklist
Fixed system roles + custom roles per merchantSession storage (stateless JWT only)
Customer + Employee specialized profilesIdentity provider chaining
Mail templates + SMS templates (EN/VI)

3. Tech Stack

External:

LibraryPurpose
@venizia/ignisIoC + DI + base classes
@venizia/ignis-helpersLogger, Redis helper, password hashing
hono + @hono/zod-openapiHTTP + OpenAPI generation
@scalar/hono-api-referenceScalar viewer at /doc
drizzle-orm + pgDB
casbinRBAC engine
nodemailerEmail transport
bullmq + ioredisMail/OTP queue (when Redis configured)

Internal:

PackagePurpose
@nx/coreSchemas, repositories, IssuerApplication, JWKSIssuerTokenService, MQSMSComponent, MailComponent

4. Project Structure

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 folders → 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. Architecture

Detail: see Architecture.

6. Domain Snapshot

Full ERD + per-entity tables: see Domain Model.

7. Surface Summary

REST controllers — full reference rendered live from /v1/api/identity/doc/openapi.json (live spec — Scalar viewer at /doc, gateway portal):

ControllerBase pathNotes
IdentityAuthController/authsign-in/up, change-password, refresh, OTP flows (verify email/phone, forgot password, link account)
UserController/usersmerchant-scoped CRUD
RoleController/rolespriority-aware CRUD; system roles immutable
PermissionController/permissionscatalogue read; writes via migration seed
PolicyDefinitionController/policy-definitionslow-level RBAC edges
OrganizerPolicyDefinitionController/policy-definitions/...organizer-scoped policy targeting
RolePolicyDefinitionController/policy-definitions/...role-scoped policy targeting
UserPolicyDefinitionController/policy-definitions/...user-scoped policy targeting
CustomerController/customerscustomer profile
EmployeeController/employeesemployee profile + organizational mapping
UserIdentifierController/user-identifiersemail/phone/username CRUD
UserConfigurationController/user-configurationsper-user settings

Async surface — full reference in API Events:

DirectionChannelNotes
OutboundWebSocketidentity events broadcast (auth state, role/policy changes)
OutboundMail (Nodemailer)verification, forgot-password, welcome, password-changed
OutboundSMS (MQ-SMS)phone-auth, add-phone OTP

Identity is not a Kafka producer or consumer — it is the auth boundary; sister services pull JWKS over HTTP.

8. Components

ComponentFilePurpose
NodemailerComponentsrc/components/mail/component.tsSMTP transport + template registry
ApplicationSMSComponentsrc/components/sms/sms.component.tsVN Pay SMS via MQSMSComponent; loads config from DB at startup
ApplicationWebSocketComponentsrc/components/websocket/component.tsRedis-backed emitter (single/cluster)

9. Services (15 total)

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

ServiceFileOne-liner
AuthenticationServiceauthentication.service.ts (369 lines)Sign-in, sign-up, change-password, refresh, generate-token (JWT ES256)
UserServiceuser.service.ts (535 lines)User aggregate CRUD: identifier + credential + profile + role assignment
RoleServicerole.service.ts (409 lines)Role CRUD with priority validation + scope resolution
PermissionServicepermission.service.tsPermission catalogue management
ConfigurationServiceconfiguration.service.tsSystem config (mail, SMS, OTP) read/write
CustomerServicecustomer.service.tsCustomer profile CRUD
EmployeeServiceemployee.service.tsEmployee profile + org mapping
UserConfigurationServiceuser-configuration.service.tsPer-user setting defaults
OTPservices/otp/
BaseOTPBasedMFAServicebaseAbstract: hash + TTL + attempt limit + cooldown + daily quota
EmailOtpServiceemail-otp.service.tsEmail OTP delivery + verification
PhoneOtpServicephone-otp.service.tsSMS OTP delivery + verification
VerifyEmailServiceverify-email.service.tsEmail verification flow (code → token)
VerifyPhoneServiceverify-phone.service.tsPhone verification flow
ForgotPasswordServiceforgot-password.service.tsOTP → reset-token → new password
LinkAccountServicelink-account.service.tsAdd phone/email to authenticated account
Policyservices/policy-definition/
BasePolicyDefinitionServicebaseAbstract policy CRUD by subject type
UserPolicyDefinitionServiceconcreteUser → Role/Permission/Organizer/Merchant edges
RolePolicyDefinitionServiceconcreteRole → Permission/User edges
OrganizerPolicyDefinitionServiceconcreteOrganizer-scoped edges
PermissionPolicyDefinitionServiceconcretePermission-scoped edges

10. Repositories (12)

RepositorySourceNotes
UserRepositoryidentity-localAggregate-aware (identifier + credential atomic create)
UserIdentifierRepositoryidentity-localLookup by (scheme, value) — sign-in entry point
UserCredentialRepository@nx/coreHashed credential persistence (Bun.password)
UserProfileRepository@nx/core1:1 with User
UserConfigurationRepository@nx/corePer-user settings
RoleRepository@nx/corePriority + scope semantics
PermissionRepository@nx/coreCatalogue
PolicyDefinitionRepository@nx/coreRBAC edges (variant: GROUP/PERMISSION)
CustomerRepository@nx/core
MerchantRepository@nx/coreCross-package read
OrganizerRepository@nx/coreCross-package read
ConfigurationRepository@nx/coreMail/SMS/OTP system configuration

11. Entry Points

FilePurpose
src/index.tsService entry → bootstrapApplication()
src/migrate.tsMigration entry → bootstrapMigration()
src/application.tsApplication extends IssuerApplication

12. Configuration

Env vars + seeded data: see Configuration.

13. Operations

Deployment + observability + security + runbook: see Operations.

Concepts — why/how:

Reference — lookup:

  • API Events — mail/SMS/WS surfaces
  • Configuration
  • Operations
  • REST endpoints — live OpenAPI at /v1/api/identity/doc/openapi.json (live spec — Scalar viewer at /doc, gateway portal)

Features — deep dives:

Decisions:

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