arkos 1.4.1-canary.8 → 1.5.0-canary.2

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 (126) hide show
  1. package/dist/cjs/modules/auth/auth.controller.js +13 -0
  2. package/dist/cjs/modules/auth/auth.controller.js.map +1 -1
  3. package/dist/cjs/modules/auth/auth.service.js +40 -14
  4. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  5. package/dist/cjs/modules/auth/utils/services/auth-action.service.js +1 -1
  6. package/dist/cjs/modules/auth/utils/services/auth-action.service.js.map +1 -1
  7. package/dist/cjs/modules/base/base.middlewares.js +6 -4
  8. package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
  9. package/dist/cjs/modules/base/utils/error-prettifier.js +185 -0
  10. package/dist/cjs/modules/base/utils/error-prettifier.js.map +1 -0
  11. package/dist/cjs/modules/email/email.service.js +4 -1
  12. package/dist/cjs/modules/email/email.service.js.map +1 -1
  13. package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
  14. package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js +9 -3
  15. package/dist/cjs/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
  16. package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +27 -9
  17. package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
  18. package/dist/cjs/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js +28 -11
  19. package/dist/cjs/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js.map +1 -1
  20. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
  21. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  22. package/dist/cjs/types/auth.js.map +1 -1
  23. package/dist/cjs/utils/arkos-router/index.js +7 -1
  24. package/dist/cjs/utils/arkos-router/index.js.map +1 -1
  25. package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
  26. package/dist/cjs/utils/arkos-router/utils/helpers/index.js +51 -0
  27. package/dist/cjs/utils/arkos-router/utils/helpers/index.js.map +1 -1
  28. package/dist/cjs/utils/cli/generate.js +38 -0
  29. package/dist/cjs/utils/cli/generate.js.map +1 -1
  30. package/dist/cjs/utils/cli/index.js +37 -4
  31. package/dist/cjs/utils/cli/index.js.map +1 -1
  32. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  33. package/dist/cjs/utils/cli/utils/template-generator/templates/auth-configs-template.js +70 -37
  34. package/dist/cjs/utils/cli/utils/template-generator/templates/auth-configs-template.js.map +1 -1
  35. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +556 -0
  36. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -0
  37. package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js +327 -0
  38. package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -0
  39. package/dist/cjs/utils/cli/utils/template-generators.js +14 -8
  40. package/dist/cjs/utils/cli/utils/template-generators.js.map +1 -1
  41. package/dist/cjs/utils/dynamic-loader.js +2 -2
  42. package/dist/cjs/utils/dynamic-loader.js.map +1 -1
  43. package/dist/cjs/utils/helpers/routers.helpers.js +2 -3
  44. package/dist/cjs/utils/helpers/routers.helpers.js.map +1 -1
  45. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +5 -5
  46. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  47. package/dist/esm/modules/auth/auth.controller.js +13 -0
  48. package/dist/esm/modules/auth/auth.controller.js.map +1 -1
  49. package/dist/esm/modules/auth/auth.service.js +40 -14
  50. package/dist/esm/modules/auth/auth.service.js.map +1 -1
  51. package/dist/esm/modules/auth/utils/services/auth-action.service.js +1 -1
  52. package/dist/esm/modules/auth/utils/services/auth-action.service.js.map +1 -1
  53. package/dist/esm/modules/base/base.middlewares.js +6 -4
  54. package/dist/esm/modules/base/base.middlewares.js.map +1 -1
  55. package/dist/esm/modules/base/utils/error-prettifier.js +181 -0
  56. package/dist/esm/modules/base/utils/error-prettifier.js.map +1 -0
  57. package/dist/esm/modules/email/email.service.js +4 -1
  58. package/dist/esm/modules/email/email.service.js.map +1 -1
  59. package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
  60. package/dist/esm/modules/error-handler/utils/error-handler.helpers.js +9 -3
  61. package/dist/esm/modules/error-handler/utils/error-handler.helpers.js.map +1 -1
  62. package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +27 -9
  63. package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
  64. package/dist/esm/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js +28 -11
  65. package/dist/esm/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js.map +1 -1
  66. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
  67. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  68. package/dist/esm/types/auth.js.map +1 -1
  69. package/dist/esm/utils/arkos-router/index.js +8 -2
  70. package/dist/esm/utils/arkos-router/index.js.map +1 -1
  71. package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
  72. package/dist/esm/utils/arkos-router/utils/helpers/index.js +50 -0
  73. package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
  74. package/dist/esm/utils/cli/generate.js +38 -0
  75. package/dist/esm/utils/cli/generate.js.map +1 -1
  76. package/dist/esm/utils/cli/index.js +37 -4
  77. package/dist/esm/utils/cli/index.js.map +1 -1
  78. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  79. package/dist/esm/utils/cli/utils/template-generator/templates/auth-configs-template.js +70 -37
  80. package/dist/esm/utils/cli/utils/template-generator/templates/auth-configs-template.js.map +1 -1
  81. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +549 -0
  82. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -0
  83. package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js +320 -0
  84. package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -0
  85. package/dist/esm/utils/cli/utils/template-generators.js +14 -8
  86. package/dist/esm/utils/cli/utils/template-generators.js.map +1 -1
  87. package/dist/esm/utils/dynamic-loader.js +2 -2
  88. package/dist/esm/utils/dynamic-loader.js.map +1 -1
  89. package/dist/esm/utils/helpers/routers.helpers.js +2 -3
  90. package/dist/esm/utils/helpers/routers.helpers.js.map +1 -1
  91. package/dist/esm/utils/prisma/prisma-json-schema-generator.js +5 -5
  92. package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  93. package/dist/types/modules/auth/auth.service.d.ts +5 -0
  94. package/dist/types/modules/auth/utils/services/auth-action.service.d.ts +1 -1
  95. package/dist/types/modules/base/utils/error-prettifier.d.ts +19 -0
  96. package/dist/types/modules/email/email.service.d.ts +4 -8
  97. package/dist/types/types/auth.d.ts +3 -3
  98. package/dist/types/utils/arkos-router/index.d.ts +3 -1
  99. package/dist/types/utils/arkos-router/types/index.d.ts +2 -2
  100. package/dist/types/utils/arkos-router/utils/helpers/index.d.ts +4 -0
  101. package/dist/types/utils/cli/generate.d.ts +4 -0
  102. package/dist/types/utils/cli/utils/template-generator/templates/auth-configs-template.d.ts +3 -1
  103. package/dist/types/utils/cli/utils/template-generator/templates/class-validator-dto-generator.d.ts +18 -0
  104. package/dist/types/utils/cli/utils/template-generator/templates/zod-schema-generator.d.ts +14 -0
  105. package/dist/types/utils/helpers/routers.helpers.d.ts +1 -1
  106. package/package.json +1 -1
  107. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +0 -187
  108. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +0 -1
  109. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +0 -181
  110. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +0 -1
  111. package/dist/cjs/utils/cli/utils/template-generator/templates/zod/create-schema-template.js +0 -106
  112. package/dist/cjs/utils/cli/utils/template-generator/templates/zod/create-schema-template.js.map +0 -1
  113. package/dist/cjs/utils/cli/utils/template-generator/templates/zod/update-schema-template.js +0 -104
  114. package/dist/cjs/utils/cli/utils/template-generator/templates/zod/update-schema-template.js.map +0 -1
  115. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js +0 -181
  116. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.js.map +0 -1
  117. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js +0 -175
  118. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.js.map +0 -1
  119. package/dist/esm/utils/cli/utils/template-generator/templates/zod/create-schema-template.js +0 -100
  120. package/dist/esm/utils/cli/utils/template-generator/templates/zod/create-schema-template.js.map +0 -1
  121. package/dist/esm/utils/cli/utils/template-generator/templates/zod/update-schema-template.js +0 -98
  122. package/dist/esm/utils/cli/utils/template-generator/templates/zod/update-schema-template.js.map +0 -1
  123. package/dist/types/utils/cli/utils/template-generator/templates/class-validator/create-dto-template.d.ts +0 -2
  124. package/dist/types/utils/cli/utils/template-generator/templates/class-validator/update-dto-template.d.ts +0 -2
  125. package/dist/types/utils/cli/utils/template-generator/templates/zod/create-schema-template.d.ts +0 -2
  126. package/dist/types/utils/cli/utils/template-generator/templates/zod/update-schema-template.d.ts +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":"AAAA,OAAO,GAAoB,MAAM,cAAc,CAAC;AAChD,OAAO,MAAM,MAAM,UAAU,CAAC;AAE9B,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAA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BAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,eAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure:\n authConfigs?.jwt?.cookie?.secure ??\n (process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\" ||\n sameSite === \"none\"),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles: string[] = [];\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = Array.isArray(accessControl[action])\n ? accessControl[action]\n : accessControl[action].roles || [];\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return !!userRoles.some((role: string) => authorizedRoles.includes(role));\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call getAuthenticatedUser without setting up authentication\"\n );\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) throw loginRequiredError;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n {},\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (isAuthenticationEnabled())\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any> | undefined): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n\n if (!isUsingAuthentication())\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!user) throw loginRequiredError;\n if (user.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl && appModules.includes(kebabCase(resource)))\n accessControl = getModuleComponents(kebabCase(resource))?.authConfigs\n ?.accessControl;\n\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
1
+ {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":"AAAA,OAAO,GAAoB,MAAM,cAAc,CAAC;AAChD,OAAO,MAAM,MAAM,UAAU,CAAC;AAE9B,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,QAAQ,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAevE,OAAO,EAAc,IAAI,EAAE,MAAM,yCAAyC,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EACL,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,iBAAiB,MAAM,sCAAsC,CAAC;AACrE,OAAO,EACL,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,0C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AAE,IAAI,KAAK,SAAS,EAAE,CAAC;gBAChD,OAAO,MAAM,IAAI,CAAC,yBAAyB,CAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC1E,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,IAAI,CAAC,aAAa,IAAI,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;oBAC5D,aAAa,GAAG,mBAAmB,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,EAAE,WAAW;wBACnE,EAAE,aAAa,CAAC;gBAEpB,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,eAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n AccessControlRules,\n DetailedAccessControlRule,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure:\n authConfigs?.jwt?.cookie?.secure ??\n (process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\" ||\n sameSite === \"none\"),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n private isWildcardAccess(config: AccessControlConfig): config is \"*\" {\n return config === \"*\";\n }\n\n private isRoleList(config: AccessControlConfig): config is string[] {\n return Array.isArray(config);\n }\n\n private isAccessRules(\n config: AccessControlConfig\n ): config is Partial<AccessControlRules> {\n return (\n typeof config === \"object\" && config !== null && !Array.isArray(config)\n );\n }\n\n private normalizeRuleToRoles(\n rule: string[] | DetailedAccessControlRule | \"*\" | undefined\n ): string[] {\n if (!rule) return [];\n if (rule === \"*\") return [\"*\"];\n if (Array.isArray(rule)) return rule;\n return rule.roles === \"*\" ? [\"*\"] : (rule.roles ?? []);\n }\n\n private resolveAuthorizedRoles(\n action: AccessAction,\n accessControl: AccessControlConfig\n ): string[] {\n if (this.isWildcardAccess(accessControl)) return [\"*\"];\n if (this.isRoleList(accessControl)) return accessControl;\n if (this.isAccessRules(accessControl))\n return this.normalizeRuleToRoles(accessControl[action]);\n return [];\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles = this.resolveAuthorizedRoles(action, accessControl);\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return (\n authorizedRoles?.[0] === \"*\" ||\n !!userRoles.some((role: string) => authorizedRoles.includes(role))\n );\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call AuthService.getAuthenticatedUser without setting up authentication\"\n );\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) return null;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (isAuthenticationEnabled()) {\n const user = (await this.getAuthenticatedUser(req)) as User;\n if (!user) throw loginRequiredError;\n req.user = user;\n }\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any> | undefined): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n\n if (!isUsingAuthentication())\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!user) throw loginRequiredError;\n if (user.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl && appModules.includes(kebabCase(resource)))\n accessControl = getModuleComponents(kebabCase(resource))?.authConfigs\n ?.accessControl;\n\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
@@ -107,7 +107,7 @@ class AuthActionService {
107
107
  return baseAuthAction;
108
108
  if (Array.isArray(accessControl))
109
109
  return baseAuthAction;
110
- const actionRule = accessControl[action];
110
+ const actionRule = accessControl !== "*" ? accessControl[action] : undefined;
111
111
  if (actionRule) {
112
112
  if (Array.isArray(actionRule)) {
113
113
  return baseAuthAction;
@@ -1 +1 @@
1
- {"version":3,"file":"auth-action.service.js","sourceRoot":"","sources":["../../../../../../src/modules/auth/utils/services/auth-action.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAKtD,OAAO,EAAE,cAAc,EAAE,MAAM,gDAAgD,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,wCAAwC,CAAC;AAWpE,MAAM,iBAAiB;IAAvB;QACE,gBAAW,GAAiB;YAC1B;gBACE,KAAK,EAAE,EAAE;gBACT,MAAM,EAAE,MAAM;gBACd,QAAQ,EAAE,aAAa;gBACvB,IAAI,EAAE,kBAAkB;gBACxB,WAAW,EAAE,qBAAqB;gBAClC,YAAY,EAAE,sDAAsD;aACrE;SACF,CAAC;IA+LJ,CAAC;IA7LC,GAAG,CAAC,MAAc,EAAE,QAAgB,EAAE,aAAmC;QACvE,MAAM,iBAAiB,GAAG,IAAI,CAAC,uCAAuC,CACpE,MAAM,EACN,QAAQ,EACR,aAAa,CACd,CAAC;QACF,MAAM,kBAAkB,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAEzD,IAAI,kBAAkB,EAAE,CA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,IAAI,EAAE,UAAU,CAAC,IAAI,IAAI,cAAc,CAAC,IAAI;oBAC5C,WAAW,EAAE,UAAU,EAAE,WAAW,IAAI,cAAc,CAAC,WAAW;oBAClE,YAAY,EAAE,UAAU,EAAE,YAAY,IAAI,cAAc,CAAC,YAAY;iBACtE,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO,cAAc,CAAC;IACxB,CAAC;IAED,gBAAgB;QACd,OAAO;YACL,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;SACpE,CAAC;IACJ,CAAC;IAED,kBAAkB;QAChB,OAAO;YACL,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;SACtE,CAAC;IACJ,CAAC;IAED,aAAa,CAAC,QAAgB;QAC5B,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAC5B,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,KAAK,QAAQ,CACjD,CAAC;IACJ,CAAC;IAED,WAAW,CAAC,MAAc;QACxB,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAC5B,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,KAAK,MAAM,CAC7C,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,QAAgB;QACrC,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACzC,CAAC;CACF;AAED,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAAE,CAAC;AAElD,eAAe,iBAAiB,CAAC","sourcesContent":["import { kebabCase } from \"../../../../exports/utils\";\nimport {\n AccessControlConfig,\n DetailedAccessControlRule,\n} from \"../../../../types/auth\";\nimport { getArkosConfig } from \"../../../../utils/helpers/arkos-config.helpers\";\nimport { capitalize } from \"../../../../utils/helpers/text.helpers\";\n\ninterface AuthAction {\n roles?: string[];\n action: string;\n resource: string;\n name?: string;\n description?: string;\n errorMessage?: string;\n}\n\nclass AuthActionService {\n authActions: AuthAction[] = [\n {\n roles: [],\n action: \"View\",\n resource: \"auth-action\",\n name: \"View auth action\",\n description: \"View an auth action\",\n errorMessage: \"You do not have permission to perform this operation\",\n },\n ];\n\n add(action: string, resource: string, accessControl?: AccessControlConfig) {\n const transformedAction = this.transformAccessControlToValidAuthAction(\n action,\n resource,\n accessControl\n );\n const existingAuthAction = this.getOne(action, resource);\n\n if (existingAuthAction) {\n const inconsistencies: string[] = [];\n\n const defaultName = `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`;\n const defaultDescription = `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`;\n const defaultErrorMessage =\n \"You do not have permission to perform this operation\";\n\n const isNonDefault = (\n value: string | undefined,\n defaultValue: string\n ): boolean => {\n return value !== undefined && value !== defaultValue;\n };\n\n if (\n isNonDefault(existingAuthAction.name, defaultName) &&\n isNonDefault(transformedAction.name, defaultName) &&\n existingAuthAction.name !== transformedAction.name\n ) {\n inconsistencies.push(\n ` - name: \"${existingAuthAction.name}\" vs \"${transformedAction.name}\"`\n );\n }\n\n if (\n isNonDefault(existingAuthAction.description, defaultDescription) &&\n isNonDefault(transformedAction.description, defaultDescription) &&\n existingAuthAction.description !== transformedAction.description\n ) {\n inconsistencies.push(\n ` - description: \"${existingAuthAction.description}\" vs \"${transformedAction.description}\"`\n );\n }\n\n if (\n isNonDefault(existingAuthAction.errorMessage, defaultErrorMessage) &&\n isNonDefault(transformedAction.errorMessage, defaultErrorMessage) &&\n existingAuthAction.errorMessage !== transformedAction.errorMessage\n ) {\n inconsistencies.push(\n ` - errorMessage: \"${existingAuthAction.errorMessage}\" vs \"${transformedAction.errorMessage}\"`\n );\n }\n if (inconsistencies.length > 0) {\n throw new Error(\n `Inconsistent metadata for permission \"${action}:${resource}\". ` +\n `The same action+resource combination is being defined with different values:\\n` +\n inconsistencies.join(\"\\n\") +\n `\\n\\nPlease ensure all definitions of \"${action}:${resource}\" have the same name, description, and errorMessage values.`\n );\n }\n\n const mergedRoles =\n existingAuthAction.roles || transformedAction.roles\n ? [\n ...(existingAuthAction.roles || []),\n ...(transformedAction.roles || []),\n ]\n : undefined;\n\n const uniqueRoles = mergedRoles\n ? [...new Set(mergedRoles)].sort()\n : undefined;\n\n const merged: AuthAction = {\n action: existingAuthAction.action,\n resource: existingAuthAction.resource,\n roles: uniqueRoles,\n name: existingAuthAction.name ?? transformedAction.name,\n description:\n existingAuthAction.description ?? transformedAction.description,\n errorMessage:\n existingAuthAction.errorMessage ?? transformedAction.errorMessage,\n };\n\n this.remove(action, resource);\n this.authActions.push(merged);\n } else {\n if (transformedAction.roles) {\n transformedAction.roles = [...transformedAction.roles].sort();\n }\n this.authActions.push(transformedAction);\n }\n }\n\n remove(action: string, resource: string) {\n this.authActions = this.authActions.filter(\n (authAction) =>\n !(authAction.action === action && authAction.resource === resource)\n );\n }\n\n getAll(): AuthAction[] {\n return this.authActions;\n }\n\n getOne(action: string, resource: string): AuthAction | undefined {\n return this.authActions.find(\n (authAction) =>\n authAction.action === action && authAction.resource === resource\n );\n }\n\n private transformAccessControlToValidAuthAction(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ): AuthAction {\n const baseAuthAction: AuthAction = {\n roles:\n (accessControl &&\n (Array.isArray(accessControl)\n ? accessControl\n : typeof accessControl === \"string\"\n ? [accessControl]\n : Array.isArray(accessControl?.[action] || {})\n ? (accessControl[action] as string[])\n : (accessControl[action] as DetailedAccessControlRule)\n ?.roles)) ||\n [],\n action,\n resource,\n name: `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`,\n description: `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`,\n errorMessage: `You do not have permission to perform this operation`,\n };\n\n const config = getArkosConfig();\n\n if (config?.authentication?.mode === \"dynamic\") delete baseAuthAction.roles;\n\n if (!accessControl) return baseAuthAction;\n\n if (Array.isArray(accessControl)) return baseAuthAction;\n\n const actionRule = accessControl[action];\n\n if (actionRule) {\n if (Array.isArray(actionRule)) {\n return baseAuthAction;\n } else if (typeof actionRule === \"object\") {\n return {\n ...baseAuthAction,\n name: actionRule.name || baseAuthAction.name,\n description: actionRule?.description || baseAuthAction.description,\n errorMessage: actionRule?.errorMessage || baseAuthAction.errorMessage,\n };\n }\n }\n\n return baseAuthAction;\n }\n\n getUniqueActions(): string[] {\n return [\n ...new Set(this.authActions.map((authAction) => authAction.action)),\n ];\n }\n\n getUniqueResources(): string[] {\n return [\n ...new Set(this.authActions.map((authAction) => authAction.resource)),\n ];\n }\n\n getByResource(resource: string): AuthAction[] | undefined {\n return this.authActions.filter(\n (authAction) => authAction.resource === resource\n );\n }\n\n getByAction(action: string): AuthAction[] {\n return this.authActions.filter(\n (authAction) => authAction.action === action\n );\n }\n\n exists(action: string, resource: string): boolean {\n return !!this.getOne(action, resource);\n }\n}\n\nconst authActionService = new AuthActionService();\n\nexport default authActionService;\n"]}
1
+ {"version":3,"file":"auth-action.service.js","sourceRoot":"","sources":["../../../../../../src/modules/auth/utils/services/auth-action.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAKtD,OAAO,EAAE,cAAc,EAAE,MAAM,gDAAgD,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,wCAAwC,CAAC;AAWpE,MAAM,iBAAiB;IAAvB;QACE,gBAAW,GAAiB;YAC1B;gBACE,KAAK,EAAE,EAAE;gBACT,MAAM,EAAE,MAAM;gBACd,QAAQ,EAAE,aAAa;gBACvB,IAAI,EAAE,kBAAk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5B,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,KAAK,MAAM,CAC7C,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,QAAgB;QACrC,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACzC,CAAC;CACF;AAED,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAAE,CAAC;AAElD,eAAe,iBAAiB,CAAC","sourcesContent":["import { kebabCase } from \"../../../../exports/utils\";\nimport {\n AccessControlConfig,\n DetailedAccessControlRule,\n} from \"../../../../types/auth\";\nimport { getArkosConfig } from \"../../../../utils/helpers/arkos-config.helpers\";\nimport { capitalize } from \"../../../../utils/helpers/text.helpers\";\n\ninterface AuthAction {\n roles?: string[] | \"*\";\n action: string;\n resource: string;\n name?: string;\n description?: string;\n errorMessage?: string;\n}\n\nclass AuthActionService {\n authActions: AuthAction[] = [\n {\n roles: [],\n action: \"View\",\n resource: \"auth-action\",\n name: \"View auth action\",\n description: \"View an auth action\",\n errorMessage: \"You do not have permission to perform this operation\",\n },\n ];\n\n add(action: string, resource: string, accessControl?: AccessControlConfig) {\n const transformedAction = this.transformAccessControlToValidAuthAction(\n action,\n resource,\n accessControl\n );\n const existingAuthAction = this.getOne(action, resource);\n\n if (existingAuthAction) {\n const inconsistencies: string[] = [];\n\n const defaultName = `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`;\n const defaultDescription = `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`;\n const defaultErrorMessage =\n \"You do not have permission to perform this operation\";\n\n const isNonDefault = (\n value: string | undefined,\n defaultValue: string\n ): boolean => {\n return value !== undefined && value !== defaultValue;\n };\n\n if (\n isNonDefault(existingAuthAction.name, defaultName) &&\n isNonDefault(transformedAction.name, defaultName) &&\n existingAuthAction.name !== transformedAction.name\n ) {\n inconsistencies.push(\n ` - name: \"${existingAuthAction.name}\" vs \"${transformedAction.name}\"`\n );\n }\n\n if (\n isNonDefault(existingAuthAction.description, defaultDescription) &&\n isNonDefault(transformedAction.description, defaultDescription) &&\n existingAuthAction.description !== transformedAction.description\n ) {\n inconsistencies.push(\n ` - description: \"${existingAuthAction.description}\" vs \"${transformedAction.description}\"`\n );\n }\n\n if (\n isNonDefault(existingAuthAction.errorMessage, defaultErrorMessage) &&\n isNonDefault(transformedAction.errorMessage, defaultErrorMessage) &&\n existingAuthAction.errorMessage !== transformedAction.errorMessage\n ) {\n inconsistencies.push(\n ` - errorMessage: \"${existingAuthAction.errorMessage}\" vs \"${transformedAction.errorMessage}\"`\n );\n }\n if (inconsistencies.length > 0) {\n throw new Error(\n `Inconsistent metadata for permission \"${action}:${resource}\". ` +\n `The same action+resource combination is being defined with different values:\\n` +\n inconsistencies.join(\"\\n\") +\n `\\n\\nPlease ensure all definitions of \"${action}:${resource}\" have the same name, description, and errorMessage values.`\n );\n }\n\n const mergedRoles =\n existingAuthAction.roles || transformedAction.roles\n ? [\n ...(existingAuthAction.roles || []),\n ...(transformedAction.roles || []),\n ]\n : undefined;\n\n const uniqueRoles = mergedRoles\n ? [...new Set(mergedRoles)].sort()\n : undefined;\n\n const merged: AuthAction = {\n action: existingAuthAction.action,\n resource: existingAuthAction.resource,\n roles: uniqueRoles,\n name: existingAuthAction.name ?? transformedAction.name,\n description:\n existingAuthAction.description ?? transformedAction.description,\n errorMessage:\n existingAuthAction.errorMessage ?? transformedAction.errorMessage,\n };\n\n this.remove(action, resource);\n this.authActions.push(merged);\n } else {\n if (transformedAction.roles) {\n transformedAction.roles = [...transformedAction.roles].sort();\n }\n this.authActions.push(transformedAction);\n }\n }\n\n remove(action: string, resource: string) {\n this.authActions = this.authActions.filter(\n (authAction) =>\n !(authAction.action === action && authAction.resource === resource)\n );\n }\n\n getAll(): AuthAction[] {\n return this.authActions;\n }\n\n getOne(action: string, resource: string): AuthAction | undefined {\n return this.authActions.find(\n (authAction) =>\n authAction.action === action && authAction.resource === resource\n );\n }\n\n private transformAccessControlToValidAuthAction(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ): AuthAction {\n const baseAuthAction: AuthAction = {\n roles:\n (accessControl &&\n (Array.isArray(accessControl)\n ? accessControl\n : typeof accessControl === \"string\"\n ? [accessControl]\n : Array.isArray(accessControl?.[action] || {})\n ? (accessControl[action] as string[])\n : (accessControl[action] as DetailedAccessControlRule)\n ?.roles)) ||\n [],\n action,\n resource,\n name: `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`,\n description: `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`,\n errorMessage: `You do not have permission to perform this operation`,\n };\n\n const config = getArkosConfig();\n\n if (config?.authentication?.mode === \"dynamic\") delete baseAuthAction.roles;\n\n if (!accessControl) return baseAuthAction;\n\n if (Array.isArray(accessControl)) return baseAuthAction;\n\n const actionRule =\n accessControl !== \"*\" ? accessControl[action] : undefined;\n\n if (actionRule) {\n if (Array.isArray(actionRule)) {\n return baseAuthAction;\n } else if (typeof actionRule === \"object\") {\n return {\n ...baseAuthAction,\n name: actionRule.name || baseAuthAction.name,\n description: actionRule?.description || baseAuthAction.description,\n errorMessage: actionRule?.errorMessage || baseAuthAction.errorMessage,\n };\n }\n }\n\n return baseAuthAction;\n }\n\n getUniqueActions(): string[] {\n return [\n ...new Set(this.authActions.map((authAction) => authAction.action)),\n ];\n }\n\n getUniqueResources(): string[] {\n return [\n ...new Set(this.authActions.map((authAction) => authAction.resource)),\n ];\n }\n\n getByResource(resource: string): AuthAction[] | undefined {\n return this.authActions.filter(\n (authAction) => authAction.resource === resource\n );\n }\n\n getByAction(action: string): AuthAction[] {\n return this.authActions.filter(\n (authAction) => authAction.action === action\n );\n }\n\n exists(action: string, resource: string): boolean {\n return !!this.getOne(action, resource);\n }\n}\n\nconst authActionService = new AuthActionService();\n\nexport default authActionService;\n"]}
@@ -6,7 +6,7 @@ import validateSchema from "../../utils/validate-schema.js";
6
6
  import { resolvePrismaQueryOptions } from "./utils/helpers/base.middlewares.helpers.js";
7
7
  import { capitalize } from "../../utils/helpers/text.helpers.js";
8
8
  import { isClass, isZodSchema } from "../../utils/dynamic-loader.js";
9
- import { pascalCase } from "../../exports/utils/index.js";
9
+ import errorPrettifier from "./utils/error-prettifier.js";
10
10
  export function callNext(_, _1, next) {
11
11
  next();
12
12
  }
@@ -205,9 +205,11 @@ export function validateRequestInputs(routeConfig) {
205
205
  req[key] = await validatorFn(validator, req[key], arkosConfig.validation?.validationOptions);
206
206
  }
207
207
  catch (err) {
208
- throw new AppError(`Invalid request ${key}`, 400, `InvalidRequest${pascalCase(key)}`, (err &&
209
- (validationConfig?.resolver === "zod" ? err.format() : err)) ||
210
- {});
208
+ const resolver = validationConfig?.resolver;
209
+ const isZod = validationConfig?.resolver === "zod";
210
+ const prettifiedError = errorPrettifier.prettify(resolver, err);
211
+ const error = prettifiedError[0];
212
+ throw new AppError(error.message, 400, error.code, isZod ? err.format() : err);
211
213
  }
212
214
  }
213
215
  next();
@@ -1 +1 @@
1
- {"version":3,"file":"base.middlewares.js","sourceRoot":"","sources":["../../../../src/modules/base/base.middlewares.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,WAAW,MAAM,0BAA0B,CAAC;AACnD,OAAO,cAAc,MAAM,6BAA6B,CAAC;AAIzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AAErF,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,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AAoB,CAAC;YAC7B,IAAI,SAAS;gBACX,IAAI,CAAC;oBACH,GAAG,CAAC,GAAG,CAAC,GAAG,MAAM,WAAW,CAC1B,SAAS,EACT,GAAG,CAAC,GAAG,CAAC,EACR,WAAW,CAAC,UAAU,EAAE,iBAAiB,CAC1C,CAAC;gBACJ,CAAC;gBAAC,OAAO,GAAQ,EAAE,CAAC;oBAClB,MAAM,IAAI,QAAQ,CAChB,mBAAmB,GAAG,EAAE,EACxB,GAAG,EACH,iBAAiB,UAAU,CAAC,GAAG,CAAC,EAAE,EAClC,CAAC,GAAG;wBACF,CAAC,gBAAgB,EAAE,QAAQ,KAAK,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;wBAC5D,EAAE,CACL,CAAC;gBACJ,CAAC;QACL,CAAC;QAED,IAAI,EAAE,CAAC;IACT,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport {\n PrismaQueryOptions,\n ArkosNextFunction,\n ArkosRequest,\n ArkosRequestHandler,\n ArkosResponse,\n AuthPrismaQueryOptions,\n} from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AppError, catchAsync } from \"../../exports/error-handler\";\nimport validateDto from \"../../utils/validate-dto\";\nimport validateSchema from \"../../utils/validate-schema\";\nimport { ZodSchema } from \"zod\";\nimport { ClassConstructor } from \"class-transformer\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { resolvePrismaQueryOptions } from \"./utils/helpers/base.middlewares.helpers\";\nimport { ArkosRouteConfig } from \"../../utils/arkos-router/types\";\nimport { capitalize } from \"../../utils/helpers/text.helpers\";\nimport { isClass, isZodSchema } from \"../../utils/dynamic-loader\";\nimport { pascalCase } from \"../../exports/utils\";\n\nexport function callNext(_: Request, _1: Response, next: NextFunction) {\n next();\n}\n\n/**\n * Deep comparison helper for objects\n */\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a == null || b == null) return false;\n if (typeof a !== \"object\" || typeof b !== \"object\") return a === b;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (!keysB.includes(key)) return false;\n if (!deepEqual(a[key], b[key])) return false;\n }\n\n return true;\n}\n\n/**\n * Sends response with backward compatibility support\n * Compares current values against original values to detect middleware changes\n * If values were modified by subsequent middleware, use the modified version\n */\nexport function sendResponse(req: ArkosRequest, res: ArkosResponse) {\n let responseData;\n let responseStatus;\n\n const originalData = (res as any).originalData;\n const originalStatus = (res as any).originalStatus;\n\n const currentReqData = req.responseData;\n const currentReqStatus = req.responseStatus;\n const currentLocalsData = res.locals?.data;\n const currentLocalsStatus = res.locals?.status;\n\n if (\n currentReqData !== undefined &&\n !deepEqual(currentReqData, originalData)\n ) {\n responseData = currentReqData;\n } else if (\n currentLocalsData !== undefined &&\n !deepEqual(currentLocalsData, originalData)\n ) {\n responseData = currentLocalsData;\n } else if (originalData !== undefined) {\n responseData = originalData;\n } else {\n responseData = currentReqData ?? currentLocalsData;\n }\n\n if (currentReqStatus !== undefined && currentReqStatus !== originalStatus) {\n responseStatus = currentReqStatus;\n } else if (\n currentLocalsStatus !== undefined &&\n currentLocalsStatus !== originalStatus\n ) {\n responseStatus = currentLocalsStatus;\n } else if (originalStatus !== undefined) {\n responseStatus = originalStatus;\n } else {\n responseStatus = currentReqStatus ?? currentLocalsStatus;\n }\n\n // Send response\n\n if (Number(responseStatus) === 204) {\n res.status(Number(responseStatus)).send();\n } else if (\n (responseData !== undefined || responseData !== null) &&\n responseStatus\n ) {\n res.status(Number(responseStatus)).json(responseData);\n } else if (\n Number(responseStatus) &&\n (responseData === undefined || responseData === null)\n ) {\n res.status(Number(responseStatus)).send();\n } else {\n res.status(500).json({\n message: \"No status or data attached to the response\",\n });\n }\n}\n\n/**\n * Type representing all possible actions that can be performed on a controller\n * Combines both standard CRUD operations and auth-specific operations\n */\nexport type ControllerActions =\n | keyof PrismaQueryOptions<any>\n | keyof Omit<AuthPrismaQueryOptions<any>, keyof PrismaQueryOptions<any>>;\n\n/**\n * Middleware to add Prisma query options to the request's query parameters.\n *\n * @template T - The type of the Prisma model.\n * @param {PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>} prismaQueryOptions - The Prisma query options to attach.\n * @param {ControllerActions} action - The controller action to apply.\n * @returns A middleware function that attaches the query options to the request.\n */\nexport function addPrismaQueryOptionsToRequest<T extends Record<string, any>>(\n prismaQueryOptions: PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>,\n action: ControllerActions\n) {\n return (req: ArkosRequest, _: ArkosResponse, next: NextFunction) => {\n const configs = getArkosConfig();\n\n const resolvedOptions = resolvePrismaQueryOptions(\n prismaQueryOptions,\n action\n );\n\n const requestQueryOptions = configs?.request?.parameters\n ?.allowDangerousPrismaQueryOptions\n ? JSON.parse((req.query?.prismaQueryOptions as string) || \"{}\")\n : {};\n\n req.prismaQueryOptions = deepmerge(resolvedOptions, requestQueryOptions);\n\n next();\n };\n}\n\n/**\n * Logs request events with colored text such as errors, requests responses.\n *\n */\nexport function handleRequestLogs(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const startTime = Date.now();\n\n const methodColors = {\n GET: \"\\x1b[36m\", // Cyan\n POST: \"\\x1b[32m\", // Green\n PUT: \"\\x1b[33m\", // Orange/Yellow\n PATCH: \"\\x1b[33m\", // Orange/Yellow\n DELETE: \"\\x1b[31m\", // Red\n HEAD: \"\\x1b[34m\", // Blue\n OPTIONS: \"\\x1b[34m\", // Blue\n };\n\n const getStatusColor = (statusCode: number) => {\n if (statusCode >= 200 && statusCode < 300) return \"\\x1b[32m\";\n if (statusCode >= 300 && statusCode < 400) return \"\\x1b[33m\";\n if (statusCode >= 400 && statusCode < 500) return \"\\x1b[33m\";\n if (statusCode >= 500) return \"\\x1b[31m\";\n return \"\\x1b[0m\";\n };\n\n res.on(\"finish\", () => {\n const duration = Date.now() - startTime;\n\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n const methodColor =\n methodColors[req.method as keyof typeof methodColors] || \"\\x1b[0m\";\n const statusColor = getStatusColor(res.statusCode);\n\n console.info(\n `[\\x1b[36mInfo\\x1b[0m] \\x1b[90m${time}\\x1b[0m ${methodColor}${\n req.method\n }\\x1b[0m ${decodeURIComponent(req.originalUrl)} ${statusColor}${\n res.statusCode\n }\\x1b[0m \\x1b[35m${duration}ms\\x1b[0m`\n );\n });\n\n next();\n}\n\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T>\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T> | ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n) {\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const validationConfigs = getArkosConfig()?.validation;\n let body = req.body;\n\n if (validationConfigs?.resolver === \"class-validator\" && schemaOrDtoClass)\n req.body = await validateDto(\n schemaOrDtoClass as ClassConstructor<T>,\n body,\n deepmerge(\n {\n whitelist: true,\n ...classValidatorValidationOptions,\n },\n validationConfigs?.validationOptions || {}\n )\n );\n else if (validationConfigs?.resolver === \"zod\" && schemaOrDtoClass)\n req.body = await validateSchema(schemaOrDtoClass as ZodSchema<T>, body);\n\n next();\n }\n );\n}\n\nexport function validateRequestInputs(routeConfig: ArkosRouteConfig) {\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const strictValidation = validationConfig?.strict;\n const validators = routeConfig?.validation;\n const openapi = routeConfig?.experimental?.openapi;\n\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (!validationConfig?.resolver && validators)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos config { validation: {} }.\"\n );\n\n if ((validators as any) === true)\n throw Error(\n `Invalid value ${validators} passed to validation option, it can only receive false or object of { query, body, params }.`\n );\n\n const validatorFn: (validator: any, data: any, options: any) => Promise<any> =\n validationConfig?.resolver == \"zod\" ? validateSchema : validateDto;\n const validatorsKey: (\"body\" | \"query\" | \"params\")[] = [\n \"body\",\n \"query\",\n \"params\",\n ];\n\n const isValidValidator =\n validationConfig?.resolver == \"zod\" ? isZodSchema : isClass;\n const validatorName =\n validationConfig?.resolver == \"zod\" ? \"zod schema\" : \"class-validator dto\";\n const validatorNameType =\n validationConfig?.resolver == \"zod\" ? \"Schema\" : \"Dto\";\n\n if (typeof validators === \"object\")\n validatorsKey.forEach((key) => {\n if (\n openapi &&\n typeof openapi === \"object\" &&\n key != \"body\" &&\n openapi.parameters?.some(\n (parameter: any) => parameter.in === validationToParameterMapping[key]\n ) &&\n validators[key]\n ) {\n throw Error(\n `When usign validation.${key} you must not define parameters under openapi.parameters as documentation of req.${key} because the ${validatorName} you passed under validation.${key} will be added as jsonSchema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`\n );\n }\n\n if (\n openapi &&\n typeof openapi === \"object\" &&\n openapi.requestBody &&\n validators[key] &&\n key === \"body\"\n ) {\n throw Error(\n `When usign validation.${key} you must not define json-schema under openapi.requestBody as documentation for req.${key}, because the ${validatorName} you passed under validation.${key} will be added as json-schema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`\n );\n }\n\n if (strictValidation && !(key in validators))\n throw Error(\n `No { validation: { ${key}: ${validatorNameType} } } was found, while using strict validation you will need to pass undefined into ${key} in order to deny any request ${key} input.`\n );\n\n if (\n key in validators &&\n validators?.[key] !== undefined &&\n validators?.[key] !== false &&\n !isValidValidator(validators[key])\n )\n throw Error(\n `Your validation resolver is set to ${arkosConfig.validation!.resolver}, please provide a valid ${validatorName} in order to use in { validation: { ${key}: ${validatorNameType} } } under route ${routeConfig.path}`\n );\n });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n for (const key of validatorsKey) {\n const reqInput = Object.keys(req[key] || {}).length > 0;\n const validator = (validators as any)?.[key];\n const notAllowedInputError = new AppError(\n `Request ${key} is not allowed on this route`,\n 400,\n `Request${capitalize(key)}NotAllowed`,\n { [key]: req[key] }\n );\n\n if (\n ((typeof validators === \"boolean\" && validators === false) ||\n validator === false) &&\n reqInput\n )\n throw notAllowedInputError;\n\n if (strictValidation && !validator && reqInput)\n throw notAllowedInputError;\n if (validator)\n try {\n req[key] = await validatorFn(\n validator,\n req[key],\n arkosConfig.validation?.validationOptions\n );\n } catch (err: any) {\n throw new AppError(\n `Invalid request ${key}`,\n 400,\n `InvalidRequest${pascalCase(key)}`,\n (err &&\n (validationConfig?.resolver === \"zod\" ? err.format() : err)) ||\n {}\n );\n }\n }\n\n next();\n }\n );\n}\n"]}
1
+ {"version":3,"file":"base.middlewares.js","sourceRoot":"","sources":["../../../../src/modules/base/base.middlewares.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,SAAS,MAAM,sCAAsC,CAAC;AAC7D,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACnE,OAAO,WAAW,MAAM,0BAA0B,CAAC;AACnD,OAAO,cAAc,MAAM,6BAA6B,CAAC;AAIzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,0CAA0C,CAAC;AAErF,OAAO,EAAE,UAAU,EAAE,MAAM,kCAAkC,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAClE,OAAO,eAAe,MAAM,0BAA0B,CAAC;AAEvD,MAAM,UAAU,QAAQ,CAAC,CAAU,EAAE,EAAY,EAAE,IAAkB;IACnE,IAAI,EAAE,CAAC;AACT,C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,CAAC,EACR,WAAW,CAAC,UAAU,EAAE,iBAAiB,CAC1C,CAAC;gBACJ,CAAC;gBAAC,OAAO,GAAQ,EAAE,CAAC;oBAClB,MAAM,QAAQ,GAAG,gBAAgB,EAAE,QAAQ,CAAC;oBAC5C,MAAM,KAAK,GAAG,gBAAgB,EAAE,QAAQ,KAAK,KAAK,CAAC;oBAEnD,MAAM,eAAe,GAAG,eAAe,CAAC,QAAQ,CAC9C,QAAe,EACf,GAAG,CACJ,CAAC;oBACF,MAAM,KAAK,GAAG,eAAe,CAAC,CAAC,CAAC,CAAC;oBACjC,MAAM,IAAI,QAAQ,CAChB,KAAK,CAAC,OAAO,EACb,GAAG,EACH,KAAK,CAAC,IAAI,EACV,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,GAAG,CAC3B,CAAC;gBACJ,CAAC;QACL,CAAC;QAED,IAAI,EAAE,CAAC;IACT,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport {\n PrismaQueryOptions,\n ArkosNextFunction,\n ArkosRequest,\n ArkosRequestHandler,\n ArkosResponse,\n AuthPrismaQueryOptions,\n} from \"../../types\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AppError, catchAsync } from \"../../exports/error-handler\";\nimport validateDto from \"../../utils/validate-dto\";\nimport validateSchema from \"../../utils/validate-schema\";\nimport { ZodSchema } from \"zod\";\nimport { ClassConstructor } from \"class-transformer\";\nimport { ValidatorOptions } from \"class-validator\";\nimport { resolvePrismaQueryOptions } from \"./utils/helpers/base.middlewares.helpers\";\nimport { ArkosRouteConfig } from \"../../utils/arkos-router/types\";\nimport { capitalize } from \"../../utils/helpers/text.helpers\";\nimport { isClass, isZodSchema } from \"../../utils/dynamic-loader\";\nimport errorPrettifier from \"./utils/error-prettifier\";\n\nexport function callNext(_: Request, _1: Response, next: NextFunction) {\n next();\n}\n\n/**\n * Deep comparison helper for objects\n */\nfunction deepEqual(a: any, b: any): boolean {\n if (a === b) return true;\n if (a == null || b == null) return false;\n if (typeof a !== \"object\" || typeof b !== \"object\") return a === b;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (!keysB.includes(key)) return false;\n if (!deepEqual(a[key], b[key])) return false;\n }\n\n return true;\n}\n\n/**\n * Sends response with backward compatibility support\n * Compares current values against original values to detect middleware changes\n * If values were modified by subsequent middleware, use the modified version\n */\nexport function sendResponse(req: ArkosRequest, res: ArkosResponse) {\n let responseData;\n let responseStatus;\n\n const originalData = (res as any).originalData;\n const originalStatus = (res as any).originalStatus;\n\n const currentReqData = req.responseData;\n const currentReqStatus = req.responseStatus;\n const currentLocalsData = res.locals?.data;\n const currentLocalsStatus = res.locals?.status;\n\n if (\n currentReqData !== undefined &&\n !deepEqual(currentReqData, originalData)\n ) {\n responseData = currentReqData;\n } else if (\n currentLocalsData !== undefined &&\n !deepEqual(currentLocalsData, originalData)\n ) {\n responseData = currentLocalsData;\n } else if (originalData !== undefined) {\n responseData = originalData;\n } else {\n responseData = currentReqData ?? currentLocalsData;\n }\n\n if (currentReqStatus !== undefined && currentReqStatus !== originalStatus) {\n responseStatus = currentReqStatus;\n } else if (\n currentLocalsStatus !== undefined &&\n currentLocalsStatus !== originalStatus\n ) {\n responseStatus = currentLocalsStatus;\n } else if (originalStatus !== undefined) {\n responseStatus = originalStatus;\n } else {\n responseStatus = currentReqStatus ?? currentLocalsStatus;\n }\n\n // Send response\n\n if (Number(responseStatus) === 204) {\n res.status(Number(responseStatus)).send();\n } else if (\n (responseData !== undefined || responseData !== null) &&\n responseStatus\n ) {\n res.status(Number(responseStatus)).json(responseData);\n } else if (\n Number(responseStatus) &&\n (responseData === undefined || responseData === null)\n ) {\n res.status(Number(responseStatus)).send();\n } else {\n res.status(500).json({\n message: \"No status or data attached to the response\",\n });\n }\n}\n\n/**\n * Type representing all possible actions that can be performed on a controller\n * Combines both standard CRUD operations and auth-specific operations\n */\nexport type ControllerActions =\n | keyof PrismaQueryOptions<any>\n | keyof Omit<AuthPrismaQueryOptions<any>, keyof PrismaQueryOptions<any>>;\n\n/**\n * Middleware to add Prisma query options to the request's query parameters.\n *\n * @template T - The type of the Prisma model.\n * @param {PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>} prismaQueryOptions - The Prisma query options to attach.\n * @param {ControllerActions} action - The controller action to apply.\n * @returns A middleware function that attaches the query options to the request.\n */\nexport function addPrismaQueryOptionsToRequest<T extends Record<string, any>>(\n prismaQueryOptions: PrismaQueryOptions<T> | AuthPrismaQueryOptions<T>,\n action: ControllerActions\n) {\n return (req: ArkosRequest, _: ArkosResponse, next: NextFunction) => {\n const configs = getArkosConfig();\n\n const resolvedOptions = resolvePrismaQueryOptions(\n prismaQueryOptions,\n action\n );\n\n const requestQueryOptions = configs?.request?.parameters\n ?.allowDangerousPrismaQueryOptions\n ? JSON.parse((req.query?.prismaQueryOptions as string) || \"{}\")\n : {};\n\n req.prismaQueryOptions = deepmerge(resolvedOptions, requestQueryOptions);\n\n next();\n };\n}\n\n/**\n * Logs request events with colored text such as errors, requests responses.\n *\n */\nexport function handleRequestLogs(\n req: Request,\n res: Response,\n next: NextFunction\n) {\n const startTime = Date.now();\n\n const methodColors = {\n GET: \"\\x1b[36m\", // Cyan\n POST: \"\\x1b[32m\", // Green\n PUT: \"\\x1b[33m\", // Orange/Yellow\n PATCH: \"\\x1b[33m\", // Orange/Yellow\n DELETE: \"\\x1b[31m\", // Red\n HEAD: \"\\x1b[34m\", // Blue\n OPTIONS: \"\\x1b[34m\", // Blue\n };\n\n const getStatusColor = (statusCode: number) => {\n if (statusCode >= 200 && statusCode < 300) return \"\\x1b[32m\";\n if (statusCode >= 300 && statusCode < 400) return \"\\x1b[33m\";\n if (statusCode >= 400 && statusCode < 500) return \"\\x1b[33m\";\n if (statusCode >= 500) return \"\\x1b[31m\";\n return \"\\x1b[0m\";\n };\n\n res.on(\"finish\", () => {\n const duration = Date.now() - startTime;\n\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n const methodColor =\n methodColors[req.method as keyof typeof methodColors] || \"\\x1b[0m\";\n const statusColor = getStatusColor(res.statusCode);\n\n console.info(\n `[\\x1b[36mInfo\\x1b[0m] \\x1b[90m${time}\\x1b[0m ${methodColor}${\n req.method\n }\\x1b[0m ${decodeURIComponent(req.originalUrl)} ${statusColor}${\n res.statusCode\n }\\x1b[0m \\x1b[35m${duration}ms\\x1b[0m`\n );\n });\n\n next();\n}\n\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T>\n): ArkosRequestHandler;\nexport function handleRequestBodyValidationAndTransformation<T extends object>(\n schemaOrDtoClass?: ZodSchema<T> | ClassConstructor<T>,\n classValidatorValidationOptions?: ValidatorOptions\n) {\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const validationConfigs = getArkosConfig()?.validation;\n let body = req.body;\n\n if (validationConfigs?.resolver === \"class-validator\" && schemaOrDtoClass)\n req.body = await validateDto(\n schemaOrDtoClass as ClassConstructor<T>,\n body,\n deepmerge(\n {\n whitelist: true,\n ...classValidatorValidationOptions,\n },\n validationConfigs?.validationOptions || {}\n )\n );\n else if (validationConfigs?.resolver === \"zod\" && schemaOrDtoClass)\n req.body = await validateSchema(schemaOrDtoClass as ZodSchema<T>, body);\n\n next();\n }\n );\n}\n\nexport function validateRequestInputs(routeConfig: ArkosRouteConfig) {\n const arkosConfig = getArkosConfig();\n const validationConfig = arkosConfig.validation;\n const strictValidation = validationConfig?.strict;\n const validators = routeConfig?.validation;\n const openapi = routeConfig?.experimental?.openapi;\n\n const validationToParameterMapping = {\n query: \"query\",\n params: \"path\",\n headers: \"header\",\n cookies: \"cookie\",\n };\n\n if (!validationConfig?.resolver && validators)\n throw Error(\n \"Trying to pass validators into route config validation option without choosing a validation resolver under arkos config { validation: {} }.\"\n );\n\n if ((validators as any) === true)\n throw Error(\n `Invalid value ${validators} passed to validation option, it can only receive false or object of { query, body, params }.`\n );\n\n const validatorFn: (validator: any, data: any, options: any) => Promise<any> =\n validationConfig?.resolver == \"zod\" ? validateSchema : validateDto;\n const validatorsKey: (\"body\" | \"query\" | \"params\")[] = [\n \"body\",\n \"query\",\n \"params\",\n ];\n\n const isValidValidator =\n validationConfig?.resolver == \"zod\" ? isZodSchema : isClass;\n const validatorName =\n validationConfig?.resolver == \"zod\" ? \"zod schema\" : \"class-validator dto\";\n const validatorNameType =\n validationConfig?.resolver == \"zod\" ? \"Schema\" : \"Dto\";\n\n if (typeof validators === \"object\")\n validatorsKey.forEach((key) => {\n if (\n openapi &&\n typeof openapi === \"object\" &&\n key != \"body\" &&\n openapi.parameters?.some(\n (parameter: any) => parameter.in === validationToParameterMapping[key]\n ) &&\n validators[key]\n ) {\n throw Error(\n `When usign validation.${key} you must not define parameters under openapi.parameters as documentation of req.${key} because the ${validatorName} you passed under validation.${key} will be added as jsonSchema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`\n );\n }\n\n if (\n openapi &&\n typeof openapi === \"object\" &&\n openapi.requestBody &&\n validators[key] &&\n key === \"body\"\n ) {\n throw Error(\n `When usign validation.${key} you must not define json-schema under openapi.requestBody as documentation for req.${key}, because the ${validatorName} you passed under validation.${key} will be added as json-schema into the api documenation, if you wish to define documenation by yourself do not define validation.${key}.`\n );\n }\n\n if (strictValidation && !(key in validators))\n throw Error(\n `No { validation: { ${key}: ${validatorNameType} } } was found, while using strict validation you will need to pass undefined into ${key} in order to deny any request ${key} input.`\n );\n\n if (\n key in validators &&\n validators?.[key] !== undefined &&\n validators?.[key] !== false &&\n !isValidValidator(validators[key])\n )\n throw Error(\n `Your validation resolver is set to ${arkosConfig.validation!.resolver}, please provide a valid ${validatorName} in order to use in { validation: { ${key}: ${validatorNameType} } } under route ${routeConfig.path}`\n );\n });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n for (const key of validatorsKey) {\n const reqInput = Object.keys(req[key] || {}).length > 0;\n const validator = (validators as any)?.[key];\n const notAllowedInputError = new AppError(\n `Request ${key} is not allowed on this route`,\n 400,\n `Request${capitalize(key)}NotAllowed`,\n { [key]: req[key] }\n );\n\n if (\n ((typeof validators === \"boolean\" && validators === false) ||\n validator === false) &&\n reqInput\n )\n throw notAllowedInputError;\n\n if (strictValidation && !validator && reqInput)\n throw notAllowedInputError;\n if (validator)\n try {\n req[key] = await validatorFn(\n validator,\n req[key],\n arkosConfig.validation?.validationOptions\n );\n } catch (err: any) {\n const resolver = validationConfig?.resolver;\n const isZod = validationConfig?.resolver === \"zod\";\n\n const prettifiedError = errorPrettifier.prettify(\n resolver as any,\n err\n );\n const error = prettifiedError[0];\n throw new AppError(\n error.message,\n 400,\n error.code,\n isZod ? err.format() : err\n );\n }\n }\n\n next();\n }\n );\n}\n"]}
@@ -0,0 +1,181 @@
1
+ export class ErrorPrettifier {
2
+ prettify(library, error) {
3
+ if (library === "class-validator") {
4
+ return this.prettifyClassValidator(error);
5
+ }
6
+ else {
7
+ return this.prettifyZod(error);
8
+ }
9
+ }
10
+ toPascalCase(path) {
11
+ return path
12
+ .split(".")
13
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
14
+ .join("");
15
+ }
16
+ replaceFieldInMessage(message, fieldName, fullPath) {
17
+ if (!fullPath.includes(".") && !fullPath.includes("[")) {
18
+ return message;
19
+ }
20
+ const regex = new RegExp(`^${fieldName}\\b`, "i");
21
+ if (regex.test(message)) {
22
+ return message.replace(regex, fullPath);
23
+ }
24
+ const wordBoundaryRegex = new RegExp(`\\b${fieldName}\\b`, "gi");
25
+ if (wordBoundaryRegex.test(message)) {
26
+ return message.replace(wordBoundaryRegex, fullPath);
27
+ }
28
+ return `${fullPath} ${message}`;
29
+ }
30
+ prettifyClassValidator(errors, parentPath = "") {
31
+ const result = [];
32
+ for (const error of errors) {
33
+ const currentPath = parentPath
34
+ ? `${parentPath}.${error.property}`
35
+ : error.property;
36
+ if (error.children && error.children.length > 0) {
37
+ result.push(...this.prettifyClassValidator(error.children, currentPath));
38
+ continue;
39
+ }
40
+ if (error.constraints) {
41
+ const fieldPascal = this.toPascalCase(currentPath);
42
+ for (const [constraintKey, originalMessage] of Object.entries(error.constraints)) {
43
+ const constraintName = constraintKey.charAt(0).toUpperCase() + constraintKey.slice(1);
44
+ const message = this.replaceFieldInMessage(originalMessage, error.property, currentPath);
45
+ result.push({
46
+ message: message,
47
+ code: `${fieldPascal}${constraintName}Constraint`,
48
+ });
49
+ }
50
+ }
51
+ }
52
+ return result;
53
+ }
54
+ mapZodToConstraintName(issue) {
55
+ switch (issue.code) {
56
+ case "invalid_type":
57
+ const expected = issue.expected;
58
+ switch (expected) {
59
+ case "string":
60
+ return "IsStringConstraint";
61
+ case "number":
62
+ return "IsNumberConstraint";
63
+ case "boolean":
64
+ return "IsBooleanConstraint";
65
+ case "array":
66
+ return "IsArrayConstraint";
67
+ case "object":
68
+ return "IsObjectConstraint";
69
+ case "date":
70
+ return "IsDateConstraint";
71
+ default:
72
+ return "InvalidTypeConstraint";
73
+ }
74
+ case "too_small":
75
+ if (issue.type === "string") {
76
+ return "MinLengthConstraint";
77
+ }
78
+ else if (issue.type === "number") {
79
+ return "MinConstraint";
80
+ }
81
+ else if (issue.type === "array") {
82
+ return "ArrayMinSizeConstraint";
83
+ }
84
+ return "TooSmallConstraint";
85
+ case "too_big":
86
+ if (issue.type === "string") {
87
+ return "MaxLengthConstraint";
88
+ }
89
+ else if (issue.type === "number") {
90
+ return "MaxConstraint";
91
+ }
92
+ else if (issue.type === "array") {
93
+ return "ArrayMaxSizeConstraint";
94
+ }
95
+ return "TooBigConstraint";
96
+ case "invalid_string":
97
+ if ("validation" in issue) {
98
+ const validation = issue.validation;
99
+ if (validation === "email")
100
+ return "IsEmailConstraint";
101
+ if (validation === "uuid")
102
+ return "IsUuidConstraint";
103
+ if (validation === "url")
104
+ return "IsUrlConstraint";
105
+ if (typeof validation === "object" && "includes" in validation)
106
+ return "ContainsConstraint";
107
+ if (typeof validation === "object" && "startsWith" in validation)
108
+ return "StartsWithConstraint";
109
+ if (typeof validation === "object" && "endsWith" in validation)
110
+ return "EndsWithConstraint";
111
+ }
112
+ return "InvalidStringConstraint";
113
+ case "invalid_enum_value":
114
+ return "IsEnumConstraint";
115
+ case "invalid_literal":
116
+ return "EqualsConstraint";
117
+ case "unrecognized_keys":
118
+ return "UnrecognizedKeysConstraint";
119
+ case "invalid_union":
120
+ return "InvalidUnionConstraint";
121
+ case "invalid_date":
122
+ return "IsDateConstraint";
123
+ case "custom":
124
+ return "CustomConstraint";
125
+ default:
126
+ return "ValidationConstraint";
127
+ }
128
+ }
129
+ prettifyZod(error) {
130
+ const result = [];
131
+ for (const issue of error.issues) {
132
+ const fieldPath = issue.path
133
+ .map((segment, index) => {
134
+ if (typeof segment === "number") {
135
+ return `[${segment}]`;
136
+ }
137
+ return index === 0 ? segment : `.${segment}`;
138
+ })
139
+ .join("")
140
+ .replace(/\.\[/g, "[");
141
+ const fieldPascal = fieldPath
142
+ ? this.toPascalCase(fieldPath.replace(/\[\d+\]/g, ""))
143
+ : "Root";
144
+ const constraintName = this.mapZodToConstraintName(issue);
145
+ const message = this.injectFieldPathInZodMessage(issue.message, fieldPath, issue);
146
+ result.push({
147
+ message: message,
148
+ code: `${fieldPascal}${constraintName}`,
149
+ });
150
+ }
151
+ return result;
152
+ }
153
+ injectFieldPathInZodMessage(message, fieldPath, issue) {
154
+ if (!fieldPath) {
155
+ return message;
156
+ }
157
+ if (message === "Required") {
158
+ return `${fieldPath} is required`;
159
+ }
160
+ if (message.startsWith("String must")) {
161
+ return message.replace(/^String must/, `${fieldPath} must`);
162
+ }
163
+ if (message.startsWith("Number must")) {
164
+ return message.replace(/^Number must/, `${fieldPath} must`);
165
+ }
166
+ if (message.startsWith("Array must")) {
167
+ return message.replace(/^Array must/, `${fieldPath} must`);
168
+ }
169
+ if (message.startsWith("Expected")) {
170
+ return `${fieldPath} must be valid: ${message}`;
171
+ }
172
+ if (message.startsWith("Invalid ")) {
173
+ const type = message.replace("Invalid ", "").toLowerCase();
174
+ return `${fieldPath} must be a valid ${type}`;
175
+ }
176
+ return `${fieldPath} ${message}`;
177
+ }
178
+ }
179
+ const errorPrettifier = new ErrorPrettifier();
180
+ export default errorPrettifier;
181
+ //# sourceMappingURL=error-prettifier.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-prettifier.js","sourceRoot":"","sources":["../../../../../src/modules/base/utils/error-prettifier.ts"],"names":[],"mappings":"AA2CA,MAAM,OAAO,eAAe;IAa1B,QAAQ,CACN,OAA0B,EAC1B,KAAmC;QAEnC,IAAI,OAAO,KAAK,iBAAiB,EAAE,CAAC;YAClC,OAAO,IAAI,CAAC,sBAAsB,CAAC,KAA0B,CAAC,CAAC;QACjE,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC,WAAW,CAAC,KAAiB,CAAC,CAAC;QAC7C,CAAC;IACH,CAAC;IAcO,YAAY,CAAC,IAAY;QAC/B,OAAO,IAAI;aACR,KAAK,CAAC,GAAG,CAAC;aACV,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;aAC3D,IAAI,CAAC,EAAE,CAAC,CAAC;IACd,CAAC;IAoBO,qBAAqB,CAC3B,OAAe,EACf,SAAiB,EACjB,QAAgB;QAGhB,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC;YACvD,OAAO,OAAO,CAAC;QACjB,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,CAAC;QACjB,CAAC;QAKD,IAAI,OAAO,KAAK,UAAU,EAAE,CAAC;YAC3B,OAAO,GAAG,SAAS,cAAc,CAAC;QACpC,CAAC;QAGD,IAAI,OAAO,CAAC,UAAU,CAAC,aAAa,CAAC,EAAE,CAAC;YACtC,OAAO,OAAO,CAAC,OAAO,CAAC,cAAc,EAAE,GAAG,SAAS,OAAO,CAAC,CAAC;QAC9D,CAAC;QAGD,IAAI,OAAO,CAAC,UAAU,CAAC,aAAa,CAAC,EAAE,CAAC;YACtC,OAAO,OAAO,CAAC,OAAO,CAAC,cAAc,EAAE,GAAG,SAAS,OAAO,CAAC,CAAC;QAC9D,CAAC;QAGD,IAAI,OAAO,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,CAAC;YACrC,OAAO,OAAO,CAAC,OAAO,CAAC,aAAa,EAAE,GAAG,SAAS,OAAO,CAAC,CAAC;QAC7D,CAAC;QAGD,IAAI,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YACnC,OAAO,GAAG,SAAS,mBAAmB,OAAO,EAAE,CAAC;QAClD,CAAC;QAGD,IAAI,OAAO,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YACnC,MAAM,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,UAAU,EAAE,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;YAC3D,OAAO,GAAG,SAAS,oBAAoB,IAAI,EAAE,CAAC;QAChD,CAAC;QAGD,OAAO,GAAG,SAAS,IAAI,OAAO,EAAE,CAAC;IACnC,CAAC;CACF;AAED,MAAM,eAAe,GAAG,IAAI,eAAe,EAAE,CAAC;AAE9C,eAAe,eAAe,CAAC","sourcesContent":["import { ValidationError } from \"class-validator\";\nimport { ZodError, ZodIssue } from \"zod\";\n\n/**\n * Prettified error result with consistent format\n */\nexport interface PrettifiedError {\n /** Human-readable error message */\n message: string;\n /** Field name + constraint type code (e.g., 'NameIsStringConstraint') */\n code: string;\n}\n\n/**\n * Supported validation library types\n */\nexport type ValidationLibrary = \"class-validator\" | \"zod\";\n\n/**\n * ErrorPrettifier class for normalizing validation errors from class-validator and Zod\n * into a consistent format with field name + constraint code pattern.\n *\n * @example\n * ```typescript\n * const prettifier = new ErrorPrettifier();\n *\n * // Class-validator example\n * const classValidatorErrors = await validate(userDto);\n * const prettified = prettifier.prettify('class-validator', classValidatorErrors);\n * // [{ message: 'name must be a string', code: 'NameIsStringConstraint' }]\n *\n * // Zod example\n * try {\n * schema.parse(data);\n * } catch (error) {\n * const prettified = prettifier.prettify('zod', error);\n * // [{ message: 'name must be a string', code: 'NameIsStringConstraint' }]\n * }\n *\n * // Nested errors\n * // [{ message: 'user.address.street must be a string', code: 'UserAddressStreetIsStringConstraint' }]\n * ```\n */\nexport class ErrorPrettifier {\n /**\n * Prettifies validation errors from class-validator or Zod into a consistent format.\n *\n * @param library - The validation library type ('class-validator' or 'zod')\n * @param error - The validation error(s) from the library\n * @returns Array of prettified errors with consistent message and code format\n */\n prettify(\n library: \"class-validator\",\n error: ValidationError[]\n ): PrettifiedError[];\n prettify(library: \"zod\", error: ZodError): PrettifiedError[];\n prettify(\n library: ValidationLibrary,\n error: ValidationError[] | ZodError\n ): PrettifiedError[] {\n if (library === \"class-validator\") {\n return this.prettifyClassValidator(error as ValidationError[]);\n } else {\n return this.prettifyZod(error as ZodError);\n }\n }\n\n /**\n * Converts a field path to PascalCase for code generation.\n *\n * @example\n * ```typescript\n * toPascalCase('user.address.street') // 'UserAddressStreet'\n * toPascalCase('email') // 'Email'\n * ```\n *\n * @param path - Dot-separated field path\n * @returns PascalCase version of the path\n */\n private toPascalCase(path: string): string {\n return path\n .split(\".\")\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(\"\");\n }\n\n /**\n * Replaces the field name in the validation message with the full path.\n * Handles array indices like tags[0] and nested paths like user.address.street.\n *\n * @example\n * ```typescript\n * replaceFieldInMessage('id must be a UUID', 'id', 'user.id')\n * // Returns: 'user.id must be a UUID'\n *\n * replaceFieldInMessage('name must be a string', 'name', 'tags[0].name')\n * // Returns: 'tags[0].name must be a string'\n * ```\n *\n * @param message - Original validation message\n * @param fieldName - Original field name\n * @param fullPath - Full path including parent properties\n * @returns Message with field name replaced by full path\n */\n private replaceFieldInMessage(\n message: string,\n fieldName: string,\n fullPath: string\n ): string {\n // If it's a top-level field (no dots or brackets), return original message\n if (!fullPath.includes(\".\") && !fullPath.includes(\"[\")) {\n return message;\n }\n\n // Replace the field name at the start of the message with the full path\n // Handle cases like \"id must be a UUID\" -> \"user.id must be a UUID\"\n const regex = new RegExp(`^${fieldName}\\\\b`, \"i\");\n if (regex.test(message)) {\n return message.replace(regex, fullPath);\n }\n\n // If field name is not at the start, try to find it and replace\n // This handles cases like \"must be a valid id\" or other formats\n const wordBoundaryRegex = new RegExp(`\\\\b${fieldName}\\\\b`, \"gi\");\n if (wordBoundaryRegex.test(message)) {\n return message.replace(wordBoundaryRegex, fullPath);\n }\n\n // If we can't find the field name in the message, prepend the path\n return `${fullPath} ${message}`;\n }\n\n /**\n * Prettifies class-validator ValidationError array.\n * Handles nested validation errors recursively.\n *\n * @param errors - Array of ValidationError from class-validator\n * @param parentPath - Parent path for nested errors (used internally)\n * @returns Array of prettified errors\n */\n private prettifyClassValidator(\n errors: ValidationError[],\n parentPath: string = \"\"\n ): PrettifiedError[] {\n const result: PrettifiedError[] = [];\n\n for (const error of errors) {\n const currentPath = parentPath\n ? `${parentPath}.${error.property}`\n : error.property;\n\n // Handle nested errors\n if (error.children && error.children.length > 0) {\n result.push(\n ...this.prettifyClassValidator(error.children, currentPath)\n );\n continue;\n }\n\n // Handle constraints on current field\n if (error.constraints) {\n const fieldPascal = this.toPascalCase(currentPath);\n\n for (const [constraintKey, originalMessage] of Object.entries(\n error.constraints\n )) {\n // Convert constraint key to PascalCase (e.g., 'isString' -> 'IsString')\n const constraintName =\n constraintKey.charAt(0).toUpperCase() + constraintKey.slice(1);\n\n // Replace the field name in the message with the full path\n const message = this.replaceFieldInMessage(\n originalMessage,\n error.property,\n currentPath\n );\n\n result.push({\n message: message,\n code: `${fieldPascal}${constraintName}Constraint`,\n });\n }\n }\n }\n\n return result;\n }\n\n /**\n * Maps Zod error codes and validation info to class-validator style constraint names.\n *\n * @param issue - Zod validation issue\n * @returns Class-validator style constraint name\n */\n private mapZodToConstraintName(issue: ZodIssue): string {\n switch (issue.code) {\n case \"invalid_type\":\n const expected = issue.expected;\n switch (expected) {\n case \"string\":\n return \"IsStringConstraint\";\n case \"number\":\n return \"IsNumberConstraint\";\n case \"boolean\":\n return \"IsBooleanConstraint\";\n case \"array\":\n return \"IsArrayConstraint\";\n case \"object\":\n return \"IsObjectConstraint\";\n case \"date\":\n return \"IsDateConstraint\";\n default:\n return \"InvalidTypeConstraint\";\n }\n\n case \"too_small\":\n if (issue.type === \"string\") {\n return \"MinLengthConstraint\";\n } else if (issue.type === \"number\") {\n return \"MinConstraint\";\n } else if (issue.type === \"array\") {\n return \"ArrayMinSizeConstraint\";\n }\n return \"TooSmallConstraint\";\n\n case \"too_big\":\n if (issue.type === \"string\") {\n return \"MaxLengthConstraint\";\n } else if (issue.type === \"number\") {\n return \"MaxConstraint\";\n } else if (issue.type === \"array\") {\n return \"ArrayMaxSizeConstraint\";\n }\n return \"TooBigConstraint\";\n\n case \"invalid_string\":\n if (\"validation\" in issue) {\n const validation = issue.validation;\n if (validation === \"email\") return \"IsEmailConstraint\";\n if (validation === \"uuid\") return \"IsUuidConstraint\";\n if (validation === \"url\") return \"IsUrlConstraint\";\n if (typeof validation === \"object\" && \"includes\" in validation)\n return \"ContainsConstraint\";\n if (typeof validation === \"object\" && \"startsWith\" in validation)\n return \"StartsWithConstraint\";\n if (typeof validation === \"object\" && \"endsWith\" in validation)\n return \"EndsWithConstraint\";\n }\n return \"InvalidStringConstraint\";\n\n case \"invalid_enum_value\":\n return \"IsEnumConstraint\";\n\n case \"invalid_literal\":\n return \"EqualsConstraint\";\n\n case \"unrecognized_keys\":\n return \"UnrecognizedKeysConstraint\";\n\n case \"invalid_union\":\n return \"InvalidUnionConstraint\";\n\n case \"invalid_date\":\n return \"IsDateConstraint\";\n\n case \"custom\":\n return \"CustomConstraint\";\n\n default:\n return \"ValidationConstraint\";\n }\n }\n\n /**\n * Prettifies Zod ZodError.\n * Handles nested paths and multiple issues per field.\n *\n * @param error - ZodError from Zod validation\n * @returns Array of prettified errors\n */\n private prettifyZod(error: ZodError): PrettifiedError[] {\n const result: PrettifiedError[] = [];\n\n for (const issue of error.issues) {\n // Build the field path from the issue path\n const fieldPath = issue.path\n .map((segment, index) => {\n // Handle array indices: convert to bracket notation\n if (typeof segment === \"number\") {\n return `[${segment}]`;\n }\n // First segment doesn't need a dot prefix\n return index === 0 ? segment : `.${segment}`;\n })\n .join(\"\")\n .replace(/\\.\\[/g, \"[\"); // Clean up .[ to just [\n\n const fieldPascal = fieldPath\n ? this.toPascalCase(fieldPath.replace(/\\[\\d+\\]/g, \"\"))\n : \"Root\";\n\n // Map Zod error code to constraint name\n const constraintName = this.mapZodToConstraintName(issue);\n\n // Inject the field path into the message naturally\n const message = this.injectFieldPathInZodMessage(\n issue.message,\n fieldPath,\n issue\n );\n\n result.push({\n message: message,\n code: `${fieldPascal}${constraintName}`,\n });\n }\n\n return result;\n }\n\n /**\n * Injects the field path into Zod error messages naturally.\n *\n * @example\n * ```typescript\n * injectFieldPathInZodMessage('String must contain at least 100 character(s)', 'user.id', issue)\n * // Returns: 'user.id must contain at least 100 character(s)'\n *\n * injectFieldPathInZodMessage('Required', 'email', issue)\n * // Returns: 'email is required'\n * ```\n *\n * @param message - Original Zod error message\n * @param fieldPath - Full field path (e.g., 'user.id', 'tags[0].name')\n * @param issue - Zod issue for context\n * @returns Message with field path injected naturally\n */\n private injectFieldPathInZodMessage(\n message: string,\n fieldPath: string,\n issue: ZodIssue\n ): string {\n // If no field path (root level), return original message\n if (!fieldPath) {\n return message;\n }\n\n // Handle common Zod message patterns\n\n // \"Required\" -> \"fieldPath is required\"\n if (message === \"Required\") {\n return `${fieldPath} is required`;\n }\n\n // \"String must...\" -> \"fieldPath must...\"\n if (message.startsWith(\"String must\")) {\n return message.replace(/^String must/, `${fieldPath} must`);\n }\n\n // \"Number must...\" -> \"fieldPath must...\"\n if (message.startsWith(\"Number must\")) {\n return message.replace(/^Number must/, `${fieldPath} must`);\n }\n\n // \"Array must...\" -> \"fieldPath must...\"\n if (message.startsWith(\"Array must\")) {\n return message.replace(/^Array must/, `${fieldPath} must`);\n }\n\n // \"Expected string, received number\" -> \"fieldPath: Expected string, received number\"\n if (message.startsWith(\"Expected\")) {\n return `${fieldPath} must be valid: ${message}`;\n }\n\n // \"Invalid email\" -> \"fieldPath must be a valid email\"\n if (message.startsWith(\"Invalid \")) {\n const type = message.replace(\"Invalid \", \"\").toLowerCase();\n return `${fieldPath} must be a valid ${type}`;\n }\n\n // For any other message, prepend the field path\n return `${fieldPath} ${message}`;\n }\n}\n\nconst errorPrettifier = new ErrorPrettifier();\n\nexport default errorPrettifier;\n"]}
@@ -68,7 +68,10 @@ export class EmailService {
68
68
  const info = await transporter.sendMail({
69
69
  ...options,
70
70
  from: fromAddress,
71
- text: options?.text || convert(options.html),
71
+ text: options?.text ||
72
+ (typeof options.html === "string" && options.html
73
+ ? convert(options.html)
74
+ : undefined),
72
75
  });
73
76
  return { success: true, ...info };
74
77
  }