@nauth-toolkit/core 0.1.39 → 0.1.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/dto/get-user-sessions-response.dto.d.ts +88 -0
  2. package/dist/dto/get-user-sessions-response.dto.d.ts.map +1 -0
  3. package/dist/dto/get-user-sessions-response.dto.js +181 -0
  4. package/dist/dto/get-user-sessions-response.dto.js.map +1 -0
  5. package/dist/dto/get-user-sessions.dto.d.ts +17 -0
  6. package/dist/dto/get-user-sessions.dto.d.ts.map +1 -0
  7. package/dist/dto/get-user-sessions.dto.js +38 -0
  8. package/dist/dto/get-user-sessions.dto.js.map +1 -0
  9. package/dist/dto/index.d.ts +4 -0
  10. package/dist/dto/index.d.ts.map +1 -1
  11. package/dist/dto/index.js +4 -0
  12. package/dist/dto/index.js.map +1 -1
  13. package/dist/dto/logout-session-response.dto.d.ts +20 -0
  14. package/dist/dto/logout-session-response.dto.d.ts.map +1 -0
  15. package/dist/dto/logout-session-response.dto.js +42 -0
  16. package/dist/dto/logout-session-response.dto.js.map +1 -0
  17. package/dist/dto/logout-session.dto.d.ts +22 -0
  18. package/dist/dto/logout-session.dto.d.ts.map +1 -0
  19. package/dist/dto/logout-session.dto.js +48 -0
  20. package/dist/dto/logout-session.dto.js.map +1 -0
  21. package/dist/interfaces/hooks.interface.d.ts +3 -3
  22. package/dist/interfaces/hooks.interface.d.ts.map +1 -1
  23. package/dist/services/auth-service-internal-helpers.d.ts +229 -0
  24. package/dist/services/auth-service-internal-helpers.d.ts.map +1 -0
  25. package/dist/services/auth-service-internal-helpers.js +1004 -0
  26. package/dist/services/auth-service-internal-helpers.js.map +1 -0
  27. package/dist/services/auth.service.d.ts +178 -156
  28. package/dist/services/auth.service.d.ts.map +1 -1
  29. package/dist/services/auth.service.js +486 -2308
  30. package/dist/services/auth.service.js.map +1 -1
  31. package/dist/services/hook-registry.service.d.ts +4 -4
  32. package/dist/services/hook-registry.service.d.ts.map +1 -1
  33. package/dist/services/hook-registry.service.js +2 -2
  34. package/dist/services/hook-registry.service.js.map +1 -1
  35. package/dist/services/user.service.d.ts +274 -0
  36. package/dist/services/user.service.d.ts.map +1 -0
  37. package/dist/services/user.service.js +1327 -0
  38. package/dist/services/user.service.js.map +1 -0
  39. package/package.json +1 -1
