arkos 1.4.0-canary.69 → 1.4.0-canary.71
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.
- package/dist/cjs/exports/services/index.js +6 -1
- package/dist/cjs/exports/services/index.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +2 -5
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/auth/utils/services/auth-action.service.js +16 -10
- package/dist/cjs/modules/auth/utils/services/auth-action.service.js.map +1 -1
- package/dist/cjs/server.js +11 -29
- package/dist/cjs/server.js.map +1 -1
- package/dist/cjs/utils/cli/dev.js.map +1 -1
- package/dist/cjs/utils/cli/export-auth-action.js +78 -0
- package/dist/cjs/utils/cli/export-auth-action.js.map +1 -0
- package/dist/cjs/utils/cli/generate.js +28 -11
- package/dist/cjs/utils/cli/generate.js.map +1 -1
- package/dist/cjs/utils/cli/index.js +32 -18
- package/dist/cjs/utils/cli/index.js.map +1 -1
- package/dist/cjs/utils/cli/prisma-generate.js +2 -2
- package/dist/cjs/utils/cli/prisma-generate.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/cjs/utils/cli/utils/runtime-cli-commander.js +58 -0
- package/dist/cjs/utils/cli/utils/runtime-cli-commander.js.map +1 -0
- package/dist/cjs/utils/cli/utils/template-generator/templates/hooks-template.js +1 -34
- package/dist/cjs/utils/cli/utils/template-generator/templates/hooks-template.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/middlewares-template.js +97 -265
- package/dist/cjs/utils/cli/utils/template-generator/templates/middlewares-template.js.map +1 -1
- package/dist/cjs/utils/cli/utils/template-generator/templates/query-options-template.js +16 -16
- package/dist/cjs/utils/cli/utils/template-generator/templates/query-options-template.js.map +1 -1
- package/dist/cjs/utils/cli/utils/watermark-stamper.js.map +1 -1
- package/dist/cjs/utils/dynamic-loader.js +1 -1
- package/dist/cjs/utils/dynamic-loader.js.map +1 -1
- package/dist/cjs/utils/helpers/arkos-config.helpers.js +34 -3
- package/dist/cjs/utils/helpers/arkos-config.helpers.js.map +1 -1
- package/dist/esm/exports/services/index.js +2 -1
- package/dist/esm/exports/services/index.js.map +1 -1
- package/dist/esm/modules/auth/auth.service.js +2 -5
- package/dist/esm/modules/auth/auth.service.js.map +1 -1
- package/dist/esm/modules/auth/utils/services/auth-action.service.js +12 -9
- package/dist/esm/modules/auth/utils/services/auth-action.service.js.map +1 -1
- package/dist/esm/server.js +10 -30
- package/dist/esm/server.js.map +1 -1
- package/dist/esm/utils/cli/dev.js.map +1 -1
- package/dist/esm/utils/cli/export-auth-action.js +72 -0
- package/dist/esm/utils/cli/export-auth-action.js.map +1 -0
- package/dist/esm/utils/cli/generate.js +28 -11
- package/dist/esm/utils/cli/generate.js.map +1 -1
- package/dist/esm/utils/cli/index.js +32 -18
- package/dist/esm/utils/cli/index.js.map +1 -1
- package/dist/esm/utils/cli/prisma-generate.js +2 -2
- package/dist/esm/utils/cli/prisma-generate.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/utils/cli/utils/runtime-cli-commander.js +53 -0
- package/dist/esm/utils/cli/utils/runtime-cli-commander.js.map +1 -0
- package/dist/esm/utils/cli/utils/template-generator/templates/hooks-template.js +1 -34
- package/dist/esm/utils/cli/utils/template-generator/templates/hooks-template.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/middlewares-template.js +97 -265
- package/dist/esm/utils/cli/utils/template-generator/templates/middlewares-template.js.map +1 -1
- package/dist/esm/utils/cli/utils/template-generator/templates/query-options-template.js +16 -16
- package/dist/esm/utils/cli/utils/template-generator/templates/query-options-template.js.map +1 -1
- package/dist/esm/utils/cli/utils/watermark-stamper.js.map +1 -1
- package/dist/esm/utils/dynamic-loader.js +1 -1
- package/dist/esm/utils/dynamic-loader.js.map +1 -1
- package/dist/esm/utils/helpers/arkos-config.helpers.js +29 -1
- package/dist/esm/utils/helpers/arkos-config.helpers.js.map +1 -1
- package/dist/types/exports/services/index.d.ts +2 -1
- package/dist/types/modules/auth/utils/services/auth-action.service.d.ts +1 -0
- package/dist/types/server.d.ts +0 -3
- package/dist/types/utils/cli/export-auth-action.d.ts +4 -0
- package/dist/types/utils/cli/generate.d.ts +2 -1
- package/dist/types/utils/cli/utils/runtime-cli-commander.d.ts +11 -0
- package/dist/types/utils/cli/utils/watermark-stamper.d.ts +3 -3
- package/dist/types/utils/helpers/arkos-config.helpers.d.ts +5 -0
- package/package.json +1 -1
|
@@ -32,8 +32,11 @@ var __importStar = (this && this.__importStar) || (function () {
|
|
|
32
32
|
return result;
|
|
33
33
|
};
|
|
34
34
|
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
35
38
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
-
exports.FileUploadService = exports.getFileUploadServices = exports.EmailService = exports.emailService = exports.BaseService = exports.AuthService = exports.authService = void 0;
|
|
39
|
+
exports.FileUploadService = exports.getFileUploadServices = exports.EmailService = exports.emailService = exports.BaseService = exports.authActionService = exports.AuthService = exports.authService = void 0;
|
|
37
40
|
const file_upload_service_1 = require("../../modules/file-upload/file-upload.service");
|
|
38
41
|
Object.defineProperty(exports, "getFileUploadServices", { enumerable: true, get: function () { return file_upload_service_1.getFileUploadServices; } });
|
|
39
42
|
Object.defineProperty(exports, "FileUploadService", { enumerable: true, get: function () { return file_upload_service_1.FileUploadService; } });
|
|
@@ -45,4 +48,6 @@ exports.emailService = email_service_1.default;
|
|
|
45
48
|
Object.defineProperty(exports, "EmailService", { enumerable: true, get: function () { return email_service_1.EmailService; } });
|
|
46
49
|
const base_service_1 = require("../../modules/base/base.service");
|
|
47
50
|
Object.defineProperty(exports, "BaseService", { enumerable: true, get: function () { return base_service_1.BaseService; } });
|
|
51
|
+
const auth_action_service_1 = __importDefault(require("../../modules/auth/utils/services/auth-action.service"));
|
|
52
|
+
exports.authActionService = auth_action_service_1.default;
|
|
48
53
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/exports/services/index.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/exports/services/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uFAGuD;AAuF9C,sGAzFP,2CAAqB,OAyFO;AAAE,kGAxF9B,uCAAiB,OAwF8B;AArFjD,gFAA2E;AAuClE,sBAvCF,sBAAW,CAuCE;AAAE,4FAvCA,0BAAW,OAuCA;AAtCjC,mFAA+E;AA+EtE,uBA/EF,uBAAY,CA+EE;AAAE,6FA/EA,4BAAY,OA+EA;AA9EnC,kEAA8D;AA2C5D,4FA3CO,0BAAW,OA2CP;AA1Cb,gHAAsF;AAoCnD,4BApC5B,6BAAiB,CAoC4B","sourcesContent":["import {\n getFileUploadServices,\n FileUploadService,\n} from \"../../modules/file-upload/file-upload.service\";\nimport { EmailOptions } from \"../../modules/email/email.service\";\nimport authService, { AuthService } from \"../../modules/auth/auth.service\";\nimport emailService, { EmailService } from \"../../modules/email/email.service\";\nimport { BaseService } from \"../../modules/base/base.service\";\nimport authActionService from \"../../modules/auth/utils/services/auth-action.service\";\nimport {\n ServiceBaseContext,\n BeforeCreateOneHookArgs,\n AfterCreateOneHookArgs,\n BeforeCreateManyHookArgs,\n AfterCreateManyHookArgs,\n BeforeCountHookArgs,\n AfterCountHookArgs,\n BeforeFindManyHookArgs,\n AfterFindManyHookArgs,\n BeforeFindOneHookArgs,\n AfterFindOneHookArgs,\n BeforeUpdateOneHookArgs,\n AfterUpdateOneHookArgs,\n BeforeUpdateManyHookArgs,\n AfterUpdateManyHookArgs,\n BeforeDeleteOneHookArgs,\n AfterDeleteOneHookArgs,\n BeforeDeleteManyHookArgs,\n AfterDeleteManyHookArgs,\n OnCreateOneErrorHookArgs,\n OnCreateManyErrorHookArgs,\n OnCountErrorHookArgs,\n OnFindManyErrorHookArgs,\n OnFindByIdErrorHookArgs,\n OnFindOneErrorHookArgs,\n OnUpdateOneErrorHookArgs,\n OnUpdateManyErrorHookArgs,\n OnDeleteOneErrorHookArgs,\n OnDeleteManyErrorHookArgs,\n} from \"../../modules/base/types/base.service.types\";\n\n/**\n * Authentication service.\n */\nexport { authService, AuthService, authActionService };\n\n/**\n * Base service.\n */\nexport {\n BaseService,\n ServiceBaseContext,\n BeforeCreateOneHookArgs,\n AfterCreateOneHookArgs,\n BeforeCreateManyHookArgs,\n AfterCreateManyHookArgs,\n BeforeCountHookArgs,\n AfterCountHookArgs,\n BeforeFindManyHookArgs,\n AfterFindManyHookArgs,\n BeforeFindOneHookArgs,\n AfterFindOneHookArgs,\n BeforeUpdateOneHookArgs,\n AfterUpdateOneHookArgs,\n BeforeUpdateManyHookArgs,\n AfterUpdateManyHookArgs,\n BeforeDeleteOneHookArgs,\n AfterDeleteOneHookArgs,\n BeforeDeleteManyHookArgs,\n AfterDeleteManyHookArgs,\n OnCreateOneErrorHookArgs,\n OnCreateManyErrorHookArgs,\n OnCountErrorHookArgs,\n OnFindManyErrorHookArgs,\n OnFindByIdErrorHookArgs,\n OnFindOneErrorHookArgs,\n OnUpdateOneErrorHookArgs,\n OnUpdateManyErrorHookArgs,\n OnDeleteOneErrorHookArgs,\n OnDeleteManyErrorHookArgs,\n};\n\n/**\n * Email service.\n */\nexport { emailService, EmailService, EmailOptions };\n\n/**\n * File upload services.\n */\nexport { getFileUploadServices, FileUploadService };\n"]}
|
|
@@ -22,11 +22,8 @@ class AuthService {
|
|
|
22
22
|
constructor() {
|
|
23
23
|
this.actionsPerResource = {};
|
|
24
24
|
this.authenticate = (0, catch_async_1.default)(async (req, _, next) => {
|
|
25
|
-
if (
|
|
26
|
-
|
|
27
|
-
return;
|
|
28
|
-
}
|
|
29
|
-
req.user = (await this.getAuthenticatedUser(req));
|
|
25
|
+
if ((0, arkos_config_helpers_1.isAuthenticationEnabled)())
|
|
26
|
+
req.user = (await this.getAuthenticatedUser(req));
|
|
30
27
|
next();
|
|
31
28
|
});
|
|
32
29
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAavE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AACrE,mFAAmF;AAKnF,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA4arD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,IAAI,CAAC,IAAA,8CAAuB,GAAE,EAAE,CAAC;gBAC/B,IAAI,EAAE,CAAC;gBACP,OAAO;YACT,CAAC;YAED,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;YAC1D,IAAI,EAAE,CAAC;QACT,CAAC,CACF,CAAC;IAqFJ,CAAC;IAjgBC,YAAY,CACV,EAAmB,EACnB,SAA+B,EAC/B,MAAe;QAEf,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;QAErD,IACE,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;YAClC,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU;YACvB,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM;YAErB,MAAM,IAAI,mBAAQ,CAChB,mCAAmC,EACnC,GAAG,EACH,wBAAwB,CACzB,CAAC;QAEJ,MAAM;Y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Q,CAAC,CAAC;oBAC5D,aAAa,GAAG,IAAA,oCAAmB,EAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC,EAAE,WAAW;wBACnE,EAAE,aAAa,CAAC;gBAEpB,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AA/gBD,kCA+gBC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport { isAuthenticationEnabled } from \"../../utils/helpers/arkos-config.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure:\n authConfigs?.jwt?.cookie?.secure ??\n (process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\" ||\n sameSite === \"none\"),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles: string[] = [];\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = Array.isArray(accessControl[action])\n ? accessControl[action]\n : accessControl[action].roles;\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return !!userRoles.some((role: string) => authorizedRoles.includes(role));\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) return null;\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) throw loginRequiredError;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n {},\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (!isAuthenticationEnabled()) {\n next();\n return;\n }\n\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any>): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n if (!configs?.authentication)\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!user) throw loginRequiredError;\n if (user.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl && appModules.includes(kebabCase(resource)))\n accessControl = getModuleComponents(kebabCase(resource))?.authConfigs\n ?.accessControl;\n\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
|
|
1
|
+
{"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAavE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AACrE,mFAAmF;AAKnF,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA4arD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,IAAI,IAAA,8CAAuB,GAAE;gBAC3B,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;YAC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gBAAE,MAAM,uCAAkB,CAAC;YACpC,IAAI,IAAI,CAAC,WAAW;gBAAE,OAAO,IAAI,CAAC;YAElC,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,SAAS,EAAE,CAAC;gBAChD,OAAO,MAAM,IAAI,CAAC,yBAAyB,CAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC1E,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,IAAI,CAAC,aAAa,IAAI,2BAAU,CAAC,QAAQ,CAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC;oBAC5D,aAAa,GAAG,IAAA,oCAAmB,EAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC,EAAE,WAAW;wBACnE,EAAE,aAAa,CAAC;gBAEpB,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AA3gBD,kCA2gBC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport { isAuthenticationEnabled } from \"../../utils/helpers/arkos-config.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure:\n authConfigs?.jwt?.cookie?.secure ??\n (process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\" ||\n sameSite === \"none\"),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles: string[] = [];\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = Array.isArray(accessControl[action])\n ? accessControl[action]\n : accessControl[action].roles;\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return !!userRoles.some((role: string) => authorizedRoles.includes(role));\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n const arkosConfig = getArkosConfig();\n if (!arkosConfig?.authentication) return null;\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) throw loginRequiredError;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n {},\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (isAuthenticationEnabled())\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any>): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n if (!configs?.authentication)\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!user) throw loginRequiredError;\n if (user.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl && appModules.includes(kebabCase(resource)))\n accessControl = getModuleComponents(kebabCase(resource))?.authConfigs\n ?.accessControl;\n\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
2
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
const exports_1 = require("../../../../exports");
|
|
4
6
|
const utils_1 = require("../../../../exports/utils");
|
|
7
|
+
const arkos_config_helpers_1 = require("../../../../utils/helpers/arkos-config.helpers");
|
|
8
|
+
const deepmerge_helper_1 = __importDefault(require("../../../../utils/helpers/deepmerge.helper"));
|
|
5
9
|
const text_helpers_1 = require("../../../../utils/helpers/text.helpers");
|
|
6
10
|
class AuthActionService {
|
|
7
11
|
constructor() {
|
|
@@ -17,10 +21,14 @@ class AuthActionService {
|
|
|
17
21
|
];
|
|
18
22
|
}
|
|
19
23
|
add(action, resource, accessControl) {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
+
const transformedAction = this.transformAccessControlToValidAuthAction(action, resource, accessControl);
|
|
25
|
+
const existingAuthAction = this.getOne(action, resource);
|
|
26
|
+
if (existingAuthAction)
|
|
27
|
+
this.remove(action, resource);
|
|
28
|
+
this.authActions.push((0, deepmerge_helper_1.default)(existingAuthAction || {}, transformedAction));
|
|
29
|
+
}
|
|
30
|
+
remove(action, resource) {
|
|
31
|
+
this.authActions = this.authActions.filter((authAction) => authAction.action !== action && authAction.resource !== resource);
|
|
24
32
|
}
|
|
25
33
|
getAll() {
|
|
26
34
|
return this.authActions;
|
|
@@ -46,15 +54,13 @@ class AuthActionService {
|
|
|
46
54
|
description: `${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(action).replace(/-/g, " "))} ${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(resource).replace(/-/g, " "))}`,
|
|
47
55
|
errorMessage: `You do not have permission to perform this operation`,
|
|
48
56
|
};
|
|
49
|
-
const config = (0,
|
|
57
|
+
const config = (0, arkos_config_helpers_1.getArkosConfig)();
|
|
50
58
|
if (config?.authentication?.mode === "dynamic")
|
|
51
59
|
delete baseAuthAction.roles;
|
|
52
|
-
if (!accessControl)
|
|
60
|
+
if (!accessControl)
|
|
53
61
|
return baseAuthAction;
|
|
54
|
-
|
|
55
|
-
if (Array.isArray(accessControl)) {
|
|
62
|
+
if (Array.isArray(accessControl))
|
|
56
63
|
return baseAuthAction;
|
|
57
|
-
}
|
|
58
64
|
const actionRule = accessControl[action];
|
|
59
65
|
if (actionRule) {
|
|
60
66
|
if (Array.isArray(actionRule)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-action.service.js","sourceRoot":"","sources":["../../../../../../src/modules/auth/utils/services/auth-action.service.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"auth-action.service.js","sourceRoot":"","sources":["../../../../../../src/modules/auth/utils/services/auth-action.service.ts"],"names":[],"mappings":";;;;;AAAA,qDAAsD;AAKtD,yFAAgF;AAChF,kGAAmE;AACnE,yEAAoE;AAoBpE,MAAM,iBAAiB;IAAvB;QACE,gBAAW,GAAiB;YAC1B;gBACE,KAAK,EAAE,EAAE;gBACT,MAAM,EAAE,MAAM;gBACd,QAAQ,EAAE,aAAa;gBACvB,IAAI,EAAE,kBAAkB;gBACxB,WAAW,EAAE,sBAAsB;gBACnC,YAAY,EAAE,sDAAsD;aACrE;SACF,CAAC;IA+HJ,CAAC;IA7HC,GAAG,CAAC,MAAc,EAAE,QAAgB,EAAE,aAAmC;QACvE,MAAM,iBAAiB,GAAG,IAAI,CAAC,uCAAuC,CACpE,MAAM,EACN,QAAQ,EACR,aAAa,CACd,CAAC;QACF,MAAM,kBAAkB,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QACzD,IAAI,kBAAkB;YAAE,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QACtD,IAAI,CAAC,WAAW,CAAC,IAAI,CACnB,IAAA,0BAAS,EAAC,kBAAkB,IAAI,EAAE,EAAE,iBAAiB,CAAC,CACvD,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,QAAgB;QACrC,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,CACxC,CA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AAU,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;SACtE,CAAC;IACJ,CAAC;IAKD,aAAa,CAAC,QAAgB;QAC5B,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAC5B,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,KAAK,QAAQ,CACjD,CAAC;IACJ,CAAC;IAKD,WAAW,CAAC,MAAc;QACxB,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAC5B,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,KAAK,MAAM,CAC7C,CAAC;IACJ,CAAC;IAKD,MAAM,CAAC,MAAc,EAAE,QAAgB;QACrC,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACzC,CAAC;CACF;AAED,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAAE,CAAC;AAElD,kBAAe,iBAAiB,CAAC","sourcesContent":["import { kebabCase } from \"../../../../exports/utils\";\nimport {\n AccessControlConfig,\n DetailedAccessControlRule,\n} from \"../../../../types/auth\";\nimport { getArkosConfig } from \"../../../../utils/helpers/arkos-config.helpers\";\nimport deepmerge from \"../../../../utils/helpers/deepmerge.helper\";\nimport { capitalize } from \"../../../../utils/helpers/text.helpers\";\n\ninterface AuthAction {\n /** role name, e.g Admin, Manager */\n roles?: string[];\n /** action name, e.g Create, View, Update, Download, Cancel */\n action: string;\n /** resource name, e.g user, user-role, product, author */\n resource: string;\n /** Human-readable name for this permission (optional) */\n name?: string;\n /** Detailed description of what this permission allows (optional) */\n description?: string;\n /** Detailed error message of what must be returned on forbidden response (optional)\n *\n * Note: not yet implemented\n */\n errorMessage?: string;\n}\n\nclass AuthActionService {\n authActions: AuthAction[] = [\n {\n roles: [],\n action: \"View\",\n resource: \"auth-action\",\n name: \"View auth action\",\n description: \"Viewm an auth action\",\n errorMessage: \"You do not have permission to perform this operation\",\n },\n ];\n\n add(action: string, resource: string, accessControl?: AccessControlConfig) {\n const transformedAction = this.transformAccessControlToValidAuthAction(\n action,\n resource,\n accessControl\n );\n const existingAuthAction = this.getOne(action, resource);\n if (existingAuthAction) this.remove(action, resource);\n this.authActions.push(\n deepmerge(existingAuthAction || {}, transformedAction)\n );\n }\n\n remove(action: string, resource: string) {\n this.authActions = this.authActions.filter(\n (authAction) =>\n authAction.action !== action && authAction.resource !== resource\n );\n }\n\n getAll(): AuthAction[] {\n return this.authActions;\n }\n\n getOne(action: string, resource: string): AuthAction | undefined {\n return this.authActions.find(\n (authAction) =>\n authAction.action === action && authAction.resource === resource\n );\n }\n\n private transformAccessControlToValidAuthAction(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ): AuthAction {\n const baseAuthAction: AuthAction = {\n roles:\n (accessControl &&\n (Array.isArray(accessControl)\n ? accessControl\n : typeof accessControl === \"string\"\n ? [accessControl]\n : Array.isArray(accessControl?.[action] || {})\n ? (accessControl[action] as string[])\n : (accessControl[action] as DetailedAccessControlRule)\n ?.roles)) ||\n [],\n action,\n resource,\n name: `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`,\n description: `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`,\n errorMessage: `You do not have permission to perform this operation`,\n };\n\n const config = getArkosConfig();\n\n if (config?.authentication?.mode === \"dynamic\") delete baseAuthAction.roles;\n\n if (!accessControl) return baseAuthAction;\n\n if (Array.isArray(accessControl)) return baseAuthAction;\n\n const actionRule = accessControl[action];\n\n if (actionRule) {\n if (Array.isArray(actionRule)) {\n // If it's just an array of roles, keep the base action\n return baseAuthAction;\n } else if (typeof actionRule === \"object\") {\n // If it's a detailed rule object, use its metadata\n return {\n ...baseAuthAction,\n name: actionRule.name || baseAuthAction.name,\n description: actionRule?.description || baseAuthAction.description,\n errorMessage: actionRule?.errorMessage || baseAuthAction.errorMessage,\n };\n }\n }\n\n return baseAuthAction;\n }\n\n /**\n * Get all unique actions across all auth actions\n */\n getUniqueActions(): string[] {\n return [\n ...new Set(this.authActions.map((authAction) => authAction.action)),\n ];\n }\n\n /**\n * Get all unique resources across all auth actions\n */\n getUniqueResources(): string[] {\n return [\n ...new Set(this.authActions.map((authAction) => authAction.resource)),\n ];\n }\n\n /**\n * Get all auth actions for a specific resource\n */\n getByResource(resource: string): AuthAction[] | undefined {\n return this.authActions.filter(\n (authAction) => authAction.resource === resource\n );\n }\n\n /**\n * Get all auth actions for a specific action\n */\n getByAction(action: string): AuthAction[] {\n return this.authActions.filter(\n (authAction) => authAction.action === action\n );\n }\n\n /**\n * Check if an auth action exists\n */\n exists(action: string, resource: string): boolean {\n return !!this.getOne(action, resource);\n }\n}\n\nconst authActionService = new AuthActionService();\n\nexport default authActionService;\n"]}
|
package/dist/cjs/server.js
CHANGED
|
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
3
3
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
4
|
};
|
|
5
5
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
-
exports.server =
|
|
6
|
+
exports.server = void 0;
|
|
7
7
|
exports.getArkosConfig = getArkosConfig;
|
|
8
8
|
exports.terminateApplicationRunningProcessAndServer = terminateApplicationRunningProcessAndServer;
|
|
9
9
|
exports.getExpressApp = getExpressApp;
|
|
@@ -16,32 +16,10 @@ const port_and_host_allocator_1 = __importDefault(require("./utils/features/port
|
|
|
16
16
|
const dev_1 = require("./utils/cli/dev");
|
|
17
17
|
const cli_helpers_1 = require("./utils/cli/utils/cli.helpers");
|
|
18
18
|
const start_1 = require("./utils/cli/start");
|
|
19
|
-
const
|
|
20
|
-
const
|
|
21
|
-
const definedArkosConfig = __importDefault(require(`${fs_helpers_1.crd()}/arkos.config.${fs_helpers_1.getUserFileExtension()}`));
|
|
22
|
-
exports.defaultArkosConfig = {
|
|
23
|
-
welcomeMessage: "Welcome to our RESTful API generated by Arkos, find out more about Arkos at www.arkosjs.com",
|
|
24
|
-
port: Number(process.env.CLI_PORT) || Number(process.env.PORT) || 8000,
|
|
25
|
-
host: process.env.CLI_HOST ||
|
|
26
|
-
process.env.HOST ||
|
|
27
|
-
(process.env.ARKOS_BUILD !== "true" ? "0.0.0.0" : "127.0.0.1"),
|
|
28
|
-
fileUpload: {
|
|
29
|
-
baseUploadDir: "uploads",
|
|
30
|
-
baseRoute: "/api/uploads",
|
|
31
|
-
},
|
|
32
|
-
routers: {
|
|
33
|
-
strict: false,
|
|
34
|
-
},
|
|
35
|
-
debugging: {
|
|
36
|
-
requests: {
|
|
37
|
-
level: 1,
|
|
38
|
-
},
|
|
39
|
-
},
|
|
40
|
-
};
|
|
19
|
+
const arkos_config_helpers_1 = require("./utils/helpers/arkos-config.helpers");
|
|
20
|
+
const runtime_cli_commander_1 = __importDefault(require("./utils/cli/utils/runtime-cli-commander"));
|
|
41
21
|
function getArkosConfig() {
|
|
42
|
-
return (0,
|
|
43
|
-
? {}
|
|
44
|
-
: definedArkosConfig.default);
|
|
22
|
+
return (0, arkos_config_helpers_1.getArkosConfig)();
|
|
45
23
|
}
|
|
46
24
|
process.on("uncaughtException", (err) => {
|
|
47
25
|
if (err.message.includes("EPIPE"))
|
|
@@ -63,8 +41,10 @@ async function initApp(initConfig = {}) {
|
|
|
63
41
|
let networkHost = port_and_host_allocator_1.default.getFirstNonLocalIp();
|
|
64
42
|
_app = await (0, app_1.bootstrap)(initConfig);
|
|
65
43
|
const time = new Date().toTimeString().split(" ")[0];
|
|
66
|
-
|
|
67
|
-
|
|
44
|
+
const cliCommand = process.env.CLI_COMMAND;
|
|
45
|
+
if (!cliCommand &&
|
|
46
|
+
(("port" in arkosConfig && arkosConfig?.port !== undefined) ||
|
|
47
|
+
!("port" in arkosConfig))) {
|
|
68
48
|
exports.server = server = http_1.default.createServer(_app);
|
|
69
49
|
if (initConfig?.configureServer)
|
|
70
50
|
await initConfig.configureServer(server);
|
|
@@ -85,9 +65,11 @@ async function initApp(initConfig = {}) {
|
|
|
85
65
|
sheu_1.default.ready(`${message.replace("{{server}}", "Documentation")}${arkosConfig?.swagger?.endpoint || "/api/docs"}`);
|
|
86
66
|
});
|
|
87
67
|
}
|
|
88
|
-
else {
|
|
68
|
+
else if (!cliCommand) {
|
|
89
69
|
sheu_1.default.warn(`${sheu_1.default.gray(time)} Port set to undefined, hence no internal http server was setup.`);
|
|
90
70
|
}
|
|
71
|
+
else if (cliCommand)
|
|
72
|
+
runtime_cli_commander_1.default.handle();
|
|
91
73
|
return _app;
|
|
92
74
|
}
|
|
93
75
|
catch (err) {
|
package/dist/cjs/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";;;;;;AAqBA,wCAGC;AA6HD,kGAIC;AAED,sCAEC;AAEgB,0BAAO;AA5JxB,+BAAkC;AAClC,gDAAwB;AACxB,wDAAgC;AAChC,+DAA0D;AAC1D,uGAA4E;AAC5E,yCAAoE;AACpE,+DAAuE;AACvE,6CAAqE;AAGrE,+EAA8F;AAC9F,oGAA0E;AAO1E,SAAgB,cAAc;IAE5B,OAAO,IAAA,qCAAoB,GAAE,CAAC;AAChC,CAAC;AAED,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;IAEH,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC;IACrC,OAAO,CAAC,KA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AK,CACR,GAAG,EAAE,OAAO,IAAI,uDAAuD,CACxE,CAAC;QACF,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;QACnB,IAAA,uCAAiC,CAAA,EAAE,EAAE,CAAC;QACtC,IAAA,oCAAsB,CAAA,EAAE,EAAE,CAAC;QAC3B,IAAA,wCAAgC,CAAA,EAAE,EAAE,CAAC;IACvC,CAAC;AACH,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;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 http from \"http\";\nimport sheu from \"./utils/sheu\";\nimport { capitalize } from \"./utils/helpers/text.helpers\";\nimport portAndHostAllocator from \"./utils/features/port-and-host-allocator\";\nimport { killDevelopmentServerChildProcess } from \"./utils/cli/dev\";\nimport { killServerChildProcess } from \"./utils/cli/utils/cli.helpers\";\nimport { killProductionServerChildProcess } from \"./utils/cli/start\";\nimport { ArkosConfig } from \"./types/new-arkos-config\";\nimport { ArkosInitConfig } from \"./exports\";\nimport { getArkosConfig as getArkosConfigHelper } from \"./utils/helpers/arkos-config.helpers\";\nimport runtimeCliCommander from \"./utils/cli/utils/runtime-cli-commander\";\n\n/**\n * Gives access to the underlying current configurations being used by **Arkos** by default and also loaded through `arkos.config.{ts|js}`\n *\n * @returns {ArkosConfig}\n */\nexport function getArkosConfig(): ArkosConfig {\n // This was kept only not to require many changes on the given time\n return getArkosConfigHelper();\n}\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\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\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 {ArkosInitConfig} initConfig - 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(\n initConfig: ArkosInitConfig = {}\n): Promise<Express | undefined> {\n try {\n const arkosConfig = getArkosConfig();\n\n const portAndHost = await portAndHostAllocator.getHostAndAvailablePort(\n process.env,\n arkosConfig\n );\n\n let networkHost = portAndHostAllocator.getFirstNonLocalIp();\n\n _app = await bootstrap(initConfig);\n const time = new Date().toTimeString().split(\" \")[0];\n const cliCommand = process.env.CLI_COMMAND;\n\n if (\n !cliCommand &&\n ((\"port\" in arkosConfig && arkosConfig?.port !== undefined) ||\n !(\"port\" in arkosConfig))\n ) {\n server = http.createServer(_app);\n\n if (initConfig?.configureServer) await initConfig.configureServer(server);\n\n server.listen(\n Number(portAndHost?.port),\n portAndHost.host! === \"localhost\" ? \"127.0.0.1\" : portAndHost.host!,\n () => {\n const host = [\"0.0.0.0\", \"127.0.0.1\"].includes(portAndHost?.host)\n ? \"localhost\"\n : portAndHost?.host;\n\n const message = `${sheu.gray(time)} {{server}} waiting on http://${host}:${portAndHost?.port}`;\n\n sheu.ready(\n message.replace(\n \"{{server}}\",\n `${capitalize(process.env.NODE_ENV || \"development\")} server`\n )\n );\n if (networkHost && portAndHost.host === \"0.0.0.0\")\n sheu.ready(\n message\n .replace(host, networkHost)\n .replace(\"{{server}}\", `Network server`)\n );\n if (\n arkosConfig?.swagger?.mode &&\n ((arkosConfig?.swagger?.enableAfterBuild &&\n process.env.ARKOS_BUILD === \"true\") ||\n process.env.ARKOS_BUILD !== \"true\")\n )\n sheu.ready(\n `${message.replace(\"{{server}}\", \"Documentation\")}${arkosConfig?.swagger?.endpoint || \"/api/docs\"}`\n );\n }\n );\n } else if (!cliCommand) {\n sheu.warn(\n `${sheu.gray(time)} Port set to undefined, hence no internal http server was setup.`\n );\n } else if (cliCommand) runtimeCliCommander.handle();\n\n return _app;\n } catch (err: any) {\n sheu.error(\n err?.message || \"Something went wrong while starting your application!\"\n );\n console.error(err);\n killDevelopmentServerChildProcess?.();\n killServerChildProcess?.();\n killProductionServerChildProcess?.();\n }\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\nexport function getExpressApp() {\n return _app;\n}\n\nexport { server, initApp };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dev.js","sourceRoot":"","sources":["../../../../src/utils/cli/dev.ts"],"names":[],"mappings":";;;;;AA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,CAAC,EAAE,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAE/B,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,KAAK,EAAE,EAAE;YACxC,OAAO,CAAC,KAAK,CAAC,qBAAqB,EAAE,KAAK,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAE5D,IAAI,KAAK,EAAE,CAAC;YACT,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;YAClC,KAAK,GAAG,IAAI,CAAC;QACf,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC;AAKD,SAAgB,iCAAiC;IAC9C,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;IAClC,KAAK,GAAG,IAAI,CAAC;AACf,CAAC","sourcesContent":["import { spawn, ChildProcess } from \"child_process\";\nimport chokidar from \"chokidar\";\nimport { fullCleanCwd, getUserFileExtension } from \"../helpers/fs.helpers\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport sheu from \"../sheu\";\nimport portAndHostAllocator from \"../features/port-and-host-allocator\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\n\ninterface DevOptions {\n port?: string;\n host?: string;\n}\n\nlet child: ChildProcess | null = null;\nlet envFiles: string[] | undefined;\n\n/**\n * Dev server command for the arkos CLI\n */\nexport async function devCommand(options: DevOptions = {}) {\n if (process.env.NODE_ENV === \"test\" || !process.env.NODE_ENV)\n process.env.NODE_ENV = \"development\";\n envFiles = loadEnvironmentVariables();\n child = null;\n let restartTimeout: NodeJS.Timeout | null = null;\n\n try {\n const { port, host } = options;\n let isRestarting = false;\n let restartingFiles = new Set<string>();\n\n const fileExt = getUserFileExtension();\n const entryPoint = path.resolve(process.cwd(), `src/app.${fileExt}`);\n\n if (!fs.existsSync(entryPoint)) {\n console.error(`Could not find application entry point at ${entryPoint}`);\n process.exit(1);\n }\n\n const getEnv = () =>\n ({\n NODE_ENV: \"development\",\n ...process.env,\n ...(port && { CLI_PORT: port }),\n ...(host && { CLI_HOST: host }),\n }) as { [x: string]: string };\n\n const startServer = () => {\n if (child) {\n child.kill();\n child = null;\n }\n\n const env = getEnv();\n\n if (fileExt === \"ts\") {\n child = spawn(\"npx\", [\"tsx-strict\", \"--watch\", entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n } else {\n child = spawn(\n \"npx\",\n [\"tsx-strict\", \"--no-type-check\", \"--watch\", entryPoint],\n {\n stdio: \"inherit\",\n env,\n shell: true,\n }\n );\n }\n\n if (child) {\n child.on(\"error\", (error) => {\n console.error(\"Failed to start server:\", error);\n });\n\n child.on(\"exit\", (code, signal) => {\n if (!isRestarting && signal !== \"SIGTERM\" && signal !== \"SIGINT\") {\n console.info(`Server exited with code ${code}, restarting...`);\n startServer();\n }\n });\n }\n };\n\n const scheduleRestart = (reason: string, filePath?: string) => {\n if (filePath) restartingFiles.add(filePath);\n\n if (restartTimeout) clearTimeout(restartTimeout);\n const now = new Date();\n const time = now.toTimeString().split(\" \")[0];\n\n isRestarting = true;\n if (child) {\n child.kill();\n child = null;\n }\n\n restartTimeout = setTimeout(() => {\n sheu.info(`\\x1b[90m${time}\\x1b[0m Restarting: ${reason.toLowerCase()}`);\n startServer();\n isRestarting = false;\n restartTimeout = null;\n if (filePath) restartingFiles.delete(filePath);\n }, 1000);\n };\n\n const setupEnvWatcher = () => {\n const envWatcher = chokidar.watch(\n fullCleanCwd(envFiles?.join(\",\") || \"\")\n .replaceAll(\"/\", \"\")\n .split(\",\") || [],\n {\n ignoreInitial: true,\n persistent: true,\n }\n );\n\n envWatcher.on(\"all\", (_, filePath) => {\n try {\n envFiles = loadEnvironmentVariables();\n scheduleRestart(\"Environment files changed\", \"env-files\");\n } catch (error) {\n console.error(`Error reloading ${filePath}:`, error);\n }\n });\n\n return envWatcher;\n };\n\n startServer();\n\n const envWatcher = setupEnvWatcher();\n\n const env = getEnv();\n const hostAndPort = await portAndHostAllocator.getHostAndAvailablePort(\n env,\n { logWarning: true }\n );\n\n watermarkStamper.stamp({\n ...hostAndPort,\n envFiles,\n });\n\n const cleanup = () => {\n if (restartTimeout) clearTimeout(restartTimeout);\n\n if (envWatcher) envWatcher.close();\n\n if (child) {\n child.kill(\"SIGTERM\");\n\n setTimeout(() => {\n if (child && !child.killed) child.kill(\"SIGKILL\");\n }, 5000);\n }\n\n process.exit(0);\n };\n\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n process.on(\"uncaughtException\", (error) => {\n console.error(\"Uncaught Exception:\", error);\n cleanup();\n });\n } catch (error) {\n console.error(\"Development server failed to start:\", error);\n\n if (child) {\n (child as ChildProcess)?.kill?.();\n child = null;\n }\n\n process.exit(1);\n }\n}\n\n/**\n * Help function to help other processes to terminate the development server child process\n */\nexport function killDevelopmentServerChildProcess() {\n (child as ChildProcess)?.kill?.();\n child = null;\n}\n"]}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.default = exportAuthActionCommand;
|
|
7
|
+
const child_process_1 = require("child_process");
|
|
8
|
+
const dotenv_helpers_1 = require("../dotenv.helpers");
|
|
9
|
+
const fs_helpers_1 = require("../helpers/fs.helpers");
|
|
10
|
+
const path_1 = __importDefault(require("path"));
|
|
11
|
+
const fs_1 = __importDefault(require("fs"));
|
|
12
|
+
const watermark_stamper_1 = __importDefault(require("./utils/watermark-stamper"));
|
|
13
|
+
async function exportAuthActionCommand(options) {
|
|
14
|
+
process.env.CLI_COMMAND = "EXPORT_AUTH_ACTION";
|
|
15
|
+
process.env.CLI_COMMAND_OPTIONS = JSON.stringify(options);
|
|
16
|
+
if (process.env.NODE_ENV === "test" || !process.env.NODE_ENV)
|
|
17
|
+
process.env.NODE_ENV = "development";
|
|
18
|
+
const envFiles = (0, dotenv_helpers_1.loadEnvironmentVariables)() || [];
|
|
19
|
+
let child = null;
|
|
20
|
+
try {
|
|
21
|
+
const fileExt = (0, fs_helpers_1.getUserFileExtension)();
|
|
22
|
+
const entryPoint = path_1.default.resolve(process.cwd(), `src/app.${fileExt}`);
|
|
23
|
+
if (!fs_1.default.existsSync(entryPoint)) {
|
|
24
|
+
console.error(`Could not find application entry point at ${entryPoint}`);
|
|
25
|
+
process.exit(1);
|
|
26
|
+
}
|
|
27
|
+
const getEnv = () => ({
|
|
28
|
+
NODE_ENV: "development",
|
|
29
|
+
...process.env,
|
|
30
|
+
});
|
|
31
|
+
const startServer = () => {
|
|
32
|
+
if (child) {
|
|
33
|
+
child.kill();
|
|
34
|
+
child = null;
|
|
35
|
+
}
|
|
36
|
+
const env = getEnv();
|
|
37
|
+
if (fileExt === "ts")
|
|
38
|
+
child = (0, child_process_1.spawn)("npx", ["tsx-strict", "--no-type-check", entryPoint], {
|
|
39
|
+
stdio: "inherit",
|
|
40
|
+
env,
|
|
41
|
+
shell: true,
|
|
42
|
+
});
|
|
43
|
+
if (child)
|
|
44
|
+
child.on("error", (error) => {
|
|
45
|
+
console.error("Failed to start server:", error);
|
|
46
|
+
});
|
|
47
|
+
};
|
|
48
|
+
startServer();
|
|
49
|
+
watermark_stamper_1.default.stamp({
|
|
50
|
+
envFiles,
|
|
51
|
+
});
|
|
52
|
+
const cleanup = () => {
|
|
53
|
+
if (child) {
|
|
54
|
+
child.kill("SIGTERM");
|
|
55
|
+
setTimeout(() => {
|
|
56
|
+
if (child && !child.killed)
|
|
57
|
+
child.kill("SIGKILL");
|
|
58
|
+
}, 5000);
|
|
59
|
+
}
|
|
60
|
+
process.exit(0);
|
|
61
|
+
};
|
|
62
|
+
process.on("SIGINT", cleanup);
|
|
63
|
+
process.on("SIGTERM", cleanup);
|
|
64
|
+
process.on("uncaughtException", (error) => {
|
|
65
|
+
console.error("Uncaught Exception:", error);
|
|
66
|
+
cleanup();
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
catch (error) {
|
|
70
|
+
console.error("Development server failed to start:", error);
|
|
71
|
+
if (child) {
|
|
72
|
+
child?.kill?.();
|
|
73
|
+
child = null;
|
|
74
|
+
}
|
|
75
|
+
process.exit(1);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=export-auth-action.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"export-auth-action.js","sourceRoot":"","sources":["../../../../src/utils/cli/export-auth-action.ts"],"names":[],"mappings":";;;;;AAOA,0CAmFC;AA1FD,iDAAoD;AACpD,sDAA6D;AAC7D,sDAA6D;AAC7D,gDAAwB;AACxB,4CAAoB;AACpB,kFAAyD;AAE1C,KAAK,UAAU,uBAAuB,CAAC,OAGrD;IACC,OAAO,CAAC,GAAG,CAAC,WAAW,GAAG,oBAAoB,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,mBAAmB,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC;IAE1D,IAAI,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,MAAM,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,QAAQ;QAC1D,OAAO,CAAC,GAAG,CAAC,QAAQ,GAAG,aAAa,CAAC;IAEvC,MAAM,QAAQ,GAAG,IAAA,yCAAwB,GAAE,IAAI,EAAE,CAAC;IAClD,IAAI,KAAK,GAAwB,IAAI,CAAC;IAEtC,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,IAAA,iCAAoB,GAAE,CAAC;QACvC,MAAM,UAAU,GAAG,cAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,WAAW,OAAO,EAA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AAC,CAAC;gBACpD,CAAC,EAAE,IAAI,CAAC,CAAC;YACX,CAAC;YAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;QAClB,CAAC,CAAC;QAEF,OAAO,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;QAC9B,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QAE/B,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,KAAK,EAAE,EAAE;YACxC,OAAO,CAAC,KAAK,CAAC,qBAAqB,EAAE,KAAK,CAAC,CAAC;YAC5C,OAAO,EAAE,CAAC;QACZ,CAAC,CAAC,CAAC;IACL,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,KAAK,CAAC,qCAAqC,EAAE,KAAK,CAAC,CAAC;QAE5D,IAAI,KAAK,EAAE,CAAC;YACT,KAAsB,EAAE,IAAI,EAAE,EAAE,CAAC;YAClC,KAAK,GAAG,IAAI,CAAC;QACf,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC;AACH,CAAC","sourcesContent":["import { ChildProcess, spawn } from \"child_process\";\nimport { loadEnvironmentVariables } from \"../dotenv.helpers\";\nimport { getUserFileExtension } from \"../helpers/fs.helpers\";\nimport path from \"path\";\nimport fs from \"fs\";\nimport watermarkStamper from \"./utils/watermark-stamper\";\n\nexport default async function exportAuthActionCommand(options: {\n overwrite?: boolean;\n path?: string;\n}) {\n process.env.CLI_COMMAND = \"EXPORT_AUTH_ACTION\";\n process.env.CLI_COMMAND_OPTIONS = JSON.stringify(options);\n\n if (process.env.NODE_ENV === \"test\" || !process.env.NODE_ENV)\n process.env.NODE_ENV = \"development\";\n\n const envFiles = loadEnvironmentVariables() || [];\n let child: ChildProcess | null = null;\n\n try {\n const fileExt = getUserFileExtension();\n const entryPoint = path.resolve(process.cwd(), `src/app.${fileExt}`);\n\n if (!fs.existsSync(entryPoint)) {\n console.error(`Could not find application entry point at ${entryPoint}`);\n process.exit(1);\n }\n\n const getEnv = () =>\n ({\n NODE_ENV: \"development\",\n ...process.env,\n }) as { [x: string]: string };\n\n const startServer = () => {\n if (child) {\n child.kill();\n child = null;\n }\n\n const env = getEnv();\n\n if (fileExt === \"ts\")\n child = spawn(\"npx\", [\"tsx-strict\", \"--no-type-check\", entryPoint], {\n stdio: \"inherit\",\n env,\n shell: true,\n });\n\n if (child)\n child.on(\"error\", (error) => {\n console.error(\"Failed to start server:\", error);\n });\n };\n\n startServer();\n\n watermarkStamper.stamp({\n envFiles,\n });\n\n const cleanup = () => {\n if (child) {\n child.kill(\"SIGTERM\");\n setTimeout(() => {\n if (child && !child.killed) child.kill(\"SIGKILL\");\n }, 5000);\n }\n\n process.exit(0);\n };\n\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n process.on(\"uncaughtException\", (error) => {\n console.error(\"Uncaught Exception:\", error);\n cleanup();\n });\n } catch (error) {\n console.error(\"Development server failed to start:\", error);\n\n if (child) {\n (child as ChildProcess)?.kill?.();\n child = null;\n }\n\n process.exit(1);\n }\n}\n"]}
|