arkos 1.4.1-canary.1 → 1.4.1-canary.11

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 (62) hide show
  1. package/dist/cjs/modules/auth/auth.service.js +1 -1
  2. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  3. package/dist/cjs/modules/auth/utils/services/auth-action.service.js +15 -9
  4. package/dist/cjs/modules/auth/utils/services/auth-action.service.js.map +1 -1
  5. package/dist/cjs/modules/base/base.middlewares.js +10 -2
  6. package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
  7. package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +27 -9
  8. package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
  9. package/dist/cjs/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js +28 -11
  10. package/dist/cjs/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js.map +1 -1
  11. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
  12. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  13. package/dist/cjs/utils/arkos-router/index.js +19 -6
  14. package/dist/cjs/utils/arkos-router/index.js.map +1 -1
  15. package/dist/cjs/utils/cli/dev.js +1 -45
  16. package/dist/cjs/utils/cli/dev.js.map +1 -1
  17. package/dist/cjs/utils/cli/start.js +11 -8
  18. package/dist/cjs/utils/cli/start.js.map +1 -1
  19. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  20. package/dist/cjs/utils/cli/utils/runtime-cli-commander.js +6 -6
  21. package/dist/cjs/utils/cli/utils/runtime-cli-commander.js.map +1 -1
  22. package/dist/cjs/utils/dotenv.helpers.js +6 -2
  23. package/dist/cjs/utils/dotenv.helpers.js.map +1 -1
  24. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +19 -4
  25. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  26. package/dist/cjs/utils/validate-dto.js +1 -5
  27. package/dist/cjs/utils/validate-dto.js.map +1 -1
  28. package/dist/cjs/utils/validate-schema.js +2 -7
  29. package/dist/cjs/utils/validate-schema.js.map +1 -1
  30. package/dist/esm/modules/auth/auth.service.js +1 -1
  31. package/dist/esm/modules/auth/auth.service.js.map +1 -1
  32. package/dist/esm/modules/auth/utils/services/auth-action.service.js +15 -9
  33. package/dist/esm/modules/auth/utils/services/auth-action.service.js.map +1 -1
  34. package/dist/esm/modules/base/base.middlewares.js +10 -2
  35. package/dist/esm/modules/base/base.middlewares.js.map +1 -1
  36. package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +27 -9
  37. package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
  38. package/dist/esm/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js +28 -11
  39. package/dist/esm/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js.map +1 -1
  40. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
  41. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  42. package/dist/esm/utils/arkos-router/index.js +19 -6
  43. package/dist/esm/utils/arkos-router/index.js.map +1 -1
  44. package/dist/esm/utils/cli/dev.js +2 -46
  45. package/dist/esm/utils/cli/dev.js.map +1 -1
  46. package/dist/esm/utils/cli/start.js +11 -8
  47. package/dist/esm/utils/cli/start.js.map +1 -1
  48. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  49. package/dist/esm/utils/cli/utils/runtime-cli-commander.js +6 -6
  50. package/dist/esm/utils/cli/utils/runtime-cli-commander.js.map +1 -1
  51. package/dist/esm/utils/dotenv.helpers.js +6 -2
  52. package/dist/esm/utils/dotenv.helpers.js.map +1 -1
  53. package/dist/esm/utils/prisma/prisma-json-schema-generator.js +19 -4
  54. package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  55. package/dist/esm/utils/validate-dto.js +1 -2
  56. package/dist/esm/utils/validate-dto.js.map +1 -1
  57. package/dist/esm/utils/validate-schema.js +2 -4
  58. package/dist/esm/utils/validate-schema.js.map +1 -1
  59. package/dist/types/utils/arkos-router/index.d.ts +2 -1
  60. package/dist/types/utils/cli/dev.d.ts +1 -1
  61. package/dist/types/utils/cli/start.d.ts +1 -1
  62. package/package.json +2 -2
