servcraft 0.1.0

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 (106) hide show
  1. package/.dockerignore +45 -0
  2. package/.env.example +46 -0
  3. package/.husky/commit-msg +1 -0
  4. package/.husky/pre-commit +1 -0
  5. package/.prettierignore +4 -0
  6. package/.prettierrc +11 -0
  7. package/Dockerfile +76 -0
  8. package/Dockerfile.dev +31 -0
  9. package/README.md +232 -0
  10. package/commitlint.config.js +24 -0
  11. package/dist/cli/index.cjs +3968 -0
  12. package/dist/cli/index.cjs.map +1 -0
  13. package/dist/cli/index.d.cts +1 -0
  14. package/dist/cli/index.d.ts +1 -0
  15. package/dist/cli/index.js +3945 -0
  16. package/dist/cli/index.js.map +1 -0
  17. package/dist/index.cjs +2458 -0
  18. package/dist/index.cjs.map +1 -0
  19. package/dist/index.d.cts +828 -0
  20. package/dist/index.d.ts +828 -0
  21. package/dist/index.js +2332 -0
  22. package/dist/index.js.map +1 -0
  23. package/docker-compose.prod.yml +118 -0
  24. package/docker-compose.yml +147 -0
  25. package/eslint.config.js +27 -0
  26. package/npm-cache/_cacache/content-v2/sha512/1c/d0/03440d500a0487621aad1d6402978340698976602046db8e24fa03c01ee6c022c69b0582f969042d9442ee876ac35c038e960dd427d1e622fa24b8eb7dba +0 -0
  27. package/npm-cache/_cacache/content-v2/sha512/42/55/28b493ca491833e5aab0e9c3108d29ab3f36c248ca88f45d4630674fce9130959e56ae308797ac2b6328fa7f09a610b9550ed09cb971d039876d293fc69d +0 -0
  28. package/npm-cache/_cacache/content-v2/sha512/e0/12/f360dc9315ee5f17844a0c8c233ee6bf7c30837c4a02ea0d56c61c7f7ab21c0e958e50ed2c57c59f983c762b93056778c9009b2398ffc26def0183999b13 +0 -0
  29. package/npm-cache/_cacache/content-v2/sha512/ed/b0/fae1161902898f4c913c67d7f6cdf6be0665aec3b389b9c4f4f0a101ca1da59badf1b59c4e0030f5223023b8d63cfe501c46a32c20c895d4fb3f11ca2232 +0 -0
  30. package/npm-cache/_cacache/index-v5/58/94/c2cba79e0f16b4c10e95a87e32255741149e8222cc314a476aab67c39cc0 +5 -0
  31. package/npm-cache/_update-notifier-last-checked +0 -0
  32. package/package.json +112 -0
  33. package/prisma/schema.prisma +157 -0
  34. package/src/cli/commands/add-module.ts +422 -0
  35. package/src/cli/commands/db.ts +137 -0
  36. package/src/cli/commands/docs.ts +16 -0
  37. package/src/cli/commands/generate.ts +459 -0
  38. package/src/cli/commands/init.ts +640 -0
  39. package/src/cli/index.ts +32 -0
  40. package/src/cli/templates/controller.ts +67 -0
  41. package/src/cli/templates/dynamic-prisma.ts +89 -0
  42. package/src/cli/templates/dynamic-schemas.ts +232 -0
  43. package/src/cli/templates/dynamic-types.ts +60 -0
  44. package/src/cli/templates/module-index.ts +33 -0
  45. package/src/cli/templates/prisma-model.ts +17 -0
  46. package/src/cli/templates/repository.ts +104 -0
  47. package/src/cli/templates/routes.ts +70 -0
  48. package/src/cli/templates/schemas.ts +26 -0
  49. package/src/cli/templates/service.ts +58 -0
  50. package/src/cli/templates/types.ts +27 -0
  51. package/src/cli/utils/docs-generator.ts +47 -0
  52. package/src/cli/utils/field-parser.ts +315 -0
  53. package/src/cli/utils/helpers.ts +89 -0
  54. package/src/config/env.ts +80 -0
  55. package/src/config/index.ts +97 -0
  56. package/src/core/index.ts +5 -0
  57. package/src/core/logger.ts +43 -0
  58. package/src/core/server.ts +132 -0
  59. package/src/database/index.ts +7 -0
  60. package/src/database/prisma.ts +54 -0
  61. package/src/database/seed.ts +59 -0
  62. package/src/index.ts +63 -0
  63. package/src/middleware/error-handler.ts +73 -0
  64. package/src/middleware/index.ts +3 -0
  65. package/src/middleware/security.ts +116 -0
  66. package/src/modules/audit/audit.service.ts +192 -0
  67. package/src/modules/audit/index.ts +2 -0
  68. package/src/modules/audit/types.ts +37 -0
  69. package/src/modules/auth/auth.controller.ts +182 -0
  70. package/src/modules/auth/auth.middleware.ts +87 -0
  71. package/src/modules/auth/auth.routes.ts +123 -0
  72. package/src/modules/auth/auth.service.ts +142 -0
  73. package/src/modules/auth/index.ts +49 -0
  74. package/src/modules/auth/schemas.ts +52 -0
  75. package/src/modules/auth/types.ts +69 -0
  76. package/src/modules/email/email.service.ts +212 -0
  77. package/src/modules/email/index.ts +10 -0
  78. package/src/modules/email/templates.ts +213 -0
  79. package/src/modules/email/types.ts +57 -0
  80. package/src/modules/swagger/index.ts +3 -0
  81. package/src/modules/swagger/schema-builder.ts +263 -0
  82. package/src/modules/swagger/swagger.service.ts +169 -0
  83. package/src/modules/swagger/types.ts +68 -0
  84. package/src/modules/user/index.ts +30 -0
  85. package/src/modules/user/schemas.ts +49 -0
  86. package/src/modules/user/types.ts +78 -0
  87. package/src/modules/user/user.controller.ts +139 -0
  88. package/src/modules/user/user.repository.ts +156 -0
  89. package/src/modules/user/user.routes.ts +199 -0
  90. package/src/modules/user/user.service.ts +145 -0
  91. package/src/modules/validation/index.ts +18 -0
  92. package/src/modules/validation/validator.ts +104 -0
  93. package/src/types/common.ts +61 -0
  94. package/src/types/index.ts +10 -0
  95. package/src/utils/errors.ts +66 -0
  96. package/src/utils/index.ts +33 -0
  97. package/src/utils/pagination.ts +38 -0
  98. package/src/utils/response.ts +63 -0
  99. package/tests/integration/auth.test.ts +59 -0
  100. package/tests/setup.ts +17 -0
  101. package/tests/unit/modules/validation.test.ts +88 -0
  102. package/tests/unit/utils/errors.test.ts +113 -0
  103. package/tests/unit/utils/pagination.test.ts +82 -0
  104. package/tsconfig.json +33 -0
  105. package/tsup.config.ts +14 -0
  106. package/vitest.config.ts +34 -0
