arkos 1.3.0-canary → 1.3.0-canary.1

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.
@@ -1 +1,2 @@
1
- "use strict";var __importDefault=this&&this.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.AuthService=void 0;const jsonwebtoken_1=__importDefault(require("jsonwebtoken")),bcryptjs_1=__importDefault(require("bcryptjs")),catch_async_1=__importDefault(require("../error-handler/utils/catch-async")),app_error_1=__importDefault(require("../error-handler/utils/app-error")),base_middlewares_1=require("../base/base.middlewares"),server_1=require("../../server"),arkos_env_1=__importDefault(require("../../utils/arkos-env")),prisma_helpers_1=require("../../utils/helpers/prisma.helpers");class AuthService{constructor(){this.actionsPerResource={},this.authenticate=(0,catch_async_1.default)(async(e,t,s)=>{if(!(0,server_1.getArkosConfig)()?.authentication){s();return}e.user=await this.getAuthenticatedUser(e),s()})}signJwtToken(e,t,s){const{authentication:r}=(0,server_1.getArkosConfig)();if(process.env.NODE_ENV==="production"&&!process.env.JWT_SECRET&&!r?.jwt?.secret)throw new app_error_1.default("Missing JWT secret on production!",500,{},"MissingJWTOnProduction");return s=s||r?.jwt?.secret||process.env.JWT_SECRET||arkos_env_1.default.JWT_SECRET,t=t||r?.jwt?.expiresIn||process.env.JWT_EXPIRES_IN||arkos_env_1.default.JWT_EXPIRES_IN,jsonwebtoken_1.default.sign({id:e},s,{expiresIn:t})}isPasswordHashed(e){return!Number.isNaN(bcryptjs_1.default.getRounds(e)*1)}async isCorrectPassword(e,t){return await bcryptjs_1.default.compare(e,t)}async hashPassword(e){return await bcryptjs_1.default.hash(e,12)}isPasswordStrong(e){return((0,server_1.getArkosConfig)()?.authentication?.passwordValidation?.regex||/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).+$/).test(e)}userChangedPasswordAfter(e,t){if(e.passwordChangedAt){const s=parseInt(String(e.passwordChangedAt.getTime()/1e3),10);return t<s}return!1}async verifyJwtToken(e,t){const{authentication:s}=(0,server_1.getArkosConfig)();if(process.env.NODE_ENV==="production"&&!process.env.JWT_SECRET&&!s?.jwt?.secret)throw new app_error_1.default("Missing JWT secret!",500);return t=t||s?.jwt?.secret||process.env.JWT_SECRET||arkos_env_1.default.JWT_SECRET,new Promise((r,o)=>{jsonwebtoken_1.default.verify(e,t,(i,n)=>{i?o(i):r(n)})})}handleAccessControl(e,t,s){return(0,catch_async_1.default)(async(r,o,i)=>{if(r.user){const n=r.user,d=(0,prisma_helpers_1.getPrismaInstance)(),c=(0,server_1.getArkosConfig)();if(n.isSuperUser){i();return}if(c?.authentication?.mode==="dynamic"){if(!await d.userRole.findFirst({where:{userId:r.user.id,role:{permissions:{some:{resource:t,action:e}}}},select:{id:!0}}))return i(new app_error_1.default("You do not have permission to perfom this action",403))}else if(c?.authentication?.mode==="static"){let u=[];if(!s)return i(new app_error_1.default("You do not have permission to perform this action",403));if(Array.isArray(s)?u=s:s[e]&&(u=s[e]||[]),!(Array.isArray(n?.roles)?n.roles:[n.role]).some(l=>u.includes(l)))return i(new app_error_1.default("You do not have permission to perform this action",403))}}i()})}async getAuthenticatedUser(e){if(!(0,server_1.getArkosConfig)()?.authentication)return null;const s=(0,prisma_helpers_1.getPrismaInstance)();let r;if(e?.headers?.authorization&&e?.headers?.authorization.startsWith("Bearer")?r=e?.headers?.authorization.split(" ")[1]:e?.cookies?.arkos_access_token!=="no-token"&&e.cookies&&(r=e?.cookies?.arkos_access_token),!r)throw new app_error_1.default("You are not logged in! please log in to get access",401,{},"LoginRequired");let o;try{o=await this.verifyJwtToken(r)}catch{throw new app_error_1.default("Your auth token is invalid, please login again.",401,{},"InvalidAuthToken")}if(!o?.id)throw new app_error_1.default("Your auth token is invalid, please login again.",401,{},"InvalidAuthToken");const i=await s.user.findUnique({where:{id:String(o.id)}});if(!i)throw new app_error_1.default("The user belonging to this token does no longer exists",401);if(this.userChangedPasswordAfter(i,o.iat)&&!e.path?.includes?.("logout"))throw new app_error_1.default("User recently changed password! Please log in again.",401,{},"PasswordChanged");return e.accessToken=r,i}handleAuthenticationControl(e,t){if(t&&typeof t=="object"){if(t[e]===!1)return base_middlewares_1.callNext;if(t[e]===!0)return this.authenticate}else return this.authenticate;return this.authenticate}}exports.AuthService=AuthService;const authService=new AuthService;exports.default=authService;
1
+ "use strict";var __importDefault=this&&this.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.AuthService=void 0;const jsonwebtoken_1=__importDefault(require("jsonwebtoken")),bcryptjs_1=__importDefault(require("bcryptjs")),catch_async_1=__importDefault(require("../error-handler/utils/catch-async")),app_error_1=__importDefault(require("../error-handler/utils/app-error")),base_middlewares_1=require("../base/base.middlewares"),server_1=require("../../server"),arkos_env_1=__importDefault(require("../../utils/arkos-env")),prisma_helpers_1=require("../../utils/helpers/prisma.helpers");class AuthService{constructor(){this.actionsPerResource={},this.authenticate=(0,catch_async_1.default)(async(e,t,s)=>{if(!(0,server_1.getArkosConfig)()?.authentication){s();return}e.user=await this.getAuthenticatedUser(e),s()})}signJwtToken(e,t,s){const{authentication:r}=(0,server_1.getArkosConfig)();if(process.env.NODE_ENV==="production"&&!process.env.JWT_SECRET&&!r?.jwt?.secret)throw new app_error_1.default("Missing JWT secret on production!",500,{},"MissingJWTOnProduction");return s=s||r?.jwt?.secret||process.env.JWT_SECRET||arkos_env_1.default.JWT_SECRET,t=t||r?.jwt?.expiresIn||process.env.JWT_EXPIRES_IN||arkos_env_1.default.JWT_EXPIRES_IN,jsonwebtoken_1.default.sign({id:e},s,{expiresIn:t})}isPasswordHashed(e){return!Number.isNaN(bcryptjs_1.default.getRounds(e)*1)}async isCorrectPassword(e,t){return await bcryptjs_1.default.compare(e,t)}async hashPassword(e){return await bcryptjs_1.default.hash(e,12)}isPasswordStrong(e){return((0,server_1.getArkosConfig)()?.authentication?.passwordValidation?.regex||/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).+$/).test(e)}userChangedPasswordAfter(e,t){if(e.passwordChangedAt){const s=parseInt(String(e.passwordChangedAt.getTime()/1e3),10);return t<s}return!1}async verifyJwtToken(e,t){const{authentication:s}=(0,server_1.getArkosConfig)();if(process.env.NODE_ENV==="production"&&!process.env.JWT_SECRET&&!s?.jwt?.secret)throw new app_error_1.default("Missing JWT secret!",500);return t=t||s?.jwt?.secret||process.env.JWT_SECRET||arkos_env_1.default.JWT_SECRET,new Promise((r,o)=>{jsonwebtoken_1.default.verify(e,t,(i,n)=>{i?o(i):r(n)})})}checkStaticAccessControl(e,t,s){if(!e?.role&&!e.roles)throw Error("Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.");let r=[];return Array.isArray(s)?r=s:s[t]&&(r=s[t]||[]),!!(Array.isArray(e?.roles)?e.roles:[e.role]).some(i=>r.includes(i))}async checkDynamicAccessControl(e,t,s){return!!await(0,prisma_helpers_1.getPrismaInstance)().userRole.findFirst({where:{userId:e,role:{permissions:{some:{resource:s,action:t}}}},select:{id:!0}})}handleAccessControl(e,t,s){return(0,catch_async_1.default)(async(r,o,i)=>{if(r.user){const n=r.user,u=(0,server_1.getArkosConfig)();if(n.isSuperUser){i();return}const c=new app_error_1.default("You do not have permission to perfom this action",403,{},"NotEnoughPermissions");if(u?.authentication?.mode==="dynamic"){if(!await this.checkDynamicAccessControl(n.id,e,t))return i(c)}else if(u?.authentication?.mode==="static"&&(!s||!this.checkStaticAccessControl(n,e,s)))return i(c)}i()})}async getAuthenticatedUser(e){if(!(0,server_1.getArkosConfig)()?.authentication)return null;const s=(0,prisma_helpers_1.getPrismaInstance)();let r;if(e?.headers?.authorization&&e?.headers?.authorization.startsWith("Bearer")?r=e?.headers?.authorization.split(" ")[1]:e?.cookies?.arkos_access_token!=="no-token"&&e.cookies&&(r=e?.cookies?.arkos_access_token),!r)throw new app_error_1.default("You are not logged in! please log in to get access",401,{},"LoginRequired");let o;try{o=await this.verifyJwtToken(r)}catch{throw new app_error_1.default("Your auth token is invalid, please login again.",401,{},"InvalidAuthToken")}if(!o?.id)throw new app_error_1.default("Your auth token is invalid, please login again.",401,{},"InvalidAuthToken");const i=await s.user.findUnique({where:{id:String(o.id)}});if(!i)throw new app_error_1.default("The user belonging to this token does no longer exists",401,{},"UserNoLongerExists");if(this.userChangedPasswordAfter(i,o.iat)&&!e.path?.includes?.("logout"))throw new app_error_1.default("User recently changed password! Please log in again.",401,{},"PasswordChanged");return e.accessToken=r,i}handleAuthenticationControl(e,t){if(t&&typeof t=="object"){if(t[e]===!1)return base_middlewares_1.callNext;if(t[e]===!0)return this.authenticate}else return this.authenticate;return this.authenticate}async permission(e,t,s){const r=new Error().stack;if((r?r.split(`
2
+ `).length:0)>10)throw new Error("authService.permission() should be called during application initialization level.");return async i=>{const n=(0,server_1.getArkosConfig)();if(!n?.authentication)throw Error("Validation Error: Trying to use authService.permission without setting up authentication.");return n?.authentication?.mode==="dynamic"?await this.checkDynamicAccessControl(i.id,e,t):n?.authentication?.mode==="static"?!!s&&this.checkStaticAccessControl(i,e,s):!1}}}exports.AuthService=AuthService;const authService=new AuthService;exports.default=authService;
@@ -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;AAkBvE,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA8UrD,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,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B,CACzB,MAAoB,EACpB,qBAA+D;QAE/D,IAAI,qBAAqB,IAAI,OAAO,qBAAqB,KAAK,QAAQ,EAAE,CAAC;YACvE,IAAI,qBAAqB,CAAC,MAAM,CAAC,KAAK,KAAK;gBAAE,OAAO,2BAAQ,CAAC;iBACxD,IAAI,qBAAqB,CAAC,MAAM,CAAC,KAAK,IAAI;gBAAE,OAAO,IAAI,CAAC,YAAY,CAAC;QAC5E,CAAC;;YAAM,OAAO,IAAI,CAAC,YAAY,CAAC;QAEhC,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;CACF;AAjXD,kCAiXC;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 } from \"./utils/helpers/auth.controller.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n {},\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 * 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.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\"Missing JWT secret!\", 500);\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 * 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} resourceName - 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 resourceName: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as any;\n const prisma = getPrismaInstance();\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const matchingRole = await prisma.userRole.findFirst({\n where: {\n userId: req.user.id,\n role: {\n permissions: {\n some: {\n resource: resourceName,\n action: action,\n },\n },\n },\n },\n select: { id: true },\n });\n\n if (!matchingRole)\n return next(\n new AppError(\n \"You do not have permission to perfom this action\",\n 403\n )\n );\n } else if (configs?.authentication?.mode === \"static\") {\n let authorizedRoles: string[] = [];\n\n if (!accessControl)\n return next(\n new AppError(\n \"You do not have permission to perform this action\",\n 403\n )\n );\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = accessControl[action] || [];\n\n const userRoles = Array.isArray(user?.roles)\n ? user.roles\n : [user.role];\n const hasPermission = userRoles.some((role: string) =>\n authorizedRoles.includes(role)\n );\n\n if (!hasPermission) {\n return next(\n new AppError(\n \"You do not have permission to perform this action\",\n 403\n )\n );\n }\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)\n throw new AppError(\n \"You are not logged in! please log in to get access\",\n 401,\n {},\n \"LoginRequired\"\n );\n\n let decoded: AuthJwtPayload | undefined;\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n }\n\n if (!decoded?.id)\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n\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\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/**\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;AAmBvE,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA6WrD,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;IA8EJ,CAAC;IA5bC,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,QAAQ,KAAK,YAAY;YACrC,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU;YACvB,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM;YAErB,MAAM,IAAI,m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,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AA1cD,kCA0cC;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 AccessControlRules,\n} from \"../../types/auth\";\nimport { MsDuration } from \"./utils/helpers/auth.controller.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n {},\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 * 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.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\"Missing JWT secret!\", 500);\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 let authorizedRoles: string[] = [];\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = accessControl[action] || [];\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\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} resourceName - 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 resourceName: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\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 resourceName\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)\n throw new AppError(\n \"You are not logged in! please log in to get access\",\n 401,\n {},\n \"LoginRequired\"\n );\n\n let decoded: AuthJwtPayload | undefined;\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n }\n\n if (!decoded?.id)\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n\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 *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed (e.g., 'user', 'product', 'order')\n * @param accessControl - Access control rules (required for static authentication mode)\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 async permission(\n action: string,\n resource: string,\n accessControl?: AccessControlRules\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n const stackDepth = stack ? stack.split(\"\\n\").length : 0;\n // console.log(stackDepth, stack);\n\n if (stackDepth > 10) {\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n }\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 (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AA2HA,kGAIC;AAOD,wCAEC;AAED,sCAEC;AAEgB,0BAAO;AA3IxB,+BAAkC;AAElC,wFAAyD;AACzD,gDAAwB;AACxB,wDAAgC;AAChC,+DAA0D;AAC1D,uGAA4E;AAE5E,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;QAAE,OAAO;IAE1C,cAAI,CAAC,KAAK,CAAC,0CAA0C,EAAE;QACrD,SAAS,EAAE,IAAI;QACf,IAAI,EAAE,IAAI;KACX,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC;AAEH,IAAI,MAA6D,CAAC;AAClE,IAAI,IAAa,CAAC;AAEP,QAAA,YAAY,GAA0C;IAC/D,cAAc,EACZ,6FAA6F;IAC/F,IAAI,EAAE,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI;IACtE,IAAI,EAAE,OAAO,CAAC,GAAG,CAAC,QAAQ,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,IAAI,WAAW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AC5B,OAAO,oBAAY,CAAC;AACtB,CAAC;AAED,SAAgB,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\nimport sheu from \"./utils/sheu\";\nimport { capitalize } from \"./utils/helpers/text.helpers\";\nimport portAndHostAllocator from \"./utils/features/port-and-host-allocator\";\n\nprocess.on(\"uncaughtException\", (err) => {\n if (err.message.includes(\"EPIPE\")) return;\n\n sheu.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nexport let _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n routers: {\n strict: false,\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n try {\n _arkosConfig.available = true;\n\n const portAndHost = await portAndHostAllocator.getHostAndAvailablePort(\n process.env,\n arkosConfig\n );\n\n // initializePrismaModels();\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n _app = await bootstrap(_arkosConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n\n if (\n (\"port\" in arkosConfig && arkosConfig?.port !== undefined) ||\n !(\"port\" in arkosConfig)\n ) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(Number(portAndHost?.port), portAndHost.host!, () => {\n const message = `${sheu.gray(time)} {{server}} waiting on http://${portAndHost?.host}:${portAndHost?.port}`;\n\n sheu.ready(\n message.replace(\n \"{{server}}\",\n `${capitalize(process.env.NODE_ENV || \"development\")} server`\n )\n );\n if (_arkosConfig?.swagger?.mode)\n sheu.ready(\n `${message.replace(\"{{server}}\", \"Documentation\")}${_arkosConfig?.swagger?.endpoint || \"/api/docs\"}`\n );\n });\n } else {\n sheu.warn(\n `${sheu.gray(time)} Port set to undefined, hence no internal http server was setup.`\n );\n }\n } catch (err: any) {\n sheu.error(\n err?.message || \"Something went wrong while starting your application!\"\n );\n console.error(err);\n }\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n sheu.error(\"\\nUNHANDLED REJECTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AA0HA,kGAIC;AAOD,wCAEC;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,IAAI,CACP,GAAG,cAAI,CAAC,IAAI,CAAC,IAAI,CAAC,kEAAkE,CACrF,CAAC;QACJ,CAAC;IACH,CAAC;IAAC,OAAO,GAAQ,EAAE,CAAC;QAClB,cAAI,CAAC,KAAK,CACR,GAAG,EAAE,OAAO,IAAI,uDAAuD,CACxE,CAAC;QACF,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACrB,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAa,EAAE,EAAE;IACjD,cAAI,CAAC,KAAK,CAAC,2CAA2C,EAAE;QACtD,SAAS,EAAE,IAAI;QACf,IAAI,EAAE,IAAI;KACX,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAOH,SAAgB,2CAA2C;IACzD,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAOD,SAAgB,cAAc;IAC5B,OAAO,oBAAY,CAAC;AACtB,CAAC;AAED,SAAgB,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\nimport sheu from \"./utils/sheu\";\nimport { capitalize } from \"./utils/helpers/text.helpers\";\nimport portAndHostAllocator from \"./utils/features/port-and-host-allocator\";\n\nprocess.on(\"uncaughtException\", (err) => {\n if (err.message.includes(\"EPIPE\")) return;\n\n sheu.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nexport let _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n routers: {\n strict: false,\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n try {\n _arkosConfig.available = true;\n\n const portAndHost = await portAndHostAllocator.getHostAndAvailablePort(\n process.env,\n arkosConfig\n );\n\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n _app = await bootstrap(_arkosConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n\n if (\n (\"port\" in arkosConfig && arkosConfig?.port !== undefined) ||\n !(\"port\" in arkosConfig)\n ) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(Number(portAndHost?.port), portAndHost.host!, () => {\n const message = `${sheu.gray(time)} {{server}} waiting on http://${portAndHost?.host}:${portAndHost?.port}`;\n\n sheu.ready(\n message.replace(\n \"{{server}}\",\n `${capitalize(process.env.NODE_ENV || \"development\")} server`\n )\n );\n if (_arkosConfig?.swagger?.mode)\n sheu.ready(\n `${message.replace(\"{{server}}\", \"Documentation\")}${_arkosConfig?.swagger?.endpoint || \"/api/docs\"}`\n );\n });\n } else {\n sheu.warn(\n `${sheu.gray(time)} Port set to undefined, hence no internal http server was setup.`\n );\n }\n } catch (err: any) {\n sheu.error(\n err?.message || \"Something went wrong while starting your application!\"\n );\n console.error(err);\n }\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n sheu.error(\"\\nUNHANDLED REJECTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
@@ -1 +1 @@
1
- "use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ensureDirectoryExists=ensureDirectoryExists,exports.killServerChildProcess=killServerChildProcess,exports.getVersion=getVersion;const fs_1=__importDefault(require("fs")),dev_1=require("../dev"),start_1=require("../start");function ensureDirectoryExists(e){fs_1.default.existsSync(e)||fs_1.default.mkdirSync(e,{recursive:!0})}function killServerChildProcess(){(0,dev_1.killDevelopmentServerChildProcess)(),(0,start_1.killProductionServerChildProcess)()}function getVersion(){return"1.3.0-canary"}
1
+ "use strict";var __importDefault=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(exports,"__esModule",{value:!0}),exports.ensureDirectoryExists=ensureDirectoryExists,exports.killServerChildProcess=killServerChildProcess,exports.getVersion=getVersion;const fs_1=__importDefault(require("fs")),dev_1=require("../dev"),start_1=require("../start");function ensureDirectoryExists(e){fs_1.default.existsSync(e)||fs_1.default.mkdirSync(e,{recursive:!0})}function killServerChildProcess(){(0,dev_1.killDevelopmentServerChildProcess)(),(0,start_1.killProductionServerChildProcess)()}function getVersion(){return"1.3.0-canary.1"}
@@ -1 +1 @@
1
- {"version":3,"file":"port-and-host-allocator.js","sourceRoot":"","sources":["../../../../src/utils/features/port-and-host-allocator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,yCAA2B;AAC3B,mDAA2B;AAE3B,MAAM,oBAAoB;IAA1B;QAGU,iBAAY,GAAG,IAAI,GAAG,EAAU,CAAC;IAsG3C,CAAC;IA5FC,0BAA0B,CACxB,GAAwB,EACxB,MAAoB;QAEpB,MAAM,IAAI,GAAG,GAAG,EAAE,QAAQ,IAAI,MAAM,EAAE,IAAI,IAAI,GAAG,EAAE,IAAI,IAAI,WAAW,CAAC;QACvE,MAAM,IAAI,GAAG,GAAG,EAAE,QAAQ,IAAI,MAAM,EAAE,IAAI,IAAI,GAAG,EAAE,IAAI,IAAI,MAAM,CAAC;QAClE,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC;IACpD,CAAC;IASD,KAAK,CAAC,uBAAuB,CAC3B,GAAwB,EACxB,MAAgE;QAEhE,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YAC3B,IAAI,MAAM,EAAE,UAAU,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;gBACrD,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBACjB,KAAK,C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AW,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC;gBAC3D,CAAC,CAAC,IAAI;gBACN,CAAC,CAAC,WAAW,CAAC;YAChB,MAAM,MAAM,GAAG,GAAG,CAAC,gBAAgB,CAAC;gBAClC,IAAI,EAAE,UAAU;gBAChB,IAAI;gBACJ,OAAO,EAAE,GAAG;aACb,CAAC,CAAC;YAEH,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;gBACxB,MAAM,CAAC,OAAO,EAAE,CAAC;gBACjB,OAAO,CAAC,KAAK,CAAC,CAAC;YACjB,CAAC,CAAC,CAAC;YAEH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;gBACtB,OAAO,CAAC,IAAI,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;YAEH,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;gBACxB,MAAM,CAAC,OAAO,EAAE,CAAC;gBACjB,OAAO,CAAC,IAAI,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IACD,WAAW;QACT,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACjB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,cAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IACjE,CAAC;CACF;AAED,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,oBAAoB,CAAC","sourcesContent":["import { ArkosConfig } from \"../../exports\";\nimport * as net from \"net\";\nimport sheu from \"../sheu\";\n\nclass PortAndHostAllocator {\n private host: string | undefined;\n private port: string | undefined;\n private prevWarnings = new Set<string>();\n\n /**\n * Helps in correcting getting the right host and port to be used according to cli params, arkos config, env and default host and port.\n *\n * Is worth mentioning that this will be preserved along the application until it restarts.\n *\n * @param config {ArkosConfig} - your application configuraiton\n * @param env {Record<string,any>} - current env, may pass process.env\n */\n getCorrectHostAndPortToUse(\n env: Record<string, any>,\n config?: ArkosConfig\n ): { port: string; host: string } {\n const host = env?.CLI_HOST || config?.host || env?.HOST || \"localhost\";\n const port = env?.CLI_PORT || config?.port || env?.PORT || \"8000\";\n return { host: String(host), port: String(port) };\n }\n\n /**\n * Finds an available port starting from the configured port and incrementing until one is found\n *\n * @param env {Record<string,any>} - current env, may pass process.env\n * @param config {ArkosConfig} - your application configuration\n * @returns Promise<{port: string; host: string}> - available port and host\n */\n async getHostAndAvailablePort(\n env: Record<string, any>,\n config?: ArkosConfig & { logWarning?: boolean; caller?: string }\n ): Promise<{ port: string; host: string }> {\n if (this.port && this.host) {\n if (config?.logWarning && this.prevWarnings.size > 0) {\n console.info(\"\");\n Array.from(this.prevWarnings).forEach((msg) => sheu.warn(msg));\n }\n return { port: this.port, host: this.host };\n }\n\n const { host, port: initialPort } = this.getCorrectHostAndPortToUse(\n env,\n config\n );\n let currentPort = parseInt(initialPort, 10);\n\n while (true) {\n const isAvailable = await this.isPortAvailable(host, currentPort);\n\n if (isAvailable) {\n this.port = currentPort.toString();\n this.host = host;\n return { host, port: currentPort.toString() };\n }\n\n const msg = `Port ${currentPort} is in use, trying port ${currentPort + 1} instead...`;\n this.prevWarnings.add(msg);\n\n if (config?.logWarning) {\n // console.info(\"\");\n sheu.warn(`${msg}`);\n }\n\n currentPort++;\n }\n }\n\n /**\n * Checks if a port is available on the given host\n *\n * @param host {string} - host to check\n * @param port {number} - port to check\n * @returns Promise<boolean> - true if port is available, false otherwise\n */\n private async isPortAvailable(host: string, port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const actualHost = ![\"localhost\", \"127.0.0.1\"].includes(host)\n ? host\n : \"localhost\";\n const socket = net.createConnection({\n host: actualHost,\n port,\n timeout: 100,\n });\n\n socket.on(\"connect\", () => {\n socket.destroy();\n resolve(false); // Port is in use\n });\n\n socket.on(\"error\", () => {\n resolve(true); // Port is available\n });\n\n socket.on(\"timeout\", () => {\n socket.destroy();\n resolve(true); // Port is available\n });\n });\n }\n logWarnings() {\n console.info(\"\");\n Array.from(this.prevWarnings).forEach((msg) => sheu.warn(msg));\n }\n}\n\nconst portAndHostAllocator = new PortAndHostAllocator();\n\nexport default portAndHostAllocator;\n"]}
1
+ {"version":3,"file":"port-and-host-allocator.js","sourceRoot":"","sources":["../../../../src/utils/features/port-and-host-allocator.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,yCAA2B;AAC3B,mDAA2B;AAE3B,MAAM,oBAAoB;IAA1B;QAGU,iBAAY,GAAG,IAAI,GAAG,EAAU,CAAC;IAuG3C,CAAC;IA7FC,0BAA0B,CACxB,GAAwB,EACxB,MAAoB;QAEpB,MAAM,IAAI,GAAG,GAAG,EAAE,QAAQ,IAAI,MAAM,EAAE,IAAI,IAAI,GAAG,EAAE,IAAI,IAAI,WAAW,CAAC;QACvE,MAAM,IAAI,GAAG,GAAG,EAAE,QAAQ,IAAI,MAAM,EAAE,IAAI,IAAI,GAAG,EAAE,IAAI,IAAI,MAAM,CAAC;QAClE,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC;IACpD,CAAC;IASD,KAAK,CAAC,uBAAuB,CAC3B,GAAwB,EACxB,MAAgE;QAEhE,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YAC3B,IAAI,MAAM,EAAE,UAAU,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,GAAG,CAAC,EAAE,CAAC;gBACrD,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;gBACjB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,cAAI,CAAC,IAAI,CAAC,GAAG,CAAC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AG,CAAC,gBAAgB,CAAC;gBAClC,IAAI,EAAE,UAAU;gBAChB,IAAI;gBACJ,OAAO,EAAE,GAAG;aACb,CAAC,CAAC;YAEH,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;gBACxB,MAAM,CAAC,OAAO,EAAE,CAAC;gBACjB,OAAO,CAAC,KAAK,CAAC,CAAC;YACjB,CAAC,CAAC,CAAC;YAEH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;gBACtB,OAAO,CAAC,IAAI,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;YAEH,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;gBACxB,MAAM,CAAC,OAAO,EAAE,CAAC;gBACjB,OAAO,CAAC,IAAI,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAED,WAAW;QACT,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACjB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,cAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IACjE,CAAC;CACF;AAED,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,kBAAe,oBAAoB,CAAC","sourcesContent":["import { ArkosConfig } from \"../../exports\";\nimport * as net from \"net\";\nimport sheu from \"../sheu\";\n\nclass PortAndHostAllocator {\n private host: string | undefined;\n private port: string | undefined;\n private prevWarnings = new Set<string>();\n\n /**\n * Helps in correcting getting the right host and port to be used according to cli params, arkos config, env and default host and port.\n *\n * Is worth mentioning that this will be preserved along the application until it restarts.\n *\n * @param config {ArkosConfig} - your application configuraiton\n * @param env {Record<string,any>} - current env, may pass process.env\n */\n getCorrectHostAndPortToUse(\n env: Record<string, any>,\n config?: ArkosConfig\n ): { port: string; host: string } {\n const host = env?.CLI_HOST || config?.host || env?.HOST || \"localhost\";\n const port = env?.CLI_PORT || config?.port || env?.PORT || \"8000\";\n return { host: String(host), port: String(port) };\n }\n\n /**\n * Finds an available port starting from the configured port and incrementing until one is found\n *\n * @param env {Record<string,any>} - current env, may pass process.env\n * @param config {ArkosConfig} - your application configuration\n * @returns Promise<{port: string; host: string}> - available port and host\n */\n async getHostAndAvailablePort(\n env: Record<string, any>,\n config?: ArkosConfig & { logWarning?: boolean; caller?: string }\n ): Promise<{ port: string; host: string }> {\n if (this.port && this.host) {\n if (config?.logWarning && this.prevWarnings.size > 0) {\n console.info(\"\");\n Array.from(this.prevWarnings).forEach((msg) => sheu.warn(msg));\n }\n return { port: this.port, host: this.host };\n }\n\n const { host, port: initialPort } = this.getCorrectHostAndPortToUse(\n env,\n config\n );\n let currentPort = parseInt(initialPort, 10);\n\n while (true) {\n const isAvailable = await this.isPortAvailable(host, currentPort);\n\n if (isAvailable) {\n this.port = currentPort.toString();\n this.host = host;\n return { host, port: currentPort.toString() };\n }\n\n const msg = `Port ${currentPort} is in use, trying port ${currentPort + 1} instead...`;\n this.prevWarnings.add(msg);\n\n if (config?.logWarning) {\n // console.info(\"\");\n sheu.warn(`${msg}`);\n }\n\n currentPort++;\n }\n }\n\n /**\n * Checks if a port is available on the given host\n *\n * @param host {string} - host to check\n * @param port {number} - port to check\n * @returns Promise<boolean> - true if port is available, false otherwise\n */\n private async isPortAvailable(host: string, port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const actualHost = ![\"localhost\", \"127.0.0.1\"].includes(host)\n ? host\n : \"localhost\";\n const socket = net.createConnection({\n host: actualHost,\n port,\n timeout: 100,\n });\n\n socket.on(\"connect\", () => {\n socket.destroy();\n resolve(false);\n });\n\n socket.on(\"error\", () => {\n resolve(true);\n });\n\n socket.on(\"timeout\", () => {\n socket.destroy();\n resolve(true); // Port is available\n });\n });\n }\n\n logWarnings() {\n console.info(\"\");\n Array.from(this.prevWarnings).forEach((msg) => sheu.warn(msg));\n }\n}\n\nconst portAndHostAllocator = new PortAndHostAllocator();\n\nexport default portAndHostAllocator;\n"]}
@@ -1 +1,2 @@
1
- "use strict";import g from"jsonwebtoken";import h from"bcryptjs";import w from"../error-handler/utils/catch-async.js";import i from"../error-handler/utils/app-error.js";import{callNext as T}from"../base/base.middlewares.js";import{getArkosConfig as c}from"../../server.js";import d from"../../utils/arkos-env.js";import{getPrismaInstance as l}from"../../utils/helpers/prisma.helpers.js";export class AuthService{constructor(){this.actionsPerResource={},this.authenticate=w(async(e,t,s)=>{if(!c()?.authentication){s();return}e.user=await this.getAuthenticatedUser(e),s()})}signJwtToken(e,t,s){const{authentication:o}=c();if(process.env.NODE_ENV==="production"&&!process.env.JWT_SECRET&&!o?.jwt?.secret)throw new i("Missing JWT secret on production!",500,{},"MissingJWTOnProduction");return s=s||o?.jwt?.secret||process.env.JWT_SECRET||d.JWT_SECRET,t=t||o?.jwt?.expiresIn||process.env.JWT_EXPIRES_IN||d.JWT_EXPIRES_IN,g.sign({id:e},s,{expiresIn:t})}isPasswordHashed(e){return!Number.isNaN(h.getRounds(e)*1)}async isCorrectPassword(e,t){return await h.compare(e,t)}async hashPassword(e){return await h.hash(e,12)}isPasswordStrong(e){return(c()?.authentication?.passwordValidation?.regex||/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).+$/).test(e)}userChangedPasswordAfter(e,t){if(e.passwordChangedAt){const s=parseInt(String(e.passwordChangedAt.getTime()/1e3),10);return t<s}return!1}async verifyJwtToken(e,t){const{authentication:s}=c();if(process.env.NODE_ENV==="production"&&!process.env.JWT_SECRET&&!s?.jwt?.secret)throw new i("Missing JWT secret!",500);return t=t||s?.jwt?.secret||process.env.JWT_SECRET||d.JWT_SECRET,new Promise((o,n)=>{g.verify(e,t,(r,a)=>{r?n(r):o(a)})})}handleAccessControl(e,t,s){return w(async(o,n,r)=>{if(o.user){const a=o.user,p=l(),f=c();if(a.isSuperUser){r();return}if(f?.authentication?.mode==="dynamic"){if(!await p.userRole.findFirst({where:{userId:o.user.id,role:{permissions:{some:{resource:t,action:e}}}},select:{id:!0}}))return r(new i("You do not have permission to perfom this action",403))}else if(f?.authentication?.mode==="static"){let u=[];if(!s)return r(new i("You do not have permission to perform this action",403));if(Array.isArray(s)?u=s:s[e]&&(u=s[e]||[]),!(Array.isArray(a?.roles)?a.roles:[a.role]).some(m=>u.includes(m)))return r(new i("You do not have permission to perform this action",403))}}r()})}async getAuthenticatedUser(e){if(!c()?.authentication)return null;const s=l();let o;if(e?.headers?.authorization&&e?.headers?.authorization.startsWith("Bearer")?o=e?.headers?.authorization.split(" ")[1]:e?.cookies?.arkos_access_token!=="no-token"&&e.cookies&&(o=e?.cookies?.arkos_access_token),!o)throw new i("You are not logged in! please log in to get access",401,{},"LoginRequired");let n;try{n=await this.verifyJwtToken(o)}catch{throw new i("Your auth token is invalid, please login again.",401,{},"InvalidAuthToken")}if(!n?.id)throw new i("Your auth token is invalid, please login again.",401,{},"InvalidAuthToken");const r=await s.user.findUnique({where:{id:String(n.id)}});if(!r)throw new i("The user belonging to this token does no longer exists",401);if(this.userChangedPasswordAfter(r,n.iat)&&!e.path?.includes?.("logout"))throw new i("User recently changed password! Please log in again.",401,{},"PasswordChanged");return e.accessToken=o,r}handleAuthenticationControl(e,t){if(t&&typeof t=="object"){if(t[e]===!1)return T;if(t[e]===!0)return this.authenticate}else return this.authenticate;return this.authenticate}}const k=new AuthService;export default k;
1
+ "use strict";import f from"jsonwebtoken";import u from"bcryptjs";import g from"../error-handler/utils/catch-async.js";import a from"../error-handler/utils/app-error.js";import{callNext as m}from"../base/base.middlewares.js";import{getArkosConfig as c}from"../../server.js";import d from"../../utils/arkos-env.js";import{getPrismaInstance as w}from"../../utils/helpers/prisma.helpers.js";export class AuthService{constructor(){this.actionsPerResource={},this.authenticate=g(async(e,t,s)=>{if(!c()?.authentication){s();return}e.user=await this.getAuthenticatedUser(e),s()})}signJwtToken(e,t,s){const{authentication:i}=c();if(process.env.NODE_ENV==="production"&&!process.env.JWT_SECRET&&!i?.jwt?.secret)throw new a("Missing JWT secret on production!",500,{},"MissingJWTOnProduction");return s=s||i?.jwt?.secret||process.env.JWT_SECRET||d.JWT_SECRET,t=t||i?.jwt?.expiresIn||process.env.JWT_EXPIRES_IN||d.JWT_EXPIRES_IN,f.sign({id:e},s,{expiresIn:t})}isPasswordHashed(e){return!Number.isNaN(u.getRounds(e)*1)}async isCorrectPassword(e,t){return await u.compare(e,t)}async hashPassword(e){return await u.hash(e,12)}isPasswordStrong(e){return(c()?.authentication?.passwordValidation?.regex||/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).+$/).test(e)}userChangedPasswordAfter(e,t){if(e.passwordChangedAt){const s=parseInt(String(e.passwordChangedAt.getTime()/1e3),10);return t<s}return!1}async verifyJwtToken(e,t){const{authentication:s}=c();if(process.env.NODE_ENV==="production"&&!process.env.JWT_SECRET&&!s?.jwt?.secret)throw new a("Missing JWT secret!",500);return t=t||s?.jwt?.secret||process.env.JWT_SECRET||d.JWT_SECRET,new Promise((i,n)=>{f.verify(e,t,(r,o)=>{r?n(r):i(o)})})}checkStaticAccessControl(e,t,s){if(!e?.role&&!e.roles)throw Error("Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.");let i=[];return Array.isArray(s)?i=s:s[t]&&(i=s[t]||[]),!!(Array.isArray(e?.roles)?e.roles:[e.role]).some(r=>i.includes(r))}async checkDynamicAccessControl(e,t,s){return!!await w().userRole.findFirst({where:{userId:e,role:{permissions:{some:{resource:s,action:t}}}},select:{id:!0}})}handleAccessControl(e,t,s){return g(async(i,n,r)=>{if(i.user){const o=i.user,l=c();if(o.isSuperUser){r();return}const h=new a("You do not have permission to perfom this action",403,{},"NotEnoughPermissions");if(l?.authentication?.mode==="dynamic"){if(!await this.checkDynamicAccessControl(o.id,e,t))return r(h)}else if(l?.authentication?.mode==="static"&&(!s||!this.checkStaticAccessControl(o,e,s)))return r(h)}r()})}async getAuthenticatedUser(e){if(!c()?.authentication)return null;const s=w();let i;if(e?.headers?.authorization&&e?.headers?.authorization.startsWith("Bearer")?i=e?.headers?.authorization.split(" ")[1]:e?.cookies?.arkos_access_token!=="no-token"&&e.cookies&&(i=e?.cookies?.arkos_access_token),!i)throw new a("You are not logged in! please log in to get access",401,{},"LoginRequired");let n;try{n=await this.verifyJwtToken(i)}catch{throw new a("Your auth token is invalid, please login again.",401,{},"InvalidAuthToken")}if(!n?.id)throw new a("Your auth token is invalid, please login again.",401,{},"InvalidAuthToken");const r=await s.user.findUnique({where:{id:String(n.id)}});if(!r)throw new a("The user belonging to this token does no longer exists",401,{},"UserNoLongerExists");if(this.userChangedPasswordAfter(r,n.iat)&&!e.path?.includes?.("logout"))throw new a("User recently changed password! Please log in again.",401,{},"PasswordChanged");return e.accessToken=i,r}handleAuthenticationControl(e,t){if(t&&typeof t=="object"){if(t[e]===!1)return m;if(t[e]===!0)return this.authenticate}else return this.authenticate;return this.authenticate}async permission(e,t,s){const i=new Error().stack;if((i?i.split(`
2
+ `).length:0)>10)throw new Error("authService.permission() should be called during application initialization level.");return async r=>{const o=c();if(!o?.authentication)throw Error("Validation Error: Trying to use authService.permission without setting up authentication.");return o?.authentication?.mode==="dynamic"?await this.checkDynamicAccessControl(r.id,e,t):o?.authentication?.mode==="static"?!!s&&this.checkStaticAccessControl(r,e,s):!1}}}const k=new AuthService;export default k;
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":"AAAA,OAAO,GAAoB,MAAM,cAAc,CAAC;AAChD,OAAO,MAAM,MAAM,UAAU,CAAC;AAE9B,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,QAAQ,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,i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AE,OAAO,CAAC,GAAI,CAAC;YACjD,CAAC,GAAG,CAAC,IAAI,EAAE,QAAQ,EAAE,CAAC,QAAQ,CAAC;YAE/B,MAAM,IAAI,QAAQ,CAChB,sDAAsD,EACtD,GAAG,EACH,EAAE,EACF,iBAAiB,CAClB,CAAC;QAEJ,GAAG,CAAC,WAAW,GAAG,KAAK,CAAC;QACxB,OAAO,IAAI,CAAC;IACd,CAAC;IA8BD,2BAA2B,CACzB,MAAoB,EACpB,qBAA+D;QAE/D,IAAI,qBAAqB,IAAI,OAAO,qBAAqB,KAAK,QAAQ,EAAE,CAAC;YACvE,IAAI,qBAAqB,CAAC,MAAM,CAAC,KAAK,KAAK;gBAAE,OAAO,QAAQ,CAAC;iBACxD,IAAI,qBAAqB,CAAC,MAAM,CAAC,KAAK,IAAI;gBAAE,OAAO,IAAI,CAAC,YAAY,CAAC;QAC5E,CAAC;;YAAM,OAAO,IAAI,CAAC,YAAY,CAAC;QAEhC,OAAO,IAAI,CAAC,YAAY,CAAC;IAC3B,CAAC;CACF;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,eAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration } from \"./utils/helpers/auth.controller.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n {},\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 * 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.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\"Missing JWT secret!\", 500);\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 * 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} resourceName - 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 resourceName: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as any;\n const prisma = getPrismaInstance();\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const matchingRole = await prisma.userRole.findFirst({\n where: {\n userId: req.user.id,\n role: {\n permissions: {\n some: {\n resource: resourceName,\n action: action,\n },\n },\n },\n },\n select: { id: true },\n });\n\n if (!matchingRole)\n return next(\n new AppError(\n \"You do not have permission to perfom this action\",\n 403\n )\n );\n } else if (configs?.authentication?.mode === \"static\") {\n let authorizedRoles: string[] = [];\n\n if (!accessControl)\n return next(\n new AppError(\n \"You do not have permission to perform this action\",\n 403\n )\n );\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = accessControl[action] || [];\n\n const userRoles = Array.isArray(user?.roles)\n ? user.roles\n : [user.role];\n const hasPermission = userRoles.some((role: string) =>\n authorizedRoles.includes(role)\n );\n\n if (!hasPermission) {\n return next(\n new AppError(\n \"You do not have permission to perform this action\",\n 403\n )\n );\n }\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)\n throw new AppError(\n \"You are not logged in! please log in to get access\",\n 401,\n {},\n \"LoginRequired\"\n );\n\n let decoded: AuthJwtPayload | undefined;\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n }\n\n if (!decoded?.id)\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n\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\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/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
1
+ {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":"AAAA,OAAO,GAAoB,MAAM,cAAc,CAAC;AAChD,OAAO,MAAM,MAAM,UAAU,CAAC;AAE9B,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,QAAQ,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAmBvE,MAAM,OAAO,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA6WrD,iBAAY,GAAG,UAAU,CACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;YACrC,IAAI,CAAC,WAAW,EAAE,cAAc,EAAE,CAAC;gBACjC,IAA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FAA2F,CAC5F,CAAC;YAEJ,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,SAAS,EAAE,CAAC;gBAChD,OAAO,MAAM,IAAI,CAAC,yBAAyB,CAAC,IAAI,CAAC,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YACzE,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,eAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n AccessControlRules,\n} from \"../../types/auth\";\nimport { MsDuration } from \"./utils/helpers/auth.controller.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n {},\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 * 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.NODE_ENV === \"production\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\"Missing JWT secret!\", 500);\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 let authorizedRoles: string[] = [];\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = accessControl[action] || [];\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\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} resourceName - 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 resourceName: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\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 resourceName\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)\n throw new AppError(\n \"You are not logged in! please log in to get access\",\n 401,\n {},\n \"LoginRequired\"\n );\n\n let decoded: AuthJwtPayload | undefined;\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n }\n\n if (!decoded?.id)\n throw new AppError(\n \"Your auth token is invalid, please login again.\",\n 401,\n {},\n \"InvalidAuthToken\"\n );\n\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 *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed (e.g., 'user', 'product', 'order')\n * @param accessControl - Access control rules (required for static authentication mode)\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 async permission(\n action: string,\n resource: string,\n accessControl?: AccessControlRules\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n const stackDepth = stack ? stack.split(\"\\n\").length : 0;\n // console.log(stackDepth, stack);\n\n if (stackDepth > 10) {\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n }\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 (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,IAAI,MAAM,cAAc,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,oBAAoB,MAAM,0CAA0C,CAAC;AAE5E,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;QAAE,OAAO;IAE1C,IAAI,CAAC,KAAK,CAAC,0CAA0C,EAAE;QACrD,SAAS,EAAE,IAAI;QACf,IAAI,EAAE,IAAI;KACX,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAA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,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAOH,MAAM,UAAU,2CAA2C;IACzD,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAOD,MAAM,UAAU,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\nimport sheu from \"./utils/sheu\";\nimport { capitalize } from \"./utils/helpers/text.helpers\";\nimport portAndHostAllocator from \"./utils/features/port-and-host-allocator\";\n\nprocess.on(\"uncaughtException\", (err) => {\n if (err.message.includes(\"EPIPE\")) return;\n\n sheu.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nexport let _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n routers: {\n strict: false,\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n try {\n _arkosConfig.available = true;\n\n const portAndHost = await portAndHostAllocator.getHostAndAvailablePort(\n process.env,\n arkosConfig\n );\n\n // initializePrismaModels();\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n _app = await bootstrap(_arkosConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n\n if (\n (\"port\" in arkosConfig && arkosConfig?.port !== undefined) ||\n !(\"port\" in arkosConfig)\n ) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(Number(portAndHost?.port), portAndHost.host!, () => {\n const message = `${sheu.gray(time)} {{server}} waiting on http://${portAndHost?.host}:${portAndHost?.port}`;\n\n sheu.ready(\n message.replace(\n \"{{server}}\",\n `${capitalize(process.env.NODE_ENV || \"development\")} server`\n )\n );\n if (_arkosConfig?.swagger?.mode)\n sheu.ready(\n `${message.replace(\"{{server}}\", \"Documentation\")}${_arkosConfig?.swagger?.endpoint || \"/api/docs\"}`\n );\n });\n } else {\n sheu.warn(\n `${sheu.gray(time)} Port set to undefined, hence no internal http server was setup.`\n );\n }\n } catch (err: any) {\n sheu.error(\n err?.message || \"Something went wrong while starting your application!\"\n );\n console.error(err);\n }\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n sheu.error(\"\\nUNHANDLED REJECTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
1
+ {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAElC,OAAO,SAAS,MAAM,kCAAkC,CAAC;AACzD,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,IAAI,MAAM,cAAc,CAAC;AAChC,OAAO,EAAE,UAAU,EAAE,MAAM,8BAA8B,CAAC;AAC1D,OAAO,oBAAoB,MAAM,0CAA0C,CAAC;AAE5E,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACtC,IAAI,GAAG,CAAC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAC;QAAE,OAAO;IAE1C,IAAI,CAAC,KAAK,CAAC,0CAA0C,EAAE;QACrD,SAAS,EAAE,IAAI;QACf,IAAI,EAAE,IAAI;KACX,CAAC,CAAC;IACH,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AAClB,CAAC,CAAC,CAAC;AAEH,IAAI,MAA6D,CAAC;AAClE,IAAI,IAAa,CAAC;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B,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC;AAOH,MAAM,UAAU,2CAA2C;IACzD,MAAM,EAAE,KAAK,CAAC,GAAG,EAAE;QACjB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAOD,MAAM,UAAU,cAAc;IAC5B,OAAO,YAAY,CAAC;AACtB,CAAC;AAED,MAAM,UAAU,aAAa;IAC3B,OAAO,IAAI,CAAC;AACd,CAAC;AAED,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC","sourcesContent":["import { IncomingMessage, Server, ServerResponse } from \"http\";\nimport AppError from \"./modules/error-handler/utils/app-error\";\nimport { Express } from \"express\";\nimport { bootstrap } from \"./app\";\nimport { ArkosConfig } from \"./types/arkos-config\";\nimport deepmerge from \"./utils/helpers/deepmerge.helper\";\nimport http from \"http\";\nimport sheu from \"./utils/sheu\";\nimport { capitalize } from \"./utils/helpers/text.helpers\";\nimport portAndHostAllocator from \"./utils/features/port-and-host-allocator\";\n\nprocess.on(\"uncaughtException\", (err) => {\n if (err.message.includes(\"EPIPE\")) return;\n\n sheu.error(\"\\nUNCAUGHT EXCEPTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n process.exit(1);\n});\n\nlet server: Server<typeof IncomingMessage, typeof ServerResponse>;\nlet _app: Express;\n\nexport let _arkosConfig: ArkosConfig & { available?: boolean } = {\n welcomeMessage:\n \"Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com\",\n port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,\n host: process.env.CLI_HOST || process.env.HOST || \"localhost\",\n fileUpload: {\n baseUploadDir: \"uploads\",\n baseRoute: \"/api/uploads\",\n },\n routers: {\n strict: false,\n },\n available: false,\n};\n\n/**\n * Initializes the application server.\n *\n * This function starts the server by listening on a specified port.\n * The port is determined by the following order of precedence:\n * 1. The `port` argument passed to the function.\n * 2. Defaults to `8000` if neither is provided.\n *\n * @param {ArkosConfig} arkosConfig - initial configs for the api ( authentication, port).\n * @returns {Promise<Express>} This function returns the Express App after all middlewares configurations.\n * You can prevent it from listen py passing port as undefined\n *\n */\nasync function initApp(arkosConfig: ArkosConfig = {}): Promise<Express> {\n try {\n _arkosConfig.available = true;\n\n const portAndHost = await portAndHostAllocator.getHostAndAvailablePort(\n process.env,\n arkosConfig\n );\n\n _arkosConfig = deepmerge(_arkosConfig, arkosConfig);\n\n _app = await bootstrap(_arkosConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n\n if (\n (\"port\" in arkosConfig && arkosConfig?.port !== undefined) ||\n !(\"port\" in arkosConfig)\n ) {\n server = http.createServer(_app);\n\n if (_arkosConfig?.configureServer)\n await _arkosConfig.configureServer(server);\n\n server.listen(Number(portAndHost?.port), portAndHost.host!, () => {\n const message = `${sheu.gray(time)} {{server}} waiting on http://${portAndHost?.host}:${portAndHost?.port}`;\n\n sheu.ready(\n message.replace(\n \"{{server}}\",\n `${capitalize(process.env.NODE_ENV || \"development\")} server`\n )\n );\n if (_arkosConfig?.swagger?.mode)\n sheu.ready(\n `${message.replace(\"{{server}}\", \"Documentation\")}${_arkosConfig?.swagger?.endpoint || \"/api/docs\"}`\n );\n });\n } else {\n sheu.warn(\n `${sheu.gray(time)} Port set to undefined, hence no internal http server was setup.`\n );\n }\n } catch (err: any) {\n sheu.error(\n err?.message || \"Something went wrong while starting your application!\"\n );\n console.error(err);\n }\n return _app;\n}\n\nprocess.on(\"unhandledRejection\", (err: AppError) => {\n sheu.error(\"\\nUNHANDLED REJECTION! SHUTTING DOWN...\\n\", {\n timestamp: true,\n bold: true,\n });\n console.error(err.name, err.message);\n console.error(err);\n server?.close(() => {\n process.exit(1);\n });\n});\n\n/**\n * Terminates the current running express application, server and process.\n *\n * @returns {void}\n */\nexport function terminateApplicationRunningProcessAndServer(): void {\n server?.close(() => {\n process.exit(1);\n });\n}\n\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also passed through `arkos.init()`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n return _arkosConfig;\n}\n\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
@@ -1 +1 @@
1
- "use strict";import e from"fs";import{killDevelopmentServerChildProcess as o}from"../dev.js";import{killProductionServerChildProcess as i}from"../start.js";export function ensureDirectoryExists(r){e.existsSync(r)||e.mkdirSync(r,{recursive:!0})}export function killServerChildProcess(){o(),i()}export function getVersion(){return"1.3.0-canary"}
1
+ "use strict";import e from"fs";import{killDevelopmentServerChildProcess as o}from"../dev.js";import{killProductionServerChildProcess as i}from"../start.js";export function ensureDirectoryExists(r){e.existsSync(r)||e.mkdirSync(r,{recursive:!0})}export function killServerChildProcess(){o(),i()}export function getVersion(){return"1.3.0-canary.1"}
@@ -1 +1 @@
1
- {"version":3,"file":"port-and-host-allocator.js","sourceRoot":"","sources":["../../../../src/utils/features/port-and-host-allocator.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,IAAI,MAAM,SAAS,CAAC;AAE3B,MAAM,oBAAoB;IAA1B;QAGU,iBAAY,GAAG,IAAI,GAAG,EAAU,CAAC;IAsG3C,CAAC;IA5FC,0BAA0B,CACxB,GAAwB,EACxB,MAAoB;QAEpB,MAAM,IAAI,GAAG,GAAG,EAAE,QAAQ,IAAI,MAAM,EAAE,IAAI,IAAI,GAAG,EAAE,IAAI,IAAI,WAAW,CAAC;QACvE,MAAM,IAAI,GAAG,GAAG,EAAE,QAAQ,IAAI,MAAM,EAAE,IAAI,IAAI,GAAG,EAAE,IAAI,IAAI,MAAM,CAAC;QAClE,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC;IACpD,CA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,CAAC;AAExD,eAAe,oBAAoB,CAAC","sourcesContent":["import { ArkosConfig } from \"../../exports\";\nimport * as net from \"net\";\nimport sheu from \"../sheu\";\n\nclass PortAndHostAllocator {\n private host: string | undefined;\n private port: string | undefined;\n private prevWarnings = new Set<string>();\n\n /**\n * Helps in correcting getting the right host and port to be used according to cli params, arkos config, env and default host and port.\n *\n * Is worth mentioning that this will be preserved along the application until it restarts.\n *\n * @param config {ArkosConfig} - your application configuraiton\n * @param env {Record<string,any>} - current env, may pass process.env\n */\n getCorrectHostAndPortToUse(\n env: Record<string, any>,\n config?: ArkosConfig\n ): { port: string; host: string } {\n const host = env?.CLI_HOST || config?.host || env?.HOST || \"localhost\";\n const port = env?.CLI_PORT || config?.port || env?.PORT || \"8000\";\n return { host: String(host), port: String(port) };\n }\n\n /**\n * Finds an available port starting from the configured port and incrementing until one is found\n *\n * @param env {Record<string,any>} - current env, may pass process.env\n * @param config {ArkosConfig} - your application configuration\n * @returns Promise<{port: string; host: string}> - available port and host\n */\n async getHostAndAvailablePort(\n env: Record<string, any>,\n config?: ArkosConfig & { logWarning?: boolean; caller?: string }\n ): Promise<{ port: string; host: string }> {\n if (this.port && this.host) {\n if (config?.logWarning && this.prevWarnings.size > 0) {\n console.info(\"\");\n Array.from(this.prevWarnings).forEach((msg) => sheu.warn(msg));\n }\n return { port: this.port, host: this.host };\n }\n\n const { host, port: initialPort } = this.getCorrectHostAndPortToUse(\n env,\n config\n );\n let currentPort = parseInt(initialPort, 10);\n\n while (true) {\n const isAvailable = await this.isPortAvailable(host, currentPort);\n\n if (isAvailable) {\n this.port = currentPort.toString();\n this.host = host;\n return { host, port: currentPort.toString() };\n }\n\n const msg = `Port ${currentPort} is in use, trying port ${currentPort + 1} instead...`;\n this.prevWarnings.add(msg);\n\n if (config?.logWarning) {\n // console.info(\"\");\n sheu.warn(`${msg}`);\n }\n\n currentPort++;\n }\n }\n\n /**\n * Checks if a port is available on the given host\n *\n * @param host {string} - host to check\n * @param port {number} - port to check\n * @returns Promise<boolean> - true if port is available, false otherwise\n */\n private async isPortAvailable(host: string, port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const actualHost = ![\"localhost\", \"127.0.0.1\"].includes(host)\n ? host\n : \"localhost\";\n const socket = net.createConnection({\n host: actualHost,\n port,\n timeout: 100,\n });\n\n socket.on(\"connect\", () => {\n socket.destroy();\n resolve(false); // Port is in use\n });\n\n socket.on(\"error\", () => {\n resolve(true); // Port is available\n });\n\n socket.on(\"timeout\", () => {\n socket.destroy();\n resolve(true); // Port is available\n });\n });\n }\n logWarnings() {\n console.info(\"\");\n Array.from(this.prevWarnings).forEach((msg) => sheu.warn(msg));\n }\n}\n\nconst portAndHostAllocator = new PortAndHostAllocator();\n\nexport default portAndHostAllocator;\n"]}
1
+ {"version":3,"file":"port-and-host-allocator.js","sourceRoot":"","sources":["../../../../src/utils/features/port-and-host-allocator.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,GAAG,MAAM,KAAK,CAAC;AAC3B,OAAO,IAAI,MAAM,SAAS,CAAC;AAE3B,MAAM,oBAAoB;IAA1B;QAGU,iBAAY,GAAG,IAAI,GAAG,EAAU,CAAC;IAuG3C,CAAC;IA7FC,0BAA0B,CACxB,GAAwB,EACxB,MAAoB;QAEpB,MAAM,IAAI,GAAG,GAAG,EAAE,QAAQ,IAAI,MAAM,EAAE,IAAI,IAAI,GAAG,EAAE,IAAI,IAAI,WAAW,CAAC;QACvE,MAAM,IAAI,GAAG,GAAG,EAAE,QAAQ,IAAI,MAAM,EAAE,IAAI,IAAI,GAAG,EAAE,IAAI,IAAI,MAAM,CAAC;QAClE,OAAO,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC;IACpD,CAAC;IASD,KAAK,CAAC,uBAAuB,CAC3B,GAAwB,EACxB,MAAgE;QAEhE,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,EAAE,CA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CAAC;IASO,KAAK,CAAC,eAAe,CAAC,IAAY,EAAE,IAAY;QACtD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;YAC7B,MAAM,UAAU,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC;gBAC3D,CAAC,CAAC,IAAI;gBACN,CAAC,CAAC,WAAW,CAAC;YAChB,MAAM,MAAM,GAAG,GAAG,CAAC,gBAAgB,CAAC;gBAClC,IAAI,EAAE,UAAU;gBAChB,IAAI;gBACJ,OAAO,EAAE,GAAG;aACb,CAAC,CAAC;YAEH,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;gBACxB,MAAM,CAAC,OAAO,EAAE,CAAC;gBACjB,OAAO,CAAC,KAAK,CAAC,CAAC;YACjB,CAAC,CAAC,CAAC;YAEH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE;gBACtB,OAAO,CAAC,IAAI,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;YAEH,MAAM,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;gBACxB,MAAM,CAAC,OAAO,EAAE,CAAC;gBACjB,OAAO,CAAC,IAAI,CAAC,CAAC;YAChB,CAAC,CAAC,CAAC;QACL,CAAC,CAAC,CAAC;IACL,CAAC;IAED,WAAW;QACT,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QACjB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,YAAY,CAAC,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;IACjE,CAAC;CACF;AAED,MAAM,oBAAoB,GAAG,IAAI,oBAAoB,EAAE,CAAC;AAExD,eAAe,oBAAoB,CAAC","sourcesContent":["import { ArkosConfig } from \"../../exports\";\nimport * as net from \"net\";\nimport sheu from \"../sheu\";\n\nclass PortAndHostAllocator {\n private host: string | undefined;\n private port: string | undefined;\n private prevWarnings = new Set<string>();\n\n /**\n * Helps in correcting getting the right host and port to be used according to cli params, arkos config, env and default host and port.\n *\n * Is worth mentioning that this will be preserved along the application until it restarts.\n *\n * @param config {ArkosConfig} - your application configuraiton\n * @param env {Record<string,any>} - current env, may pass process.env\n */\n getCorrectHostAndPortToUse(\n env: Record<string, any>,\n config?: ArkosConfig\n ): { port: string; host: string } {\n const host = env?.CLI_HOST || config?.host || env?.HOST || \"localhost\";\n const port = env?.CLI_PORT || config?.port || env?.PORT || \"8000\";\n return { host: String(host), port: String(port) };\n }\n\n /**\n * Finds an available port starting from the configured port and incrementing until one is found\n *\n * @param env {Record<string,any>} - current env, may pass process.env\n * @param config {ArkosConfig} - your application configuration\n * @returns Promise<{port: string; host: string}> - available port and host\n */\n async getHostAndAvailablePort(\n env: Record<string, any>,\n config?: ArkosConfig & { logWarning?: boolean; caller?: string }\n ): Promise<{ port: string; host: string }> {\n if (this.port && this.host) {\n if (config?.logWarning && this.prevWarnings.size > 0) {\n console.info(\"\");\n Array.from(this.prevWarnings).forEach((msg) => sheu.warn(msg));\n }\n return { port: this.port, host: this.host };\n }\n\n const { host, port: initialPort } = this.getCorrectHostAndPortToUse(\n env,\n config\n );\n let currentPort = parseInt(initialPort, 10);\n\n while (true) {\n const isAvailable = await this.isPortAvailable(host, currentPort);\n\n if (isAvailable) {\n this.port = currentPort.toString();\n this.host = host;\n return { host, port: currentPort.toString() };\n }\n\n const msg = `Port ${currentPort} is in use, trying port ${currentPort + 1} instead...`;\n this.prevWarnings.add(msg);\n\n if (config?.logWarning) {\n // console.info(\"\");\n sheu.warn(`${msg}`);\n }\n\n currentPort++;\n }\n }\n\n /**\n * Checks if a port is available on the given host\n *\n * @param host {string} - host to check\n * @param port {number} - port to check\n * @returns Promise<boolean> - true if port is available, false otherwise\n */\n private async isPortAvailable(host: string, port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const actualHost = ![\"localhost\", \"127.0.0.1\"].includes(host)\n ? host\n : \"localhost\";\n const socket = net.createConnection({\n host: actualHost,\n port,\n timeout: 100,\n });\n\n socket.on(\"connect\", () => {\n socket.destroy();\n resolve(false);\n });\n\n socket.on(\"error\", () => {\n resolve(true);\n });\n\n socket.on(\"timeout\", () => {\n socket.destroy();\n resolve(true); // Port is available\n });\n });\n }\n\n logWarnings() {\n console.info(\"\");\n Array.from(this.prevWarnings).forEach((msg) => sheu.warn(msg));\n }\n}\n\nconst portAndHostAllocator = new PortAndHostAllocator();\n\nexport default portAndHostAllocator;\n"]}
@@ -1,6 +1,6 @@
1
1
  import { User } from "../../types";
2
2
  import { ArkosRequest, ArkosResponse, ArkosNextFunction, ArkosRequestHandler } from "../../types";
3
- import { AuthJwtPayload, AccessAction, AccessControlConfig, AuthenticationControlConfig } from "../../types/auth";
3
+ import { AuthJwtPayload, AccessAction, AccessControlConfig, AuthenticationControlConfig, AccessControlRules } from "../../types/auth";
4
4
  import { MsDuration } from "./utils/helpers/auth.controller.helpers";
5
5
  export declare class AuthService {
6
6
  actionsPerResource: Record<string, Set<string>>;
@@ -11,10 +11,13 @@ export declare class AuthService {
11
11
  isPasswordStrong(password: string): boolean;
12
12
  userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean;
13
13
  verifyJwtToken(token: string, secret?: string): Promise<AuthJwtPayload>;
14
+ protected checkStaticAccessControl(user: User, action: string, accessControl: AccessControlConfig): boolean;
15
+ protected checkDynamicAccessControl(userId: string, action: string, resource: string): Promise<boolean>;
14
16
  handleAccessControl(action: AccessAction, resourceName: string, accessControl?: AccessControlConfig): ArkosRequestHandler;
15
17
  getAuthenticatedUser(req: ArkosRequest): Promise<User | null>;
16
18
  authenticate: (req: ArkosRequest, res: ArkosResponse, next: ArkosNextFunction) => Promise<void>;
17
19
  handleAuthenticationControl(action: AccessAction, authenticationControl?: AuthenticationControlConfig | undefined): ArkosRequestHandler;
20
+ permission(action: string, resource: string, accessControl?: AccessControlRules): Promise<(user: Record<string, any>) => Promise<boolean>>;
18
21
  }
19
22
  declare const authService: AuthService;
20
23
  export default authService;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arkos",
3
- "version": "1.3.0-canary",
3
+ "version": "1.3.0-canary.1",
4
4
  "description": "The Express & Prisma RESTful Framework",
5
5
  "main": "dist/cjs/exports/index.js",
6
6
  "module": "dist/esm/exports/index.js",