arkos 2.0.0-next.18 → 2.0.0-next.19

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 (112) hide show
  1. package/cli.js +8 -1
  2. package/dist/esm/app.js +1 -1
  3. package/dist/esm/app.js.map +1 -1
  4. package/dist/esm/components/arkos-gateway/arkos-gateway.js +5 -4
  5. package/dist/esm/components/arkos-gateway/arkos-gateway.js.map +1 -1
  6. package/dist/esm/components/arkos-gateway/socket-extensions.js +7 -0
  7. package/dist/esm/components/arkos-gateway/socket-extensions.js.map +1 -1
  8. package/dist/esm/components/arkos-gateway/utils/memory-gateway-store.js +2 -4
  9. package/dist/esm/components/arkos-gateway/utils/memory-gateway-store.js.map +1 -1
  10. package/dist/esm/components/arkos-gateway/utils/multi-tier-arkos-gateway-store.js +1 -0
  11. package/dist/esm/components/arkos-gateway/utils/multi-tier-arkos-gateway-store.js.map +1 -1
  12. package/dist/esm/components/arkos-loadable-registry/index.js +1 -3
  13. package/dist/esm/components/arkos-loadable-registry/index.js.map +1 -1
  14. package/dist/esm/components/arkos-route-hook/reader.js.map +1 -1
  15. package/dist/esm/components/arkos-route-hook/types.js.map +1 -1
  16. package/dist/esm/exports/index.js +1 -1
  17. package/dist/esm/exports/index.js.map +1 -1
  18. package/dist/esm/exports/middlewares/index.js +1 -1
  19. package/dist/esm/exports/middlewares/index.js.map +1 -1
  20. package/dist/esm/modules/auth/auth.controller.js +213 -221
  21. package/dist/esm/modules/auth/auth.controller.js.map +1 -1
  22. package/dist/esm/modules/auth/auth.service.js +11 -58
  23. package/dist/esm/modules/auth/auth.service.js.map +1 -1
  24. package/dist/esm/modules/auth/utils/auth-prisma-json-schema-generator.js +1 -0
  25. package/dist/esm/modules/auth/utils/auth-prisma-json-schema-generator.js.map +1 -1
  26. package/dist/esm/modules/auth/utils/services/auth-action.service.js +10 -12
  27. package/dist/esm/modules/auth/utils/services/auth-action.service.js.map +1 -1
  28. package/dist/esm/modules/base/base.controller.js +179 -177
  29. package/dist/esm/modules/base/base.controller.js.map +1 -1
  30. package/dist/esm/modules/base/base.middlewares.js +6 -21
  31. package/dist/esm/modules/base/base.middlewares.js.map +1 -1
  32. package/dist/esm/modules/base/base.service.js +28 -25
  33. package/dist/esm/modules/base/base.service.js.map +1 -1
  34. package/dist/esm/modules/base/utils/error-prettifier.js +26 -30
  35. package/dist/esm/modules/base/utils/error-prettifier.js.map +1 -1
  36. package/dist/esm/modules/email/email.service.js +2 -2
  37. package/dist/esm/modules/email/email.service.js.map +1 -1
  38. package/dist/esm/modules/error-handler/utils/app-error.js +5 -1
  39. package/dist/esm/modules/error-handler/utils/app-error.js.map +1 -1
  40. package/dist/esm/modules/file-upload/file-upload.controller.js +203 -205
  41. package/dist/esm/modules/file-upload/file-upload.controller.js.map +1 -1
  42. package/dist/esm/modules/file-upload/file-upload.router.js +3 -3
  43. package/dist/esm/modules/file-upload/file-upload.router.js.map +1 -1
  44. package/dist/esm/modules/file-upload/file-upload.service.js +12 -7
  45. package/dist/esm/modules/file-upload/file-upload.service.js.map +1 -1
  46. package/dist/esm/modules/file-upload/utils/file-upload-json-schema-generator.js +1 -1
  47. package/dist/esm/modules/file-upload/utils/file-upload-json-schema-generator.js.map +1 -1
  48. package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
  49. package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js +1 -0
  50. package/dist/esm/modules/swagger/utils/helpers/openapi-schema-converter.js.map +1 -1
  51. package/dist/esm/types/index.js.map +1 -1
  52. package/dist/esm/types/new-arkos-config.js.map +1 -1
  53. package/dist/esm/types/router-config.js.map +1 -1
  54. package/dist/esm/types/validation/validation-manager.js +21 -22
  55. package/dist/esm/types/validation/validation-manager.js.map +1 -1
  56. package/dist/esm/utils/arkos-router/index.js +1 -6
  57. package/dist/esm/utils/arkos-router/index.js.map +1 -1
  58. package/dist/esm/utils/arkos-router/route-config-registry.js +2 -3
  59. package/dist/esm/utils/arkos-router/route-config-registry.js.map +1 -1
  60. package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
  61. package/dist/esm/utils/arkos-router/utils/helpers/index.js +86 -43
  62. package/dist/esm/utils/arkos-router/utils/helpers/index.js.map +1 -1
  63. package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js +12 -14
  64. package/dist/esm/utils/arkos-router/utils/helpers/upload-manager.js.map +1 -1
  65. package/dist/esm/utils/bundler.js +6 -6
  66. package/dist/esm/utils/bundler.js.map +1 -1
  67. package/dist/esm/utils/cli/dev.js +4 -17
  68. package/dist/esm/utils/cli/dev.js.map +1 -1
  69. package/dist/esm/utils/cli/prisma-generate.js +8 -37
  70. package/dist/esm/utils/cli/prisma-generate.js.map +1 -1
  71. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  72. package/dist/esm/utils/cli/utils/smart-fs-watcher.js +3 -0
  73. package/dist/esm/utils/cli/utils/smart-fs-watcher.js.map +1 -1
  74. package/dist/esm/utils/cli/utils/template-generator/templates/router-template.js +1 -1
  75. package/dist/esm/utils/cli/utils/template-generator/templates/router-template.js.map +1 -1
  76. package/dist/esm/utils/dynamic-loader.js +2 -1
  77. package/dist/esm/utils/dynamic-loader.js.map +1 -1
  78. package/dist/esm/utils/features/api.features.js +24 -20
  79. package/dist/esm/utils/features/api.features.js.map +1 -1
  80. package/dist/esm/utils/features/port-and-host-allocator.js +4 -3
  81. package/dist/esm/utils/features/port-and-host-allocator.js.map +1 -1
  82. package/dist/esm/utils/helpers/arkos-config.helpers.js.map +1 -1
  83. package/dist/esm/utils/helpers/query-parser.helpers.js +7 -22
  84. package/dist/esm/utils/helpers/query-parser.helpers.js.map +1 -1
  85. package/dist/esm/utils/initialize-app.js +1 -1
  86. package/dist/esm/utils/initialize-app.js.map +1 -1
  87. package/dist/esm/utils/prisma/prisma-json-schema-generator.js +1 -3
  88. package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  89. package/dist/esm/utils/prisma/prisma-schema-parser.js +14 -8
  90. package/dist/esm/utils/prisma/prisma-schema-parser.js.map +1 -1
  91. package/dist/esm/utils/validate-schema.js +23 -21
  92. package/dist/esm/utils/validate-schema.js.map +1 -1
  93. package/dist/types/app.d.ts +1 -1
  94. package/dist/types/components/arkos-route-hook/reader.d.ts +2 -5
  95. package/dist/types/components/arkos-route-hook/types.d.ts +4 -4
  96. package/dist/types/exports/index.d.ts +3 -4
  97. package/dist/types/exports/middlewares/index.d.ts +1 -1
  98. package/dist/types/modules/auth/auth.service.d.ts +1 -40
  99. package/dist/types/modules/base/base.middlewares.d.ts +1 -10
  100. package/dist/types/modules/swagger/swagger.router.d.ts +1 -2
  101. package/dist/types/types/index.d.ts +3 -3
  102. package/dist/types/types/new-arkos-config.d.ts +0 -14
  103. package/dist/types/types/router-config.d.ts +0 -111
  104. package/dist/types/utils/arkos-router/types/index.d.ts +3 -3
  105. package/dist/types/utils/arkos-router/utils/helpers/index.d.ts +2 -6
  106. package/dist/types/utils/dynamic-loader.d.ts +2 -2
  107. package/dist/types/utils/helpers/query-parser.helpers.d.ts +1 -1
  108. package/dist/types/utils/prisma/prisma-schema-parser.d.ts +1 -0
  109. package/package.json +41 -41
  110. package/dist/esm/components/arkos-loadable-translator/index.js +0 -138
  111. package/dist/esm/components/arkos-loadable-translator/index.js.map +0 -1
  112. package/dist/types/components/arkos-loadable-translator/index.d.ts +0 -53