@@ -176,7 +176,7 @@ class AuthService {
176
176
  }
177
177
  async getAuthenticatedUser(req) {
178
178
  if (!(0, arkos_config_helpers_1.isAuthenticationEnabled)())
179
- return null;
179
+ throw Error("ValidationError: Trying to call getAuthenticatedUser without setting up authentication");
180
180
  const prisma = (0, prisma_helpers_1.getPrismaInstance)();
181
181
  let token;
182
182
  if (req?.headers?.authorization &&
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAavE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AACrE,mFAGkD;AAKlD,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA2arD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,IAAI,IAAA,8CAAuB,GAAE;gBAC3B,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;YAC5D,IAAI,EAAE,CAAC;QACT,CAAC,CACF,CAAC;IAqFJ,CAAC;IA5fC,YAAY,CACV,EAAmB,EACnB,SAA+B,EAC/B,MAAe;QAEf,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GA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B,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,2BAAU,CAAC,QAAQ,CAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC;oBAC5D,aAAa,GAAG,IAAA,oCAAmB,EAAC,IAAA,iBAAS,EAAC,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;AA1gBD,kCA0gBC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,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()) return null;\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 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,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAavE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AACrE,mFAGkD;AAKlD,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA8arD,iBAAY,GAAG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AAO,KAAK,EAAE,IAAqC,EAAoB,EAAE;YAEvE,MAAM,OAAO,GAAG,IAAA,uBAAc,GAAE,CAAC;YAEjC,IAAI,CAAC,IAAA,4CAAqB,GAAE;gBAC1B,MAAM,KAAK,CACT,2FAA2F,CAC5F,CAAC;YAEJ,IAAI,CAAC,IAAI;gBAAE,MAAM,uCAAkB,CAAC;YACpC,IAAI,IAAI,CAAC,WAAW;gBAAE,OAAO,IAAI,CAAC;YAElC,IAAI,OAAO,EAAE,cAAc,EAAE,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,2BAAU,CAAC,QAAQ,CAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC;oBAC5D,aAAa,GAAG,IAAA,oCAAmB,EAAC,IAAA,iBAAS,EAAC,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;AA9gBD,kCA8gBC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,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"]}
@@ -21,19 +21,25 @@ class AuthActionService {
21
21
  const existingAuthAction = this.getOne(action, resource);
22
22
  if (existingAuthAction) {
23
23
  const inconsistencies = [];
24
- if (existingAuthAction.name !== transformedAction.name &&
25
- existingAuthAction.name !== undefined &&
26
- transformedAction.name !== undefined) {
24
+ const defaultName = `${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(action).replace(/-/g, " "))} ${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(resource).replace(/-/g, " "))}`;
25
+ const defaultDescription = `${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(action).replace(/-/g, " "))} ${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(resource).replace(/-/g, " "))}`;
26
+ const defaultErrorMessage = "You do not have permission to perform this operation";
27
+ const isNonDefault = (value, defaultValue) => {
28
+ return value !== undefined && value !== defaultValue;
29
+ };
30
+ if (isNonDefault(existingAuthAction.name, defaultName) &&
31
+ isNonDefault(transformedAction.name, defaultName) &&
32
+ existingAuthAction.name !== transformedAction.name) {
27
33
  inconsistencies.push(` - name: "${existingAuthAction.name}" vs "${transformedAction.name}"`);
28
34
  }
29
- if (existingAuthAction.description !== transformedAction.description &&
30
- existingAuthAction.description !== undefined &&
31
- transformedAction.description !== undefined) {
35
+ if (isNonDefault(existingAuthAction.description, defaultDescription) &&
36
+ isNonDefault(transformedAction.description, defaultDescription) &&
37
+ existingAuthAction.description !== transformedAction.description) {
32
38
  inconsistencies.push(` - description: "${existingAuthAction.description}" vs "${transformedAction.description}"`);
33
39
  }
34
- if (existingAuthAction.errorMessage !== transformedAction.errorMessage &&
35
- existingAuthAction.errorMessage !== undefined &&
36
- transformedAction.errorMessage !== undefined) {
40
+ if (isNonDefault(existingAuthAction.errorMessage, defaultErrorMessage) &&
41
+ isNonDefault(transformedAction.errorMessage, defaultErrorMessage) &&
42
+ existingAuthAction.errorMessage !== transformedAction.errorMessage) {
37
43
  inconsistencies.push(` - errorMessage: "${existingAuthAction.errorMessage}" vs "${transformedAction.errorMessage}"`);
38
44
  }
39
45
  if (inconsistencies.length > 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"auth-action.service.js","sourceRoot":"","sources":["../../../../../../src/modules/auth/utils/services/auth-action.service.ts"],"names":[],"mappings":";;AAAA,qDAAsD;AAKtD,yFAAgF;AAChF,yEAAoE;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;IAoLJ,CAAC;IAlLC,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,CAAC;YACvB,MAAM,eAAe,GAAa,EAAE,CAAC;YAErC,IACE,kBAAkB,CAAC,IAAI,KAAK,iBAAiB,CAAC,IAAI;gBAClD,kBAAkB,CAAC,IAAI,KAAK,SAAS;gBACrC,iBAAiB,CAAC,IAAI,KAAK,SAAS,EACpC,CAAC;gBACD,eAAe,CAAC,IAAI,CAClB,cAAc,kBAAkB,CAAC,IAAI,SAAS,iBAAiB,CAAC,IAAI,GAAG,CACxE,CAAC;YACJ,CAAC;YAED,IACE,kBAAkB,CAAC,WAAW,KAAK,iBAAiB,CAAC,WAAW;gBAChE,kBAAkB,CAAC,WAAW,KAAK,SAAS;gBAC5C,iBAAiB,CAAC,WAAW,KAAK,SAAS,EAC3C,CAAC;gBACD,eAAe,CAAC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["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 if (\n existingAuthAction.name !== transformedAction.name &&\n existingAuthAction.name !== undefined &&\n transformedAction.name !== undefined\n ) {\n inconsistencies.push(\n ` - name: \"${existingAuthAction.name}\" vs \"${transformedAction.name}\"`\n );\n }\n\n if (\n existingAuthAction.description !== transformedAction.description &&\n existingAuthAction.description !== undefined &&\n transformedAction.description !== undefined\n ) {\n inconsistencies.push(\n ` - description: \"${existingAuthAction.description}\" vs \"${transformedAction.description}\"`\n );\n }\n\n if (\n existingAuthAction.errorMessage !== transformedAction.errorMessage &&\n existingAuthAction.errorMessage !== undefined &&\n transformedAction.errorMessage !== undefined\n ) {\n inconsistencies.push(\n ` - errorMessage: \"${existingAuthAction.errorMessage}\" vs \"${transformedAction.errorMessage}\"`\n );\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,qDAAsD;AAKtD,yFAAgF;AAChF,yEAAoE;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,CAAC;YACvB,MAAM,eAAe,GA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esContent":["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"]}
@@ -17,6 +17,7 @@ const validate_schema_1 = __importDefault(require("../../utils/validate-schema")
17
17
  const base_middlewares_helpers_1 = require("./utils/helpers/base.middlewares.helpers");
18
18
  const text_helpers_1 = require("../../utils/helpers/text.helpers");
19
19
  const dynamic_loader_1 = require("../../utils/dynamic-loader");
20
+ const utils_1 = require("../../exports/utils");
20
21
  function callNext(_, _1, next) {
21
22
  next();
22
23
  }
@@ -201,7 +202,7 @@ function validateRequestInputs(routeConfig) {
201
202
  });
202
203
  return (0, error_handler_1.catchAsync)(async (req, _, next) => {
203
204
  for (const key of validatorsKey) {
204
- const reqInput = Object.keys(req[key]).length > 0;
205
+ const reqInput = Object.keys(req[key] || {}).length > 0;
205
206
  const validator = validators?.[key];
206
207
  const notAllowedInputError = new error_handler_1.AppError(`Request ${key} is not allowed on this route`, 400, `Request${(0, text_helpers_1.capitalize)(key)}NotAllowed`, { [key]: req[key] });
207
208
  if (((typeof validators === "boolean" && validators === false) ||
@@ -211,7 +212,14 @@ function validateRequestInputs(routeConfig) {
211
212
  if (strictValidation && !validator && reqInput)
212
213
  throw notAllowedInputError;
213
214
  if (validator)
214
- req[key] = await validatorFn(validator, req[key], arkosConfig.validation?.validationOptions);
215
+ try {
216
+ req[key] = await validatorFn(validator, req[key], arkosConfig.validation?.validationOptions);
217
+ }
218
+ catch (err) {
219
+ throw new error_handler_1.AppError(`Invalid request ${key}`, 400, `InvalidRequest${(0, utils_1.pascalCase)(key)}`, (err &&
220
+ (validationConfig?.resolver === "zod" ? err.format() : err)) ||
221
+ {});
222
+ }
215
223
  }
216
224
  next();
217
225
  });
@@ -1 +1 @@
1
- {"version":3,"file":"base.middlewares.js","sourceRoot":"","sources":["../../../../src/modules/base/base.middlewares.ts"],"names":[],"mappings":";;;;;AAsBA,4BAEC;AA4BD,oCA4DC;AAkBD,wEAqBC;AAMD,8CA6CC;AASD,oGA2BC;AAED,sDAmHC;AA1VD,yCAA8C;AAC9C,4FAA6D;AAC7D,+DAAmE;AACnE,4EAAmD;AACnD,kFAAyD;AAIzD,uFAAqF;AAErF,mEAA8D;AAC9D,+DAAkE;AAElE,SAAgB,QAAQ,CAAC,CAAU,EAAE,EAAY,EAAE,IAAkB;IACnE,IAAI,EAAE,CAAC;AACT,CAAC;AAKD,SAAS,SAAS,CAAC,CAAM,EAAE,CAAM;IAC/B,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAA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,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\";\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 req[key] = await validatorFn(\n validator,\n req[key],\n arkosConfig.validation?.validationOptions\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":";;;;;AAuBA,4BAEC;AA4BD,oCA4DC;AAkBD,wEAqBC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AAO,UAAU,KAAK,SAAS,IAAI,UAAU,KAAK,KAAK,CAAC;gBACxD,SAAS,KAAK,KAAK,CAAC;gBACtB,QAAQ;gBAER,MAAM,oBAAoB,CAAC;YAE7B,IAAI,gBAAgB,IAAI,CAAC,SAAS,IAAI,QAAQ;gBAC5C,MAAM,oBAAoB,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,wBAAQ,CAChB,mBAAmB,GAAG,EAAE,EACxB,GAAG,EACH,iBAAiB,IAAA,kBAAU,EAAC,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"]}
@@ -44,7 +44,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
44
44
  : currentPath?.summary,
45
45
  description: currentPath?.description ||
46
46
  "Authenticates a user and returns an access token",
47
- operationId: currentPath?.operationId || "login",
47
+ operationId: currentPath?.operationId?.includes(pathname)
48
+ ? "login"
49
+ : currentPath?.operationId,
48
50
  requestBody: currentPath?.requestBody || {
49
51
  description: "User credentials",
50
52
  required: true,
@@ -95,7 +97,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
95
97
  ? "Logout from the system"
96
98
  : currentPath?.summary,
97
99
  description: currentPath?.description || "Invalidates the current user's JWT token",
98
- operationId: currentPath?.operationId || "logout",
100
+ operationId: currentPath?.operationId?.includes(pathname)
101
+ ? "logout"
102
+ : currentPath?.operationId,
99
103
  security: [{ BearerAuth: [] }],
100
104
  responses: {
101
105
  ...(currentPath?.responses || {}),
@@ -122,7 +126,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
122
126
  ? "Register a new user"
123
127
  : currentPath?.summary,
124
128
  description: currentPath?.description || "Creates a new user account",
125
- operationId: currentPath?.operationId || "signup",
129
+ operationId: currentPath?.operationId?.includes(pathname)
130
+ ? "signup"
131
+ : currentPath?.operationId,
126
132
  requestBody: currentPath?.requestBody || {
127
133
  description: "User registration data",
128
134
  required: true,
@@ -169,7 +175,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
169
175
  : currentPath?.summary,
170
176
  description: currentPath?.description ||
171
177
  "Changes the password for the authenticated user",
172
- operationId: currentPath?.operationId || "updatePassword",
178
+ operationId: currentPath?.operationId?.includes(pathname)
179
+ ? "updatePassword"
180
+ : currentPath?.operationId,
173
181
  security: [{ BearerAuth: [] }],
174
182
  requestBody: currentPath?.requestBody || {
175
183
  description: "Current and new password",
@@ -227,7 +235,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
227
235
  : currentPath?.summary,
228
236
  description: currentPath?.description ||
229
237
  "Retrieves information about the currently authenticated user",
230
- operationId: currentPath?.operationId || "getMe",
238
+ operationId: currentPath?.operationId?.includes(pathname)
239
+ ? "getMe"
240
+ : currentPath?.operationId,
231
241
  security: [{ BearerAuth: [] }],
232
242
  responses: {
233
243
  ...(currentPath?.responses || {}),
@@ -262,7 +272,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
262
272
  : currentPath?.summary,
263
273
  description: currentPath?.description ||
264
274
  "Updates information for the currently authenticated user",
265
- operationId: currentPath?.operationId || "updateMe",
275
+ operationId: currentPath?.operationId?.includes(pathname)
276
+ ? "updateMe"
277
+ : currentPath?.operationId,
266
278
  security: [{ BearerAuth: [] }],
267
279
  requestBody: currentPath?.requestBody || {
268
280
  description: "User data to update",
@@ -309,7 +321,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
309
321
  : currentPath?.summary,
310
322
  description: currentPath?.description ||
311
323
  "Marks the current user's account as deleted",
312
- operationId: currentPath?.operationId || "deleteMe",
324
+ operationId: currentPath?.operationId?.includes(pathname)
325
+ ? "deleteMe"
326
+ : currentPath?.operationId,
313
327
  security: [{ BearerAuth: [] }],
314
328
  responses: {
315
329
  ...(currentPath?.responses || {}),
@@ -348,7 +362,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
348
362
  : currentPath?.summary,
349
363
  description: currentPath?.description ||
350
364
  "Retrieves a list of all available authentication actions and permissions",
351
- operationId: currentPath?.operationId || "findManyAuthAction",
365
+ operationId: currentPath?.operationId?.includes(pathname)
366
+ ? "findManyAuthAction"
367
+ : currentPath?.operationId,
352
368
  security: [{ BearerAuth: [] }],
353
369
  responses: {
354
370
  ...(currentPath?.responses || {}),
@@ -415,7 +431,9 @@ function getAuthenticationJsonSchemaPaths(arkosConfig, existingPaths) {
415
431
  : currentPath?.summary,
416
432
  description: currentPath?.description ||
417
433
  "Retrieves all authentication actions for a specific resource",
418
- operationId: currentPath?.operationId || "findOneAuthAction",
434
+ operationId: currentPath?.operationId?.includes(pathname)
435
+ ? "findOneAuthAction"
436
+ : currentPath?.operationId,
419
437
  security: [{ BearerAuth: [] }],
420
438
  parameters: mergedParameters,
421
439
  responses: {