package/dist/index.js ADDED
@@ -0,0 +1,2332 @@
1
+ // src/core/server.ts
2
+ import Fastify from "fastify";
3
+
4
+ // src/core/logger.ts
5
+ import pino from "pino";
6
+ var defaultConfig = {
7
+ level: process.env.LOG_LEVEL || "info",
8
+ pretty: process.env.NODE_ENV !== "production",
9
+ name: "servcraft"
10
+ };
11
+ function createLogger(config2 = {}) {
12
+ const mergedConfig = { ...defaultConfig, ...config2 };
13
+ const transport = mergedConfig.pretty ? {
14
+ target: "pino-pretty",
15
+ options: {
16
+ colorize: true,
17
+ translateTime: "SYS:standard",
18
+ ignore: "pid,hostname"
19
+ }
20
+ } : void 0;
21
+ return pino({
22
+ name: mergedConfig.name,
23
+ level: mergedConfig.level,
24
+ transport,
25
+ formatters: {
26
+ level: (label) => ({ level: label })
27
+ },
28
+ timestamp: pino.stdTimeFunctions.isoTime
29
+ });
30
+ }
31
+ var logger = createLogger();
32
+
33
+ // src/core/server.ts
34
+ var defaultConfig2 = {
35
+ port: parseInt(process.env.PORT || "3000", 10),
36
+ host: process.env.HOST || "0.0.0.0",
37
+ trustProxy: true,
38
+ bodyLimit: 1048576,
39
+ // 1MB
40
+ requestTimeout: 3e4
41
+ // 30s
42
+ };
43
+ var Server = class {
44
+ app;
45
+ config;
46
+ logger;
47
+ isShuttingDown = false;
48
+ constructor(config2 = {}) {
49
+ this.config = { ...defaultConfig2, ...config2 };
50
+ this.logger = this.config.logger || logger;
51
+ const fastifyOptions = {
52
+ logger: this.logger,
53
+ trustProxy: this.config.trustProxy,
54
+ bodyLimit: this.config.bodyLimit,
55
+ requestTimeout: this.config.requestTimeout
56
+ };
57
+ this.app = Fastify(fastifyOptions);
58
+ this.setupHealthCheck();
59
+ this.setupGracefulShutdown();
60
+ }
61
+ get instance() {
62
+ return this.app;
63
+ }
64
+ setupHealthCheck() {
65
+ this.app.get("/health", async (_request, reply) => {
66
+ const healthcheck = {
67
+ status: "ok",
68
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
69
+ uptime: process.uptime(),
70
+ memory: process.memoryUsage(),
71
+ version: process.env.npm_package_version || "0.1.0"
72
+ };
73
+ return reply.status(200).send(healthcheck);
74
+ });
75
+ this.app.get("/ready", async (_request, reply) => {
76
+ if (this.isShuttingDown) {
77
+ return reply.status(503).send({ status: "shutting_down" });
78
+ }
79
+ return reply.status(200).send({ status: "ready" });
80
+ });
81
+ }
82
+ setupGracefulShutdown() {
83
+ const signals = ["SIGINT", "SIGTERM", "SIGQUIT"];
84
+ signals.forEach((signal) => {
85
+ process.on(signal, async () => {
86
+ this.logger.info(`Received ${signal}, starting graceful shutdown...`);
87
+ await this.shutdown();
88
+ });
89
+ });
90
+ process.on("uncaughtException", async (error2) => {
91
+ this.logger.error({ err: error2 }, "Uncaught exception");
92
+ await this.shutdown(1);
93
+ });
94
+ process.on("unhandledRejection", async (reason) => {
95
+ this.logger.error({ err: reason }, "Unhandled rejection");
96
+ await this.shutdown(1);
97
+ });
98
+ }
99
+ async shutdown(exitCode = 0) {
100
+ if (this.isShuttingDown) {
101
+ return;
102
+ }
103
+ this.isShuttingDown = true;
104
+ this.logger.info("Graceful shutdown initiated...");
105
+ const shutdownTimeout = setTimeout(() => {
106
+ this.logger.error("Graceful shutdown timeout, forcing exit");
107
+ process.exit(1);
108
+ }, 3e4);
109
+ try {
110
+ await this.app.close();
111
+ this.logger.info("Server closed successfully");
112
+ clearTimeout(shutdownTimeout);
113
+ process.exit(exitCode);
114
+ } catch (error2) {
115
+ this.logger.error({ err: error2 }, "Error during shutdown");
116
+ clearTimeout(shutdownTimeout);
117
+ process.exit(1);
118
+ }
119
+ }
120
+ async start() {
121
+ try {
122
+ await this.app.listen({
123
+ port: this.config.port,
124
+ host: this.config.host
125
+ });
126
+ this.logger.info(`Server listening on ${this.config.host}:${this.config.port}`);
127
+ } catch (error2) {
128
+ this.logger.error({ err: error2 }, "Failed to start server");
129
+ throw error2;
130
+ }
131
+ }
132
+ };
133
+ function createServer(config2 = {}) {
134
+ return new Server(config2);
135
+ }
136
+
137
+ // src/config/env.ts
138
+ import { z } from "zod";
139
+ import dotenv from "dotenv";
140
+ dotenv.config();
141
+ var envSchema = z.object({
142
+ // Server
143
+ NODE_ENV: z.enum(["development", "staging", "production", "test"]).default("development"),
144
+ PORT: z.string().transform(Number).default("3000"),
145
+ HOST: z.string().default("0.0.0.0"),
146
+ // Database
147
+ DATABASE_URL: z.string().optional(),
148
+ // JWT
149
+ JWT_SECRET: z.string().min(32).optional(),
150
+ JWT_ACCESS_EXPIRES_IN: z.string().default("15m"),
151
+ JWT_REFRESH_EXPIRES_IN: z.string().default("7d"),
152
+ // Security
153
+ CORS_ORIGIN: z.string().default("*"),
154
+ RATE_LIMIT_MAX: z.string().transform(Number).default("100"),
155
+ RATE_LIMIT_WINDOW_MS: z.string().transform(Number).default("60000"),
156
+ // Email
157
+ SMTP_HOST: z.string().optional(),
158
+ SMTP_PORT: z.string().transform(Number).optional(),
159
+ SMTP_USER: z.string().optional(),
160
+ SMTP_PASS: z.string().optional(),
161
+ SMTP_FROM: z.string().optional(),
162
+ // Redis (optional)
163
+ REDIS_URL: z.string().optional(),
164
+ // Swagger/OpenAPI
165
+ SWAGGER_ENABLED: z.union([z.literal("true"), z.literal("false")]).default("true").transform((val) => val === "true"),
166
+ SWAGGER_ROUTE: z.string().default("/docs"),
167
+ SWAGGER_TITLE: z.string().default("Servcraft API"),
168
+ SWAGGER_DESCRIPTION: z.string().default("API documentation"),
169
+ SWAGGER_VERSION: z.string().default("1.0.0"),
170
+ // Logging
171
+ LOG_LEVEL: z.enum(["fatal", "error", "warn", "info", "debug", "trace"]).default("info")
172
+ });
173
+ function validateEnv() {
174
+ const parsed = envSchema.safeParse(process.env);
175
+ if (!parsed.success) {
176
+ logger.error({ errors: parsed.error.flatten().fieldErrors }, "Invalid environment variables");
177
+ throw new Error("Invalid environment variables");
178
+ }
179
+ return parsed.data;
180
+ }
181
+ var env = validateEnv();
182
+ function isDevelopment() {
183
+ return env.NODE_ENV === "development";
184
+ }
185
+ function isProduction() {
186
+ return env.NODE_ENV === "production";
187
+ }
188
+ function isTest() {
189
+ return env.NODE_ENV === "test";
190
+ }
191
+ function isStaging() {
192
+ return env.NODE_ENV === "staging";
193
+ }
194
+
195
+ // src/config/index.ts
196
+ function parseCorsOrigin(origin) {
197
+ if (origin === "*") return "*";
198
+ if (origin.includes(",")) {
199
+ return origin.split(",").map((o) => o.trim());
200
+ }
201
+ return origin;
202
+ }
203
+ function createConfig() {
204
+ return {
205
+ env,
206
+ server: {
207
+ port: env.PORT,
208
+ host: env.HOST
209
+ },
210
+ jwt: {
211
+ secret: env.JWT_SECRET || "change-me-in-production-please-32chars",
212
+ accessExpiresIn: env.JWT_ACCESS_EXPIRES_IN,
213
+ refreshExpiresIn: env.JWT_REFRESH_EXPIRES_IN
214
+ },
215
+ security: {
216
+ corsOrigin: parseCorsOrigin(env.CORS_ORIGIN),
217
+ rateLimit: {
218
+ max: env.RATE_LIMIT_MAX,
219
+ windowMs: env.RATE_LIMIT_WINDOW_MS
220
+ }
221
+ },
222
+ email: {
223
+ host: env.SMTP_HOST,
224
+ port: env.SMTP_PORT,
225
+ user: env.SMTP_USER,
226
+ pass: env.SMTP_PASS,
227
+ from: env.SMTP_FROM
228
+ },
229
+ database: {
230
+ url: env.DATABASE_URL
231
+ },
232
+ redis: {
233
+ url: env.REDIS_URL
234
+ },
235
+ swagger: {
236
+ enabled: env.SWAGGER_ENABLED,
237
+ route: env.SWAGGER_ROUTE,
238
+ title: env.SWAGGER_TITLE,
239
+ description: env.SWAGGER_DESCRIPTION,
240
+ version: env.SWAGGER_VERSION
241
+ }
242
+ };
243
+ }
244
+ var config = createConfig();
245
+
246
+ // src/utils/errors.ts
247
+ var AppError = class _AppError extends Error {
248
+ statusCode;
249
+ isOperational;
250
+ errors;
251
+ constructor(message, statusCode = 500, isOperational = true, errors) {
252
+ super(message);
253
+ this.statusCode = statusCode;
254
+ this.isOperational = isOperational;
255
+ this.errors = errors;
256
+ Object.setPrototypeOf(this, _AppError.prototype);
257
+ Error.captureStackTrace(this, this.constructor);
258
+ }
259
+ };
260
+ var NotFoundError = class extends AppError {
261
+ constructor(resource = "Resource") {
262
+ super(`${resource} not found`, 404);
263
+ }
264
+ };
265
+ var UnauthorizedError = class extends AppError {
266
+ constructor(message = "Unauthorized") {
267
+ super(message, 401);
268
+ }
269
+ };
270
+ var ForbiddenError = class extends AppError {
271
+ constructor(message = "Forbidden") {
272
+ super(message, 403);
273
+ }
274
+ };
275
+ var BadRequestError = class extends AppError {
276
+ constructor(message = "Bad request", errors) {
277
+ super(message, 400, true, errors);
278
+ }
279
+ };
280
+ var ConflictError = class extends AppError {
281
+ constructor(message = "Resource already exists") {
282
+ super(message, 409);
283
+ }
284
+ };
285
+ var ValidationError = class extends AppError {
286
+ constructor(errors) {
287
+ super("Validation failed", 422, true, errors);
288
+ }
289
+ };
290
+ var TooManyRequestsError = class extends AppError {
291
+ constructor(message = "Too many requests") {
292
+ super(message, 429);
293
+ }
294
+ };
295
+ function isAppError(error2) {
296
+ return error2 instanceof AppError;
297
+ }
298
+
299
+ // src/middleware/error-handler.ts
300
+ function registerErrorHandler(app) {
301
+ app.setErrorHandler(
302
+ (error2, request, reply) => {
303
+ logger.error(
304
+ {
305
+ err: error2,
306
+ requestId: request.id,
307
+ method: request.method,
308
+ url: request.url
309
+ },
310
+ "Request error"
311
+ );
312
+ if (isAppError(error2)) {
313
+ return reply.status(error2.statusCode).send({
314
+ success: false,
315
+ message: error2.message,
316
+ errors: error2.errors,
317
+ ...isProduction() ? {} : { stack: error2.stack }
318
+ });
319
+ }
320
+ if ("validation" in error2 && error2.validation) {
321
+ const errors = {};
322
+ for (const err of error2.validation) {
323
+ const field = err.instancePath?.replace("/", "") || "body";
324
+ if (!errors[field]) {
325
+ errors[field] = [];
326
+ }
327
+ errors[field].push(err.message || "Invalid value");
328
+ }
329
+ return reply.status(400).send({
330
+ success: false,
331
+ message: "Validation failed",
332
+ errors
333
+ });
334
+ }
335
+ if ("statusCode" in error2 && typeof error2.statusCode === "number") {
336
+ return reply.status(error2.statusCode).send({
337
+ success: false,
338
+ message: error2.message,
339
+ ...isProduction() ? {} : { stack: error2.stack }
340
+ });
341
+ }
342
+ return reply.status(500).send({
343
+ success: false,
344
+ message: isProduction() ? "Internal server error" : error2.message,
345
+ ...isProduction() ? {} : { stack: error2.stack }
346
+ });
347
+ }
348
+ );
349
+ app.setNotFoundHandler((request, reply) => {
350
+ return reply.status(404).send({
351
+ success: false,
352
+ message: `Route ${request.method} ${request.url} not found`
353
+ });
354
+ });
355
+ }
356
+
357
+ // src/middleware/security.ts
358
+ import helmet from "@fastify/helmet";
359
+ import cors from "@fastify/cors";
360
+ import rateLimit from "@fastify/rate-limit";
361
+ var defaultOptions = {
362
+ helmet: true,
363
+ cors: true,
364
+ rateLimit: true
365
+ };
366
+ async function registerSecurity(app, options = {}) {
367
+ const opts = { ...defaultOptions, ...options };
368
+ if (opts.helmet) {
369
+ await app.register(helmet, {
370
+ contentSecurityPolicy: {
371
+ directives: {
372
+ defaultSrc: ["'self'"],
373
+ styleSrc: ["'self'", "'unsafe-inline'"],
374
+ scriptSrc: ["'self'"],
375
+ imgSrc: ["'self'", "data:", "https:"]
376
+ }
377
+ },
378
+ crossOriginEmbedderPolicy: false
379
+ });
380
+ logger.debug("Helmet security headers enabled");
381
+ }
382
+ if (opts.cors) {
383
+ await app.register(cors, {
384
+ origin: config.security.corsOrigin,
385
+ credentials: true,
386
+ methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
387
+ allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
388
+ exposedHeaders: ["X-Total-Count", "X-Page", "X-Limit"],
389
+ maxAge: 86400
390
+ // 24 hours
391
+ });
392
+ logger.debug({ origin: config.security.corsOrigin }, "CORS enabled");
393
+ }
394
+ if (opts.rateLimit) {
395
+ await app.register(rateLimit, {
396
+ max: config.security.rateLimit.max,
397
+ timeWindow: config.security.rateLimit.windowMs,
398
+ errorResponseBuilder: (_request, context) => ({
399
+ success: false,
400
+ message: "Too many requests, please try again later",
401
+ retryAfter: context.after
402
+ }),
403
+ keyGenerator: (request) => {
404
+ return request.headers["x-forwarded-for"]?.toString().split(",")[0] || request.ip || "unknown";
405
+ }
406
+ });
407
+ logger.debug(
408
+ {
409
+ max: config.security.rateLimit.max,
410
+ windowMs: config.security.rateLimit.windowMs
411
+ },
412
+ "Rate limiting enabled"
413
+ );
414
+ }
415
+ }
416
+ async function registerBruteForceProtection(app, routePrefix, options = {}) {
417
+ const { max = 5, timeWindow = 3e5 } = options;
418
+ await app.register(rateLimit, {
419
+ max,
420
+ timeWindow,
421
+ keyGenerator: (request) => {
422
+ const ip = request.headers["x-forwarded-for"]?.toString().split(",")[0] || request.ip || "unknown";
423
+ return `brute:${routePrefix}:${ip}`;
424
+ },
425
+ errorResponseBuilder: () => ({
426
+ success: false,
427
+ message: "Too many attempts. Please try again later."
428
+ }),
429
+ onExceeded: (request) => {
430
+ logger.warn(
431
+ {
432
+ ip: request.ip,
433
+ route: routePrefix
434
+ },
435
+ "Brute force protection triggered"
436
+ );
437
+ }
438
+ });
439
+ }
440
+
441
+ // src/modules/auth/index.ts
442
+ import jwt from "@fastify/jwt";
443
+ import cookie from "@fastify/cookie";
444
+
445
+ // src/modules/auth/auth.service.ts
446
+ import bcrypt from "bcryptjs";
447
+ var tokenBlacklist = /* @__PURE__ */ new Set();
448
+ var AuthService = class {
449
+ app;
450
+ SALT_ROUNDS = 12;
451
+ constructor(app) {
452
+ this.app = app;
453
+ }
454
+ async hashPassword(password) {
455
+ return bcrypt.hash(password, this.SALT_ROUNDS);
456
+ }
457
+ async verifyPassword(password, hash) {
458
+ return bcrypt.compare(password, hash);
459
+ }
460
+ generateTokenPair(user) {
461
+ const accessPayload = {
462
+ sub: user.id,
463
+ email: user.email,
464
+ role: user.role,
465
+ type: "access"
466
+ };
467
+ const refreshPayload = {
468
+ sub: user.id,
469
+ email: user.email,
470
+ role: user.role,
471
+ type: "refresh"
472
+ };
473
+ const accessToken = this.app.jwt.sign(accessPayload, {
474
+ expiresIn: config.jwt.accessExpiresIn
475
+ });
476
+ const refreshToken = this.app.jwt.sign(refreshPayload, {
477
+ expiresIn: config.jwt.refreshExpiresIn
478
+ });
479
+ const expiresIn = this.parseExpiration(config.jwt.accessExpiresIn);
480
+ return { accessToken, refreshToken, expiresIn };
481
+ }
482
+ parseExpiration(expiration) {
483
+ const match = expiration.match(/^(\d+)([smhd])$/);
484
+ if (!match) return 900;
485
+ const value = parseInt(match[1] || "0", 10);
486
+ const unit = match[2];
487
+ switch (unit) {
488
+ case "s":
489
+ return value;
490
+ case "m":
491
+ return value * 60;
492
+ case "h":
493
+ return value * 3600;
494
+ case "d":
495
+ return value * 86400;
496
+ default:
497
+ return 900;
498
+ }
499
+ }
500
+ async verifyAccessToken(token) {
501
+ try {
502
+ if (this.isTokenBlacklisted(token)) {
503
+ throw new UnauthorizedError("Token has been revoked");
504
+ }
505
+ const payload = this.app.jwt.verify(token);
506
+ if (payload.type !== "access") {
507
+ throw new UnauthorizedError("Invalid token type");
508
+ }
509
+ return payload;
510
+ } catch (error2) {
511
+ if (error2 instanceof UnauthorizedError) throw error2;
512
+ logger.debug({ err: error2 }, "Token verification failed");
513
+ throw new UnauthorizedError("Invalid or expired token");
514
+ }
515
+ }
516
+ async verifyRefreshToken(token) {
517
+ try {
518
+ if (this.isTokenBlacklisted(token)) {
519
+ throw new UnauthorizedError("Token has been revoked");
520
+ }
521
+ const payload = this.app.jwt.verify(token);
522
+ if (payload.type !== "refresh") {
523
+ throw new UnauthorizedError("Invalid token type");
524
+ }
525
+ return payload;
526
+ } catch (error2) {
527
+ if (error2 instanceof UnauthorizedError) throw error2;
528
+ logger.debug({ err: error2 }, "Refresh token verification failed");
529
+ throw new UnauthorizedError("Invalid or expired refresh token");
530
+ }
531
+ }
532
+ blacklistToken(token) {
533
+ tokenBlacklist.add(token);
534
+ logger.debug("Token blacklisted");
535
+ }
536
+ isTokenBlacklisted(token) {
537
+ return tokenBlacklist.has(token);
538
+ }
539
+ // Clear expired tokens from blacklist periodically
540
+ cleanupBlacklist() {
541
+ tokenBlacklist.clear();
542
+ logger.debug("Token blacklist cleared");
543
+ }
544
+ };
545
+ function createAuthService(app) {
546
+ return new AuthService(app);
547
+ }
548
+
549
+ // src/modules/auth/schemas.ts
550
+ import { z as z2 } from "zod";
551
+ var loginSchema = z2.object({
552
+ email: z2.string().email("Invalid email address"),
553
+ password: z2.string().min(1, "Password is required")
554
+ });
555
+ var registerSchema = z2.object({
556
+ email: z2.string().email("Invalid email address"),
557
+ password: z2.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number"),
558
+ name: z2.string().min(2, "Name must be at least 2 characters").optional()
559
+ });
560
+ var refreshTokenSchema = z2.object({
561
+ refreshToken: z2.string().min(1, "Refresh token is required")
562
+ });
563
+ var passwordResetRequestSchema = z2.object({
564
+ email: z2.string().email("Invalid email address")
565
+ });
566
+ var passwordResetConfirmSchema = z2.object({
567
+ token: z2.string().min(1, "Token is required"),
568
+ password: z2.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number")
569
+ });
570
+ var changePasswordSchema = z2.object({
571
+ currentPassword: z2.string().min(1, "Current password is required"),
572
+ newPassword: z2.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number")
573
+ });
574
+
575
+ // src/utils/response.ts
576
+ function success(reply, data, statusCode = 200) {
577
+ const response = {
578
+ success: true,
579
+ data
580
+ };
581
+ return reply.status(statusCode).send(response);
582
+ }
583
+ function created(reply, data) {
584
+ return success(reply, data, 201);
585
+ }
586
+ function noContent(reply) {
587
+ return reply.status(204).send();
588
+ }
589
+ function error(reply, message, statusCode = 400, errors) {
590
+ const response = {
591
+ success: false,
592
+ message,
593
+ errors
594
+ };
595
+ return reply.status(statusCode).send(response);
596
+ }
597
+ function notFound(reply, message = "Resource not found") {
598
+ return error(reply, message, 404);
599
+ }
600
+ function unauthorized(reply, message = "Unauthorized") {
601
+ return error(reply, message, 401);
602
+ }
603
+ function forbidden(reply, message = "Forbidden") {
604
+ return error(reply, message, 403);
605
+ }
606
+ function badRequest(reply, message = "Bad request", errors) {
607
+ return error(reply, message, 400, errors);
608
+ }
609
+ function conflict(reply, message = "Resource already exists") {
610
+ return error(reply, message, 409);
611
+ }
612
+ function internalError(reply, message = "Internal server error") {
613
+ return error(reply, message, 500);
614
+ }
615
+
616
+ // src/modules/validation/validator.ts
617
+ import { z as z3 } from "zod";
618
+ function validateBody(schema, data) {
619
+ const result = schema.safeParse(data);
620
+ if (!result.success) {
621
+ throw new ValidationError(formatZodErrors(result.error));
622
+ }
623
+ return result.data;
624
+ }
625
+ function validateQuery(schema, data) {
626
+ const result = schema.safeParse(data);
627
+ if (!result.success) {
628
+ throw new ValidationError(formatZodErrors(result.error));
629
+ }
630
+ return result.data;
631
+ }
632
+ function validateParams(schema, data) {
633
+ const result = schema.safeParse(data);
634
+ if (!result.success) {
635
+ throw new ValidationError(formatZodErrors(result.error));
636
+ }
637
+ return result.data;
638
+ }
639
+ function validate(schema, data) {
640
+ return validateBody(schema, data);
641
+ }
642
+ function formatZodErrors(error2) {
643
+ const errors = {};
644
+ for (const issue of error2.issues) {
645
+ const path = issue.path.join(".") || "root";
646
+ if (!errors[path]) {
647
+ errors[path] = [];
648
+ }
649
+ errors[path].push(issue.message);
650
+ }
651
+ return errors;
652
+ }
653
+ var idParamSchema = z3.object({
654
+ id: z3.string().uuid("Invalid ID format")
655
+ });
656
+ var paginationSchema = z3.object({
657
+ page: z3.string().transform(Number).optional().default("1"),
658
+ limit: z3.string().transform(Number).optional().default("20"),
659
+ sortBy: z3.string().optional(),
660
+ sortOrder: z3.enum(["asc", "desc"]).optional().default("asc")
661
+ });
662
+ var searchSchema = z3.object({
663
+ q: z3.string().min(1, "Search query is required").optional(),
664
+ search: z3.string().min(1).optional()
665
+ });
666
+ var emailSchema = z3.string().email("Invalid email address");
667
+ var passwordSchema = z3.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number").regex(/[^A-Za-z0-9]/, "Password must contain at least one special character");
668
+ var urlSchema = z3.string().url("Invalid URL format");
669
+ var phoneSchema = z3.string().regex(
670
+ /^\+?[1-9]\d{1,14}$/,
671
+ "Invalid phone number format"
672
+ );
673
+ var dateSchema = z3.coerce.date();
674
+ var futureDateSchema = z3.coerce.date().refine(
675
+ (date) => date > /* @__PURE__ */ new Date(),
676
+ "Date must be in the future"
677
+ );
678
+ var pastDateSchema = z3.coerce.date().refine(
679
+ (date) => date < /* @__PURE__ */ new Date(),
680
+ "Date must be in the past"
681
+ );
682
+
683
+ // src/modules/auth/auth.controller.ts
684
+ var AuthController = class {
685
+ constructor(authService, userService) {
686
+ this.authService = authService;
687
+ this.userService = userService;
688
+ }
689
+ async register(request, reply) {
690
+ const data = validateBody(registerSchema, request.body);
691
+ const existingUser = await this.userService.findByEmail(data.email);
692
+ if (existingUser) {
693
+ throw new BadRequestError("Email already registered");
694
+ }
695
+ const hashedPassword = await this.authService.hashPassword(data.password);
696
+ const user = await this.userService.create({
697
+ email: data.email,
698
+ password: hashedPassword,
699
+ name: data.name
700
+ });
701
+ const tokens = this.authService.generateTokenPair({
702
+ id: user.id,
703
+ email: user.email,
704
+ role: user.role
705
+ });
706
+ created(reply, {
707
+ user: {
708
+ id: user.id,
709
+ email: user.email,
710
+ name: user.name,
711
+ role: user.role
712
+ },
713
+ ...tokens
714
+ });
715
+ }
716
+ async login(request, reply) {
717
+ const data = validateBody(loginSchema, request.body);
718
+ const user = await this.userService.findByEmail(data.email);
719
+ if (!user) {
720
+ throw new UnauthorizedError("Invalid credentials");
721
+ }
722
+ if (user.status !== "active") {
723
+ throw new UnauthorizedError("Account is not active");
724
+ }
725
+ const isValidPassword = await this.authService.verifyPassword(data.password, user.password);
726
+ if (!isValidPassword) {
727
+ throw new UnauthorizedError("Invalid credentials");
728
+ }
729
+ await this.userService.updateLastLogin(user.id);
730
+ const tokens = this.authService.generateTokenPair({
731
+ id: user.id,
732
+ email: user.email,
733
+ role: user.role
734
+ });
735
+ success(reply, {
736
+ user: {
737
+ id: user.id,
738
+ email: user.email,
739
+ name: user.name,
740
+ role: user.role
741
+ },
742
+ ...tokens
743
+ });
744
+ }
745
+ async refresh(request, reply) {
746
+ const data = validateBody(refreshTokenSchema, request.body);
747
+ const payload = await this.authService.verifyRefreshToken(data.refreshToken);
748
+ const user = await this.userService.findById(payload.sub);
749
+ if (!user || user.status !== "active") {
750
+ throw new UnauthorizedError("User not found or inactive");
751
+ }
752
+ this.authService.blacklistToken(data.refreshToken);
753
+ const tokens = this.authService.generateTokenPair({
754
+ id: user.id,
755
+ email: user.email,
756
+ role: user.role
757
+ });
758
+ success(reply, tokens);
759
+ }
760
+ async logout(request, reply) {
761
+ const authHeader = request.headers.authorization;
762
+ if (authHeader?.startsWith("Bearer ")) {
763
+ const token = authHeader.substring(7);
764
+ this.authService.blacklistToken(token);
765
+ }
766
+ success(reply, { message: "Logged out successfully" });
767
+ }
768
+ async me(request, reply) {
769
+ const authRequest = request;
770
+ const user = await this.userService.findById(authRequest.user.id);
771
+ if (!user) {
772
+ throw new UnauthorizedError("User not found");
773
+ }
774
+ success(reply, {
775
+ id: user.id,
776
+ email: user.email,
777
+ name: user.name,
778
+ role: user.role,
779
+ status: user.status,
780
+ createdAt: user.createdAt
781
+ });
782
+ }
783
+ async changePassword(request, reply) {
784
+ const authRequest = request;
785
+ const data = validateBody(changePasswordSchema, request.body);
786
+ const user = await this.userService.findById(authRequest.user.id);
787
+ if (!user) {
788
+ throw new UnauthorizedError("User not found");
789
+ }
790
+ const isValidPassword = await this.authService.verifyPassword(
791
+ data.currentPassword,
792
+ user.password
793
+ );
794
+ if (!isValidPassword) {
795
+ throw new BadRequestError("Current password is incorrect");
796
+ }
797
+ const hashedPassword = await this.authService.hashPassword(data.newPassword);
798
+ await this.userService.updatePassword(user.id, hashedPassword);
799
+ success(reply, { message: "Password changed successfully" });
800
+ }
801
+ };
802
+ function createAuthController(authService, userService) {
803
+ return new AuthController(authService, userService);
804
+ }
805
+
806
+ // src/modules/auth/auth.middleware.ts
807
+ function createAuthMiddleware(authService) {
808
+ return async function authenticate(request, reply) {
809
+ const authHeader = request.headers.authorization;
810
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
811
+ throw new UnauthorizedError("Missing or invalid authorization header");
812
+ }
813
+ const token = authHeader.substring(7);
814
+ const payload = await authService.verifyAccessToken(token);
815
+ request.user = {
816
+ id: payload.sub,
817
+ email: payload.email,
818
+ role: payload.role
819
+ };
820
+ };
821
+ }
822
+ function createRoleMiddleware(allowedRoles) {
823
+ return async function authorize(request, _reply) {
824
+ const user = request.user;
825
+ if (!user) {
826
+ throw new UnauthorizedError("Authentication required");
827
+ }
828
+ if (!allowedRoles.includes(user.role)) {
829
+ throw new ForbiddenError("Insufficient permissions");
830
+ }
831
+ };
832
+ }
833
+ function createPermissionMiddleware(requiredPermissions) {
834
+ return async function checkPermissions(request, _reply) {
835
+ const user = request.user;
836
+ if (!user) {
837
+ throw new UnauthorizedError("Authentication required");
838
+ }
839
+ };
840
+ }
841
+ function createOptionalAuthMiddleware(authService) {
842
+ return async function optionalAuthenticate(request, _reply) {
843
+ const authHeader = request.headers.authorization;
844
+ if (!authHeader || !authHeader.startsWith("Bearer ")) {
845
+ return;
846
+ }
847
+ try {
848
+ const token = authHeader.substring(7);
849
+ const payload = await authService.verifyAccessToken(token);
850
+ request.user = {
851
+ id: payload.sub,
852
+ email: payload.email,
853
+ role: payload.role
854
+ };
855
+ } catch {
856
+ }
857
+ };
858
+ }
859
+
860
+ // src/modules/swagger/swagger.service.ts
861
+ import swagger from "@fastify/swagger";
862
+ import swaggerUi from "@fastify/swagger-ui";
863
+ var defaultConfig3 = {
864
+ enabled: true,
865
+ route: "/docs",
866
+ title: "Servcraft API",
867
+ description: "API documentation generated by Servcraft",
868
+ version: "1.0.0",
869
+ tags: [
870
+ { name: "Auth", description: "Authentication endpoints" },
871
+ { name: "Users", description: "User management endpoints" },
872
+ { name: "Health", description: "Health check endpoints" }
873
+ ]
874
+ };
875
+ async function registerSwagger(app, customConfig) {
876
+ const swaggerConfig = { ...defaultConfig3, ...customConfig };
877
+ if (swaggerConfig.enabled === false) {
878
+ logger.info("Swagger documentation disabled");
879
+ return;
880
+ }
881
+ await app.register(swagger, {
882
+ openapi: {
883
+ openapi: "3.0.3",
884
+ info: {
885
+ title: swaggerConfig.title,
886
+ description: swaggerConfig.description,
887
+ version: swaggerConfig.version,
888
+ contact: swaggerConfig.contact,
889
+ license: swaggerConfig.license
890
+ },
891
+ servers: swaggerConfig.servers || [
892
+ {
893
+ url: `http://localhost:${config.server.port}`,
894
+ description: "Development server"
895
+ }
896
+ ],
897
+ tags: swaggerConfig.tags,
898
+ components: {
899
+ securitySchemes: {
900
+ bearerAuth: {
901
+ type: "http",
902
+ scheme: "bearer",
903
+ bearerFormat: "JWT",
904
+ description: "Enter your JWT token"
905
+ }
906
+ }
907
+ }
908
+ }
909
+ });
910
+ await app.register(swaggerUi, {
911
+ routePrefix: swaggerConfig.route || "/docs",
912
+ uiConfig: {
913
+ docExpansion: "list",
914
+ deepLinking: true,
915
+ displayRequestDuration: true,
916
+ filter: true,
917
+ showExtensions: true,
918
+ showCommonExtensions: true
919
+ },
920
+ staticCSP: true,
921
+ transformStaticCSP: (header) => header
922
+ });
923
+ logger.info("Swagger documentation registered at /docs");
924
+ }
925
+ var commonResponses = {
926
+ success: {
927
+ type: "object",
928
+ properties: {
929
+ success: { type: "boolean", example: true },
930
+ data: { type: "object" }
931
+ }
932
+ },
933
+ error: {
934
+ type: "object",
935
+ properties: {
936
+ success: { type: "boolean", example: false },
937
+ message: { type: "string" },
938
+ errors: {
939
+ type: "object",
940
+ additionalProperties: {
941
+ type: "array",
942
+ items: { type: "string" }
943
+ }
944
+ }
945
+ }
946
+ },
947
+ unauthorized: {
948
+ type: "object",
949
+ properties: {
950
+ success: { type: "boolean", example: false },
951
+ message: { type: "string", example: "Unauthorized" }
952
+ }
953
+ },
954
+ notFound: {
955
+ type: "object",
956
+ properties: {
957
+ success: { type: "boolean", example: false },
958
+ message: { type: "string", example: "Resource not found" }
959
+ }
960
+ },
961
+ paginated: {
962
+ type: "object",
963
+ properties: {
964
+ success: { type: "boolean", example: true },
965
+ data: {
966
+ type: "object",
967
+ properties: {
968
+ data: { type: "array", items: { type: "object" } },
969
+ meta: {
970
+ type: "object",
971
+ properties: {
972
+ total: { type: "number" },
973
+ page: { type: "number" },
974
+ limit: { type: "number" },
975
+ totalPages: { type: "number" },
976
+ hasNextPage: { type: "boolean" },
977
+ hasPrevPage: { type: "boolean" }
978
+ }
979
+ }
980
+ }
981
+ }
982
+ }
983
+ }
984
+ };
985
+ var paginationQuery = {
986
+ type: "object",
987
+ properties: {
988
+ page: { type: "integer", minimum: 1, default: 1, description: "Page number" },
989
+ limit: { type: "integer", minimum: 1, maximum: 100, default: 20, description: "Items per page" },
990
+ sortBy: { type: "string", description: "Field to sort by" },
991
+ sortOrder: { type: "string", enum: ["asc", "desc"], default: "asc", description: "Sort order" },
992
+ search: { type: "string", description: "Search query" }
993
+ }
994
+ };
995
+ var idParam = {
996
+ type: "object",
997
+ properties: {
998
+ id: { type: "string", format: "uuid", description: "Resource ID" }
999
+ },
1000
+ required: ["id"]
1001
+ };
1002
+
1003
+ // src/modules/auth/auth.routes.ts
1004
+ var credentialsBody = {
1005
+ type: "object",
1006
+ required: ["email", "password"],
1007
+ properties: {
1008
+ email: { type: "string", format: "email" },
1009
+ password: { type: "string", minLength: 8 }
1010
+ }
1011
+ };
1012
+ var changePasswordBody = {
1013
+ type: "object",
1014
+ required: ["currentPassword", "newPassword"],
1015
+ properties: {
1016
+ currentPassword: { type: "string", minLength: 8 },
1017
+ newPassword: { type: "string", minLength: 8 }
1018
+ }
1019
+ };
1020
+ function registerAuthRoutes(app, controller, authService) {
1021
+ const authenticate = createAuthMiddleware(authService);
1022
+ app.post("/auth/register", {
1023
+ schema: {
1024
+ tags: ["Auth"],
1025
+ summary: "Register a new user",
1026
+ body: credentialsBody,
1027
+ response: {
1028
+ 201: commonResponses.success,
1029
+ 400: commonResponses.error,
1030
+ 409: commonResponses.error
1031
+ }
1032
+ },
1033
+ handler: controller.register.bind(controller)
1034
+ });
1035
+ app.post("/auth/login", {
1036
+ schema: {
1037
+ tags: ["Auth"],
1038
+ summary: "Login and obtain tokens",
1039
+ body: credentialsBody,
1040
+ response: {
1041
+ 200: commonResponses.success,
1042
+ 400: commonResponses.error,
1043
+ 401: commonResponses.unauthorized
1044
+ }
1045
+ },
1046
+ handler: controller.login.bind(controller)
1047
+ });
1048
+ app.post("/auth/refresh", {
1049
+ schema: {
1050
+ tags: ["Auth"],
1051
+ summary: "Refresh access token",
1052
+ body: {
1053
+ type: "object",
1054
+ required: ["refreshToken"],
1055
+ properties: {
1056
+ refreshToken: { type: "string" }
1057
+ }
1058
+ },
1059
+ response: {
1060
+ 200: commonResponses.success,
1061
+ 401: commonResponses.unauthorized
1062
+ }
1063
+ },
1064
+ handler: controller.refresh.bind(controller)
1065
+ });
1066
+ app.post("/auth/logout", {
1067
+ preHandler: [authenticate],
1068
+ schema: {
1069
+ tags: ["Auth"],
1070
+ summary: "Logout current user",
1071
+ security: [{ bearerAuth: [] }],
1072
+ response: {
1073
+ 200: commonResponses.success,
1074
+ 401: commonResponses.unauthorized
1075
+ }
1076
+ },
1077
+ handler: controller.logout.bind(controller)
1078
+ });
1079
+ app.get("/auth/me", {
1080
+ preHandler: [authenticate],
1081
+ schema: {
1082
+ tags: ["Auth"],
1083
+ summary: "Get current user profile",
1084
+ security: [{ bearerAuth: [] }],
1085
+ response: {
1086
+ 200: commonResponses.success,
1087
+ 401: commonResponses.unauthorized
1088
+ }
1089
+ },
1090
+ handler: controller.me.bind(controller)
1091
+ });
1092
+ app.post("/auth/change-password", {
1093
+ preHandler: [authenticate],
1094
+ schema: {
1095
+ tags: ["Auth"],
1096
+ summary: "Change current user password",
1097
+ security: [{ bearerAuth: [] }],
1098
+ body: changePasswordBody,
1099
+ response: {
1100
+ 200: commonResponses.success,
1101
+ 400: commonResponses.error,
1102
+ 401: commonResponses.unauthorized
1103
+ }
1104
+ },
1105
+ handler: controller.changePassword.bind(controller)
1106
+ });
1107
+ }
1108
+
1109
+ // src/modules/user/user.repository.ts
1110
+ import { randomUUID } from "crypto";
1111
+
1112
+ // src/utils/pagination.ts
1113
+ var DEFAULT_PAGE = 1;
1114
+ var DEFAULT_LIMIT = 20;
1115
+ var MAX_LIMIT = 100;
1116
+ function parsePaginationParams(query) {
1117
+ const page = Math.max(1, parseInt(String(query.page || DEFAULT_PAGE), 10));
1118
+ const limit = Math.min(MAX_LIMIT, Math.max(1, parseInt(String(query.limit || DEFAULT_LIMIT), 10)));
1119
+ const sortBy = typeof query.sortBy === "string" ? query.sortBy : void 0;
1120
+ const sortOrder = query.sortOrder === "desc" ? "desc" : "asc";
1121
+ return { page, limit, sortBy, sortOrder };
1122
+ }
1123
+ function createPaginatedResult(data, total, params) {
1124
+ const totalPages = Math.ceil(total / params.limit);
1125
+ return {
1126
+ data,
1127
+ meta: {
1128
+ total,
1129
+ page: params.page,
1130
+ limit: params.limit,
1131
+ totalPages,
1132
+ hasNextPage: params.page < totalPages,
1133
+ hasPrevPage: params.page > 1
1134
+ }
1135
+ };
1136
+ }
1137
+ function getSkip(params) {
1138
+ return (params.page - 1) * params.limit;
1139
+ }
1140
+
1141
+ // src/modules/user/user.repository.ts
1142
+ var users = /* @__PURE__ */ new Map();
1143
+ var UserRepository = class {
1144
+ async findById(id) {
1145
+ return users.get(id) || null;
1146
+ }
1147
+ async findByEmail(email) {
1148
+ for (const user of users.values()) {
1149
+ if (user.email.toLowerCase() === email.toLowerCase()) {
1150
+ return user;
1151
+ }
1152
+ }
1153
+ return null;
1154
+ }
1155
+ async findMany(params, filters) {
1156
+ let filteredUsers = Array.from(users.values());
1157
+ if (filters) {
1158
+ if (filters.status) {
1159
+ filteredUsers = filteredUsers.filter((u) => u.status === filters.status);
1160
+ }
1161
+ if (filters.role) {
1162
+ filteredUsers = filteredUsers.filter((u) => u.role === filters.role);
1163
+ }
1164
+ if (filters.emailVerified !== void 0) {
1165
+ filteredUsers = filteredUsers.filter((u) => u.emailVerified === filters.emailVerified);
1166
+ }
1167
+ if (filters.search) {
1168
+ const search = filters.search.toLowerCase();
1169
+ filteredUsers = filteredUsers.filter(
1170
+ (u) => u.email.toLowerCase().includes(search) || u.name?.toLowerCase().includes(search)
1171
+ );
1172
+ }
1173
+ }
1174
+ if (params.sortBy) {
1175
+ const sortKey = params.sortBy;
1176
+ filteredUsers.sort((a, b) => {
1177
+ const aVal = a[sortKey];
1178
+ const bVal = b[sortKey];
1179
+ if (aVal === void 0 || bVal === void 0) return 0;
1180
+ if (aVal < bVal) return params.sortOrder === "desc" ? 1 : -1;
1181
+ if (aVal > bVal) return params.sortOrder === "desc" ? -1 : 1;
1182
+ return 0;
1183
+ });
1184
+ }
1185
+ const total = filteredUsers.length;
1186
+ const skip = getSkip(params);
1187
+ const data = filteredUsers.slice(skip, skip + params.limit);
1188
+ return createPaginatedResult(data, total, params);
1189
+ }
1190
+ async create(data) {
1191
+ const now = /* @__PURE__ */ new Date();
1192
+ const user = {
1193
+ id: randomUUID(),
1194
+ email: data.email,
1195
+ password: data.password,
1196
+ name: data.name,
1197
+ role: data.role || "user",
1198
+ status: "active",
1199
+ emailVerified: false,
1200
+ createdAt: now,
1201
+ updatedAt: now
1202
+ };
1203
+ users.set(user.id, user);
1204
+ return user;
1205
+ }
1206
+ async update(id, data) {
1207
+ const user = users.get(id);
1208
+ if (!user) return null;
1209
+ const updatedUser = {
1210
+ ...user,
1211
+ ...data,
1212
+ updatedAt: /* @__PURE__ */ new Date()
1213
+ };
1214
+ users.set(id, updatedUser);
1215
+ return updatedUser;
1216
+ }
1217
+ async updatePassword(id, password) {
1218
+ const user = users.get(id);
1219
+ if (!user) return null;
1220
+ const updatedUser = {
1221
+ ...user,
1222
+ password,
1223
+ updatedAt: /* @__PURE__ */ new Date()
1224
+ };
1225
+ users.set(id, updatedUser);
1226
+ return updatedUser;
1227
+ }
1228
+ async updateLastLogin(id) {
1229
+ const user = users.get(id);
1230
+ if (!user) return null;
1231
+ const updatedUser = {
1232
+ ...user,
1233
+ lastLoginAt: /* @__PURE__ */ new Date(),
1234
+ updatedAt: /* @__PURE__ */ new Date()
1235
+ };
1236
+ users.set(id, updatedUser);
1237
+ return updatedUser;
1238
+ }
1239
+ async delete(id) {
1240
+ return users.delete(id);
1241
+ }
1242
+ async count(filters) {
1243
+ let count = 0;
1244
+ for (const user of users.values()) {
1245
+ if (filters) {
1246
+ if (filters.status && user.status !== filters.status) continue;
1247
+ if (filters.role && user.role !== filters.role) continue;
1248
+ if (filters.emailVerified !== void 0 && user.emailVerified !== filters.emailVerified)
1249
+ continue;
1250
+ }
1251
+ count++;
1252
+ }
1253
+ return count;
1254
+ }
1255
+ // Helper to clear all users (for testing)
1256
+ async clear() {
1257
+ users.clear();
1258
+ }
1259
+ };
1260
+ function createUserRepository() {
1261
+ return new UserRepository();
1262
+ }
1263
+
1264
+ // src/modules/user/types.ts
1265
+ var DEFAULT_ROLE_PERMISSIONS = {
1266
+ user: ["profile:read", "profile:update"],
1267
+ moderator: [
1268
+ "profile:read",
1269
+ "profile:update",
1270
+ "users:read",
1271
+ "content:read",
1272
+ "content:update",
1273
+ "content:delete"
1274
+ ],
1275
+ admin: [
1276
+ "profile:read",
1277
+ "profile:update",
1278
+ "users:read",
1279
+ "users:update",
1280
+ "users:delete",
1281
+ "content:manage",
1282
+ "settings:read"
1283
+ ],
1284
+ super_admin: ["*:manage"]
1285
+ // All permissions
1286
+ };
1287
+
1288
+ // src/modules/user/user.service.ts
1289
+ var UserService = class {
1290
+ constructor(repository) {
1291
+ this.repository = repository;
1292
+ }
1293
+ async findById(id) {
1294
+ return this.repository.findById(id);
1295
+ }
1296
+ async findByEmail(email) {
1297
+ return this.repository.findByEmail(email);
1298
+ }
1299
+ async findMany(params, filters) {
1300
+ const result = await this.repository.findMany(params, filters);
1301
+ return {
1302
+ ...result,
1303
+ data: result.data.map(({ password, ...user }) => user)
1304
+ };
1305
+ }
1306
+ async create(data) {
1307
+ const existing = await this.repository.findByEmail(data.email);
1308
+ if (existing) {
1309
+ throw new ConflictError("User with this email already exists");
1310
+ }
1311
+ const user = await this.repository.create(data);
1312
+ logger.info({ userId: user.id, email: user.email }, "User created");
1313
+ return user;
1314
+ }
1315
+ async update(id, data) {
1316
+ const user = await this.repository.findById(id);
1317
+ if (!user) {
1318
+ throw new NotFoundError("User");
1319
+ }
1320
+ if (data.email && data.email !== user.email) {
1321
+ const existing = await this.repository.findByEmail(data.email);
1322
+ if (existing) {
1323
+ throw new ConflictError("Email already in use");
1324
+ }
1325
+ }
1326
+ const updatedUser = await this.repository.update(id, data);
1327
+ if (!updatedUser) {
1328
+ throw new NotFoundError("User");
1329
+ }
1330
+ logger.info({ userId: id }, "User updated");
1331
+ return updatedUser;
1332
+ }
1333
+ async updatePassword(id, hashedPassword) {
1334
+ const user = await this.repository.updatePassword(id, hashedPassword);
1335
+ if (!user) {
1336
+ throw new NotFoundError("User");
1337
+ }
1338
+ logger.info({ userId: id }, "User password updated");
1339
+ return user;
1340
+ }
1341
+ async updateLastLogin(id) {
1342
+ const user = await this.repository.updateLastLogin(id);
1343
+ if (!user) {
1344
+ throw new NotFoundError("User");
1345
+ }
1346
+ return user;
1347
+ }
1348
+ async delete(id) {
1349
+ const user = await this.repository.findById(id);
1350
+ if (!user) {
1351
+ throw new NotFoundError("User");
1352
+ }
1353
+ await this.repository.delete(id);
1354
+ logger.info({ userId: id }, "User deleted");
1355
+ }
1356
+ async suspend(id) {
1357
+ return this.update(id, { status: "suspended" });
1358
+ }
1359
+ async ban(id) {
1360
+ return this.update(id, { status: "banned" });
1361
+ }
1362
+ async activate(id) {
1363
+ return this.update(id, { status: "active" });
1364
+ }
1365
+ async verifyEmail(id) {
1366
+ return this.update(id, { emailVerified: true });
1367
+ }
1368
+ async changeRole(id, role) {
1369
+ return this.update(id, { role });
1370
+ }
1371
+ // RBAC helpers
1372
+ hasPermission(role, permission) {
1373
+ const permissions = DEFAULT_ROLE_PERMISSIONS[role] || [];
1374
+ if (permissions.includes("*:manage")) {
1375
+ return true;
1376
+ }
1377
+ if (permissions.includes(permission)) {
1378
+ return true;
1379
+ }
1380
+ const [resource, action] = permission.split(":");
1381
+ const managePermission = `${resource}:manage`;
1382
+ if (permissions.includes(managePermission)) {
1383
+ return true;
1384
+ }
1385
+ return false;
1386
+ }
1387
+ getPermissions(role) {
1388
+ return DEFAULT_ROLE_PERMISSIONS[role] || [];
1389
+ }
1390
+ };
1391
+ function createUserService(repository) {
1392
+ return new UserService(repository || createUserRepository());
1393
+ }
1394
+
1395
+ // src/modules/auth/index.ts
1396
+ async function registerAuthModule(app) {
1397
+ await app.register(jwt, {
1398
+ secret: config.jwt.secret,
1399
+ sign: {
1400
+ algorithm: "HS256"
1401
+ }
1402
+ });
1403
+ await app.register(cookie, {
1404
+ secret: config.jwt.secret,
1405
+ hook: "onRequest"
1406
+ });
1407
+ const authService = createAuthService(app);
1408
+ const userService = createUserService();
1409
+ const authController = createAuthController(authService, userService);
1410
+ registerAuthRoutes(app, authController, authService);
1411
+ logger.info("Auth module registered");
1412
+ return authService;
1413
+ }
1414
+
1415
+ // src/modules/user/schemas.ts
1416
+ import { z as z4 } from "zod";
1417
+ var userStatusEnum = z4.enum(["active", "inactive", "suspended", "banned"]);
1418
+ var userRoleEnum = z4.enum(["user", "admin", "moderator", "super_admin"]);
1419
+ var createUserSchema = z4.object({
1420
+ email: z4.string().email("Invalid email address"),
1421
+ password: z4.string().min(8, "Password must be at least 8 characters").regex(/[A-Z]/, "Password must contain at least one uppercase letter").regex(/[a-z]/, "Password must contain at least one lowercase letter").regex(/[0-9]/, "Password must contain at least one number"),
1422
+ name: z4.string().min(2, "Name must be at least 2 characters").optional(),
1423
+ role: userRoleEnum.optional().default("user")
1424
+ });
1425
+ var updateUserSchema = z4.object({
1426
+ email: z4.string().email("Invalid email address").optional(),
1427
+ name: z4.string().min(2, "Name must be at least 2 characters").optional(),
1428
+ role: userRoleEnum.optional(),
1429
+ status: userStatusEnum.optional(),
1430
+ emailVerified: z4.boolean().optional(),
1431
+ metadata: z4.record(z4.unknown()).optional()
1432
+ });
1433
+ var updateProfileSchema = z4.object({
1434
+ name: z4.string().min(2, "Name must be at least 2 characters").optional(),
1435
+ metadata: z4.record(z4.unknown()).optional()
1436
+ });
1437
+ var userQuerySchema = z4.object({
1438
+ page: z4.string().transform(Number).optional(),
1439
+ limit: z4.string().transform(Number).optional(),
1440
+ sortBy: z4.string().optional(),
1441
+ sortOrder: z4.enum(["asc", "desc"]).optional(),
1442
+ status: userStatusEnum.optional(),
1443
+ role: userRoleEnum.optional(),
1444
+ search: z4.string().optional(),
1445
+ emailVerified: z4.string().transform((val) => val === "true").optional()
1446
+ });
1447
+
1448
+ // src/modules/user/user.controller.ts
1449
+ var UserController = class {
1450
+ constructor(userService) {
1451
+ this.userService = userService;
1452
+ }
1453
+ async list(request, reply) {
1454
+ const query = validateQuery(userQuerySchema, request.query);
1455
+ const pagination = parsePaginationParams(query);
1456
+ const filters = {
1457
+ status: query.status,
1458
+ role: query.role,
1459
+ search: query.search,
1460
+ emailVerified: query.emailVerified
1461
+ };
1462
+ const result = await this.userService.findMany(pagination, filters);
1463
+ success(reply, result);
1464
+ }
1465
+ async getById(request, reply) {
1466
+ const user = await this.userService.findById(request.params.id);
1467
+ if (!user) {
1468
+ return reply.status(404).send({
1469
+ success: false,
1470
+ message: "User not found"
1471
+ });
1472
+ }
1473
+ const { password, ...userData } = user;
1474
+ success(reply, userData);
1475
+ }
1476
+ async update(request, reply) {
1477
+ const data = validateBody(updateUserSchema, request.body);
1478
+ const user = await this.userService.update(request.params.id, data);
1479
+ const { password, ...userData } = user;
1480
+ success(reply, userData);
1481
+ }
1482
+ async delete(request, reply) {
1483
+ const authRequest = request;
1484
+ if (authRequest.user.id === request.params.id) {
1485
+ throw new ForbiddenError("Cannot delete your own account");
1486
+ }
1487
+ await this.userService.delete(request.params.id);
1488
+ noContent(reply);
1489
+ }
1490
+ async suspend(request, reply) {
1491
+ const authRequest = request;
1492
+ if (authRequest.user.id === request.params.id) {
1493
+ throw new ForbiddenError("Cannot suspend your own account");
1494
+ }
1495
+ const user = await this.userService.suspend(request.params.id);
1496
+ const { password, ...userData } = user;
1497
+ success(reply, userData);
1498
+ }
1499
+ async ban(request, reply) {
1500
+ const authRequest = request;
1501
+ if (authRequest.user.id === request.params.id) {
1502
+ throw new ForbiddenError("Cannot ban your own account");
1503
+ }
1504
+ const user = await this.userService.ban(request.params.id);
1505
+ const { password, ...userData } = user;
1506
+ success(reply, userData);
1507
+ }
1508
+ async activate(request, reply) {
1509
+ const user = await this.userService.activate(request.params.id);
1510
+ const { password, ...userData } = user;
1511
+ success(reply, userData);
1512
+ }
1513
+ // Profile routes (for authenticated user)
1514
+ async getProfile(request, reply) {
1515
+ const authRequest = request;
1516
+ const user = await this.userService.findById(authRequest.user.id);
1517
+ if (!user) {
1518
+ return reply.status(404).send({
1519
+ success: false,
1520
+ message: "User not found"
1521
+ });
1522
+ }
1523
+ const { password, ...userData } = user;
1524
+ success(reply, userData);
1525
+ }
1526
+ async updateProfile(request, reply) {
1527
+ const authRequest = request;
1528
+ const data = validateBody(updateProfileSchema, request.body);
1529
+ const user = await this.userService.update(authRequest.user.id, data);
1530
+ const { password, ...userData } = user;
1531
+ success(reply, userData);
1532
+ }
1533
+ };
1534
+ function createUserController(userService) {
1535
+ return new UserController(userService);
1536
+ }
1537
+
1538
+ // src/modules/user/user.routes.ts
1539
+ var userTag = "Users";
1540
+ var userResponse = {
1541
+ type: "object",
1542
+ properties: {
1543
+ success: { type: "boolean", example: true },
1544
+ data: { type: "object" }
1545
+ }
1546
+ };
1547
+ function registerUserRoutes(app, controller, authService) {
1548
+ const authenticate = createAuthMiddleware(authService);
1549
+ const isAdmin = createRoleMiddleware(["admin", "super_admin"]);
1550
+ const isModerator = createRoleMiddleware(["moderator", "admin", "super_admin"]);
1551
+ app.get(
1552
+ "/profile",
1553
+ {
1554
+ preHandler: [authenticate],
1555
+ schema: {
1556
+ tags: [userTag],
1557
+ summary: "Get current user profile",
1558
+ security: [{ bearerAuth: [] }],
1559
+ response: {
1560
+ 200: userResponse,
1561
+ 401: commonResponses.unauthorized
1562
+ }
1563
+ }
1564
+ },
1565
+ controller.getProfile.bind(controller)
1566
+ );
1567
+ app.patch(
1568
+ "/profile",
1569
+ {
1570
+ preHandler: [authenticate],
1571
+ schema: {
1572
+ tags: [userTag],
1573
+ summary: "Update current user profile",
1574
+ security: [{ bearerAuth: [] }],
1575
+ body: { type: "object" },
1576
+ response: {
1577
+ 200: userResponse,
1578
+ 401: commonResponses.unauthorized,
1579
+ 400: commonResponses.error
1580
+ }
1581
+ }
1582
+ },
1583
+ controller.updateProfile.bind(controller)
1584
+ );
1585
+ app.get(
1586
+ "/users",
1587
+ {
1588
+ preHandler: [authenticate, isModerator],
1589
+ schema: {
1590
+ tags: [userTag],
1591
+ summary: "List users",
1592
+ security: [{ bearerAuth: [] }],
1593
+ querystring: {
1594
+ ...paginationQuery,
1595
+ properties: {
1596
+ ...paginationQuery.properties,
1597
+ status: { type: "string", enum: ["active", "inactive", "suspended", "banned"] },
1598
+ role: { type: "string", enum: ["user", "admin", "moderator", "super_admin"] },
1599
+ search: { type: "string" },
1600
+ emailVerified: { type: "boolean" }
1601
+ }
1602
+ },
1603
+ response: {
1604
+ 200: commonResponses.paginated,
1605
+ 401: commonResponses.unauthorized
1606
+ }
1607
+ }
1608
+ },
1609
+ controller.list.bind(controller)
1610
+ );
1611
+ app.get(
1612
+ "/users/:id",
1613
+ {
1614
+ preHandler: [authenticate, isModerator],
1615
+ schema: {
1616
+ tags: [userTag],
1617
+ summary: "Get user by id",
1618
+ security: [{ bearerAuth: [] }],
1619
+ params: idParam,
1620
+ response: {
1621
+ 200: userResponse,
1622
+ 401: commonResponses.unauthorized,
1623
+ 404: commonResponses.notFound
1624
+ }
1625
+ }
1626
+ },
1627
+ controller.getById.bind(controller)
1628
+ );
1629
+ app.patch(
1630
+ "/users/:id",
1631
+ {
1632
+ preHandler: [authenticate, isAdmin],
1633
+ schema: {
1634
+ tags: [userTag],
1635
+ summary: "Update user",
1636
+ security: [{ bearerAuth: [] }],
1637
+ params: idParam,
1638
+ body: { type: "object" },
1639
+ response: {
1640
+ 200: userResponse,
1641
+ 401: commonResponses.unauthorized,
1642
+ 404: commonResponses.notFound
1643
+ }
1644
+ }
1645
+ },
1646
+ controller.update.bind(controller)
1647
+ );
1648
+ app.delete(
1649
+ "/users/:id",
1650
+ {
1651
+ preHandler: [authenticate, isAdmin],
1652
+ schema: {
1653
+ tags: [userTag],
1654
+ summary: "Delete user",
1655
+ security: [{ bearerAuth: [] }],
1656
+ params: idParam,
1657
+ response: {
1658
+ 204: { description: "User deleted" },
1659
+ 401: commonResponses.unauthorized,
1660
+ 404: commonResponses.notFound
1661
+ }
1662
+ }
1663
+ },
1664
+ controller.delete.bind(controller)
1665
+ );
1666
+ app.post(
1667
+ "/users/:id/suspend",
1668
+ {
1669
+ preHandler: [authenticate, isAdmin],
1670
+ schema: {
1671
+ tags: [userTag],
1672
+ summary: "Suspend user",
1673
+ security: [{ bearerAuth: [] }],
1674
+ params: idParam,
1675
+ response: {
1676
+ 200: userResponse,
1677
+ 401: commonResponses.unauthorized,
1678
+ 404: commonResponses.notFound
1679
+ }
1680
+ }
1681
+ },
1682
+ controller.suspend.bind(controller)
1683
+ );
1684
+ app.post(
1685
+ "/users/:id/ban",
1686
+ {
1687
+ preHandler: [authenticate, isAdmin],
1688
+ schema: {
1689
+ tags: [userTag],
1690
+ summary: "Ban user",
1691
+ security: [{ bearerAuth: [] }],
1692
+ params: idParam,
1693
+ response: {
1694
+ 200: userResponse,
1695
+ 401: commonResponses.unauthorized,
1696
+ 404: commonResponses.notFound
1697
+ }
1698
+ }
1699
+ },
1700
+ controller.ban.bind(controller)
1701
+ );
1702
+ app.post(
1703
+ "/users/:id/activate",
1704
+ {
1705
+ preHandler: [authenticate, isAdmin],
1706
+ schema: {
1707
+ tags: [userTag],
1708
+ summary: "Activate user",
1709
+ security: [{ bearerAuth: [] }],
1710
+ params: idParam,
1711
+ response: {
1712
+ 200: userResponse,
1713
+ 401: commonResponses.unauthorized,
1714
+ 404: commonResponses.notFound
1715
+ }
1716
+ }
1717
+ },
1718
+ controller.activate.bind(controller)
1719
+ );
1720
+ }
1721
+
1722
+ // src/modules/user/index.ts
1723
+ async function registerUserModule(app, authService) {
1724
+ const repository = createUserRepository();
1725
+ const userService = createUserService(repository);
1726
+ const userController = createUserController(userService);
1727
+ registerUserRoutes(app, userController, authService);
1728
+ logger.info("User module registered");
1729
+ }
1730
+
1731
+ // src/modules/email/email.service.ts
1732
+ import nodemailer from "nodemailer";
1733
+
1734
+ // src/modules/email/templates.ts
1735
+ import Handlebars from "handlebars";
1736
+ var baseLayout = `
1737
+ <!DOCTYPE html>
1738
+ <html lang="en">
1739
+ <head>
1740
+ <meta charset="UTF-8">
1741
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
1742
+ <title>{{subject}}</title>
1743
+ <style>
1744
+ body {
1745
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
1746
+ line-height: 1.6;
1747
+ color: #333;
1748
+ max-width: 600px;
1749
+ margin: 0 auto;
1750
+ padding: 20px;
1751
+ background-color: #f5f5f5;
1752
+ }
1753
+ .container {
1754
+ background-color: #ffffff;
1755
+ border-radius: 8px;
1756
+ padding: 40px;
1757
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
1758
+ }
1759
+ .header {
1760
+ text-align: center;
1761
+ margin-bottom: 30px;
1762
+ }
1763
+ .logo {
1764
+ font-size: 24px;
1765
+ font-weight: bold;
1766
+ color: #2563eb;
1767
+ }
1768
+ .content {
1769
+ margin-bottom: 30px;
1770
+ }
1771
+ .button {
1772
+ display: inline-block;
1773
+ padding: 12px 24px;
1774
+ background-color: #2563eb;
1775
+ color: #ffffff !important;
1776
+ text-decoration: none;
1777
+ border-radius: 6px;
1778
+ font-weight: 500;
1779
+ }
1780
+ .button:hover {
1781
+ background-color: #1d4ed8;
1782
+ }
1783
+ .footer {
1784
+ text-align: center;
1785
+ font-size: 12px;
1786
+ color: #666;
1787
+ margin-top: 30px;
1788
+ padding-top: 20px;
1789
+ border-top: 1px solid #eee;
1790
+ }
1791
+ .warning {
1792
+ background-color: #fef3c7;
1793
+ border: 1px solid #f59e0b;
1794
+ border-radius: 6px;
1795
+ padding: 12px;
1796
+ margin: 20px 0;
1797
+ }
1798
+ </style>
1799
+ </head>
1800
+ <body>
1801
+ <div class="container">
1802
+ <div class="header">
1803
+ <div class="logo">{{appName}}</div>
1804
+ </div>
1805
+ <div class="content">
1806
+ {{{body}}}
1807
+ </div>
1808
+ <div class="footer">
1809
+ <p>&copy; {{year}} {{appName}}. All rights reserved.</p>
1810
+ <p>This email was sent to {{userEmail}}</p>
1811
+ </div>
1812
+ </div>
1813
+ </body>
1814
+ </html>
1815
+ `;
1816
+ var templates = {
1817
+ welcome: `
1818
+ <h2>Welcome to {{appName}}!</h2>
1819
+ <p>Hi {{userName}},</p>
1820
+ <p>Thank you for joining {{appName}}. We're excited to have you on board!</p>
1821
+ <p>To get started, please verify your email address by clicking the button below:</p>
1822
+ <p style="text-align: center; margin: 30px 0;">
1823
+ <a href="{{actionUrl}}" class="button">Verify Email</a>
1824
+ </p>
1825
+ <p>If you didn't create an account with us, you can safely ignore this email.</p>
1826
+ `,
1827
+ "verify-email": `
1828
+ <h2>Verify Your Email</h2>
1829
+ <p>Hi {{userName}},</p>
1830
+ <p>Please verify your email address by clicking the button below:</p>
1831
+ <p style="text-align: center; margin: 30px 0;">
1832
+ <a href="{{actionUrl}}" class="button">Verify Email</a>
1833
+ </p>
1834
+ <p>This link will expire in {{expiresIn}}.</p>
1835
+ <p>If you didn't request this verification, you can safely ignore this email.</p>
1836
+ `,
1837
+ "password-reset": `
1838
+ <h2>Reset Your Password</h2>
1839
+ <p>Hi {{userName}},</p>
1840
+ <p>We received a request to reset your password. Click the button below to create a new password:</p>
1841
+ <p style="text-align: center; margin: 30px 0;">
1842
+ <a href="{{actionUrl}}" class="button">Reset Password</a>
1843
+ </p>
1844
+ <p>This link will expire in {{expiresIn}}.</p>
1845
+ <div class="warning">
1846
+ <strong>Security Notice:</strong> If you didn't request this password reset, please ignore this email and your password will remain unchanged.
1847
+ </div>
1848
+ `,
1849
+ "password-changed": `
1850
+ <h2>Password Changed</h2>
1851
+ <p>Hi {{userName}},</p>
1852
+ <p>Your password has been successfully changed.</p>
1853
+ <p>If you didn't make this change, please contact our support team immediately and secure your account.</p>
1854
+ <div class="warning">
1855
+ <strong>Details:</strong><br>
1856
+ Time: {{timestamp}}<br>
1857
+ IP Address: {{ipAddress}}<br>
1858
+ Device: {{userAgent}}
1859
+ </div>
1860
+ `,
1861
+ "login-alert": `
1862
+ <h2>New Login Detected</h2>
1863
+ <p>Hi {{userName}},</p>
1864
+ <p>We detected a new login to your account.</p>
1865
+ <div class="warning">
1866
+ <strong>Login Details:</strong><br>
1867
+ Time: {{timestamp}}<br>
1868
+ IP Address: {{ipAddress}}<br>
1869
+ Device: {{userAgent}}<br>
1870
+ Location: {{location}}
1871
+ </div>
1872
+ <p>If this was you, you can safely ignore this email.</p>
1873
+ <p>If you didn't log in, please change your password immediately and contact support.</p>
1874
+ `,
1875
+ "account-suspended": `
1876
+ <h2>Account Suspended</h2>
1877
+ <p>Hi {{userName}},</p>
1878
+ <p>Your account has been suspended due to: {{reason}}</p>
1879
+ <p>If you believe this is a mistake, please contact our support team.</p>
1880
+ `
1881
+ };
1882
+ var compiledLayout = Handlebars.compile(baseLayout);
1883
+ var compiledTemplates = {};
1884
+ for (const [name, template] of Object.entries(templates)) {
1885
+ compiledTemplates[name] = Handlebars.compile(template);
1886
+ }
1887
+ function renderTemplate(templateName, data) {
1888
+ const template = compiledTemplates[templateName];
1889
+ if (!template) {
1890
+ throw new Error(`Template "${templateName}" not found`);
1891
+ }
1892
+ const body = template(data);
1893
+ return compiledLayout({
1894
+ ...data,
1895
+ body,
1896
+ year: (/* @__PURE__ */ new Date()).getFullYear(),
1897
+ appName: data.appName || "Servcraft"
1898
+ });
1899
+ }
1900
+ function renderCustomTemplate(htmlTemplate, data) {
1901
+ const template = Handlebars.compile(htmlTemplate);
1902
+ const body = template(data);
1903
+ return compiledLayout({
1904
+ ...data,
1905
+ body,
1906
+ year: (/* @__PURE__ */ new Date()).getFullYear(),
1907
+ appName: data.appName || "Servcraft"
1908
+ });
1909
+ }
1910
+ Handlebars.registerHelper("formatDate", (date) => {
1911
+ return new Date(date).toLocaleDateString("en-US", {
1912
+ year: "numeric",
1913
+ month: "long",
1914
+ day: "numeric",
1915
+ hour: "2-digit",
1916
+ minute: "2-digit"
1917
+ });
1918
+ });
1919
+ Handlebars.registerHelper("eq", (a, b) => a === b);
1920
+ Handlebars.registerHelper("ne", (a, b) => a !== b);
1921
+
1922
+ // src/modules/email/email.service.ts
1923
+ var EmailService = class {
1924
+ transporter = null;
1925
+ config = null;
1926
+ constructor(emailConfig) {
1927
+ if (emailConfig?.host || config.email.host) {
1928
+ this.config = {
1929
+ host: emailConfig?.host || config.email.host || "",
1930
+ port: emailConfig?.port || config.email.port || 587,
1931
+ secure: (emailConfig?.port || config.email.port || 587) === 465,
1932
+ auth: {
1933
+ user: emailConfig?.auth?.user || config.email.user || "",
1934
+ pass: emailConfig?.auth?.pass || config.email.pass || ""
1935
+ },
1936
+ from: emailConfig?.from || config.email.from || "noreply@localhost"
1937
+ };
1938
+ this.transporter = nodemailer.createTransport({
1939
+ host: this.config.host,
1940
+ port: this.config.port,
1941
+ secure: this.config.secure,
1942
+ auth: {
1943
+ user: this.config.auth.user,
1944
+ pass: this.config.auth.pass
1945
+ }
1946
+ });
1947
+ logger.info("Email service initialized");
1948
+ } else {
1949
+ logger.warn("Email service not configured - emails will be logged only");
1950
+ }
1951
+ }
1952
+ async send(options) {
1953
+ try {
1954
+ let html = options.html;
1955
+ let text = options.text;
1956
+ if (options.template && options.data) {
1957
+ html = renderTemplate(options.template, options.data);
1958
+ }
1959
+ if (html && !text) {
1960
+ text = this.htmlToText(html);
1961
+ }
1962
+ const mailOptions = {
1963
+ from: this.config?.from || "noreply@localhost",
1964
+ to: Array.isArray(options.to) ? options.to.join(", ") : options.to,
1965
+ subject: options.subject,
1966
+ html,
1967
+ text,
1968
+ replyTo: options.replyTo,
1969
+ cc: options.cc,
1970
+ bcc: options.bcc,
1971
+ attachments: options.attachments
1972
+ };
1973
+ if (!this.transporter) {
1974
+ logger.info({ email: mailOptions }, "Email would be sent (no transporter configured)");
1975
+ return { success: true, messageId: "dev-mode" };
1976
+ }
1977
+ const result = await this.transporter.sendMail(mailOptions);
1978
+ logger.info(
1979
+ { messageId: result.messageId, to: options.to },
1980
+ "Email sent successfully"
1981
+ );
1982
+ return {
1983
+ success: true,
1984
+ messageId: result.messageId
1985
+ };
1986
+ } catch (error2) {
1987
+ const errorMessage = error2 instanceof Error ? error2.message : "Unknown error";
1988
+ logger.error({ err: error2, to: options.to }, "Failed to send email");
1989
+ return {
1990
+ success: false,
1991
+ error: errorMessage
1992
+ };
1993
+ }
1994
+ }
1995
+ async sendTemplate(to, template, data) {
1996
+ const subjects = {
1997
+ welcome: `Welcome to ${data.appName || "Servcraft"}!`,
1998
+ "verify-email": "Verify Your Email",
1999
+ "password-reset": "Reset Your Password",
2000
+ "password-changed": "Password Changed Successfully",
2001
+ "login-alert": "New Login Detected",
2002
+ "account-suspended": "Account Suspended"
2003
+ };
2004
+ return this.send({
2005
+ to,
2006
+ subject: subjects[template] || "Notification",
2007
+ template,
2008
+ data
2009
+ });
2010
+ }
2011
+ async sendWelcome(email, name, verifyUrl) {
2012
+ return this.sendTemplate(email, "welcome", {
2013
+ userName: name,
2014
+ userEmail: email,
2015
+ actionUrl: verifyUrl
2016
+ });
2017
+ }
2018
+ async sendVerifyEmail(email, name, verifyUrl) {
2019
+ return this.sendTemplate(email, "verify-email", {
2020
+ userName: name,
2021
+ userEmail: email,
2022
+ actionUrl: verifyUrl,
2023
+ expiresIn: "24 hours"
2024
+ });
2025
+ }
2026
+ async sendPasswordReset(email, name, resetUrl) {
2027
+ return this.sendTemplate(email, "password-reset", {
2028
+ userName: name,
2029
+ userEmail: email,
2030
+ actionUrl: resetUrl,
2031
+ expiresIn: "1 hour"
2032
+ });
2033
+ }
2034
+ async sendPasswordChanged(email, name, ipAddress, userAgent) {
2035
+ return this.sendTemplate(email, "password-changed", {
2036
+ userName: name,
2037
+ userEmail: email,
2038
+ ipAddress: ipAddress || "Unknown",
2039
+ userAgent: userAgent || "Unknown",
2040
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2041
+ });
2042
+ }
2043
+ async sendLoginAlert(email, name, ipAddress, userAgent, location) {
2044
+ return this.sendTemplate(email, "login-alert", {
2045
+ userName: name,
2046
+ userEmail: email,
2047
+ ipAddress,
2048
+ userAgent,
2049
+ location: location || "Unknown",
2050
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
2051
+ });
2052
+ }
2053
+ async verify() {
2054
+ if (!this.transporter) {
2055
+ return false;
2056
+ }
2057
+ try {
2058
+ await this.transporter.verify();
2059
+ logger.info("Email service connection verified");
2060
+ return true;
2061
+ } catch (error2) {
2062
+ logger.error({ err: error2 }, "Email service connection failed");
2063
+ return false;
2064
+ }
2065
+ }
2066
+ htmlToText(html) {
2067
+ return html.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "").replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim();
2068
+ }
2069
+ };
2070
+ var emailService = null;
2071
+ function getEmailService() {
2072
+ if (!emailService) {
2073
+ emailService = new EmailService();
2074
+ }
2075
+ return emailService;
2076
+ }
2077
+ function createEmailService(config2) {
2078
+ return new EmailService(config2);
2079
+ }
2080
+
2081
+ // src/modules/audit/audit.service.ts
2082
+ import { randomUUID as randomUUID2 } from "crypto";
2083
+ var auditLogs = /* @__PURE__ */ new Map();
2084
+ var AuditService = class {
2085
+ async log(entry) {
2086
+ const id = randomUUID2();
2087
+ const auditEntry = {
2088
+ ...entry,
2089
+ id,
2090
+ createdAt: /* @__PURE__ */ new Date()
2091
+ };
2092
+ auditLogs.set(id, auditEntry);
2093
+ logger.info(
2094
+ {
2095
+ audit: true,
2096
+ userId: entry.userId,
2097
+ action: entry.action,
2098
+ resource: entry.resource,
2099
+ resourceId: entry.resourceId,
2100
+ ipAddress: entry.ipAddress
2101
+ },
2102
+ `Audit: ${entry.action} on ${entry.resource}`
2103
+ );
2104
+ }
2105
+ async query(params) {
2106
+ const { page = 1, limit = 20 } = params;
2107
+ let logs = Array.from(auditLogs.values());
2108
+ if (params.userId) {
2109
+ logs = logs.filter((log) => log.userId === params.userId);
2110
+ }
2111
+ if (params.action) {
2112
+ logs = logs.filter((log) => log.action === params.action);
2113
+ }
2114
+ if (params.resource) {
2115
+ logs = logs.filter((log) => log.resource === params.resource);
2116
+ }
2117
+ if (params.resourceId) {
2118
+ logs = logs.filter((log) => log.resourceId === params.resourceId);
2119
+ }
2120
+ if (params.startDate) {
2121
+ logs = logs.filter((log) => log.createdAt >= params.startDate);
2122
+ }
2123
+ if (params.endDate) {
2124
+ logs = logs.filter((log) => log.createdAt <= params.endDate);
2125
+ }
2126
+ logs.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
2127
+ const total = logs.length;
2128
+ const skip = (page - 1) * limit;
2129
+ const data = logs.slice(skip, skip + limit);
2130
+ return createPaginatedResult(data, total, { page, limit });
2131
+ }
2132
+ async findByUser(userId, limit = 50) {
2133
+ const result = await this.query({ userId, limit });
2134
+ return result.data;
2135
+ }
2136
+ async findByResource(resource, resourceId, limit = 50) {
2137
+ const result = await this.query({ resource, resourceId, limit });
2138
+ return result.data;
2139
+ }
2140
+ // Shortcut methods for common audit events
2141
+ async logCreate(resource, resourceId, userId, newValue, meta) {
2142
+ await this.log({
2143
+ action: "create",
2144
+ resource,
2145
+ resourceId,
2146
+ userId,
2147
+ newValue,
2148
+ ...meta
2149
+ });
2150
+ }
2151
+ async logUpdate(resource, resourceId, userId, oldValue, newValue, meta) {
2152
+ await this.log({
2153
+ action: "update",
2154
+ resource,
2155
+ resourceId,
2156
+ userId,
2157
+ oldValue,
2158
+ newValue,
2159
+ ...meta
2160
+ });
2161
+ }
2162
+ async logDelete(resource, resourceId, userId, oldValue, meta) {
2163
+ await this.log({
2164
+ action: "delete",
2165
+ resource,
2166
+ resourceId,
2167
+ userId,
2168
+ oldValue,
2169
+ ...meta
2170
+ });
2171
+ }
2172
+ async logLogin(userId, meta) {
2173
+ await this.log({
2174
+ action: "login",
2175
+ resource: "auth",
2176
+ userId,
2177
+ ...meta
2178
+ });
2179
+ }
2180
+ async logLogout(userId, meta) {
2181
+ await this.log({
2182
+ action: "logout",
2183
+ resource: "auth",
2184
+ userId,
2185
+ ...meta
2186
+ });
2187
+ }
2188
+ async logPasswordChange(userId, meta) {
2189
+ await this.log({
2190
+ action: "password_change",
2191
+ resource: "auth",
2192
+ userId,
2193
+ ...meta
2194
+ });
2195
+ }
2196
+ // Clear all logs (for testing)
2197
+ async clear() {
2198
+ auditLogs.clear();
2199
+ }
2200
+ };
2201
+ var auditService = null;
2202
+ function getAuditService() {
2203
+ if (!auditService) {
2204
+ auditService = new AuditService();
2205
+ }
2206
+ return auditService;
2207
+ }
2208
+ function createAuditService() {
2209
+ return new AuditService();
2210
+ }
2211
+
2212
+ // src/index.ts
2213
+ async function bootstrap() {
2214
+ const server = createServer({
2215
+ port: config.server.port,
2216
+ host: config.server.host
2217
+ });
2218
+ const app = server.instance;
2219
+ registerErrorHandler(app);
2220
+ await registerSecurity(app);
2221
+ await registerSwagger(app, {
2222
+ enabled: config.swagger.enabled,
2223
+ route: config.swagger.route,
2224
+ title: config.swagger.title,
2225
+ description: config.swagger.description,
2226
+ version: config.swagger.version
2227
+ });
2228
+ const authService = await registerAuthModule(app);
2229
+ await registerUserModule(app, authService);
2230
+ await server.start();
2231
+ logger.info({
2232
+ env: config.env.NODE_ENV,
2233
+ port: config.server.port
2234
+ }, "Servcraft server started");
2235
+ }
2236
+ bootstrap().catch((err) => {
2237
+ logger.error({ err }, "Failed to start server");
2238
+ process.exit(1);
2239
+ });
2240
+ export {
2241
+ AppError,
2242
+ AuditService,
2243
+ AuthController,
2244
+ AuthService,
2245
+ BadRequestError,
2246
+ ConflictError,
2247
+ DEFAULT_LIMIT,
2248
+ DEFAULT_PAGE,
2249
+ DEFAULT_ROLE_PERMISSIONS,
2250
+ EmailService,
2251
+ ForbiddenError,
2252
+ MAX_LIMIT,
2253
+ NotFoundError,
2254
+ Server,
2255
+ TooManyRequestsError,
2256
+ UnauthorizedError,
2257
+ UserController,
2258
+ UserRepository,
2259
+ UserService,
2260
+ ValidationError,
2261
+ badRequest,
2262
+ changePasswordSchema,
2263
+ config,
2264
+ conflict,
2265
+ createAuditService,
2266
+ createAuthController,
2267
+ createAuthMiddleware,
2268
+ createAuthService,
2269
+ createConfig,
2270
+ createEmailService,
2271
+ createLogger,
2272
+ createOptionalAuthMiddleware,
2273
+ createPaginatedResult,
2274
+ createPermissionMiddleware,
2275
+ createRoleMiddleware,
2276
+ createServer,
2277
+ createUserController,
2278
+ createUserRepository,
2279
+ createUserSchema,
2280
+ createUserService,
2281
+ created,
2282
+ dateSchema,
2283
+ emailSchema,
2284
+ env,
2285
+ error,
2286
+ forbidden,
2287
+ futureDateSchema,
2288
+ getAuditService,
2289
+ getEmailService,
2290
+ getSkip,
2291
+ idParamSchema,
2292
+ internalError,
2293
+ isAppError,
2294
+ isDevelopment,
2295
+ isProduction,
2296
+ isStaging,
2297
+ isTest,
2298
+ logger,
2299
+ loginSchema,
2300
+ noContent,
2301
+ notFound,
2302
+ paginationSchema,
2303
+ parsePaginationParams,
2304
+ passwordResetConfirmSchema,
2305
+ passwordResetRequestSchema,
2306
+ passwordSchema,
2307
+ pastDateSchema,
2308
+ phoneSchema,
2309
+ refreshTokenSchema,
2310
+ registerAuthModule,
2311
+ registerBruteForceProtection,
2312
+ registerErrorHandler,
2313
+ registerSchema,
2314
+ registerSecurity,
2315
+ registerUserModule,
2316
+ renderCustomTemplate,
2317
+ renderTemplate,
2318
+ searchSchema,
2319
+ success,
2320
+ unauthorized,
2321
+ updateProfileSchema,
2322
+ updateUserSchema,
2323
+ urlSchema,
2324
+ userQuerySchema,
2325
+ userRoleEnum,
2326
+ userStatusEnum,
2327
+ validate,
2328
+ validateBody,
2329
+ validateParams,
2330
+ validateQuery
2331
+ };
2332
+ //# sourceMappingURL=index.js.map