@@ -0,0 +1,274 @@
1
+ import { Repository } from 'typeorm';
2
+ import { IUser } from '../interfaces/entities.interface';
3
+ import { BaseUser, BaseMFADevice, BaseChallengeSession, BaseVerificationToken, BaseSocialAccount, BaseAuthAudit, BaseTrustedDevice, BaseSession, BaseLoginAttempt } from '../entities';
4
+ import { SessionService } from './session.service';
5
+ import { ClientInfoService } from './client-info.service';
6
+ import { InternalAuthAuditService as AuthAuditService } from './auth-audit.service';
7
+ import { HookRegistryService } from './hook-registry.service';
8
+ import { NAuthConfig } from '../interfaces/config.interface';
9
+ import { NAuthLogger } from '../utils/nauth-logger';
10
+ import { GetUsersDTO, GetUsersResponseDTO } from '../dto/get-users.dto';
11
+ import { GetUserByIdDTO } from '../dto/get-user-by-id.dto';
12
+ import { GetUserByEmailDTO } from '../dto/get-user-by-email.dto';
13
+ import { UpdateUserAttributesRequestDTO } from '../dto/update-user-attributes-request.dto';
14
+ import { UpdateVerifiedStatusRequestDTO } from '../dto/update-verified-status-request.dto';
15
+ import { DeleteUserDTO, DeleteUserResponseDTO } from '../dto/delete-user.dto';
16
+ import { DisableUserDTO, DisableUserResponseDTO } from '../dto/disable-user.dto';
17
+ import { EnableUserDTO, EnableUserResponseDTO } from '../dto/enable-user.dto';
18
+ import { SetMustChangePasswordDTO } from '../dto/set-must-change-password.dto';
19
+ import { SetMustChangePasswordResponseDTO } from '../dto/set-must-change-password-response.dto';
20
+ import { UserResponseDto } from '../dto/user-response.dto';
21
+ import { AuthServiceInternalHelpers } from './auth-service-internal-helpers';
22
+ /**
23
+ * Internal user data management service
24
+ *
25
+ * Handles all user storage, query, and lifecycle operations.
26
+ * This class is NOT exported from the package and should only be used
27
+ * internally by AuthService.
28
+ *
29
+ * INTERNAL USE ONLY - DO NOT IMPORT DIRECTLY
30
+ *
31
+ * @internal
32
+ */
33
+ export declare class UserService {
34
+ private readonly userRepository;
35
+ private readonly loginAttemptRepository;
36
+ private readonly sessionService;
37
+ private readonly config;
38
+ private readonly logger;
39
+ private readonly mfaDeviceRepository?;
40
+ private readonly auditService?;
41
+ private readonly hookRegistry?;
42
+ private readonly clientInfoService;
43
+ private readonly sessionRepository?;
44
+ private readonly verificationTokenRepository?;
45
+ private readonly socialAccountRepository?;
46
+ private readonly challengeSessionRepository?;
47
+ private readonly authAuditRepository?;
48
+ private readonly trustedDeviceRepository?;
49
+ private readonly helpers;
50
+ constructor(userRepository: Repository<BaseUser>, loginAttemptRepository: Repository<BaseLoginAttempt>, sessionService: SessionService, config: NAuthConfig, logger: NAuthLogger, mfaDeviceRepository?: Repository<BaseMFADevice> | undefined, auditService?: AuthAuditService | undefined, hookRegistry?: HookRegistryService | undefined, clientInfoService?: ClientInfoService, sessionRepository?: Repository<BaseSession> | undefined, verificationTokenRepository?: Repository<BaseVerificationToken> | undefined, socialAccountRepository?: Repository<BaseSocialAccount> | undefined, challengeSessionRepository?: Repository<BaseChallengeSession> | undefined, authAuditRepository?: Repository<BaseAuthAudit> | undefined, trustedDeviceRepository?: Repository<BaseTrustedDevice> | undefined, helpers?: AuthServiceInternalHelpers);
51
+ /**
52
+ * Get paginated list of users with advanced filtering
53
+ *
54
+ * Supports pagination, boolean filters, exact match filters,
55
+ * date filters with operators (gt, gte, lt, lte, eq), and flexible sorting.
56
+ *
57
+ * Security:
58
+ * - NO built-in authentication - endpoint MUST be protected by admin guards
59
+ * - Returns sanitized user data (no passwordHash, secrets)
60
+ *
61
+ * @param dto - Filters, pagination, sorting
62
+ * @returns Paginated user list with metadata
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * const result = await userService.getUsers({
67
+ * page: 1,
68
+ * limit: 20,
69
+ * isEmailVerified: true,
70
+ * hasSocialAuth: true,
71
+ * createdAt: { operator: 'gte', value: new Date('2024-01-01') },
72
+ * sortBy: 'createdAt',
73
+ * sortOrder: 'DESC'
74
+ * });
75
+ * ```
76
+ */
77
+ getUsers(dto: GetUsersDTO): Promise<GetUsersResponseDTO>;
78
+ /**
79
+ * Get user by external identifier (sub/UUID).
80
+ *
81
+ * @param dto - GetUserByIdDTO containing sub
82
+ * @returns User response DTO or null if not found
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * const user = await userService.getUserById({ sub: 'user-uuid' });
87
+ * ```
88
+ */
89
+ getUserById(dto: GetUserByIdDTO): Promise<UserResponseDto | null>;
90
+ /**
91
+ * Get user by email address.
92
+ *
93
+ * @param dto - GetUserByEmailDTO containing email and optional requireEmailVerified
94
+ * @returns User response DTO or null if not found
95
+ * @internal - For use by social auth providers
96
+ *
97
+ * @example
98
+ * ```typescript
99
+ * const user = await userService.getUserByEmail({ email: 'user@example.com', requireEmailVerified: true });
100
+ * ```
101
+ */
102
+ getUserByEmail(dto: GetUserByEmailDTO): Promise<UserResponseDto | null>;
103
+ /**
104
+ * Get user for authentication context
105
+ *
106
+ * Loads user by sub (external identifier) with all fields needed for auth context.
107
+ * Computes hasPasswordHash from passwordHash, then removes passwordHash and other sensitive fields.
108
+ *
109
+ * This method is used by AuthHandler and AuthGuard to load authenticated users.
110
+ * It ensures consistent user object shape across platforms (core + NestJS).
111
+ *
112
+ * @param sub - External user identifier (UUID)
113
+ * @returns User object with hasPasswordHash flag, without sensitive fields
114
+ * @throws {NAuthException} If user not found or account is inactive
115
+ *
116
+ * @example
117
+ * ```typescript
118
+ * const user = await userService.getUserForAuthContext('user-uuid-123');
119
+ * // user.hasPasswordHash === true/false
120
+ * // user.passwordHash === undefined (removed)
121
+ * ```
122
+ */
123
+ getUserForAuthContext(sub: string): Promise<IUser>;
124
+ /**
125
+ * Update user profile attributes.
126
+ *
127
+ * Updates user fields (name, email, phone, username, metadata) and enforces unique constraints and verification rules.
128
+ *
129
+ * @param dto - UpdateUserAttributesRequestDTO containing sub and fields to update
130
+ * @returns Updated user object
131
+ * @throws {NAuthException} If user not found or unique constraint violated
132
+ *
133
+ * @example
134
+ * ```typescript
135
+ * await userService.updateUserAttributes({ sub: 'user-uuid', email: 'test@example.com' });
136
+ * ```
137
+ */
138
+ updateUserAttributes(dto: UpdateUserAttributesRequestDTO): Promise<UserResponseDto>;
139
+ /**
140
+ * Update email and/or phone verification status.
141
+ *
142
+ * Intended for admin use cases such as migration or offline validation.
143
+ * Updates verification status without requiring actual verification codes.
144
+ *
145
+ * Validation:
146
+ * - Cannot set verified=true if email/phone doesn't exist
147
+ * - Can set verified=false even if email/phone doesn't exist (default state)
148
+ * - Only updates provided fields (partial update)
149
+ *
150
+ * Audit:
151
+ * - Records EMAIL_VERIFIED or PHONE_VERIFIED audit events
152
+ * - Includes performedBy from authenticated admin context
153
+ *
154
+ * @param dto - Request DTO containing sub and verification status flags
155
+ * @returns Updated user object
156
+ * @throws {NAuthException} If user not found or trying to verify non-existent email/phone
157
+ *
158
+ * @example
159
+ * ```typescript
160
+ * // Update email verification only
161
+ * await userService.updateVerifiedStatus({
162
+ * sub: 'user-uuid',
163
+ * isEmailVerified: true
164
+ * });
165
+ *
166
+ * // Update both email and phone verification
167
+ * await userService.updateVerifiedStatus({
168
+ * sub: 'user-uuid',
169
+ * isEmailVerified: true,
170
+ * isPhoneVerified: false
171
+ * });
172
+ * ```
173
+ */
174
+ updateVerifiedStatus(dto: UpdateVerifiedStatusRequestDTO): Promise<UserResponseDto>;
175
+ /**
176
+ * Delete a user and all associated data (cascade deletion).
177
+ *
178
+ * Permanently removes a user account and all related records:
179
+ * - Sessions
180
+ * - Verification tokens
181
+ * - MFA devices
182
+ * - Trusted devices
183
+ * - Social accounts
184
+ * - Login attempts
185
+ * - Challenge sessions
186
+ * - Audit logs (user-specific)
187
+ *
188
+ * Security:
189
+ * - NO built-in authentication - endpoint MUST be protected by admin guards
190
+ * - Records ACCOUNT_DELETED audit event before deletion
191
+ * - Returns counts of deleted records for confirmation
192
+ *
193
+ * @param dto - DeleteUserDTO containing sub
194
+ * @returns Response with success status and deleted record counts
195
+ * @throws {NAuthException} USER_NOT_FOUND
196
+ *
197
+ * @example
198
+ * ```typescript
199
+ * const result = await userService.deleteUser({ sub: 'user-uuid-123' });
200
+ * console.log(`Deleted ${result.deletedRecords.sessions} sessions`);
201
+ * ```
202
+ */
203
+ deleteUser(dto: DeleteUserDTO): Promise<DeleteUserResponseDTO>;
204
+ /**
205
+ * Administrative permanent account locking
206
+ *
207
+ * Sets permanent lock (lockedUntil=NULL) and immediately revokes all active sessions.
208
+ * Reuses existing rate-limit lock fields (isLocked, lockReason, lockedAt, lockedUntil).
209
+ *
210
+ * Permanent vs Temporary locks:
211
+ * - Rate limiting: lockedUntil = future date (temporary auto-unlock)
212
+ * - Admin disableUser: lockedUntil = NULL (permanent manual lock)
213
+ *
214
+ * Security:
215
+ * - NO built-in authentication - endpoint MUST be protected by admin guards
216
+ * - Revokes all sessions immediately (forced logout)
217
+ * - Records ACCOUNT_DISABLED audit event with admin identifier
218
+ *
219
+ * @param dto - User sub and optional reason
220
+ * @returns User object with updated lock status and revoked session count
221
+ * @throws {NAuthException} USER_NOT_FOUND
222
+ *
223
+ * @example
224
+ * ```typescript
225
+ * const result = await userService.disableUser({
226
+ * sub: 'user-uuid-123',
227
+ * reason: 'Suspicious activity detected'
228
+ * });
229
+ * console.log(`Revoked ${result.revokedSessions} sessions`);
230
+ * ```
231
+ */
232
+ disableUser(dto: DisableUserDTO): Promise<DisableUserResponseDTO>;
233
+ /**
234
+ * Enable (unlock) user account
235
+ *
236
+ * Unlocks a previously locked user account by clearing all lock fields.
237
+ * This reverses the effect of disableUser() or rate-limit lockouts.
238
+ *
239
+ * Security:
240
+ * - NO built-in authentication - endpoint MUST be protected by admin guards
241
+ * - Clears lock fields (isLocked, lockReason, lockedAt, lockedUntil)
242
+ * - Resets failed login attempts counter
243
+ * - Records ACCOUNT_ENABLED audit event with admin identifier
244
+ *
245
+ * @param dto - User sub to enable
246
+ * @returns User object with updated lock status
247
+ * @throws {NAuthException} USER_NOT_FOUND
248
+ *
249
+ * @example
250
+ * ```typescript
251
+ * const result = await userService.enableUser({
252
+ * sub: 'user-uuid-123'
253
+ * });
254
+ * console.log(`User unlocked: ${result.user.email}`);
255
+ * ```
256
+ */
257
+ enableUser(dto: EnableUserDTO): Promise<EnableUserResponseDTO>;
258
+ /**
259
+ * Require user to change password at next login.
260
+ *
261
+ * Throws if user not found or has no password set (e.g. social login only).
262
+ *
263
+ * @param dto - SetMustChangePasswordDTO containing userId (sub)
264
+ * @returns Success response
265
+ * @throws {NAuthException} If user is not found or cannot change password
266
+ *
267
+ * @example
268
+ * ```typescript
269
+ * await userService.setMustChangePassword({ userId: 'user-uuid-123' });
270
+ * ```
271
+ */
272
+ setMustChangePassword(dto: SetMustChangePasswordDTO): Promise<SetMustChangePasswordResponseDTO>;
273
+ }
274
+ //# sourceMappingURL=user.service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"user.service.d.ts","sourceRoot":"","sources":["../../src/services/user.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,KAAK,EAAE,MAAM,kCAAkC,CAAC;AACzD,OAAO,EACL,QAAQ,EACR,aAAa,EACb,oBAAoB,EACpB,qBAAqB,EACrB,iBAAiB,EACjB,aAAa,EACb,iBAAiB,EACjB,WAAW,EACX,gBAAgB,EACjB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAC1D,OAAO,EAAE,wBAAwB,IAAI,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AACpF,OAAO,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAO9D,OAAO,EAAE,WAAW,EAAE,MAAM,gCAAgC,CAAC;A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