arkos 1.3.9-canary.4 → 1.3.10-beta

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 (31) 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/email/email.service.js +7 -5
  4. package/dist/cjs/modules/email/email.service.js.map +1 -1
  5. package/dist/cjs/modules/file-upload/file-upload.router.js +4 -1
  6. package/dist/cjs/modules/file-upload/file-upload.router.js.map +1 -1
  7. package/dist/cjs/modules/file-upload/file-upload.service.js +1 -1
  8. package/dist/cjs/modules/file-upload/file-upload.service.js.map +1 -1
  9. package/dist/cjs/types/auth.js.map +1 -1
  10. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  11. package/dist/cjs/utils/dynamic-loader.js +4 -5
  12. package/dist/cjs/utils/dynamic-loader.js.map +1 -1
  13. package/dist/cjs/utils/prisma/prisma-schema-parser.js +3 -4
  14. package/dist/cjs/utils/prisma/prisma-schema-parser.js.map +1 -1
  15. package/dist/esm/modules/auth/auth.service.js +1 -1
  16. package/dist/esm/modules/auth/auth.service.js.map +1 -1
  17. package/dist/esm/modules/email/email.service.js +7 -5
  18. package/dist/esm/modules/email/email.service.js.map +1 -1
  19. package/dist/esm/modules/file-upload/file-upload.router.js +4 -1
  20. package/dist/esm/modules/file-upload/file-upload.router.js.map +1 -1
  21. package/dist/esm/modules/file-upload/file-upload.service.js +1 -1
  22. package/dist/esm/modules/file-upload/file-upload.service.js.map +1 -1
  23. package/dist/esm/types/auth.js.map +1 -1
  24. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  25. package/dist/esm/utils/dynamic-loader.js +4 -5
  26. package/dist/esm/utils/dynamic-loader.js.map +1 -1
  27. package/dist/esm/utils/prisma/prisma-schema-parser.js +3 -4
  28. package/dist/esm/utils/prisma/prisma-schema-parser.js.map +1 -1
  29. package/dist/types/modules/email/email.service.d.ts +1 -1
  30. package/dist/types/types/auth.d.ts +1 -1
  31. package/package.json +1 -1
@@ -126,7 +126,7 @@ class AuthService {
126
126
  else if (accessControl[action])
127
127
  authorizedRoles = Array.isArray(accessControl[action])
128
128
  ? accessControl[action]
129
- : accessControl[action].roles;
129
+ : accessControl[action].roles || [];
130
130
  const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];
131
131
  return !!userRoles.some((role) => authorizedRoles.includes(role));
132
132
  }
@@ -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;AAKrE,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA4arD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,MAAM,WAAW,GAAG,IAAA,uBAAc,GAAE,CAAC;YACrC,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,CAAC;gBACjC,IAAI,EAAE,CAAC;gBACP,OAAO;YACT,CAAC;YAED,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;YAC1D,IAAI,EAAE,CAAC;QACT,CAAC,CACF,CAAC;IAqFJ,CAAC;IAlgBC,YAAY,CACV,EAAmB,EACnB,SAA+B,EAC/B,MAAe;QAEf,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;QAErD,IACE,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;YAClC,CAAC,O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;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;AAhhBD,kCAghBC;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\";\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 const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) 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 const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) {\n next();\n return;\n }\n\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>): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n if (!configs?.authentication)\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;AAKrE,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA4arD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,MAAM,WAAW,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QAAQ,EAAE,aAAa,CAAC,CAAC;QAEvD,OAAO,KAAK,EAAE,IAAyB,EAAoB,EAAE;YAE3D,MAAM,OAAO,GAAG,IAAA,uBAAc,GAAE,CAAC;YACjC,IAAI,CAAC,OAAO,EAAE,cAAc;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;AAhhBD,kCAghBC;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\";\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 const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) 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 const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) {\n next();\n return;\n }\n\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>): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n if (!configs?.authentication)\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"]}
@@ -50,15 +50,17 @@ class EmailService {
50
50
  };
51
51
  }
52
52
  getTransporter(customConfig) {
53
- if (customConfig)
54
- return nodemailer_1.default.createTransport(customConfig);
53
+ if (customConfig) {
54
+ const { name, ...config } = customConfig;
55
+ return nodemailer_1.default.createTransport(config);
56
+ }
55
57
  if (!this.transporter) {
56
- const config = this.getEmailConfig();
58
+ const { name, ...config } = this.getEmailConfig() || {};
57
59
  this.transporter = nodemailer_1.default.createTransport(config);
58
60
  }
59
61
  return this.transporter;
60
62
  }
61
- async send(options, connectionOptions, skipVerification = false) {
63
+ async send(options, connectionOptions, skipVerification = true) {
62
64
  const config = this.getEmailConfig();
63
65
  const transporter = connectionOptions
64
66
  ? this.getTransporter(connectionOptions)
@@ -74,7 +76,7 @@ class EmailService {
74
76
  from: fromAddress,
75
77
  text: options?.text || (0, html_to_text_1.convert)(options.html),
76
78
  });
77
- return { success: true, messageId: info.messageId };
79
+ return { success: true, ...info };
78
80
  }