@@ -2,7 +2,6 @@ import jwt from "jsonwebtoken";
2
2
  import bcrypt from "bcryptjs";
3
3
  import catchAsync from "../error-handler/utils/catch-async.js";
4
4
  import AppError from "../error-handler/utils/app-error.js";
5
- import { callNext } from "../base/base.middlewares.js";
6
5
  import arkosEnv from "../../utils/arkos-env.js";
7
6
  import { getPrismaInstance } from "../../utils/helpers/prisma.helpers.js";
8
7
  import { toMs } from "./utils/helpers/auth.controller.helpers.js";
@@ -13,19 +12,7 @@ import { getUserFileExtension } from "../../utils/helpers/fs.helpers.js";
13
12
  import { authenticationDocsLinks } from "./utils/docs-links.js";
14
13
  import authHookManager from "./utils/auth-hooks-manager.js";
15
14
  export class AuthService {
16
- constructor() {
17
- this.actionsPerResource = {};
18
- this.authenticate = catchAsync(async (req, _, next) => {
19
- await authHookManager.runAuthenticate({ context: req, done: next }, async (req) => {
20
- if (!isAuthenticationEnabled())
21
- return null;
22
- const user = (await this.getAuthenticatedUser(req, req.path.includes("logout") ? "logout" : "default"));
23
- if (!user)
24
- throw loginRequiredError;
25
- return user;
26
- });
27
- });
28
- }
15
+ actionsPerResource = {};
29
16
  signJwtToken(id, expiresIn, secret) {
30
17
  const { authentication: configs } = getArkosConfig();
31
18
  if (process.env.ARKOS_BUILD === "true" &&
@@ -85,12 +72,6 @@ export class AuthService {
85
72
  async hashPassword(password) {
86
73
  return await bcrypt.hash(password, 12);
87
74
  }
88
- isPasswordStrong(password) {
89
- const initAuthConfigs = getArkosConfig()?.authentication;
90
- const strongPasswordRegex = initAuthConfigs?.passwordValidation?.regex ||
91
- /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).+$/;
92
- return strongPasswordRegex.test(password);
93
- }
94
75
  userChangedPasswordAfter(user, JWTTimestamp) {
95
76
  if (user.passwordChangedAt) {
96
77
  const convertedTimestamp = parseInt(String(new Date(user.passwordChangedAt).getTime() / 1000), 10);
@@ -186,33 +167,6 @@ export class AuthService {
186
167
  return userPermission.effect === "Allow";
187
168
  return !!hasRolePermission;
188
169
  }
189
- handleAccessControl(action, resource, accessControl) {
190
- const authAction = authActionService.add(action, resource, accessControl);
191
- return catchAsync(async (req, _, next) => {
192
- if (req.user) {
193
- const user = req.user;
194
- const configs = getArkosConfig();
195
- if (user.isSuperUser) {
196
- next();
197
- return;
198
- }
199
- const notEnoughPermissionsError = new AppError(authAction.errorMessage, 403, "NotEnoughPermissions");
200
- if (configs?.authentication?.mode === "dynamic") {
201
- const hasPermission = await this.checkDynamicAccessControl(user.id, action, resource);
202
- if (!hasPermission)
203
- return next(notEnoughPermissionsError);
204
- }
205
- else if (configs?.authentication?.mode === "static") {
206
- if (!accessControl)
207
- return next(notEnoughPermissionsError);
208
- const hasPermission = this.checkStaticAccessControl(user, action, accessControl);
209
- if (!hasPermission)
210
- return next(notEnoughPermissionsError);
211
- }
212
- }
213
- next();
214
- });
215
- }
216
170
  extractRequestToken(req, cookie = "arkos_access_token") {
217
171
  let token = null;
218
172
  if (req?.headers?.authorization &&
@@ -255,6 +209,16 @@ export class AuthService {
255
209
  ctx.accessToken = token;
256
210
  return this.validateDecodedUser(decoded, action);
257
211
  }
212
+ authenticate = catchAsync(async (req, _, next) => {
213
+ await authHookManager.runAuthenticate({ context: req, done: next }, async (req) => {
214
+ if (!isAuthenticationEnabled())
215
+ return null;
216
+ const user = (await this.getAuthenticatedUser(req, req.path.includes("logout") ? "logout" : "default"));
217
+ if (!user)
218
+ throw loginRequiredError;
219
+ return user;
220
+ });
221
+ });
258
222
  authorize(action, resource, rule) {
259
223
  const authAction = authActionService.add(action, resource, {
260
224
  [action]: rule,
@@ -263,17 +227,6 @@ export class AuthService {
263
227
  await authHookManager.runAuthorize({ context: req, done: next }, authAction);
264
228
  });
265
229
  }
266
- handleAuthenticationControl(action, authenticationControl) {
267
- if (authenticationControl && typeof authenticationControl === "object") {
268
- if (authenticationControl[action] === false)
269
- return callNext;
270
- else if (authenticationControl[action] === true)
271
- return this.authenticate;
272
- }
273
- else
274
- return this.authenticate;
275
- return this.authenticate;
276
- }
277
230
  permission(action, resource, accessControl) {
278
231
  const stack = new Error().stack;
279
232
  if (stack?.includes("node_modules/express/lib/router/index.js"))
@@ -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,MAAM,0BAA0B,CAAC;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;gBAAE,MAAM,kBAAkB,CAAC;YACpC,IAAI,IAAI,EAAE,WAAW;gBAAE,OAAO,IAAI,CAAC;YAEnC,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,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 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 {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n getArkosConfig,\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\nimport { CookieOptions } from \"express\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\nimport { authenticationDocsLinks } from \"./utils/docs-links\";\nimport authHookManager from \"./utils/auth-hooks-manager\";\nimport { ArkosSocket } from \"../../components/arkos-gateway/types\";\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 if (authConfigs?.jwt?.cookie?.secure !== undefined)\n return authConfigs?.jwt?.cookie?.secure;\n else if (process.env.JWT_COOKIE_SECURE !== undefined)\n return process.env.JWT_COOKIE_SECURE === \"true\";\n else return req.secure || req.headers[\"x-forwarded-proto\"] === \"https\";\n })(),\n sameSite,\n domain: authConfigs?.jwt?.cookie?.domain || process.env.JWT_COOKIE_DOMAIN,\n ...arkosConfig?.authentication?.jwt?.cookie,\n } as CookieOptions;\n }\n\n /**\n * Is used by default internally by Arkos under `ArkosPrismaService` 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 `ArkosPrismaService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `ArkosPrismaService` 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(new Date(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 try {\n const decoded = (await new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n })) as AuthJwtPayload;\n\n if (!decoded?.id) throw invaliAuthTokenError;\n\n return decoded;\n } catch (err) {\n throw invaliAuthTokenError;\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 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 async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n\n const [userPermission, hasRolePermission] = await Promise.all([\n prisma.userPermission\n ? prisma.userPermission.findFirst({\n where: { userId, permission: { resource, action } },\n select: { effect: true },\n })\n : Promise.resolve(null),\n\n prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: { resource, action },\n },\n },\n },\n select: { id: true },\n }),\n ]);\n\n if (userPermission) return userPermission.effect === \"Allow\";\n return !!hasRolePermission;\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 * @deprecated Will be removed on v2.0, use AuthService.authorize instead\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n const authAction = 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 authAction.errorMessage,\n 403,\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 private extractRequestToken(\n req: ArkosRequest,\n cookie: \"arkos_access_token\" = \"arkos_access_token\"\n ) {\n let token: string | null = null;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\") &&\n req?.headers?.authorization.split?.(\" \")?.[1]\n )\n token = req?.headers?.authorization.split(\" \")[1];\n\n if (\n !token &&\n req?.cookies?.arkos_access_token !== \"no-token\" &&\n req.cookies\n )\n token = req?.cookies?.[cookie];\n\n return token;\n }\n\n private extractSocketToken(socket: ArkosSocket, key: \"token\" = \"token\") {\n return (\n socket.handshake.auth?.[key] ||\n socket.handshake.headers?.authorization?.replace(\"Bearer \", \"\")\n );\n }\n\n async validateDecodedUser(\n decoded: AuthJwtPayload,\n action: \"logout\" | \"default\" = \"default\"\n ): Promise<User> {\n const prisma = getPrismaInstance();\n const user = await (prisma as any).user.findUnique({\n where: { id: decoded.id },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token no longer exists\",\n 401,\n \"UserNoLongerExists\"\n );\n\n if (\n action !== \"logout\" &&\n this.userChangedPasswordAfter(user, decoded.iat!)\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n \"PasswordChanged\"\n );\n\n return user;\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n *\n * @param ctx | socket\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(\n ctx: ArkosRequest | ArkosSocket,\n action: \"logout\" | \"default\" = \"default\"\n ): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n `Trying to call authService.getAuthenticatedUser without setting up authentication in arkos.config.${getUserFileExtension()}, see ${authenticationDocsLinks.setup}`\n );\n\n let token: string | null = null;\n\n if (\"headers\" in ctx) token = this.extractRequestToken(ctx);\n else if (\"join\" in ctx) token = this.extractSocketToken(ctx);\n\n if (!token) return null;\n\n const decoded = await this.verifyJwtToken(token);\n ctx.accessToken = token;\n\n return this.validateDecodedUser(decoded, action);\n }\n\n /**\n * Middleware to authenticate the request by extracting and verifying the JWT token and setting `req.user`.\n *\n * Runs `authentication.hooks.authenticate` before/after the authentication logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — extracts and verifies the JWT token, sets `req.user`.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if core logic throws — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * On custom routes, hooks defined in `arkosConfig` still apply since they are baked into this method.\n *\n * @example\n * ```ts\n * // custom route - hooks still run\n * router.get(\"/custom\", authService.authenticate, handler);\n * ```\n *\n * @example\n * ```ts\n * // skip built-in auth from a before hook\n * before: (ctx) => {\n * ctx.req.user = myCustomAuth(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n await authHookManager.runAuthenticate(\n { context: req, done: next },\n async (req): Promise<any> => {\n if (!isAuthenticationEnabled()) return null;\n const user = (await this.getAuthenticatedUser(\n req,\n req.path.includes(\"logout\") ? \"logout\" : \"default\"\n )) as User;\n if (!user) throw loginRequiredError;\n return user;\n }\n );\n }\n );\n\n /**\n * Middleware to authorize the authenticated user for a given action on a resource.\n *\n * Runs `authentication.hooks.authorize` before/after the authorization logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — checks user role/permissions against the access control rules.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if authorization fails — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * @param resource - The resource being accessed, in kebabCase (e.g. `\"product\"`, `\"cart-item\"`)\n * @param action - The action being performed (e.g. `\"View\"`, `\"Create\"`, `\"Delete\"`)\n * @param rule - Access control rules for this action. Accepts a role list, a wildcard, or a `DetailedAccessControlRule`.\n *\n * @example\n * ```ts\n * router.delete(\"/products/:id\",\n * authService.authenticate,\n * authService.authorize(\"product\", \"Delete\", [\"admin\"]),\n * handler\n * );\n * ```\n *\n * @example\n * ```ts\n * // skip built-in authorization from a before hook\n * before: (ctx) => {\n * ctx.req.user.role = myCustomRoleResolver(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks#authorize}\n * @since v1.6.0-beta\n */\n authorize(\n action: AccessAction,\n resource: string,\n rule?: string[] | DetailedAccessControlRule | \"*\"\n ): ArkosRequestHandler {\n const authAction = authActionService.add(action, resource, {\n [action]: rule,\n });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n await authHookManager.runAuthorize(\n { context: req, done: next },\n authAction\n );\n }\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 * @deprecated Will be removed on v2.0, use AuthService.authenticate instead\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: User | 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 (!isAuthenticationEnabled()) return false;\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 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,QAAQ,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAcvE,OAAO,EAAc,IAAI,EAAE,MAAM,yCAAyC,CAAC;AAC3E,OAAO,EACL,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,iBAAiB,MAAM,sCAAsC,CAAC;AACrE,OAAO,EACL,cAAc,EACd,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,0CAA0C,CAAC;AAElD,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,eAAe,MAAM,4BAA4B,CAAC;AAMzD,MAAM,OAAO,WAAW;IAItB,kBAAkB,GAAgC,EAAE,CAAC;IAUrD,YAAY,CACV,EAAmB,EACnB,SAA+B,EAC/B,MAAe;QAEf,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,cAAc,EAAE,CAAC;QAErD,IACE,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;YAClC,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU;YACvB,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM;YAErB,MAAM,IAAI,QAAQ,CAChB,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E,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC1E,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,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 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 AccessControlRules,\n DetailedAccessControlRule,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n getArkosConfig,\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\nimport { CookieOptions } from \"express\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\nimport { authenticationDocsLinks } from \"./utils/docs-links\";\nimport authHookManager from \"./utils/auth-hooks-manager\";\nimport { ArkosSocket } from \"../../components/arkos-gateway/types\";\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 if (authConfigs?.jwt?.cookie?.secure !== undefined)\n return authConfigs?.jwt?.cookie?.secure;\n else if (process.env.JWT_COOKIE_SECURE !== undefined)\n return process.env.JWT_COOKIE_SECURE === \"true\";\n else return req.secure || req.headers[\"x-forwarded-proto\"] === \"https\";\n })(),\n sameSite,\n domain: authConfigs?.jwt?.cookie?.domain || process.env.JWT_COOKIE_DOMAIN,\n ...arkosConfig?.authentication?.jwt?.cookie,\n } as CookieOptions;\n }\n\n /**\n * Is used by default internally by Arkos under `ArkosPrismaService` 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 `ArkosPrismaService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `ArkosPrismaService` 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 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(new Date(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 try {\n const decoded = (await new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n })) as AuthJwtPayload;\n\n if (!decoded?.id) throw invaliAuthTokenError;\n\n return decoded;\n } catch (err) {\n throw invaliAuthTokenError;\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 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 async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n\n const [userPermission, hasRolePermission] = await Promise.all([\n prisma.userPermission\n ? prisma.userPermission.findFirst({\n where: { userId, permission: { resource, action } },\n select: { effect: true },\n })\n : Promise.resolve(null),\n\n prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: { resource, action },\n },\n },\n },\n select: { id: true },\n }),\n ]);\n\n if (userPermission) return userPermission.effect === \"Allow\";\n return !!hasRolePermission;\n }\n\n private extractRequestToken(\n req: ArkosRequest,\n cookie: \"arkos_access_token\" = \"arkos_access_token\"\n ) {\n let token: string | null = null;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\") &&\n req?.headers?.authorization.split?.(\" \")?.[1]\n )\n token = req?.headers?.authorization.split(\" \")[1];\n\n if (\n !token &&\n req?.cookies?.arkos_access_token !== \"no-token\" &&\n req.cookies\n )\n token = req?.cookies?.[cookie];\n\n return token;\n }\n\n private extractSocketToken(socket: ArkosSocket, key: \"token\" = \"token\") {\n return (\n socket.handshake.auth?.[key] ||\n socket.handshake.headers?.authorization?.replace(\"Bearer \", \"\")\n );\n }\n\n async validateDecodedUser(\n decoded: AuthJwtPayload,\n action: \"logout\" | \"default\" = \"default\"\n ): Promise<User> {\n const prisma = getPrismaInstance();\n const user = await (prisma as any).user.findUnique({\n where: { id: decoded.id },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token no longer exists\",\n 401,\n \"UserNoLongerExists\"\n );\n\n if (\n action !== \"logout\" &&\n this.userChangedPasswordAfter(user, decoded.iat!)\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n \"PasswordChanged\"\n );\n\n return user;\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n *\n * @param ctx | socket\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(\n ctx: ArkosRequest | ArkosSocket,\n action: \"logout\" | \"default\" = \"default\"\n ): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n `Trying to call authService.getAuthenticatedUser without setting up authentication in arkos.config.${getUserFileExtension()}, see ${authenticationDocsLinks.setup}`\n );\n\n let token: string | null = null;\n\n if (\"headers\" in ctx) token = this.extractRequestToken(ctx);\n else if (\"join\" in ctx) token = this.extractSocketToken(ctx);\n\n if (!token) return null;\n\n const decoded = await this.verifyJwtToken(token);\n ctx.accessToken = token;\n\n return this.validateDecodedUser(decoded, action);\n }\n\n /**\n * Middleware to authenticate the request by extracting and verifying the JWT token and setting `req.user`.\n *\n * Runs `authentication.hooks.authenticate` before/after the authentication logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — extracts and verifies the JWT token, sets `req.user`.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if core logic throws — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * On custom routes, hooks defined in `arkosConfig` still apply since they are baked into this method.\n *\n * @example\n * ```ts\n * // custom route - hooks still run\n * router.get(\"/custom\", authService.authenticate, handler);\n * ```\n *\n * @example\n * ```ts\n * // skip built-in auth from a before hook\n * before: (ctx) => {\n * ctx.req.user = myCustomAuth(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n await authHookManager.runAuthenticate(\n { context: req, done: next },\n async (req): Promise<any> => {\n if (!isAuthenticationEnabled()) return null;\n const user = (await this.getAuthenticatedUser(\n req,\n req.path.includes(\"logout\") ? \"logout\" : \"default\"\n )) as User;\n if (!user) throw loginRequiredError;\n return user;\n }\n );\n }\n );\n\n /**\n * Middleware to authorize the authenticated user for a given action on a resource.\n *\n * Runs `authentication.hooks.authorize` before/after the authorization logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — checks user role/permissions against the access control rules.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if authorization fails — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * @param resource - The resource being accessed, in kebabCase (e.g. `\"product\"`, `\"cart-item\"`)\n * @param action - The action being performed (e.g. `\"View\"`, `\"Create\"`, `\"Delete\"`)\n * @param rule - Access control rules for this action. Accepts a role list, a wildcard, or a `DetailedAccessControlRule`.\n *\n * @example\n * ```ts\n * router.delete(\"/products/:id\",\n * authService.authenticate,\n * authService.authorize(\"product\", \"Delete\", [\"admin\"]),\n * handler\n * );\n * ```\n *\n * @example\n * ```ts\n * // skip built-in authorization from a before hook\n * before: (ctx) => {\n * ctx.req.user.role = myCustomRoleResolver(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks#authorize}\n * @since v1.6.0-beta\n */\n authorize(\n action: AccessAction,\n resource: string,\n rule?: string[] | DetailedAccessControlRule | \"*\"\n ): ArkosRequestHandler {\n const authAction = authActionService.add(action, resource, {\n [action]: rule,\n });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n await authHookManager.runAuthorize(\n { context: req, done: next },\n authAction\n );\n }\n );\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: User | 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 (!isAuthenticationEnabled()) return false;\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 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"]}
@@ -3,6 +3,7 @@ import { prismaSchemaParser, } from "../../../exports/prisma/index.js";
3
3
  import prismaJsonSchemaGenerator from "../../../utils/prisma/prisma-json-schema-generator.js";
4
4
  import { routeHookReader } from "../../../components/arkos-route-hook/reader.js";
5
5
  class AuthPrismaJsonSchemaGenerator {
6
+ userModel;
6
7
  getUserModel() {
7
8
  if (!this.userModel)
8
9
  this.userModel = prismaSchemaParser.models.find((m) => m.name.toLowerCase() === "user");
@@ -1 +1 @@
1
- {"version":3,"file":"auth-prisma-json-schema-generator.js","sourceRoot":"","sources":["../../../../../src/modules/auth/utils/auth-prisma-json-schema-generator.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,cAAc,EAAE,MAAM,6CAA6C,CAAC;AAM7E,OAAO,EAEL,kBAAkB,GACnB,MAAM,yBAAyB,CAAC;AACjC,OAAO,yBAAyB,MAAM,oDAAoD,CAA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;YACL,GAAG,UAAU;YACb,GAAG,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,IAAI;gBACjC,KAAK,EAAE,gBAAgB,CAAC,GAAG,CAAC,CAAC,KAAa,EAAE,EAAE,CAAC,CAAC;oBAC9C,QAAQ,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAG,CAAC,CAAC,CAAC,KAAK,CAAC;iBAClE,CAAC,CAAC;aACJ,CAAC;SACH,CAAC;IACJ,CAAC;CACF;AAED,MAAM,6BAA6B,GAAG,IAAI,6BAA6B,EAAE,CAAC;AAE1E,eAAe,6BAA6B,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { getArkosConfig } from \"../../../utils/helpers/arkos-config.helpers\";\nimport {\n JsonSchema,\n JsonSchemaProperty,\n PrismaModel,\n} from \"../../../utils/prisma/types\";\nimport {\n AuthPrismaQueryOptions,\n prismaSchemaParser,\n} from \"../../../exports/prisma\";\nimport prismaJsonSchemaGenerator from \"../../../utils/prisma/prisma-json-schema-generator\";\nimport { routeHookReader } from \"../../../components/arkos-route-hook/reader\";\n\nclass AuthPrismaJsonSchemaGenerator {\n private userModel?: PrismaModel;\n\n private getUserModel() {\n if (!this.userModel)\n this.userModel = prismaSchemaParser.models.find(\n (m) => m.name.toLowerCase() === \"user\"\n );\n\n return this.userModel!;\n }\n\n private getPrismaArgs(endpoint: keyof AuthPrismaQueryOptions<any>) {\n return routeHookReader.getPrismaArgs(\"auth\", endpoint) || {};\n }\n\n generateGetMeResponse(): JsonSchema {\n return prismaJsonSchemaGenerator.generateResponseSchema(\n this.getUserModel(),\n this.getPrismaArgs(\"getMe\")\n );\n }\n\n generateUpdatePasswordSchema(): JsonSchema {\n return {\n type: \"object\",\n properties: {\n currentPassword: { type: \"string\" },\n newPassword: { type: \"string\", minLength: 8 },\n },\n required: [\"currentPassword\", \"newPassword\"],\n };\n }\n\n generateUpdateMeSchema(): JsonSchema {\n const updateSchema = prismaJsonSchemaGenerator.generateUpdateSchema(\n this.getUserModel()\n );\n\n // Remove sensitive fields that users shouldn't update themselves\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"password\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete updateSchema?.properties?.[field];\n });\n\n return updateSchema;\n }\n\n generateSignupSchema(): JsonSchema {\n const singupSchema = prismaJsonSchemaGenerator.generateCreateSchema(\n this.getUserModel()\n );\n\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete singupSchema?.properties?.[field];\n });\n\n return singupSchema;\n }\n\n generateLoginSchema(): JsonSchema {\n const allowedUsernames = getArkosConfig()?.authentication?.login\n ?.allowedUsernames || [\"username\"];\n\n const usernameProperties: Record<string, OpenAPIV3.SchemaObject> = {};\n\n allowedUsernames.forEach((field: string) => {\n const displayName = field.includes(\".\") ? field.split(\".\").pop()! : field;\n usernameProperties[displayName] = {\n type: \"string\",\n description: `Username field: ${field}`,\n };\n });\n\n const baseSchema: JsonSchemaProperty = {\n type: \"object\",\n properties: {\n ...usernameProperties,\n password: {\n type: \"string\",\n minLength: 8,\n },\n },\n required: [\"password\"],\n };\n\n return {\n ...baseSchema,\n ...(allowedUsernames.length > 0 && {\n anyOf: allowedUsernames.map((field: string) => ({\n required: [field.includes(\".\") ? field.split(\".\").pop()! : field],\n })),\n }),\n };\n }\n}\n\nconst authPrismaJsonSchemaGenerator = new AuthPrismaJsonSchemaGenerator();\n\nexport default authPrismaJsonSchemaGenerator;\n"]}
1
+ {"version":3,"file":"auth-prisma-json-schema-generator.js","sourceRoot":"","sources":["../../../../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GAAuB;YACrC,IAAI,EAAE,QAAQ;YACd,UAAU,EAAE;gBACV,GAAG,kBAAkB;gBACrB,QAAQ,EAAE;oBACR,IAAI,EAAE,QAAQ;oBACd,SAAS,EAAE,CAAC;iBACb;aACF;YACD,QAAQ,EAAE,CAAC,UAAU,CAAC;SACvB,CAAC;QAEF,OAAO;YACL,GAAG,UAAU;YACb,GAAG,CAAC,gBAAgB,CAAC,MAAM,GAAG,CAAC,IAAI;gBACjC,KAAK,EAAE,gBAAgB,CAAC,GAAG,CAAC,CAAC,KAAa,EAAE,EAAE,CAAC,CAAC;oBAC9C,QAAQ,EAAE,CAAC,KAAK,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAG,CAAC,CAAC,CAAC,KAAK,CAAC;iBAClE,CAAC,CAAC;aACJ,CAAC;SACH,CAAC;IACJ,CAAC;CACF;AAED,MAAM,6BAA6B,GAAG,IAAI,6BAA6B,EAAE,CAAC;AAE1E,eAAe,6BAA6B,CAAC","sourcesContent":["import { OpenAPIV3 } from \"openapi-types\";\nimport { getArkosConfig } from \"../../../utils/helpers/arkos-config.helpers\";\nimport {\n JsonSchema,\n JsonSchemaProperty,\n PrismaModel,\n} from \"../../../utils/prisma/types\";\nimport {\n AuthPrismaQueryOptions,\n prismaSchemaParser,\n} from \"../../../exports/prisma\";\nimport prismaJsonSchemaGenerator from \"../../../utils/prisma/prisma-json-schema-generator\";\nimport { routeHookReader } from \"../../../components/arkos-route-hook/reader\";\n\nclass AuthPrismaJsonSchemaGenerator {\n private userModel?: PrismaModel;\n\n private getUserModel() {\n if (!this.userModel)\n this.userModel = prismaSchemaParser.models.find(\n (m) => m.name.toLowerCase() === \"user\"\n );\n\n return this.userModel!;\n }\n\n private getPrismaArgs(endpoint: keyof AuthPrismaQueryOptions<any>) {\n return routeHookReader.getPrismaArgs(\"auth\", endpoint) || {};\n }\n\n generateGetMeResponse(): JsonSchema {\n return prismaJsonSchemaGenerator.generateResponseSchema(\n this.getUserModel(),\n this.getPrismaArgs(\"getMe\")\n );\n }\n\n generateUpdatePasswordSchema(): JsonSchema {\n return {\n type: \"object\",\n properties: {\n currentPassword: { type: \"string\" },\n newPassword: { type: \"string\", minLength: 8 },\n },\n required: [\"currentPassword\", \"newPassword\"],\n };\n }\n\n generateUpdateMeSchema(): JsonSchema {\n const updateSchema = prismaJsonSchemaGenerator.generateUpdateSchema(\n this.getUserModel()\n );\n\n // Remove sensitive fields that users shouldn't update themselves\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"password\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete updateSchema?.properties?.[field];\n });\n\n return updateSchema;\n }\n\n generateSignupSchema(): JsonSchema {\n const singupSchema = prismaJsonSchemaGenerator.generateCreateSchema(\n this.getUserModel()\n );\n\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete singupSchema?.properties?.[field];\n });\n\n return singupSchema;\n }\n\n generateLoginSchema(): JsonSchema {\n const allowedUsernames = getArkosConfig()?.authentication?.login\n ?.allowedUsernames || [\"username\"];\n\n const usernameProperties: Record<string, OpenAPIV3.SchemaObject> = {};\n\n allowedUsernames.forEach((field: string) => {\n const displayName = field.includes(\".\") ? field.split(\".\").pop()! : field;\n usernameProperties[displayName] = {\n type: \"string\",\n description: `Username field: ${field}`,\n };\n });\n\n const baseSchema: JsonSchemaProperty = {\n type: \"object\",\n properties: {\n ...usernameProperties,\n password: {\n type: \"string\",\n minLength: 8,\n },\n },\n required: [\"password\"],\n };\n\n return {\n ...baseSchema,\n ...(allowedUsernames.length > 0 && {\n anyOf: allowedUsernames.map((field: string) => ({\n required: [field.includes(\".\") ? field.split(\".\").pop()! : field],\n })),\n }),\n };\n }\n}\n\nconst authPrismaJsonSchemaGenerator = new AuthPrismaJsonSchemaGenerator();\n\nexport default authPrismaJsonSchemaGenerator;\n"]}
@@ -2,18 +2,16 @@ import { kebabCase, sentenceCase } from "../../../../exports/utils/index.js";
2
2
  import { getArkosConfig } from "../../../../utils/helpers/arkos-config.helpers.js";
3
3
  import { capitalize } from "../../../../utils/helpers/text.helpers.js";
4
4
  class AuthActionService {
5
- constructor() {
6
- this.authActions = [
7
- {
8
- roles: [],
9
- action: "View",
10
- resource: "auth-action",
11
- name: "View auth action",
12
- description: "View an auth action",
13
- errorMessage: "You cannot perform view for auth action",
14
- },
15
- ];
16
- }
5
+ authActions = [
6
+ {
7
+ roles: [],
8
+ action: "View",
9
+ resource: "auth-action",
10
+ name: "View auth action",
11
+ description: "View an auth action",
12
+ errorMessage: "You cannot perform view for auth action",
13
+ },
14
+ ];
17
15
  add(action, resource, accessControl) {
18
16
  const transformedAction = this.transformAccessControlToValidAuthAction(action, resource, accessControl);
19
17
  const existingAuthAction = this.getOne(action, resource);
@@ -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,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAKpE,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,yCAAyC;aACxD;SACF,CAAC;IA2MJ,CAAC;IAzMC,GAAG,CACD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,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, sentenceCase } 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\nexport interface 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 cannot perform view for auth action\",\n },\n ];\n\n add(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ): Required<AuthAction> {\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 = `You cannot perform ${sentenceCase(action).toLowerCase()} for ${sentenceCase(resource).toLowerCase()}`;\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: Required<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 } as any;\n\n this.remove(action, resource);\n this.authActions.push(merged);\n return merged;\n } else {\n if (transformedAction.roles) {\n transformedAction.roles = [...transformedAction.roles].sort();\n }\n this.authActions.push(transformedAction);\n return 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 ): Required<AuthAction> {\n const baseAuthAction: Required<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 cannot perform ${sentenceCase(action).toLowerCase()} for ${sentenceCase(resource).toLowerCase()}`,\n };\n\n const config = getArkosConfig();\n\n if (config?.authentication?.mode === \"dynamic\")\n delete (baseAuthAction as any).roles;\n\n if (!accessControl) return baseAuthAction;\n\n if (Array.isArray(accessControl)) return baseAuthAction;\n\n const actionRule =\n (accessControl as any) !== \"*\"\n ? (accessControl as any)[action]\n : undefined;\n\n if (config?.authentication?.mode !== \"static\")\n delete (baseAuthAction as any).roles;\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,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAKpE,OAAO,EAAE,cAAc,EAAE,MAAM,gDAAgD,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,wCAAwC,CAAC;AAWpE,MAAM,iBAAiB;IACrB,WAAW,GAAiB;QAC1B;YACE,KAAK,EAAE,EAAE;YACT,MAAM,EAAE,MAAM;YACd,QAAQ,EAAE,aAAa;YACvB,IAAI,EAAE,kBAAkB;YACxB,WAAW,EAAE,qBAAqB;YAClC,YAAY,EAAE,yCAAyC;SACxD;KACF,CAAC;IAEF,GAAG,CACD,MAAc,EACd,QAAgB,EAChB,aAAmC;QAEnC,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,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AC5B,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, sentenceCase } 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\nexport interface 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 cannot perform view for auth action\",\n },\n ];\n\n add(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ): Required<AuthAction> {\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 = `You cannot perform ${sentenceCase(action).toLowerCase()} for ${sentenceCase(resource).toLowerCase()}`;\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: Required<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 } as any;\n\n this.remove(action, resource);\n this.authActions.push(merged);\n return merged;\n } else {\n if (transformedAction.roles) {\n transformedAction.roles = [...transformedAction.roles].sort();\n }\n this.authActions.push(transformedAction);\n return 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 ): Required<AuthAction> {\n const baseAuthAction: Required<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 cannot perform ${sentenceCase(action).toLowerCase()} for ${sentenceCase(resource).toLowerCase()}`,\n };\n\n const config = getArkosConfig();\n\n if (config?.authentication?.mode === \"dynamic\")\n delete (baseAuthAction as any).roles;\n\n if (!accessControl) return baseAuthAction;\n\n if (Array.isArray(accessControl)) return baseAuthAction;\n\n const actionRule =\n (accessControl as any) !== \"*\"\n ? (accessControl as any)[action]\n : undefined;\n\n if (config?.authentication?.mode !== \"static\")\n delete (baseAuthAction as any).roles;\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"]}