79
81
  async verifyConnection(transporterToVerify) {
80
82
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../../../src/modules/email/email.service.ts"],"names":[],"mappings":";;;;;;AAAA,4DAAqD;AACrD,+CAAuC;AACvC,yCAA8C;AAC9C,iFAAwD;AAqCxD,MAAa,YAAY;IAUvB,YAAY,MAA8B;QATlC,gBAAW,GAAuB,IAAI,CAAC;QACvC,iBAAY,GAAiC,IAAI,CAAC;QASxD,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC7B,CAAC;IACH,CAAC;IAUO,cAAc;QACpB,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,OAAO,IAAI,CAAC,YAAY,CAAC;QAC3B,CAAC;QAED,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;QACjD,MAAM,IAAI,GAAG,YAAY,EAAE,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IAAI,CAAC;YACH,MAAM,WAAW,GAAG,mBAAmB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACjE,MAAM,WAAW,CAAC,MAAM,EAAE,CAAC;YAC3B,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;YACvD,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAMM,YAAY,CAAC,MAA6B;QAC/C,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAOM,MAAM,CAAC,MAAM,CAAC,MAA6B;QAChD,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;CACF;AA3JD,oCA2JC;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,kBAAe,YAAY,CAAC","sourcesContent":["import nodemailer, { Transporter } from \"nodemailer\";\nimport { convert } from \"html-to-text\";\nimport { getArkosConfig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n from?: string;\n to: string | string[];\n subject: string;\n text?: string;\n html: string;\n};\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/api-reference/the-email-service-class](https://www.arkosjs.com/docs/api-reference/the-email-service-class)\n */\nexport class EmailService {\n private transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host || !user || !pass) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST, EMAIL_USER, EMAIL_PASSWORD)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/core-concepts/sending-emails\",\n }\n );\n }\n\n return {\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth: {\n user,\n pass,\n },\n name,\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) return nodemailer.createTransport(customConfig);\n\n if (!this.transporter) {\n const config = this.getEmailConfig();\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string }>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification = false\n ): Promise<{ success: boolean; messageId?: string }> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n // Send the email\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress,\n text: options?.text || convert(options.html),\n });\n\n return { success: true, messageId: info.messageId };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}
1
+ {"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../../../src/modules/email/email.service.ts"],"names":[],"mappings":";;;;;;AAAA,4DAAqD;AACrD,+CAAuC;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fig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n from?: string;\n to: string | string[];\n subject: string;\n text?: string;\n html: string;\n};\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/api-reference/the-email-service-class](https://www.arkosjs.com/docs/api-reference/the-email-service-class)\n */\nexport class EmailService {\n private transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host || !user || !pass) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST, EMAIL_USER, EMAIL_PASSWORD)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/core-concepts/sending-emails\",\n }\n );\n }\n\n return {\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth: {\n user,\n pass,\n },\n name,\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) {\n const { name, ...config } = customConfig;\n return nodemailer.createTransport(config);\n }\n\n if (!this.transporter) {\n const { name, ...config } = this.getEmailConfig() || {};\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string } & Record<string, any>>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification: boolean = true\n ): Promise<{ success: boolean; messageId?: string } & Record<string, any>> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress,\n text: options?.text || convert(options.html),\n });\n\n return { success: true, ...info };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}
@@ -45,7 +45,10 @@ async function getFileUploadRouter(arkosConfig) {
45
45
  if (!basePathname.endsWith("/"))
46
46
  basePathname = basePathname + "/";
47
47
  if (!(0, base_router_helpers_1.isEndpointDisabled)(routerConfig, "findFile")) {
48
- router.get(`${basePathname}*`, auth_service_1.default.handleAuthenticationControl("View", authConfigs.authenticationControl), auth_service_1.default.handleAccessControl("View", "file-upload", authConfigs.accessControl), ...(0, routers_helpers_1.processMiddleware)(interceptors?.beforeFindFile), file_upload_helpers_1.adjustRequestUrl, express_2.default.static(path_1.default.resolve(process.cwd(), fileUpload?.baseUploadDir || "uploads"), (0, deepmerge_helper_1.default)({
48
+ const baseUploadDirFullPath = path_1.default.resolve(path_1.default
49
+ .join(process.cwd(), fileUpload?.baseUploadDir || "uploads")
50
+ .replaceAll("//", "/"));
51
+ router.get(`${basePathname}*`, auth_service_1.default.handleAuthenticationControl("View", authConfigs.authenticationControl), auth_service_1.default.handleAccessControl("View", "file-upload", authConfigs.accessControl), ...(0, routers_helpers_1.processMiddleware)(interceptors?.beforeFindFile), file_upload_helpers_1.adjustRequestUrl, express_2.default.static(baseUploadDirFullPath, (0, deepmerge_helper_1.default)({
49
52
  maxAge: "1y",
50
53
  etag: true,
51
54
  lastModified: true,
@@ -1 +1 @@
1
- {"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":";;;;;AAmBA,kDAkIC;AArJD,qCAAiC;AACjC,+DAAiE;AACjE,wEAA+C;AAC/C,sFAA4D;AAE5D,gDAAwB;AACxB,sDAA8B;AAC9B,4FAA6D;AAE7D,+DAAwD;AACxD,yEAAwE;AACxE,6EAAuE;AACvE,mFAA+E;AAC/E,oFAA2D;AAC3D,sFAA6D;AAC7D,+DAAsE;AAEtE,MAAM,MAAM,GAAW,IAAA,gBAAM,GAAE,CAAC;AAEzB,KAAK,UAAU,mBAAmB,CAAC,WAAwB;IAChE,MAAM,EAAE,UAAU,EAAE,GAAG,WAAW,CAAC;IAEnC,MAAM,gBAAgB,GAAG,IAAA,oCAAmB,EAAC,aAAa,CAAC,CAAC;IAC5D,IAAI,EACF,YAAY,GAAG,EAAS,EACxB,WAAW,GAAG,EAAiB,EAC/B,MAAM,EAAE,kBAAkB,GAC3B,GAAQ,EAAE,CAAC;IAEZ,IAAI,gBAAgB;QAClB,CAAC;YACC,YAAY,GAAG,EAAE;YACjB,WAAW,GAAG,EAAE;YAChB,MAAM,EAAE,kBAAkB;SAC3B,GAAG,gBAAgB,CAAC,CAAC;IAExB,MAAM,YAAY,GAAG,kBAAkB,EAAE,MAAM,IAAI,EAAE,CAAC;IACtD,IAAI,YAAY,EAAE,OAAO,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC;IAElD,MAAM,YAAY,GAAG,kBAAkB,EAAE,OAAiB,CAAC;IAC3D,IAAI,YAAY,GAAG,UAAU,EAAE,SAAS,IAAI,eAAe,CAAC;IAE5D,IAAI,YAAY,IAAI,kBAAkB,EAAE,CAAC;QACvC,IAAI,0BAAe,CAAC,eAAe,CAAC,YAAY,CAAC;YAC/C,MAAM,CAAC,GAAG,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC;;YAEvC,MAAM,KAAK,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ACD,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,gBAAgB,CAAC,EACpD,gCAAoB,CAAC,UAAU,EAC/B,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,eAAe,CAAC,EACnD,+BAAY,EACZ,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,iBAAiB,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CACzE,CAAC;IACJ,CAAC;IAED,0BAAe,CAAC,oBAAoB,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport authService from \"../auth/auth.service\";\nimport fileUploadController from \"./file-upload.controller\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport path from \"path\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthConfigs } from \"../../types/auth\";\nimport { sendResponse } from \"../base/base.middlewares\";\nimport { processMiddleware } from \"../../utils/helpers/routers.helpers\";\nimport { adjustRequestUrl } from \"./utils/helpers/file-upload.helpers\";\nimport { isEndpointDisabled } from \"../base/utils/helpers/base.router.helpers\";\nimport debuggerService from \"../debugger/debugger.service\";\nimport routerValidator from \"../base/utils/router-validator\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\n\nconst router: Router = Router();\n\nexport async function getFileUploadRouter(arkosConfig: ArkosConfig) {\n const { fileUpload } = arkosConfig;\n\n const moduleComponents = getModuleComponents(\"file-upload\");\n let {\n interceptors = {} as any,\n authConfigs = {} as AuthConfigs,\n router: customRouterModule,\n }: any = {};\n\n if (moduleComponents)\n ({\n interceptors = {},\n authConfigs = {},\n router: customRouterModule,\n } = moduleComponents);\n\n const routerConfig = customRouterModule?.config || {};\n if (routerConfig?.disable === true) return router;\n\n const customRouter = customRouterModule?.default as Router;\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(basePathname, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from file-upload.router.${getUserFileExtension()} is not a valid express or arkos Router.`\n );\n }\n\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n if (!isEndpointDisabled(routerConfig, \"findFile\")) {\n router.get(\n `${basePathname}*`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeFindFile),\n adjustRequestUrl,\n express.static(\n path.resolve(process.cwd(), fileUpload?.baseUploadDir || \"uploads\"),\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStaticOptions || {}\n )\n ),\n ...processMiddleware(interceptors?.onFindFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"uploadFile\")) {\n router.post(\n `${basePathname}:fileType`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeUploadFile),\n fileUploadController.uploadFile,\n ...processMiddleware(interceptors?.afterUploadFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUploadFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"updateFile\")) {\n router.patch(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeUpdateFile),\n fileUploadController.updateFile,\n ...processMiddleware(interceptors?.afterUpdateFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"deleteFile\")) {\n router.delete(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeDeleteFile),\n fileUploadController.deleteFile,\n ...processMiddleware(interceptors?.afterDeleteFile),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteFileError, { type: \"error\" })\n );\n }\n\n debuggerService.logModuleFinalRouter(\"file-upload\", router);\n return router;\n}\n"]}
1
+ {"version":3,"file":"file-upload.router.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.router.ts"],"names":[],"mappings":";;;;;AAmBA,kDAuIC;AA1JD,qCAAiC;AACjC,+DAAiE;AACjE,wEAA+C;AAC/C,sFAA4D;AAE5D,gDAAwB;AACxB,sDAA8B;AAC9B,4FAA6D;AAE7D,+DAAwD;AACxD,yEAAwE;AACxE,6EAAuE;AACvE,mFAA+E;AAC/E,oFAA2D;AAC3D,sFAA6D;AAC7D,+DAAsE;AAEtE,MAAM,MAAM,GAAW,IAAA,gBAAM,GAAE,CAAC;AAEzB,KAAK,UAAU,mBAAmB,CAAC,WAAwB;IAChE,MAAM,EAAE,UAAU,EAAE,GAAG,WAAW,CAAC;IAEnC,MAAM,gBAAgB,GAAG,IAAA,oCAAmB,EAAC,aAAa,CAAC,CAAC;IAC5D,IAAI,EACF,YAAY,GAAG,EAAS,EACxB,WAAW,GAAG,EAAiB,EAC/B,MAAM,EAAE,kBAAkB,GAC3B,GAAQ,EAAE,CAAC;IAEZ,IAAI,gBAAgB;QAClB,CAAC;YACC,YAAY,GAAG,EAAE;YACjB,WAAW,GAAG,EAAE;YAChB,MAAM,EAAE,kBAAkB;SAC3B,GAAG,gBAAgB,CAAC,CAAC;IAEx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EAAC,YAAY,EAAE,gBAAgB,CAAC,EACpD,gCAAoB,CAAC,UAAU,EAC/B,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,eAAe,CAAC,EACnD,+BAAY,EACZ,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,iBAAiB,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CACzE,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,IAAA,wCAAkB,EAAC,YAAY,EAAE,YAAY,CAAC,EAAE,CAAC;QACpD,MAAM,CAAC,MAAM,CACX,GAAG,YAAY,qBAAqB,EACpC,sBAAW,CAAC,2BAA2B,CACrC,QAAQ,EACR,WAAW,CAAC,qBAAqB,CAClC,EACD,sBAAW,CAAC,mBAAmB,CAC7B,QAAQ,EACR,aAAa,EACb,WAAW,CAAC,aAAa,CAC1B,EACD,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,gBAAgB,CAAC,EACpD,gCAAoB,CAAC,UAAU,EAC/B,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,eAAe,CAAC,EACnD,+BAAY,EACZ,GAAG,IAAA,mCAAiB,EAAC,YAAY,EAAE,iBAAiB,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CACzE,CAAC;IACJ,CAAC;IAED,0BAAe,CAAC,oBAAoB,CAAC,aAAa,EAAE,MAAM,CAAC,CAAC;IAC5D,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { Router } from \"express\";\nimport { getModuleComponents } from \"../../utils/dynamic-loader\";\nimport authService from \"../auth/auth.service\";\nimport fileUploadController from \"./file-upload.controller\";\nimport { ArkosConfig } from \"../../types/arkos-config\";\nimport path from \"path\";\nimport express from \"express\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport { AuthConfigs } from \"../../types/auth\";\nimport { sendResponse } from \"../base/base.middlewares\";\nimport { processMiddleware } from \"../../utils/helpers/routers.helpers\";\nimport { adjustRequestUrl } from \"./utils/helpers/file-upload.helpers\";\nimport { isEndpointDisabled } from \"../base/utils/helpers/base.router.helpers\";\nimport debuggerService from \"../debugger/debugger.service\";\nimport routerValidator from \"../base/utils/router-validator\";\nimport { getUserFileExtension } from \"../../utils/helpers/fs.helpers\";\n\nconst router: Router = Router();\n\nexport async function getFileUploadRouter(arkosConfig: ArkosConfig) {\n const { fileUpload } = arkosConfig;\n\n const moduleComponents = getModuleComponents(\"file-upload\");\n let {\n interceptors = {} as any,\n authConfigs = {} as AuthConfigs,\n router: customRouterModule,\n }: any = {};\n\n if (moduleComponents)\n ({\n interceptors = {},\n authConfigs = {},\n router: customRouterModule,\n } = moduleComponents);\n\n const routerConfig = customRouterModule?.config || {};\n if (routerConfig?.disable === true) return router;\n\n const customRouter = customRouterModule?.default as Router;\n let basePathname = fileUpload?.baseRoute || \"/api/uploads/\";\n\n if (customRouter && customRouterModule) {\n if (routerValidator.isExpressRouter(customRouter))\n router.use(basePathname, customRouter);\n else\n throw Error(\n `ValidationError: The exported router from file-upload.router.${getUserFileExtension()} is not a valid express or arkos Router.`\n );\n }\n\n if (!basePathname.startsWith(\"/\")) basePathname = \"/\" + basePathname;\n if (!basePathname.endsWith(\"/\")) basePathname = basePathname + \"/\";\n\n if (!isEndpointDisabled(routerConfig, \"findFile\")) {\n const baseUploadDirFullPath = path.resolve(\n path\n .join(process.cwd(), fileUpload?.baseUploadDir || \"uploads\")\n .replaceAll(\"//\", \"/\")\n );\n router.get(\n `${basePathname}*`,\n authService.handleAuthenticationControl(\n \"View\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"View\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeFindFile),\n adjustRequestUrl,\n express.static(\n baseUploadDirFullPath,\n deepmerge(\n {\n maxAge: \"1y\",\n etag: true,\n lastModified: true,\n dotfiles: \"ignore\",\n fallthrough: true,\n index: false,\n cacheControl: true,\n },\n fileUpload?.expressStaticOptions || {}\n )\n ),\n ...processMiddleware(interceptors?.onFindFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"uploadFile\")) {\n router.post(\n `${basePathname}:fileType`,\n authService.handleAuthenticationControl(\n \"Create\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Create\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeUploadFile),\n fileUploadController.uploadFile,\n ...processMiddleware(interceptors?.afterUploadFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUploadFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"updateFile\")) {\n router.patch(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Update\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Update\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeUpdateFile),\n fileUploadController.updateFile,\n ...processMiddleware(interceptors?.afterUpdateFile),\n sendResponse,\n ...processMiddleware(interceptors?.onUpdateFileError, { type: \"error\" })\n );\n }\n\n if (!isEndpointDisabled(routerConfig, \"deleteFile\")) {\n router.delete(\n `${basePathname}:fileType/:fileName`,\n authService.handleAuthenticationControl(\n \"Delete\",\n authConfigs.authenticationControl\n ),\n authService.handleAccessControl(\n \"Delete\",\n \"file-upload\",\n authConfigs.accessControl\n ),\n ...processMiddleware(interceptors?.beforeDeleteFile),\n fileUploadController.deleteFile,\n ...processMiddleware(interceptors?.afterDeleteFile),\n sendResponse,\n ...processMiddleware(interceptors?.onDeleteFileError, { type: \"error\" })\n );\n }\n\n debuggerService.logModuleFinalRouter(\"file-upload\", router);\n return router;\n}\n"]}
@@ -20,7 +20,7 @@ class FileUploadService {
20
20
  if (extName)
21
21
  cb(null, true);
22
22
  else
23
- cb(new app_error_1.default(`File type not allowed, allowed files are ${String(this.allowedFileTypes).replaceAll("/", "").split("|").join(", ")}`, 400, "NotAllowedFileType", { filename: file.originalname }));
23
+ cb(new app_error_1.default(`File type not allowed, allowed files are ${String(this.allowedFileTypes).replaceAll("/", "").split("|").join(", ")}`, 400, "FileTypeNotAllowed", { filename: file.originalname }));
24
24
  };
25
25
  uploadDir = uploadDir.startsWith("/") ? uploadDir.substring(1) : uploadDir;
26
26
  uploadDir = uploadDir.endsWith("/") ? uploadDir.slice(0, -1) : uploadDir;
@@ -1 +1 @@
1
- {"version":3,"file":"file-upload.service.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.service.ts"],"names":[],"mappings":";;;;;;AAAA,oDAA+C;AAC/C,gDAAwB;AACxB,4CAAoB;AAEpB,iFAAwD;AACxD,+BAAiC;AACjC,yCAA8C;AAC9C,4FAA6D;AAO7D,6EAAgF;AAChF,mEAAqE;AAMrE,MAAa,iBAAiB;IAa5B,YACE,SAAiB,EACjB,gBAAwB,IAAI,GAAG,IAAI,GAAG,CAAC,EACvC,mBAA2B,IAAI,EAC/B,WAAmB,EAAE;QA+Bf,eAAU,GAAG,CAAC,CAAM,EAAE,IAAS,EAAE,EAAO,EAAE,EAAE;YAClD,MAAM,OAAO,GAAG,IAAI,CAAC,gBAAgB,CAAC,IAAI,CACxC,cAAI,CAAC,OAAO,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,WAAW,EAAE,CAC9C,CAAC;YAEF,IAAI,OAAO;gBAAE,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;;gBAE1B,EAAE,CACA,IAAI,mBAAQ,CACV,4CAA4C,MAAM,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC,UAAU,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EACrH,GAAG,EACH,oBAAoB,EACpB,EAAE,QAAQ,EAAE,IAAI,CAAC,YAAY,EAAE,CAChC,CACF,CAAC;QACN,CAAC,CAAC;QA5CA,SAAS,GAAG,SAAS,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CA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ACD,KAAK,EAAE;QACL,QAAQ,EAAE,EAAE;QACZ,OAAO,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI;QAC3B,mBAAmB,EAAE,IAAI;KAC1B;CACF,CAAC","sourcesContent":["import multer, { StorageEngine } from \"multer\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { NextFunction } from \"express\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { promisify } from \"util\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport {\n ArkosNextFunction,\n ArkosRequest,\n ArkosRequestHandler,\n ArkosResponse,\n} from \"../../types\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { removeBothSlashes } from \"../../utils/helpers/text.helpers\";\n\n/**\n * Service to handle file uploads, including single and multiple file uploads,\n * file validation (type, size), and file deletion.\n */\nexport class FileUploadService {\n public readonly uploadDir: string;\n private fileSizeLimit: number;\n private allowedFileTypes: RegExp;\n private storage: StorageEngine;\n private maxCount: number;\n\n /**\n * Constructor to initialize the file uploader service.\n * @param {string} uploadDir - The directory where files will be uploaded.\n * @param {number} fileSizeLimit - The maximum allowed file size.\n * @param {RegExp} allowedFileTypes - The regular expression for allowed file types.\n */\n constructor(\n uploadDir: string,\n fileSizeLimit: number = 1024 * 1024 * 5,\n allowedFileTypes: RegExp = /.*/,\n maxCount: number = 30\n ) {\n uploadDir = uploadDir.startsWith(\"/\") ? uploadDir.substring(1) : uploadDir;\n uploadDir = uploadDir.endsWith(\"/\") ? uploadDir.slice(0, -1) : uploadDir;\n\n this.uploadDir = path.resolve(process.cwd(), `${uploadDir}/`);\n this.fileSizeLimit = fileSizeLimit;\n this.allowedFileTypes = allowedFileTypes;\n this.maxCount = maxCount;\n\n if (!fs.existsSync(this.uploadDir)) {\n fs.mkdirSync(this.uploadDir, { recursive: true });\n }\n\n this.storage = multer.diskStorage({\n destination: (_, _1, cb) => {\n cb(null, this.uploadDir);\n },\n filename: (_, file, cb) => {\n const uniqueSuffix = Date.now() + \"-\" + Math.round(Math.random() * 1e9);\n const ext = path.extname(file.originalname);\n cb(null, `${file.originalname.replace(ext, \"\")}-${uniqueSuffix}${ext}`);\n },\n });\n }\n\n /**\n * Validates the file's type and MIME type.\n * @param {Express.Multer.File} file - The uploaded file.\n * @param {Function} cb - The callback function to indicate if file is valid.\n */\n private fileFilter = (_: any, file: any, cb: any) => {\n const extName = this.allowedFileTypes.test(\n path.extname(file.originalname).toLowerCase()\n );\n\n if (extName) cb(null, true);\n else\n cb(\n new AppError(\n `File type not allowed, allowed files are ${String(this.allowedFileTypes).replaceAll(\"/\", \"\").split(\"|\").join(\", \")}`,\n 400,\n \"NotAllowedFileType\",\n { filename: file.originalname }\n )\n );\n };\n\n /**\n * Returns the multer upload configuration.\n * @returns {multer.Multer} The multer instance configured for file uploads.\n */\n public getUpload(): multer.Multer {\n return multer({\n storage: this.storage,\n fileFilter: this.fileFilter,\n limits: { fileSize: this.fileSizeLimit },\n });\n }\n\n /**\n * Middleware to handle single file upload.\n * @param {string} [oldFilePath] - The path to the file to delete before uploading.\n * @returns {Function} Middleware function for handling file upload.\n */\n public handleSingleUpload(oldFilePath?: string): ArkosRequestHandler {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const upload = this.getUpload().single(this.getFieldName());\n upload(req, res, async (err) => {\n if (err instanceof multer.MulterError) {\n return next(err);\n } else if (err) {\n return next(err);\n }\n\n if (oldFilePath) {\n const { fileUpload: configs } = getArkosConfig();\n\n const filePath = path.resolve(\n process.cwd(),\n removeBothSlashes(configs?.baseUploadDir!),\n removeBothSlashes(oldFilePath)\n );\n try {\n const stats = await promisify(fs.stat)(filePath);\n if (stats) await promisify(fs.unlink)(filePath);\n } catch (err) {\n console.error(err);\n }\n }\n\n next();\n });\n };\n }\n\n /**\n * Middleware to handle multiple file uploads.\n * @returns {Function} Middleware function for handling multiple file uploads.\n */\n public handleMultipleUpload(): ArkosRequestHandler {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const upload = this.getUpload().array(this.getFieldName(), this.maxCount);\n upload(req, res, (err) => {\n if (err instanceof multer.MulterError) return next(err);\n else if (err) return next(err);\n next();\n });\n };\n }\n\n /**\n * Middleware to handle deletion of a single file from the filesystem.\n * @param {string} oldFilePath - The path to the file to be deleted.\n * @returns {Function} Middleware function for handling file deletion.\n */\n public handleDeleteSingleFile(oldFilePath: string): ArkosRequestHandler {\n return async (_: ArkosRequest, _1: ArkosResponse, next: NextFunction) => {\n const filePath = path.join(oldFilePath);\n try {\n const stats = await promisify(fs.stat)(filePath);\n if (stats) {\n await promisify(fs.unlink)(filePath);\n }\n } catch (err) {\n console.error(err);\n }\n\n next();\n };\n }\n\n /**\n * Deletes a file based on its URL by identifying the appropriate uploader service\n * @param {string} fileUrl - The URL of the file to delete\n * @returns {Promise<boolean>} - True if deletion successful, false otherwise\n */\n public async deleteFileByUrl(fileUrl: string): Promise<boolean> {\n try {\n // Get configuration values\n const { fileUpload } = getArkosConfig();\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // Parse the URL to get the path\n let urlPath: string;\n if (fileUrl.startsWith(\"http\")) {\n const url = new URL(fileUrl);\n urlPath = url.pathname;\n } else {\n urlPath = fileUrl;\n }\n\n // Extract the path after the base route\n const baseRouteIndex = urlPath.indexOf(baseRoute);\n if (baseRouteIndex === -1) {\n throw new AppError(\"Invalid file URL: base route not found\", 400);\n }\n\n const pathAfterBaseRoute = urlPath.substring(\n baseRouteIndex + baseRoute.length\n );\n const cleanPath = pathAfterBaseRoute.startsWith(\"/\")\n ? pathAfterBaseRoute.substring(1)\n : pathAfterBaseRoute;\n\n // Determine file type and file name\n const fileTypes = [\"images\", \"videos\", \"documents\", \"files\"];\n let fileType: string | null = null;\n let fileName: string | null = null;\n\n for (const type of fileTypes) {\n const typeIndex = cleanPath.indexOf(type + \"/\");\n if (typeIndex !== -1) {\n fileType = type;\n fileName = cleanPath.substring(typeIndex + type.length + 1);\n break;\n }\n }\n\n if (!fileType || !fileName) {\n throw new AppError(\n \"Unable to determine file type or file name from URL\",\n 400\n );\n }\n\n // Get the appropriate uploader service based on file type\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let filePath: string;\n switch (fileType) {\n case \"images\":\n filePath = path.join(imageUploadService.uploadDir, fileName);\n break;\n case \"videos\":\n filePath = path.join(videoUploadService.uploadDir, fileName);\n break;\n case \"documents\":\n filePath = path.join(documentUploadService.uploadDir, fileName);\n break;\n case \"files\":\n filePath = path.join(fileUploadService.uploadDir, fileName);\n break;\n default:\n throw new AppError(`Unsupported file type: ${fileType}`, 400);\n }\n\n // Delete the file\n\n await promisify(fs.stat)(filePath);\n await promisify(fs.unlink)(filePath);\n\n return true;\n } catch (error: any) {\n if (error instanceof AppError) {\n throw error;\n }\n\n if (error.code === \"ENOENT\") {\n throw new AppError(\"File not found\", 404);\n }\n\n throw new AppError(`Failed to delete file: ${error.message}`, 500);\n }\n }\n\n private getFieldName() {\n let fieldName = \"files\";\n if (this.uploadDir.endsWith(\"images\") || this.uploadDir.endsWith(\"images/\"))\n fieldName = \"images\";\n if (this.uploadDir.endsWith(\"videos\") || this.uploadDir.endsWith(\"videos/\"))\n fieldName = \"videos\";\n if (\n this.uploadDir.endsWith(\"documents\") ||\n this.uploadDir.endsWith(\"documents/\")\n )\n fieldName = \"documents\";\n if (this.uploadDir.endsWith(\"files\") || this.uploadDir.endsWith(\"files/\"))\n fieldName = \"files\";\n return fieldName;\n }\n\n /**\n * Handles the upload process and returns the full URLs of uploaded files\n * @param {ArkosRequest} req - Arkos request object containing the files\n * @param {ArkosResponse} res - Arkos response object\n * @param {object} options - Optional parameters for image processing\n * @returns {Promise<string|string[]>} URL or array of URLs to the uploaded files\n */\n public async upload(\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction,\n options: {\n format?: string;\n width?: number;\n height?: number;\n resizeTo?: number;\n } = {}\n ): Promise<string | string[] | null> {\n const { fileUpload } = getArkosConfig();\n fileUpload?.baseRoute || \"/api/uploads\";\n\n return new Promise((resolve, reject) => {\n // Determine if it's a single or multiple file upload\n const isMultiple = Array.isArray(req.query.multiple)\n ? req.query.multiple[0] == \"true\"\n : req.query.multiple == \"true\";\n\n // Use appropriate upload handler\n const uploadHandler = isMultiple\n ? this.getUpload().array(this.getFieldName(), this.maxCount)\n : this.getUpload().single(this.getFieldName());\n\n uploadHandler(req, res, async (err) => {\n if (err) return reject(err);\n\n try {\n // Determine the base URL for file access\n const protocol = req.get(\"host\")?.includes?.(\"localhost\")\n ? \"http\"\n : \"https\";\n `${protocol}://${req.get(\"host\")}`;\n\n // Get file type from uploadDir path\n const dirParts = this.uploadDir.split(\"/\");\n (this.uploadDir.endsWith(\"/\")\n ? dirParts[dirParts.length - 2]\n : dirParts[dirParts.length - 1]) || \"files\";\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n const isImageUpload = this.uploadDir?.includes?.(\"/images\");\n if (isImageUpload) {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n const isImageUpload = this.uploadDir?.includes?.(\"/images\");\n if (isImageUpload) {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return reject(new AppError(\"No file uploaded\", 400));\n }\n\n resolve(data);\n } catch (error) {\n reject(error);\n }\n });\n });\n }\n\n /**\n * Deletes a file based on filename and file type from request parameters\n * @param {string} fileName - The name of the file to delete\n * @returns {Promise<boolean>} - True if deletion successful, false otherwise\n */\n public async deleteFileByName(\n fileName: string,\n fileType: \"images\" | \"videos\" | \"documents\" | \"files\"\n ): Promise<boolean> {\n try {\n if (!fileType) throw new AppError(\"File type parameter is required\", 400);\n\n const validFileTypes = [\"images\", \"videos\", \"documents\", \"files\"];\n if (!validFileTypes.includes(fileType)) {\n throw new AppError(\n `Invalid file type: ${fileType}. Must be one of: ${validFileTypes.join(\n \", \"\n )}`,\n 400\n );\n }\n\n // Get the appropriate uploader service based on file type\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let targetService: FileUploadService;\n switch (fileType) {\n case \"images\":\n targetService = imageUploadService;\n break;\n case \"videos\":\n targetService = videoUploadService;\n break;\n case \"documents\":\n targetService = documentUploadService;\n break;\n case \"files\":\n targetService = fileUploadService;\n break;\n default:\n throw new AppError(`Unsupported file type: ${fileType}`, 400);\n }\n\n // Construct the full file path\n const filePath = path.join(targetService.uploadDir, fileName);\n\n // Check if file exists and delete it\n await promisify(fs.stat)(filePath);\n await promisify(fs.unlink)(filePath);\n\n return true;\n } catch (error: any) {\n if (error instanceof AppError) {\n throw error;\n }\n\n if (error.code === \"ENOENT\") {\n throw new AppError(\"File not found\", 404);\n }\n\n throw new AppError(`Failed to delete file: ${error.message}`, 500);\n }\n }\n}\n\n/**\n * Creates and returns all file uploader services based on config\n * @returns Object containing all specialized file uploader services\n */\nexport const getFileUploadServices = () => {\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const restrictions = fileUpload?.restrictions\n ? deepmerge(fileUploadDefaultRestrictions, fileUpload.restrictions)\n : fileUploadDefaultRestrictions;\n\n /**\n * Specialized file uploader service for handling image uploads.\n */\n const imageUploadService = new FileUploadService(\n `${baseUploadDir}/images`,\n restrictions.images.maxSize,\n restrictions.images.supportedFilesRegex,\n restrictions.images.maxCount\n );\n\n /**\n * Specialized file uploader service for handling video uploads.\n */\n const videoUploadService = new FileUploadService(\n `${baseUploadDir}/videos`,\n restrictions.videos.maxSize,\n restrictions.videos.supportedFilesRegex,\n restrictions.videos.maxCount\n );\n\n /**\n * Specialized file uploader service for handling document uploads.\n */\n const documentUploadService = new FileUploadService(\n `${baseUploadDir}/documents`,\n restrictions.documents.maxSize,\n restrictions.documents.supportedFilesRegex,\n restrictions.documents.maxCount\n );\n\n /**\n * Generic file uploader service for handling all file uploads.\n */\n const fileUploadService = new FileUploadService(\n `${baseUploadDir}/files`,\n restrictions.files.maxSize,\n restrictions.files.supportedFilesRegex,\n restrictions.files.maxCount\n );\n\n return {\n imageUploadService,\n videoUploadService,\n documentUploadService,\n fileUploadService,\n };\n};\n\nexport const fileUploadDefaultRestrictions = {\n images: {\n maxCount: 30,\n maxSize: 1024 * 1024 * 15, // 15 MB\n supportedFilesRegex:\n /jpeg|jpg|png|gif|webp|svg|bmp|tiff|heif|heic|ico|jfif|raw|cr2|nef|orf|sr2|arw|dng|pef|raf|rw2|psd|ai|eps|xcf|jxr|wdp|hdp|jp2|j2k|jpf|jpx|jpm|mj2|avif/,\n },\n videos: {\n maxCount: 10,\n maxSize: 1024 * 1024 * 5096, // 5 GB\n supportedFilesRegex:\n /mp4|avi|mov|mkv|flv|wmv|webm|mpg|mpeg|3gp|m4v|ts|rm|rmvb|vob|ogv|dv|qt|asf|m2ts|mts|divx|f4v|swf|mxf|roq|nsv|mvb|svi|mpe|m2v|mp2|mpv|h264|h265|hevc/,\n },\n documents: {\n maxCount: 30,\n maxSize: 1024 * 1024 * 50, // 50 MB\n supportedFilesRegex:\n /pdf|doc|docx|xls|xlsx|ppt|pptx|odt|ods|odg|odp|txt|rtf|csv|epub|md|tex|pages|numbers|key|xml|json|yaml|yml|ini|cfg|conf|log|html|htm|xhtml|djvu|mobi|azw|azw3|fb2|lit|ps|wpd|wps|dot|dotx|xlt|xltx|pot|potx|oft|one|onetoc2|opf|oxps|hwp/,\n },\n files: {\n maxCount: 10,\n maxSize: 1024 * 1024 * 5096, // 5 GB\n supportedFilesRegex: /.*/,\n },\n};\n"]}
1
+ {"version":3,"file":"file-upload.service.js","sourceRoot":"","sources":["../../../../src/modules/file-upload/file-upload.service.ts"],"names":[],"mappings":";;;;;;AAAA,oDAA+C;AAC/C,gDA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D,GAAG,aAAa,YAAY,EAC5B,YAAY,CAAC,SAAS,CAAC,OAAO,EAC9B,YAAY,CAAC,SAAS,CAAC,mBAAmB,EAC1C,YAAY,CAAC,SAAS,CAAC,QAAQ,CAChC,CAAC;IAKF,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,CAC7C,GAAG,aAAa,QAAQ,EACxB,YAAY,CAAC,KAAK,CAAC,OAAO,EAC1B,YAAY,CAAC,KAAK,CAAC,mBAAmB,EACtC,YAAY,CAAC,KAAK,CAAC,QAAQ,CAC5B,CAAC;IAEF,OAAO;QACL,kBAAkB;QAClB,kBAAkB;QAClB,qBAAqB;QACrB,iBAAiB;KAClB,CAAC;AACJ,CAAC,CAAC;AAtDW,QAAA,qBAAqB,yBAsDhC;AAEW,QAAA,6BAA6B,GAAG;IAC3C,MAAM,EAAE;QACN,QAAQ,EAAE,EAAE;QACZ,OAAO,EAAE,IAAI,GAAG,IAAI,GAAG,EAAE;QACzB,mBAAmB,EACjB,uJAAuJ;KAC1J;IACD,MAAM,EAAE;QACN,QAAQ,EAAE,EAAE;QACZ,OAAO,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI;QAC3B,mBAAmB,EACjB,qJAAqJ;KACxJ;IACD,SAAS,EAAE;QACT,QAAQ,EAAE,EAAE;QACZ,OAAO,EAAE,IAAI,GAAG,IAAI,GAAG,EAAE;QACzB,mBAAmB,EACjB,0OAA0O;KAC7O;IACD,KAAK,EAAE;QACL,QAAQ,EAAE,EAAE;QACZ,OAAO,EAAE,IAAI,GAAG,IAAI,GAAG,IAAI;QAC3B,mBAAmB,EAAE,IAAI;KAC1B;CACF,CAAC","sourcesContent":["import multer, { StorageEngine } from \"multer\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport { NextFunction } from \"express\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { promisify } from \"util\";\nimport { getArkosConfig } from \"../../server\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport {\n ArkosNextFunction,\n ArkosRequest,\n ArkosRequestHandler,\n ArkosResponse,\n} from \"../../types\";\nimport { processFile, processImage } from \"./utils/helpers/file-upload.helpers\";\nimport { removeBothSlashes } from \"../../utils/helpers/text.helpers\";\n\n/**\n * Service to handle file uploads, including single and multiple file uploads,\n * file validation (type, size), and file deletion.\n */\nexport class FileUploadService {\n public readonly uploadDir: string;\n private fileSizeLimit: number;\n private allowedFileTypes: RegExp;\n private storage: StorageEngine;\n private maxCount: number;\n\n /**\n * Constructor to initialize the file uploader service.\n * @param {string} uploadDir - The directory where files will be uploaded.\n * @param {number} fileSizeLimit - The maximum allowed file size.\n * @param {RegExp} allowedFileTypes - The regular expression for allowed file types.\n */\n constructor(\n uploadDir: string,\n fileSizeLimit: number = 1024 * 1024 * 5,\n allowedFileTypes: RegExp = /.*/,\n maxCount: number = 30\n ) {\n uploadDir = uploadDir.startsWith(\"/\") ? uploadDir.substring(1) : uploadDir;\n uploadDir = uploadDir.endsWith(\"/\") ? uploadDir.slice(0, -1) : uploadDir;\n\n this.uploadDir = path.resolve(process.cwd(), `${uploadDir}/`);\n this.fileSizeLimit = fileSizeLimit;\n this.allowedFileTypes = allowedFileTypes;\n this.maxCount = maxCount;\n\n if (!fs.existsSync(this.uploadDir)) {\n fs.mkdirSync(this.uploadDir, { recursive: true });\n }\n\n this.storage = multer.diskStorage({\n destination: (_, _1, cb) => {\n cb(null, this.uploadDir);\n },\n filename: (_, file, cb) => {\n const uniqueSuffix = Date.now() + \"-\" + Math.round(Math.random() * 1e9);\n const ext = path.extname(file.originalname);\n cb(null, `${file.originalname.replace(ext, \"\")}-${uniqueSuffix}${ext}`);\n },\n });\n }\n\n /**\n * Validates the file's type and MIME type.\n * @param {Express.Multer.File} file - The uploaded file.\n * @param {Function} cb - The callback function to indicate if file is valid.\n */\n private fileFilter = (_: any, file: any, cb: any) => {\n const extName = this.allowedFileTypes.test(\n path.extname(file.originalname).toLowerCase()\n );\n\n if (extName) cb(null, true);\n else\n cb(\n new AppError(\n `File type not allowed, allowed files are ${String(this.allowedFileTypes).replaceAll(\"/\", \"\").split(\"|\").join(\", \")}`,\n 400,\n \"FileTypeNotAllowed\",\n { filename: file.originalname }\n )\n );\n };\n\n /**\n * Returns the multer upload configuration.\n * @returns {multer.Multer} The multer instance configured for file uploads.\n */\n public getUpload(): multer.Multer {\n return multer({\n storage: this.storage,\n fileFilter: this.fileFilter,\n limits: { fileSize: this.fileSizeLimit },\n });\n }\n\n /**\n * Middleware to handle single file upload.\n * @param {string} [oldFilePath] - The path to the file to delete before uploading.\n * @returns {Function} Middleware function for handling file upload.\n */\n public handleSingleUpload(oldFilePath?: string): ArkosRequestHandler {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const upload = this.getUpload().single(this.getFieldName());\n upload(req, res, async (err) => {\n if (err instanceof multer.MulterError) {\n return next(err);\n } else if (err) {\n return next(err);\n }\n\n if (oldFilePath) {\n const { fileUpload: configs } = getArkosConfig();\n\n const filePath = path.resolve(\n process.cwd(),\n removeBothSlashes(configs?.baseUploadDir!),\n removeBothSlashes(oldFilePath)\n );\n try {\n const stats = await promisify(fs.stat)(filePath);\n if (stats) await promisify(fs.unlink)(filePath);\n } catch (err) {\n console.error(err);\n }\n }\n\n next();\n });\n };\n }\n\n /**\n * Middleware to handle multiple file uploads.\n * @returns {Function} Middleware function for handling multiple file uploads.\n */\n public handleMultipleUpload(): ArkosRequestHandler {\n return (req: ArkosRequest, res: ArkosResponse, next: NextFunction) => {\n const upload = this.getUpload().array(this.getFieldName(), this.maxCount);\n upload(req, res, (err) => {\n if (err instanceof multer.MulterError) return next(err);\n else if (err) return next(err);\n next();\n });\n };\n }\n\n /**\n * Middleware to handle deletion of a single file from the filesystem.\n * @param {string} oldFilePath - The path to the file to be deleted.\n * @returns {Function} Middleware function for handling file deletion.\n */\n public handleDeleteSingleFile(oldFilePath: string): ArkosRequestHandler {\n return async (_: ArkosRequest, _1: ArkosResponse, next: NextFunction) => {\n const filePath = path.join(oldFilePath);\n try {\n const stats = await promisify(fs.stat)(filePath);\n if (stats) {\n await promisify(fs.unlink)(filePath);\n }\n } catch (err) {\n console.error(err);\n }\n\n next();\n };\n }\n\n /**\n * Deletes a file based on its URL by identifying the appropriate uploader service\n * @param {string} fileUrl - The URL of the file to delete\n * @returns {Promise<boolean>} - True if deletion successful, false otherwise\n */\n public async deleteFileByUrl(fileUrl: string): Promise<boolean> {\n try {\n // Get configuration values\n const { fileUpload } = getArkosConfig();\n const baseRoute = fileUpload?.baseRoute || \"/api/uploads\";\n\n // Parse the URL to get the path\n let urlPath: string;\n if (fileUrl.startsWith(\"http\")) {\n const url = new URL(fileUrl);\n urlPath = url.pathname;\n } else {\n urlPath = fileUrl;\n }\n\n // Extract the path after the base route\n const baseRouteIndex = urlPath.indexOf(baseRoute);\n if (baseRouteIndex === -1) {\n throw new AppError(\"Invalid file URL: base route not found\", 400);\n }\n\n const pathAfterBaseRoute = urlPath.substring(\n baseRouteIndex + baseRoute.length\n );\n const cleanPath = pathAfterBaseRoute.startsWith(\"/\")\n ? pathAfterBaseRoute.substring(1)\n : pathAfterBaseRoute;\n\n // Determine file type and file name\n const fileTypes = [\"images\", \"videos\", \"documents\", \"files\"];\n let fileType: string | null = null;\n let fileName: string | null = null;\n\n for (const type of fileTypes) {\n const typeIndex = cleanPath.indexOf(type + \"/\");\n if (typeIndex !== -1) {\n fileType = type;\n fileName = cleanPath.substring(typeIndex + type.length + 1);\n break;\n }\n }\n\n if (!fileType || !fileName) {\n throw new AppError(\n \"Unable to determine file type or file name from URL\",\n 400\n );\n }\n\n // Get the appropriate uploader service based on file type\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let filePath: string;\n switch (fileType) {\n case \"images\":\n filePath = path.join(imageUploadService.uploadDir, fileName);\n break;\n case \"videos\":\n filePath = path.join(videoUploadService.uploadDir, fileName);\n break;\n case \"documents\":\n filePath = path.join(documentUploadService.uploadDir, fileName);\n break;\n case \"files\":\n filePath = path.join(fileUploadService.uploadDir, fileName);\n break;\n default:\n throw new AppError(`Unsupported file type: ${fileType}`, 400);\n }\n\n // Delete the file\n\n await promisify(fs.stat)(filePath);\n await promisify(fs.unlink)(filePath);\n\n return true;\n } catch (error: any) {\n if (error instanceof AppError) {\n throw error;\n }\n\n if (error.code === \"ENOENT\") {\n throw new AppError(\"File not found\", 404);\n }\n\n throw new AppError(`Failed to delete file: ${error.message}`, 500);\n }\n }\n\n private getFieldName() {\n let fieldName = \"files\";\n if (this.uploadDir.endsWith(\"images\") || this.uploadDir.endsWith(\"images/\"))\n fieldName = \"images\";\n if (this.uploadDir.endsWith(\"videos\") || this.uploadDir.endsWith(\"videos/\"))\n fieldName = \"videos\";\n if (\n this.uploadDir.endsWith(\"documents\") ||\n this.uploadDir.endsWith(\"documents/\")\n )\n fieldName = \"documents\";\n if (this.uploadDir.endsWith(\"files\") || this.uploadDir.endsWith(\"files/\"))\n fieldName = \"files\";\n return fieldName;\n }\n\n /**\n * Handles the upload process and returns the full URLs of uploaded files\n * @param {ArkosRequest} req - Arkos request object containing the files\n * @param {ArkosResponse} res - Arkos response object\n * @param {object} options - Optional parameters for image processing\n * @returns {Promise<string|string[]>} URL or array of URLs to the uploaded files\n */\n public async upload(\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction,\n options: {\n format?: string;\n width?: number;\n height?: number;\n resizeTo?: number;\n } = {}\n ): Promise<string | string[] | null> {\n const { fileUpload } = getArkosConfig();\n fileUpload?.baseRoute || \"/api/uploads\";\n\n return new Promise((resolve, reject) => {\n // Determine if it's a single or multiple file upload\n const isMultiple = Array.isArray(req.query.multiple)\n ? req.query.multiple[0] == \"true\"\n : req.query.multiple == \"true\";\n\n // Use appropriate upload handler\n const uploadHandler = isMultiple\n ? this.getUpload().array(this.getFieldName(), this.maxCount)\n : this.getUpload().single(this.getFieldName());\n\n uploadHandler(req, res, async (err) => {\n if (err) return reject(err);\n\n try {\n // Determine the base URL for file access\n const protocol = req.get(\"host\")?.includes?.(\"localhost\")\n ? \"http\"\n : \"https\";\n `${protocol}://${req.get(\"host\")}`;\n\n // Get file type from uploadDir path\n const dirParts = this.uploadDir.split(\"/\");\n (this.uploadDir.endsWith(\"/\")\n ? dirParts[dirParts.length - 2]\n : dirParts[dirParts.length - 1]) || \"files\";\n\n let data;\n if (req.files && Array.isArray(req.files) && req.files.length > 0) {\n const isImageUpload = this.uploadDir?.includes?.(\"/images\");\n if (isImageUpload) {\n data = await Promise.all(\n req.files.map((file) =>\n processImage(req, next, file.path, options)\n )\n );\n } else {\n data = await Promise.all(\n req.files.map((file) => processFile(req, file.path))\n );\n }\n // Filter out any null values from failed processing\n data = data.filter((url) => url !== null);\n } else if (req.file) {\n // Process a single file\n const isImageUpload = this.uploadDir?.includes?.(\"/images\");\n if (isImageUpload) {\n data = await processImage(req, next, req.file.path, options);\n } else {\n data = await processFile(req, req.file.path);\n }\n } else {\n return reject(new AppError(\"No file uploaded\", 400));\n }\n\n resolve(data);\n } catch (error) {\n reject(error);\n }\n });\n });\n }\n\n /**\n * Deletes a file based on filename and file type from request parameters\n * @param {string} fileName - The name of the file to delete\n * @returns {Promise<boolean>} - True if deletion successful, false otherwise\n */\n public async deleteFileByName(\n fileName: string,\n fileType: \"images\" | \"videos\" | \"documents\" | \"files\"\n ): Promise<boolean> {\n try {\n if (!fileType) throw new AppError(\"File type parameter is required\", 400);\n\n const validFileTypes = [\"images\", \"videos\", \"documents\", \"files\"];\n if (!validFileTypes.includes(fileType)) {\n throw new AppError(\n `Invalid file type: ${fileType}. Must be one of: ${validFileTypes.join(\n \", \"\n )}`,\n 400\n );\n }\n\n // Get the appropriate uploader service based on file type\n const {\n documentUploadService,\n fileUploadService,\n imageUploadService,\n videoUploadService,\n } = getFileUploadServices();\n\n let targetService: FileUploadService;\n switch (fileType) {\n case \"images\":\n targetService = imageUploadService;\n break;\n case \"videos\":\n targetService = videoUploadService;\n break;\n case \"documents\":\n targetService = documentUploadService;\n break;\n case \"files\":\n targetService = fileUploadService;\n break;\n default:\n throw new AppError(`Unsupported file type: ${fileType}`, 400);\n }\n\n // Construct the full file path\n const filePath = path.join(targetService.uploadDir, fileName);\n\n // Check if file exists and delete it\n await promisify(fs.stat)(filePath);\n await promisify(fs.unlink)(filePath);\n\n return true;\n } catch (error: any) {\n if (error instanceof AppError) {\n throw error;\n }\n\n if (error.code === \"ENOENT\") {\n throw new AppError(\"File not found\", 404);\n }\n\n throw new AppError(`Failed to delete file: ${error.message}`, 500);\n }\n }\n}\n\n/**\n * Creates and returns all file uploader services based on config\n * @returns Object containing all specialized file uploader services\n */\nexport const getFileUploadServices = () => {\n const { fileUpload } = getArkosConfig();\n const baseUploadDir = fileUpload?.baseUploadDir || \"/uploads\";\n\n const restrictions = fileUpload?.restrictions\n ? deepmerge(fileUploadDefaultRestrictions, fileUpload.restrictions)\n : fileUploadDefaultRestrictions;\n\n /**\n * Specialized file uploader service for handling image uploads.\n */\n const imageUploadService = new FileUploadService(\n `${baseUploadDir}/images`,\n restrictions.images.maxSize,\n restrictions.images.supportedFilesRegex,\n restrictions.images.maxCount\n );\n\n /**\n * Specialized file uploader service for handling video uploads.\n */\n const videoUploadService = new FileUploadService(\n `${baseUploadDir}/videos`,\n restrictions.videos.maxSize,\n restrictions.videos.supportedFilesRegex,\n restrictions.videos.maxCount\n );\n\n /**\n * Specialized file uploader service for handling document uploads.\n */\n const documentUploadService = new FileUploadService(\n `${baseUploadDir}/documents`,\n restrictions.documents.maxSize,\n restrictions.documents.supportedFilesRegex,\n restrictions.documents.maxCount\n );\n\n /**\n * Generic file uploader service for handling all file uploads.\n */\n const fileUploadService = new FileUploadService(\n `${baseUploadDir}/files`,\n restrictions.files.maxSize,\n restrictions.files.supportedFilesRegex,\n restrictions.files.maxCount\n );\n\n return {\n imageUploadService,\n videoUploadService,\n documentUploadService,\n fileUploadService,\n };\n};\n\nexport const fileUploadDefaultRestrictions = {\n images: {\n maxCount: 30,\n maxSize: 1024 * 1024 * 15, // 15 MB\n supportedFilesRegex:\n /jpeg|jpg|png|gif|webp|svg|bmp|tiff|heif|heic|ico|jfif|raw|cr2|nef|orf|sr2|arw|dng|pef|raf|rw2|psd|ai|eps|xcf|jxr|wdp|hdp|jp2|j2k|jpf|jpx|jpm|mj2|avif/,\n },\n videos: {\n maxCount: 10,\n maxSize: 1024 * 1024 * 5096, // 5 GB\n supportedFilesRegex:\n /mp4|avi|mov|mkv|flv|wmv|webm|mpg|mpeg|3gp|m4v|ts|rm|rmvb|vob|ogv|dv|qt|asf|m2ts|mts|divx|f4v|swf|mxf|roq|nsv|mvb|svi|mpe|m2v|mp2|mpv|h264|h265|hevc/,\n },\n documents: {\n maxCount: 30,\n maxSize: 1024 * 1024 * 50, // 50 MB\n supportedFilesRegex:\n /pdf|doc|docx|xls|xlsx|ppt|pptx|odt|ods|odg|odp|txt|rtf|csv|epub|md|tex|pages|numbers|key|xml|json|yaml|yml|ini|cfg|conf|log|html|htm|xhtml|djvu|mobi|azw|azw3|fb2|lit|ps|wpd|wps|dot|dotx|xlt|xltx|pot|potx|oft|one|onetoc2|opf|oxps|hwp/,\n },\n files: {\n maxCount: 10,\n maxSize: 1024 * 1024 * 5096, // 5 GB\n supportedFilesRegex: /.*/,\n },\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/types/auth.ts"],"names":[],"mappings":"","sourcesContent":["import { JwtPayload } from \"jsonwebtoken\";\n\n/**\n * Base set of controller actions available to all controllers.\n *\n * @example\n * const action: AccessAction = \"Create\";\n * const customAction: AccessAction = \"export\"; // Custom action\n */\nexport type AccessAction = \"Create\" | \"Update\" | \"Delete\" | \"View\" | string;\n\nexport type DetailedAccessControlRule = {\n /** Array of role names that have permission for this action */\n roles: string[];\n /** Human-readable name for this permission (optional) */\n name?: string;\n /** Detailed description of what this permission allows (optional) */\n description?: string;\n /** Detailed error message of what must be returned on forbidden response (optional)\n *\n * Note: not yet implemented\n * */\n errorMessage?: string;\n};\n\n/**\n * Rules defining access control for different controller actions.\n * The array contains role names that are allowed to perform the action.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n *\n * const rules: AccessControlRules = {\n * Create: {\n * roles: [\"Admin\", \"Manager\"],\n * name: \"Create a new user\",\n * description: \"Allows to create a new user\"\n * },\n * Update: [\"Admin\"],\n * Delete: [\"Admin\"],\n * View: [\"Admin\", \"User\", \"Guest\"]\n * };\n *\n */\nexport type AccessControlRules = {\n [key in AccessAction]: string[] | DetailedAccessControlRule;\n};\n\n/**\n * Rules defining authentication requirements for different controller actions.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n * const authRules: AuthenticationControlRules = {\n * Create: true,\n * Update: true,\n * Delete: true,\n * View: false // Public access\n * };\n */\nexport type AuthenticationControlRules = {\n [key in AccessAction]: boolean;\n};\n\n/**\n * Configuration for authentication control.\n *\n * @example\n * // All actions require authentication\n * const config1: AuthenticationControlConfig = true;\n *\n * // Specific rules per action\n * const config2: AuthenticationControlConfig = {\n * Create: true,\n * View: false\n * };\n */\nexport type AuthenticationControlConfig =\n | boolean\n | Partial<AuthenticationControlRules>;\n\n/**\n * Configuration for access control.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#auth-config-files---static-rbac}\n * @example\n * // All actions allowed for these roles\n * const config1: AccessControlConfig = [\"Admin\", \"Manager\"];\n *\n * // Specific rules per action\n * const config2: AccessControlConfig = {\n * Create: [\"Admin\"],\n * View: [\"User\", \"Admin\"]\n * };\n */\nexport type AccessControlConfig = string[] | Partial<AccessControlRules>;\n\n/**\n * Configuration for authentication and access control.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n * export const authConfig: AuthConfigs = {\n * authenticationControl: {\n * Create: true,\n * View: false\n * },\n * accessControl: {\n * Create: [\"Admin\"],\n * View: [\"User\", \"Admin\"]\n * }\n * };\n */\nexport type AuthConfigs = {\n authenticationControl?: AuthenticationControlConfig;\n accessControl?: AccessControlConfig;\n};\n\n/**\n * Payload structure for JWT-based authentication, extending the standard `JwtPayload`.\n *\n * @example\n * const payload: AuthJwtPayload = {\n * id: 123,\n * roles: [\"Admin\"],\n * email: \"user@example.com\"\n * };\n */\nexport interface AuthJwtPayload extends JwtPayload {\n id?: number | string;\n [x: string]: any;\n}\n"]}
1
+ {"version":3,"file":"auth.js","sourceRoot":"","sources":["../../../src/types/auth.ts"],"names":[],"mappings":"","sourcesContent":["import { JwtPayload } from \"jsonwebtoken\";\n\n/**\n * Base set of controller actions available to all controllers.\n *\n * @example\n * const action: AccessAction = \"Create\";\n * const customAction: AccessAction = \"export\"; // Custom action\n */\nexport type AccessAction = \"Create\" | \"Update\" | \"Delete\" | \"View\" | string;\n\nexport type DetailedAccessControlRule = {\n /** Array of role names that have permission for this action */\n roles?: string[];\n /** Human-readable name for this permission (optional) */\n name?: string;\n /** Detailed description of what this permission allows (optional) */\n description?: string;\n /** Detailed error message of what must be returned on forbidden response (optional)\n *\n * Note: not yet implemented\n * */\n errorMessage?: string;\n};\n\n/**\n * Rules defining access control for different controller actions.\n * The array contains role names that are allowed to perform the action.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n *\n * const rules: AccessControlRules = {\n * Create: {\n * roles: [\"Admin\", \"Manager\"],\n * name: \"Create a new user\",\n * description: \"Allows to create a new user\"\n * },\n * Update: [\"Admin\"],\n * Delete: [\"Admin\"],\n * View: [\"Admin\", \"User\", \"Guest\"]\n * };\n *\n */\nexport type AccessControlRules = {\n [key in AccessAction]: string[] | DetailedAccessControlRule;\n};\n\n/**\n * Rules defining authentication requirements for different controller actions.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n * const authRules: AuthenticationControlRules = {\n * Create: true,\n * Update: true,\n * Delete: true,\n * View: false // Public access\n * };\n */\nexport type AuthenticationControlRules = {\n [key in AccessAction]: boolean;\n};\n\n/**\n * Configuration for authentication control.\n *\n * @example\n * // All actions require authentication\n * const config1: AuthenticationControlConfig = true;\n *\n * // Specific rules per action\n * const config2: AuthenticationControlConfig = {\n * Create: true,\n * View: false\n * };\n */\nexport type AuthenticationControlConfig =\n | boolean\n | Partial<AuthenticationControlRules>;\n\n/**\n * Configuration for access control.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#auth-config-files---static-rbac}\n * @example\n * // All actions allowed for these roles\n * const config1: AccessControlConfig = [\"Admin\", \"Manager\"];\n *\n * // Specific rules per action\n * const config2: AccessControlConfig = {\n * Create: [\"Admin\"],\n * View: [\"User\", \"Admin\"]\n * };\n */\nexport type AccessControlConfig = string[] | Partial<AccessControlRules>;\n\n/**\n * Configuration for authentication and access control.\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication-system#using-auth-config-to-customize-endpoint-behavior}\n * @example\n * export const authConfig: AuthConfigs = {\n * authenticationControl: {\n * Create: true,\n * View: false\n * },\n * accessControl: {\n * Create: [\"Admin\"],\n * View: [\"User\", \"Admin\"]\n * }\n * };\n */\nexport type AuthConfigs = {\n authenticationControl?: AuthenticationControlConfig;\n accessControl?: AccessControlConfig;\n};\n\n/**\n * Payload structure for JWT-based authentication, extending the standard `JwtPayload`.\n *\n * @example\n * const payload: AuthJwtPayload = {\n * id: 123,\n * roles: [\"Admin\"],\n * email: \"user@example.com\"\n * };\n */\nexport interface AuthJwtPayload extends JwtPayload {\n id?: number | string;\n [x: string]: any;\n}\n"]}
@@ -19,6 +19,6 @@ function killServerChildProcess() {
19
19
  (0, start_1.killProductionServerChildProcess)();
20
20
  }
21
21
  function getVersion() {
22
- return "1.3.9-canary.4";
22
+ return "1.3.10-beta";
23
23
  }
24
24
  //# sourceMappingURL=cli.helpers.js.map
@@ -14,7 +14,6 @@ exports.validateNamingConventions = validateNamingConventions;
14
14
  exports.assignModuleToResult = assignModuleToResult;
15
15
  exports.importModuleComponents = importModuleComponents;
16
16
  exports.loadAllModuleComponents = loadAllModuleComponents;
17
- const zod_1 = require("zod");
18
17
  const path_1 = __importDefault(require("path"));
19
18
  const cli_helpers_1 = require("./cli/utils/cli.helpers");
20
19
  const sheu_1 = __importDefault(require("./sheu"));
@@ -92,7 +91,7 @@ function isClass(value) {
92
91
  /^class\s/.test(Function.prototype.toString.call(value)));
93
92
  }
94
93
  function isZodSchema(value) {
95
- return value instanceof zod_1.z.ZodType;
94
+ return value?._def?.typeName?.startsWith("Zod");
96
95
  }
97
96
  async function processSubdir(modelName, type) {
98
97
  const moduleDir = path_1.default.resolve((0, fs_helpers_1.crd)(), "src", "modules", (0, change_case_helpers_1.kebabCase)(modelName));
@@ -202,8 +201,9 @@ async function importModuleComponents(modelName, arkosConfig, moduleDirExists) {
202
201
  ? "schemas"
203
202
  : "dtos"
204
203
  : null;
205
- const [_, validators] = await Promise.all([
206
- Object.entries(fileStructure.core).map(async ([key, fileName]) => {
204
+ const [validators] = await Promise.all([
205
+ validationSubdir && processSubdir(modelName, validationSubdir),
206
+ ...Object.entries(fileStructure.core).map(async ([key, fileName]) => {
207
207
  if (["createMany", "findMany", "findOne", "updateMany"].includes(key) ||
208
208
  !fileName)
209
209
  return;
@@ -242,7 +242,6 @@ async function importModuleComponents(modelName, arkosConfig, moduleDirExists) {
242
242
  (0, cli_helpers_1.killServerChildProcess)();
243
243
  }
244
244
  }),
245
- validationSubdir && processSubdir(modelName, validationSubdir),
246
245
  ]);
247
246
  prismaModelsModules[(0, change_case_helpers_1.pascalCase)(modelName)] = {
248
247
  ...result,