arkos 1.6.3-canary.2 → 1.6.4-beta
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/components/arkos-policy/index.js.map +1 -1
- package/dist/cjs/modules/auth/auth.service.js +6 -4
- package/dist/cjs/modules/auth/auth.service.js.map +1 -1
- package/dist/cjs/modules/auth/utils/services/auth-action.service.js +5 -3
- package/dist/cjs/modules/auth/utils/services/auth-action.service.js.map +1 -1
- package/dist/cjs/modules/email/email.service.js +1 -0
- package/dist/cjs/modules/email/email.service.js.map +1 -1
- package/dist/cjs/modules/swagger/swagger.router.js +4 -1
- package/dist/cjs/modules/swagger/swagger.router.js.map +1 -1
- package/dist/cjs/utils/arkos-router/types/index.js.map +1 -1
- package/dist/cjs/utils/cli/build.js +11 -2
- package/dist/cjs/utils/cli/build.js.map +1 -1
- package/dist/cjs/utils/cli/index.js.map +1 -1
- package/dist/cjs/utils/cli/start.js +11 -10
- package/dist/cjs/utils/cli/start.js.map +1 -1
- package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/esm/components/arkos-policy/index.js.map +1 -1
- package/dist/esm/modules/auth/auth.service.js +6 -4
- package/dist/esm/modules/auth/auth.service.js.map +1 -1
- package/dist/esm/modules/auth/utils/services/auth-action.service.js +6 -4
- package/dist/esm/modules/auth/utils/services/auth-action.service.js.map +1 -1
- package/dist/esm/modules/email/email.service.js +1 -0
- package/dist/esm/modules/email/email.service.js.map +1 -1
- package/dist/esm/modules/swagger/swagger.router.js +4 -1
- package/dist/esm/modules/swagger/swagger.router.js.map +1 -1
- package/dist/esm/utils/arkos-router/types/index.js.map +1 -1
- package/dist/esm/utils/cli/build.js +11 -2
- package/dist/esm/utils/cli/build.js.map +1 -1
- package/dist/esm/utils/cli/index.js.map +1 -1
- package/dist/esm/utils/cli/start.js +11 -10
- package/dist/esm/utils/cli/start.js.map +1 -1
- package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
- package/dist/types/modules/auth/utils/services/auth-action.service.d.ts +1 -1
- package/dist/types/utils/arkos-router/types/index.d.ts +2 -1
- package/dist/types/utils/cli/build.d.ts +1 -1
- package/dist/types/utils/cli/start.d.ts +4 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/components/arkos-policy/index.ts"],"names":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/components/arkos-policy/index.ts"],"names":[],"mappings":";;;;;AAsCA,kCAIC;AAnCD,mFAA0D;AA+B1D,SAAgB,WAAW,CACzB,QAAmB;IAEnB,OAAO,WAAW,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,WAAW,CAClB,QAAmB,EACnB,KAAsC;IAEtC,MAAM,IAAI,GAAG,CACX,MAAe,EACf,MAAuB,EAC2B,EAAE;QACpD,MAAM,QAAQ,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;QAChD,OAAO,WAAW,CAAgC,QAAQ,EAAE,QAAQ,CAAC,CAAC;IACxE,CAAC,CAAC;IAEF,MAAM,aAAa,GAAG,MAAM,CAAC,WAAW,CACtC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,EAAE,MAAM,CAAC,EAAE,EAAE;QACjD,MAAM,SAAS,GAA8C;YAC3D,QAAQ;YACR,MAAM;YACN,IAAI,EAAE,MAAM;SACb,CAAC;QAEF,MAAM,OAAO,GAAkB,sBAAW,CAAC,UAAU,CAAC,MAAM,EAAE,QAAQ,EAAE;YACtE,CAAC,MAAM,CAAC,EAAE,MAAM,IAAI,EAAE;SACvB,CAAC,CAAC;QAEH,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,WAAW,EAAE,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;QAExE,OAAO;YACL,CAAC,MAAM,EAAE,SAAS,CAAC;YACnB,CAAC,MAAM,EAAE,OAAO,CAAC;SAClB,CAAC;IACJ,CAAC,CAAC,CACH,CAAC;IAEF,OAAO;QACL,MAAM,EAAE,aAAsB;QAC9B,QAAQ;QACR,IAAI;QACJ,GAAG,aAAa;KACoC,CAAC;AACzD,CAAC","sourcesContent":["import {\n ArkosPolicyRule,\n IArkosPolicy,\n PolicyAuthEntry,\n PolicyChecker,\n PolicyWithActions,\n} from \"./types\";\nimport authService from \"../../modules/auth/auth.service\";\n\n/**\n * Creates a typed policy for a Prisma model resource.\n *\n * Each `.rule()` call registers an action and returns the policy\n * with a typed `can{Action}` permission checker and a typed `{Action}`\n * entry — both passable to the `authentication` field on `ArkosRouteHook`\n * and `ArkosRouter`, and callable for fine-grained permission checks.\n *\n * @param resource - The resource name in kebab-case (e.g. `\"user\"`, `\"blog-post\"`)\n *\n * @example\n * ```ts\n * const userPolicy = ArkosPolicy(\"user\")\n * .rule(\"Create\", [\"Admin\", \"Editor\"])\n * .rule(\"View\", \"*\")\n * .rule(\"Delete\", [\"Admin\"]);\n *\n * // Pass to authentication field\n * userRouter.post({ path: \"/users\", authentication: userPolicy.Create });\n * userRouteHook.deleteOne({ authentication: userPolicy.Delete });\n *\n * // Fine-grained check\n * if (userPolicy.canCreate(req.user)) { ... }\n *\n * export default userPolicy;\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/api-referency/arkos-policy}\n */\nexport function ArkosPolicy<TResource extends string>(\n resource: TResource\n): IArkosPolicy<TResource, never> {\n return buildPolicy(resource, {});\n}\n\nfunction buildPolicy<TResource extends string, TActions extends string>(\n resource: TResource,\n store: Record<string, ArkosPolicyRule>\n): PolicyWithActions<TResource, TActions> {\n const rule = <TAction extends string>(\n action: TAction,\n config: ArkosPolicyRule\n ): PolicyWithActions<TResource, TActions | TAction> => {\n const newStore = { ...store, [action]: config };\n return buildPolicy<TResource, TActions | TAction>(resource, newStore);\n };\n\n const actionEntries = Object.fromEntries(\n Object.entries(store).flatMap(([action, config]) => {\n const authEntry: PolicyAuthEntry<TResource, typeof action> = {\n resource,\n action,\n rule: config,\n };\n\n const checker: PolicyChecker = authService.permission(action, resource, {\n [action]: config || {},\n });\n\n const canKey = `can${action.charAt(0).toUpperCase()}${action.slice(1)}`;\n\n return [\n [action, authEntry],\n [canKey, checker],\n ];\n })\n );\n\n return {\n __type: \"ArkosPolicy\" as const,\n resource,\n rule,\n ...actionEntries,\n } as unknown as PolicyWithActions<TResource, TActions>;\n}\n"]}
|
|
@@ -265,7 +265,7 @@ class AuthService {
|
|
|
265
265
|
if (!accessControl &&
|
|
266
266
|
dynamic_loader_1.appModules.some((appModule) => (0, utils_1.kebabCase)(appModule) === (0, utils_1.kebabCase)(resource)))
|
|
267
267
|
accessControl = (0, dynamic_loader_1.getModuleComponents)(resource)?.authConfigs?.accessControl;
|
|
268
|
-
auth_action_service_1.default.add(action, resource, accessControl);
|
|
268
|
+
const authAction = auth_action_service_1.default.add(action, resource, accessControl);
|
|
269
269
|
return (0, catch_async_1.default)(async (req, _, next) => {
|
|
270
270
|
if (req.user) {
|
|
271
271
|
const user = req.user;
|
|
@@ -274,7 +274,7 @@ class AuthService {
|
|
|
274
274
|
next();
|
|
275
275
|
return;
|
|
276
276
|
}
|
|
277
|
-
const notEnoughPermissionsError = new app_error_1.default(
|
|
277
|
+
const notEnoughPermissionsError = new app_error_1.default(authAction.errorMessage, 403, "NotEnoughPermissions");
|
|
278
278
|
if (configs?.authentication?.mode === "dynamic") {
|
|
279
279
|
const hasPermission = await this.checkDynamicAccessControl(user.id, action, resource);
|
|
280
280
|
if (!hasPermission)
|
|
@@ -328,7 +328,9 @@ class AuthService {
|
|
|
328
328
|
return user;
|
|
329
329
|
}
|
|
330
330
|
authorize(action, resource, rule) {
|
|
331
|
-
auth_action_service_1.default.add(action, resource, {
|
|
331
|
+
const authAction = auth_action_service_1.default.add(action, resource, {
|
|
332
|
+
[action]: rule,
|
|
333
|
+
});
|
|
332
334
|
return (0, catch_async_1.default)(async (req, _, next) => {
|
|
333
335
|
const hooks = (0, server_1.getArkosConfig)()?.authentication?.hooks?.authorize;
|
|
334
336
|
const before = await this.runHooks(hooks?.before, req, {
|
|
@@ -354,7 +356,7 @@ class AuthService {
|
|
|
354
356
|
const user = req.user;
|
|
355
357
|
const configs = (0, server_1.getArkosConfig)();
|
|
356
358
|
if (!user.isSuperUser) {
|
|
357
|
-
const notEnoughPermissionsError = new app_error_1.default(
|
|
359
|
+
const notEnoughPermissionsError = new app_error_1.default(authAction.errorMessage, 403, "NotEnoughPermissions");
|
|
358
360
|
if (configs?.authentication?.mode === "dynamic") {
|
|
359
361
|
const hasPermission = await this.checkDynamicAccessControl(user.id, action, resource);
|
|
360
362
|
if (!hasPermission)
|
|
@@ -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;AAevE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AACrE,mFAGkD;AAclD,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QAqnBrD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,MAAM,KAAK,GAAG,IAAA,uBAAc,GAAE,EAAE,cAAc,EAAE,KAAK,EAAE,YAAY,CAAC;YAEpE,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,CAAC,CAAC;YACvD,IAAI,MAAM,CAAC,KAAK,EAAE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ignOptions } 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 DetailedAccessControlRule,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\nimport {\n AuthenticateHookHandler,\n AuthenticateAfterHookHandler,\n AuthenticateErrorHookHandler,\n AuthorizeHookHandler,\n AuthorizeAfterHookHandler,\n AuthorizeErrorHookHandler,\n} from \"../../types/arkos-config/utils\";\nimport { CookieOptions } from \"express\";\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 * Runs a chain of `before` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to `onError` hooks.\n * - If a hook calls `skip()` — chain stops, core logic is bypassed, jumps to `after` hooks.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ skipped, error? }`\n */\n private async runHooks(\n hooks:\n | AuthenticateHookHandler\n | AuthenticateHookHandler[]\n | AuthorizeHookHandler\n | AuthorizeHookHandler[]\n | undefined,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ skipped: boolean; error?: unknown }> {\n if (!hooks) return { skipped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let skipCalled = false;\n\n try {\n await (hook as any)({\n req,\n skip: () => {\n skipCalled = true;\n },\n ...ctx,\n });\n } catch (err) {\n return { skipped: false, error: err };\n }\n\n if (skipCalled) return { skipped: true };\n }\n\n return { skipped: false };\n }\n\n /**\n * Runs a chain of `after` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to the global error handler.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ error? }`\n */\n private async runAfterHooks(\n hooks:\n | AuthenticateAfterHookHandler\n | AuthenticateAfterHookHandler[]\n | AuthorizeAfterHookHandler\n | AuthorizeAfterHookHandler[]\n | undefined,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ error?: unknown }> {\n if (!hooks) return {};\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n try {\n await (hook as any)({ req, ...ctx });\n } catch (err) {\n return { error: err };\n }\n }\n\n return {};\n }\n\n /**\n * Runs a chain of `onError` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to the global error handler.\n * - If a hook calls `skip()` — suppresses the error and jumps to `after` hooks.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ skipped, error? }`\n */\n private async runErrorHooks(\n hooks:\n | AuthenticateErrorHookHandler\n | AuthenticateErrorHookHandler[]\n | AuthorizeErrorHookHandler\n | AuthorizeErrorHookHandler[]\n | undefined,\n error: unknown,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ skipped: boolean; error?: unknown }> {\n if (!hooks) return { skipped: false, error };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let skipCalled = false;\n\n try {\n await (hook as any)({\n req,\n error,\n skip: () => {\n skipCalled = true;\n },\n ...ctx,\n });\n } catch (err) {\n return { skipped: false, error: err };\n }\n\n if (skipCalled) return { skipped: true };\n }\n\n return { skipped: false, error };\n }\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure: (() => {\n if (authConfigs?.jwt?.cookie?.secure !== undefined)\n return authConfigs?.jwt?.cookie?.secure;\n else if (process.env.JWT_COOKIE_SECURE !== undefined)\n return process.env.JWT_COOKIE_SECURE === \"true\";\n else return req.secure || req.headers[\"x-forwarded-proto\"] === \"https\";\n })(),\n sameSite,\n domain: authConfigs?.jwt?.cookie?.domain || process.env.JWT_COOKIE_DOMAIN,\n ...arkosConfig?.authentication?.jwt?.cookie,\n } as CookieOptions;\n }\n\n /**\n * Is used by default internally by Arkos under `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(new Date(user.passwordChangedAt).getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n 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 private isWildcardAccess(config: AccessControlConfig): config is \"*\" {\n return config === \"*\";\n }\n\n private isRoleList(config: AccessControlConfig): config is string[] {\n return Array.isArray(config);\n }\n\n private isAccessRules(\n config: AccessControlConfig\n ): config is Partial<AccessControlRules> {\n return (\n typeof config === \"object\" && config !== null && !Array.isArray(config)\n );\n }\n\n private normalizeRuleToRoles(\n rule: string[] | DetailedAccessControlRule | \"*\" | undefined\n ): string[] {\n if (!rule) return [];\n if (rule === \"*\") return [\"*\"];\n if (Array.isArray(rule)) return rule;\n return rule.roles === \"*\" ? [\"*\"] : (rule.roles ?? []);\n }\n\n private resolveAuthorizedRoles(\n action: AccessAction,\n accessControl: AccessControlConfig\n ): string[] {\n if (this.isWildcardAccess(accessControl)) return [\"*\"];\n if (this.isRoleList(accessControl)) return accessControl;\n if (this.isAccessRules(accessControl))\n return this.normalizeRuleToRoles(accessControl[action]);\n return [];\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n 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 = this.resolveAuthorizedRoles(action, accessControl);\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return (\n authorizedRoles?.[0] === \"*\" ||\n !!userRoles.some((role: string) => authorizedRoles.includes(role))\n );\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n 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 * @deprecated Will be removed on v2.0, use AuthService.authorize instead\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n 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 \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call AuthService.getAuthenticatedUser without setting up authentication\"\n );\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\") &&\n req?.headers?.authorization.split?.(\" \")?.[1]\n )\n token = req?.headers?.authorization.split(\" \")[1];\n\n if (\n !token &&\n req?.cookies?.arkos_access_token !== \"no-token\" &&\n req.cookies\n ) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) return null;\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 \"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 \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware to authenticate the request by extracting and verifying the JWT token and setting `req.user`.\n *\n * Runs `authentication.hooks.authenticate` before/after the authentication logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — extracts and verifies the JWT token, sets `req.user`.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if core logic throws — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * On custom routes, hooks defined in `arkosConfig` still apply since they are baked into this method.\n *\n * @example\n * ```ts\n * // custom route - hooks still run\n * router.get(\"/custom\", authService.authenticate, handler);\n * ```\n *\n * @example\n * ```ts\n * // skip built-in auth from a before hook\n * before: (ctx) => {\n * ctx.req.user = myCustomAuth(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authenticate;\n\n const before = await this.runHooks(hooks?.before, req);\n if (before.error) {\n const onError = await this.runErrorHooks(\n hooks?.onError,\n before.error,\n req\n );\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n\n if (!before.skipped) {\n try {\n if (isAuthenticationEnabled()) {\n const user = (await this.getAuthenticatedUser(req)) as User;\n if (!user) throw loginRequiredError;\n req.user = user;\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req);\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req);\n if (after.error) return next(after.error);\n\n next();\n }\n );\n\n /**\n * Middleware to authorize the authenticated user for a given action on a resource.\n *\n * Runs `authentication.hooks.authorize` before/after the authorization logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — checks user role/permissions against the access control rules.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if authorization fails — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * @param resource - The resource being accessed, in kebabCase (e.g. `\"product\"`, `\"cart-item\"`)\n * @param action - The action being performed (e.g. `\"View\"`, `\"Create\"`, `\"Delete\"`)\n * @param rule - Access control rules for this action. Accepts a role list, a wildcard, or a `DetailedAccessControlRule`.\n *\n * @example\n * ```ts\n * router.delete(\"/products/:id\",\n * authService.authenticate,\n * authService.authorize(\"product\", \"Delete\", [\"admin\"]),\n * handler\n * );\n * ```\n *\n * @example\n * ```ts\n * // skip built-in authorization from a before hook\n * before: (ctx) => {\n * ctx.req.user.role = myCustomRoleResolver(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks#authorize}\n * @since v1.6.0-beta\n */\n authorize(\n action: AccessAction,\n resource: string,\n rule?: string[] | DetailedAccessControlRule | \"*\"\n ): ArkosRequestHandler {\n authActionService.add(action, resource, { [action]: rule });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authorize;\n\n const before = await this.runHooks(hooks?.before, req, {\n action,\n resource,\n rule,\n });\n if (before.error) {\n const onError = await this.runErrorHooks(\n hooks?.onError,\n before.error,\n req,\n { action, resource, rule }\n );\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n\n if (!before.skipped) {\n try {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (!user.isSuperUser) {\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perform this action\",\n 403,\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n } else if (configs?.authentication?.mode === \"static\") {\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n { [action]: rule }\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n }\n }\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req, {\n action,\n resource,\n rule,\n });\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n if (after.error) return next(after.error);\n\n next();\n }\n );\n }\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n *\n * @deprecated Will be removed on v2.0, use AuthService.authenticate instead\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: User | undefined): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n\n if (!isUsingAuthentication())\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!isAuthenticationEnabled()) return false;\n if (!user) throw loginRequiredError;\n if (user?.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n 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;AAevE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AACrE,mFAGkD;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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;AAh4BD,kCAg4BC;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 DetailedAccessControlRule,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\nimport {\n AuthenticateHookHandler,\n AuthenticateAfterHookHandler,\n AuthenticateErrorHookHandler,\n AuthorizeHookHandler,\n AuthorizeAfterHookHandler,\n AuthorizeErrorHookHandler,\n} from \"../../types/arkos-config/utils\";\nimport { CookieOptions } from \"express\";\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 * Runs a chain of `before` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to `onError` hooks.\n * - If a hook calls `skip()` — chain stops, core logic is bypassed, jumps to `after` hooks.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ skipped, error? }`\n */\n private async runHooks(\n hooks:\n | AuthenticateHookHandler\n | AuthenticateHookHandler[]\n | AuthorizeHookHandler\n | AuthorizeHookHandler[]\n | undefined,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ skipped: boolean; error?: unknown }> {\n if (!hooks) return { skipped: false };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let skipCalled = false;\n\n try {\n await (hook as any)({\n req,\n skip: () => {\n skipCalled = true;\n },\n ...ctx,\n });\n } catch (err) {\n return { skipped: false, error: err };\n }\n\n if (skipCalled) return { skipped: true };\n }\n\n return { skipped: false };\n }\n\n /**\n * Runs a chain of `after` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to the global error handler.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ error? }`\n */\n private async runAfterHooks(\n hooks:\n | AuthenticateAfterHookHandler\n | AuthenticateAfterHookHandler[]\n | AuthorizeAfterHookHandler\n | AuthorizeAfterHookHandler[]\n | undefined,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ error?: unknown }> {\n if (!hooks) return {};\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n try {\n await (hook as any)({ req, ...ctx });\n } catch (err) {\n return { error: err };\n }\n }\n\n return {};\n }\n\n /**\n * Runs a chain of `onError` hooks in sequence.\n *\n * - If a hook throws — chain aborts, error is forwarded to the global error handler.\n * - If a hook calls `skip()` — suppresses the error and jumps to `after` hooks.\n * - If a hook returns — next hook in chain runs.\n *\n * @returns Promise resolving to `{ skipped, error? }`\n */\n private async runErrorHooks(\n hooks:\n | AuthenticateErrorHookHandler\n | AuthenticateErrorHookHandler[]\n | AuthorizeErrorHookHandler\n | AuthorizeErrorHookHandler[]\n | undefined,\n error: unknown,\n req: ArkosRequest,\n ctx?: {\n action?: AccessAction;\n resource?: string;\n rule?: string[] | DetailedAccessControlRule | \"*\";\n }\n ): Promise<{ skipped: boolean; error?: unknown }> {\n if (!hooks) return { skipped: false, error };\n\n const hookArray = Array.isArray(hooks) ? hooks : [hooks];\n\n for (const hook of hookArray) {\n let skipCalled = false;\n\n try {\n await (hook as any)({\n req,\n error,\n skip: () => {\n skipCalled = true;\n },\n ...ctx,\n });\n } catch (err) {\n return { skipped: false, error: err };\n }\n\n if (skipCalled) return { skipped: true };\n }\n\n return { skipped: false, error };\n }\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure: (() => {\n if (authConfigs?.jwt?.cookie?.secure !== undefined)\n return authConfigs?.jwt?.cookie?.secure;\n else if (process.env.JWT_COOKIE_SECURE !== undefined)\n return process.env.JWT_COOKIE_SECURE === \"true\";\n else return req.secure || req.headers[\"x-forwarded-proto\"] === \"https\";\n })(),\n sameSite,\n domain: authConfigs?.jwt?.cookie?.domain || process.env.JWT_COOKIE_DOMAIN,\n ...arkosConfig?.authentication?.jwt?.cookie,\n } as CookieOptions;\n }\n\n /**\n * Is used by default internally by Arkos under `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(new Date(user.passwordChangedAt).getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n 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 private isWildcardAccess(config: AccessControlConfig): config is \"*\" {\n return config === \"*\";\n }\n\n private isRoleList(config: AccessControlConfig): config is string[] {\n return Array.isArray(config);\n }\n\n private isAccessRules(\n config: AccessControlConfig\n ): config is Partial<AccessControlRules> {\n return (\n typeof config === \"object\" && config !== null && !Array.isArray(config)\n );\n }\n\n private normalizeRuleToRoles(\n rule: string[] | DetailedAccessControlRule | \"*\" | undefined\n ): string[] {\n if (!rule) return [];\n if (rule === \"*\") return [\"*\"];\n if (Array.isArray(rule)) return rule;\n return rule.roles === \"*\" ? [\"*\"] : (rule.roles ?? []);\n }\n\n private resolveAuthorizedRoles(\n action: AccessAction,\n accessControl: AccessControlConfig\n ): string[] {\n if (this.isWildcardAccess(accessControl)) return [\"*\"];\n if (this.isRoleList(accessControl)) return accessControl;\n if (this.isAccessRules(accessControl))\n return this.normalizeRuleToRoles(accessControl[action]);\n return [];\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n 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 = this.resolveAuthorizedRoles(action, accessControl);\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return (\n authorizedRoles?.[0] === \"*\" ||\n !!userRoles.some((role: string) => authorizedRoles.includes(role))\n );\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n 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 * @deprecated Will be removed on v2.0, use AuthService.authorize instead\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n const authAction = authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n authAction.errorMessage,\n 403,\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call AuthService.getAuthenticatedUser without setting up authentication\"\n );\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\") &&\n req?.headers?.authorization.split?.(\" \")?.[1]\n )\n token = req?.headers?.authorization.split(\" \")[1];\n\n if (\n !token &&\n req?.cookies?.arkos_access_token !== \"no-token\" &&\n req.cookies\n ) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) return null;\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 \"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 \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware to authenticate the request by extracting and verifying the JWT token and setting `req.user`.\n *\n * Runs `authentication.hooks.authenticate` before/after the authentication logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — extracts and verifies the JWT token, sets `req.user`.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if core logic throws — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * On custom routes, hooks defined in `arkosConfig` still apply since they are baked into this method.\n *\n * @example\n * ```ts\n * // custom route - hooks still run\n * router.get(\"/custom\", authService.authenticate, handler);\n * ```\n *\n * @example\n * ```ts\n * // skip built-in auth from a before hook\n * before: (ctx) => {\n * ctx.req.user = myCustomAuth(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authenticate;\n\n const before = await this.runHooks(hooks?.before, req);\n if (before.error) {\n const onError = await this.runErrorHooks(\n hooks?.onError,\n before.error,\n req\n );\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n\n if (!before.skipped) {\n try {\n if (isAuthenticationEnabled()) {\n const user = (await this.getAuthenticatedUser(req)) as User;\n if (!user) throw loginRequiredError;\n req.user = user;\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req);\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req);\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req);\n if (after.error) return next(after.error);\n\n next();\n }\n );\n\n /**\n * Middleware to authorize the authenticated user for a given action on a resource.\n *\n * Runs `authentication.hooks.authorize` before/after the authorization logic.\n *\n * Hook execution flow:\n * - `before` hooks run first — call `ctx.skip()` to bypass core logic and jump to `after` hooks,\n * call `ctx.next()` to stop the chain early, or return without calling anything to continue.\n * - Core logic runs — checks user role/permissions against the access control rules.\n * - `after` hooks run — call `ctx.next(err)` to abort or return without calling anything to continue.\n * - `onError` hooks run if authorization fails — call `ctx.skip()` to suppress the error and jump to\n * `after` hooks, or call `ctx.next(err)` to forward it to the global error handler.\n *\n * @param resource - The resource being accessed, in kebabCase (e.g. `\"product\"`, `\"cart-item\"`)\n * @param action - The action being performed (e.g. `\"View\"`, `\"Create\"`, `\"Delete\"`)\n * @param rule - Access control rules for this action. Accepts a role list, a wildcard, or a `DetailedAccessControlRule`.\n *\n * @example\n * ```ts\n * router.delete(\"/products/:id\",\n * authService.authenticate,\n * authService.authorize(\"product\", \"Delete\", [\"admin\"]),\n * handler\n * );\n * ```\n *\n * @example\n * ```ts\n * // skip built-in authorization from a before hook\n * before: (ctx) => {\n * ctx.req.user.role = myCustomRoleResolver(ctx.req);\n * ctx.skip();\n * }\n * ```\n *\n * @see {@link https://www.arkosjs.com/docs/core-concepts/authentication/hooks#authorize}\n * @since v1.6.0-beta\n */\n authorize(\n action: AccessAction,\n resource: string,\n rule?: string[] | DetailedAccessControlRule | \"*\"\n ): ArkosRequestHandler {\n const authAction = authActionService.add(action, resource, {\n [action]: rule,\n });\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n const hooks = getArkosConfig()?.authentication?.hooks?.authorize;\n\n const before = await this.runHooks(hooks?.before, req, {\n action,\n resource,\n rule,\n });\n if (before.error) {\n const onError = await this.runErrorHooks(\n hooks?.onError,\n before.error,\n req,\n { action, resource, rule }\n );\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n\n if (!before.skipped) {\n try {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (!user.isSuperUser) {\n const notEnoughPermissionsError = new AppError(\n authAction.errorMessage,\n 403,\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n } else if (configs?.authentication?.mode === \"static\") {\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n { [action]: rule }\n );\n if (!hasPermission) throw notEnoughPermissionsError;\n }\n }\n }\n } catch (err) {\n const onError = await this.runErrorHooks(hooks?.onError, err, req, {\n action,\n resource,\n rule,\n });\n if (onError.skipped) {\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n return after.error ? next(after.error) : next();\n }\n return next(onError.error);\n }\n }\n\n const after = await this.runAfterHooks(hooks?.after, req, {\n action,\n resource,\n rule,\n });\n if (after.error) return next(after.error);\n\n next();\n }\n );\n }\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n *\n * @deprecated Will be removed on v2.0, use AuthService.authenticate instead\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: User | undefined): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n\n if (!isUsingAuthentication())\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!isAuthenticationEnabled()) return false;\n if (!user) throw loginRequiredError;\n if (user?.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n 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"]}
|
|
@@ -12,7 +12,7 @@ class AuthActionService {
|
|
|
12
12
|
resource: "auth-action",
|
|
13
13
|
name: "View auth action",
|
|
14
14
|
description: "View an auth action",
|
|
15
|
-
errorMessage: "You
|
|
15
|
+
errorMessage: "You cannot perform view for auth action",
|
|
16
16
|
},
|
|
17
17
|
];
|
|
18
18
|
}
|
|
@@ -23,7 +23,7 @@ class AuthActionService {
|
|
|
23
23
|
const inconsistencies = [];
|
|
24
24
|
const defaultName = `${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(action).replace(/-/g, " "))} ${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(resource).replace(/-/g, " "))}`;
|
|
25
25
|
const defaultDescription = `${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(action).replace(/-/g, " "))} ${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(resource).replace(/-/g, " "))}`;
|
|
26
|
-
const defaultErrorMessage =
|
|
26
|
+
const defaultErrorMessage = `You cannot perform ${(0, utils_1.sentenceCase)(action).toLowerCase()} for ${(0, utils_1.sentenceCase)(resource).toLowerCase()}`;
|
|
27
27
|
const isNonDefault = (value, defaultValue) => {
|
|
28
28
|
return value !== undefined && value !== defaultValue;
|
|
29
29
|
};
|
|
@@ -67,12 +67,14 @@ class AuthActionService {
|
|
|
67
67
|
};
|
|
68
68
|
this.remove(action, resource);
|
|
69
69
|
this.authActions.push(merged);
|
|
70
|
+
return merged;
|
|
70
71
|
}
|
|
71
72
|
else {
|
|
72
73
|
if (transformedAction.roles) {
|
|
73
74
|
transformedAction.roles = [...transformedAction.roles].sort();
|
|
74
75
|
}
|
|
75
76
|
this.authActions.push(transformedAction);
|
|
77
|
+
return transformedAction;
|
|
76
78
|
}
|
|
77
79
|
}
|
|
78
80
|
remove(action, resource) {
|
|
@@ -100,7 +102,7 @@ class AuthActionService {
|
|
|
100
102
|
resource,
|
|
101
103
|
name: `${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(action).replace(/-/g, " "))} ${(0, text_helpers_1.capitalize)((0, utils_1.kebabCase)(resource).replace(/-/g, " "))}`,
|
|
102
104
|
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, " "))}`,
|
|
103
|
-
errorMessage: `You
|
|
105
|
+
errorMessage: `You cannot perform ${(0, utils_1.sentenceCase)(action).toLowerCase()} for ${(0, utils_1.sentenceCase)(resource).toLowerCase()}`,
|
|
104
106
|
};
|
|
105
107
|
const config = (0, arkos_config_helpers_1.getArkosConfig)();
|
|
106
108
|
if (config?.authentication?.mode === "dynamic")
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"auth-action.service.js","sourceRoot":"","sources":["../../../../../../src/modules/auth/utils/services/auth-action.service.ts"],"names":[],"mappings":";;AAAA,qDAAsD;AAKtD,yFAAgF;AAChF,yEAAoE;AAWpE,MAAM,iBAAiB;IAAvB;QACE,gBAAW,GAAiB;YAC1B;gBACE,KAAK,EAAE,EAAE;gBACT,MAAM,EAAE,MAAM;gBACd,QAAQ,EAAE,aAAa;gBACvB,IAAI,EAAE,kBAAkB;gBACxB,WAAW,EAAE,qBAAqB;gBAClC,YAAY,EAAE,sDAAsD;aACrE;SACF,CAAC;IAoMJ,CAAC;IAlMC,GAAG,CAAC,MAAc,EAAE,QAAgB,EAAE,aAAmC;QACvE,MAAM,iBAAiB,GAAG,IAAI,CAAC,uCAAuC,CACpE,MAAM,EACN,QAAQ,EACR,aAAa,CACd,CAAC;QACF,MAAM,kBAAkB,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAEzD,IAAI,kBAAkB,EAAE,CAAC;YACvB,MAAM,e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,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 { capitalize } from \"../../../../utils/helpers/text.helpers\";\n\ninterface AuthAction {\n roles?: string[] | \"*\";\n action: string;\n resource: string;\n name?: string;\n description?: string;\n errorMessage?: string;\n}\n\nclass AuthActionService {\n authActions: AuthAction[] = [\n {\n roles: [],\n action: \"View\",\n resource: \"auth-action\",\n name: \"View auth action\",\n description: \"View an auth action\",\n errorMessage: \"You do not have permission to perform this operation\",\n },\n ];\n\n add(action: string, resource: string, accessControl?: AccessControlConfig) {\n const transformedAction = this.transformAccessControlToValidAuthAction(\n action,\n resource,\n accessControl\n );\n const existingAuthAction = this.getOne(action, resource);\n\n if (existingAuthAction) {\n const inconsistencies: string[] = [];\n\n const defaultName = `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`;\n const defaultDescription = `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`;\n const defaultErrorMessage =\n \"You do not have permission to perform this operation\";\n\n const isNonDefault = (\n value: string | undefined,\n defaultValue: string\n ): boolean => {\n return value !== undefined && value !== defaultValue;\n };\n\n if (\n isNonDefault(existingAuthAction.name, defaultName) &&\n isNonDefault(transformedAction.name, defaultName) &&\n existingAuthAction.name !== transformedAction.name\n ) {\n inconsistencies.push(\n ` - name: \"${existingAuthAction.name}\" vs \"${transformedAction.name}\"`\n );\n }\n\n if (\n isNonDefault(existingAuthAction.description, defaultDescription) &&\n isNonDefault(transformedAction.description, defaultDescription) &&\n existingAuthAction.description !== transformedAction.description\n ) {\n inconsistencies.push(\n ` - description: \"${existingAuthAction.description}\" vs \"${transformedAction.description}\"`\n );\n }\n\n if (\n isNonDefault(existingAuthAction.errorMessage, defaultErrorMessage) &&\n isNonDefault(transformedAction.errorMessage, defaultErrorMessage) &&\n existingAuthAction.errorMessage !== transformedAction.errorMessage\n ) {\n inconsistencies.push(\n ` - errorMessage: \"${existingAuthAction.errorMessage}\" vs \"${transformedAction.errorMessage}\"`\n );\n }\n if (inconsistencies.length > 0) {\n throw new Error(\n `Inconsistent metadata for permission \"${action}:${resource}\". ` +\n `The same action+resource combination is being defined with different values:\\n` +\n inconsistencies.join(\"\\n\") +\n `\\n\\nPlease ensure all definitions of \"${action}:${resource}\" have the same name, description, and errorMessage values.`\n );\n }\n\n const mergedRoles =\n existingAuthAction.roles || transformedAction.roles\n ? [\n ...(existingAuthAction.roles || []),\n ...(transformedAction.roles || []),\n ]\n : undefined;\n\n const uniqueRoles = mergedRoles\n ? [...new Set(mergedRoles)].sort()\n : undefined;\n\n const merged: AuthAction = {\n action: existingAuthAction.action,\n resource: existingAuthAction.resource,\n roles: uniqueRoles,\n name: existingAuthAction.name ?? transformedAction.name,\n description:\n existingAuthAction.description ?? transformedAction.description,\n errorMessage:\n existingAuthAction.errorMessage ?? transformedAction.errorMessage,\n };\n\n this.remove(action, resource);\n this.authActions.push(merged);\n } else {\n if (transformedAction.roles) {\n transformedAction.roles = [...transformedAction.roles].sort();\n }\n this.authActions.push(transformedAction);\n }\n }\n\n remove(action: string, resource: string) {\n this.authActions = this.authActions.filter(\n (authAction) =>\n !(authAction.action === action && authAction.resource === resource)\n );\n }\n\n getAll(): AuthAction[] {\n return this.authActions;\n }\n\n getOne(action: string, resource: string): AuthAction | undefined {\n return this.authActions.find(\n (authAction) =>\n authAction.action === action && authAction.resource === resource\n );\n }\n\n private transformAccessControlToValidAuthAction(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ): AuthAction {\n const baseAuthAction: AuthAction = {\n roles:\n (accessControl &&\n (Array.isArray(accessControl)\n ? accessControl\n : typeof accessControl === \"string\"\n ? [accessControl]\n : Array.isArray(accessControl?.[action] || {})\n ? (accessControl[action] as string[])\n : (accessControl[action] as DetailedAccessControlRule)\n ?.roles)) ||\n [],\n action,\n resource,\n name: `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`,\n description: `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`,\n errorMessage: `You do not have permission to perform this operation`,\n };\n\n const config = getArkosConfig();\n\n if (config?.authentication?.mode === \"dynamic\") delete baseAuthAction.roles;\n\n if (!accessControl) return baseAuthAction;\n\n if (Array.isArray(accessControl)) return baseAuthAction;\n\n const actionRule =\n (accessControl as any) !== \"*\"\n ? (accessControl as any)[action]\n : undefined;\n\n if (config?.authentication?.mode !== \"static\") delete baseAuthAction.roles;\n\n if (actionRule) {\n if (Array.isArray(actionRule)) {\n return baseAuthAction;\n } else if (typeof actionRule === \"object\") {\n return {\n ...baseAuthAction,\n name: actionRule.name || baseAuthAction.name,\n description: actionRule?.description || baseAuthAction.description,\n errorMessage: actionRule?.errorMessage || baseAuthAction.errorMessage,\n };\n }\n }\n\n return baseAuthAction;\n }\n\n getUniqueActions(): string[] {\n return [\n ...new Set(this.authActions.map((authAction) => authAction.action)),\n ];\n }\n\n getUniqueResources(): string[] {\n return [\n ...new Set(this.authActions.map((authAction) => authAction.resource)),\n ];\n }\n\n getByResource(resource: string): AuthAction[] | undefined {\n return this.authActions.filter(\n (authAction) => authAction.resource === resource\n );\n }\n\n getByAction(action: string): AuthAction[] {\n return this.authActions.filter(\n (authAction) => authAction.action === action\n );\n }\n\n exists(action: string, resource: string): boolean {\n return !!this.getOne(action, resource);\n }\n}\n\nconst authActionService = new AuthActionService();\n\nexport default authActionService;\n"]}
|
|
1
|
+
{"version":3,"file":"auth-action.service.js","sourceRoot":"","sources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AAE,UAAU,EAAE,WAAW,IAAI,cAAc,CAAC,WAAW;oBAClE,YAAY,EAAE,UAAU,EAAE,YAAY,IAAI,cAAc,CAAC,YAAY;iBACtE,CAAC;YACJ,CAAC;QACH,CAAC;QAED,OAAO,cAAc,CAAC;IACxB,CAAC;IAED,gBAAgB;QACd,OAAO;YACL,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;SACpE,CAAC;IACJ,CAAC;IAED,kBAAkB;QAChB,OAAO;YACL,GAAG,IAAI,GAAG,CAAC,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC;SACtE,CAAC;IACJ,CAAC;IAED,aAAa,CAAC,QAAgB;QAC5B,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAC5B,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,KAAK,QAAQ,CACjD,CAAC;IACJ,CAAC;IAED,WAAW,CAAC,MAAc;QACxB,OAAO,IAAI,CAAC,WAAW,CAAC,MAAM,CAC5B,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,KAAK,MAAM,CAC7C,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,MAAc,EAAE,QAAgB;QACrC,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACzC,CAAC;CACF;AAED,MAAM,iBAAiB,GAAG,IAAI,iBAAiB,EAAE,CAAC;AAElD,kBAAe,iBAAiB,CAAC","sourcesContent":["import { kebabCase, sentenceCase } from \"../../../../exports/utils\";\nimport {\n AccessControlConfig,\n DetailedAccessControlRule,\n} from \"../../../../types/auth\";\nimport { getArkosConfig } from \"../../../../utils/helpers/arkos-config.helpers\";\nimport { capitalize } from \"../../../../utils/helpers/text.helpers\";\n\ninterface AuthAction {\n roles?: string[] | \"*\";\n action: string;\n resource: string;\n name?: string;\n description?: string;\n errorMessage?: string;\n}\n\nclass AuthActionService {\n authActions: AuthAction[] = [\n {\n roles: [],\n action: \"View\",\n resource: \"auth-action\",\n name: \"View auth action\",\n description: \"View an auth action\",\n errorMessage: \"You cannot perform view for auth action\",\n },\n ];\n\n add(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ): Required<AuthAction> {\n const transformedAction = this.transformAccessControlToValidAuthAction(\n action,\n resource,\n accessControl\n );\n const existingAuthAction = this.getOne(action, resource);\n\n if (existingAuthAction) {\n const inconsistencies: string[] = [];\n\n const defaultName = `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`;\n const defaultDescription = `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`;\n const defaultErrorMessage = `You cannot perform ${sentenceCase(action).toLowerCase()} for ${sentenceCase(resource).toLowerCase()}`;\n\n const isNonDefault = (\n value: string | undefined,\n defaultValue: string\n ): boolean => {\n return value !== undefined && value !== defaultValue;\n };\n\n if (\n isNonDefault(existingAuthAction.name, defaultName) &&\n isNonDefault(transformedAction.name, defaultName) &&\n existingAuthAction.name !== transformedAction.name\n ) {\n inconsistencies.push(\n ` - name: \"${existingAuthAction.name}\" vs \"${transformedAction.name}\"`\n );\n }\n\n if (\n isNonDefault(existingAuthAction.description, defaultDescription) &&\n isNonDefault(transformedAction.description, defaultDescription) &&\n existingAuthAction.description !== transformedAction.description\n ) {\n inconsistencies.push(\n ` - description: \"${existingAuthAction.description}\" vs \"${transformedAction.description}\"`\n );\n }\n\n if (\n isNonDefault(existingAuthAction.errorMessage, defaultErrorMessage) &&\n isNonDefault(transformedAction.errorMessage, defaultErrorMessage) &&\n existingAuthAction.errorMessage !== transformedAction.errorMessage\n ) {\n inconsistencies.push(\n ` - errorMessage: \"${existingAuthAction.errorMessage}\" vs \"${transformedAction.errorMessage}\"`\n );\n }\n if (inconsistencies.length > 0) {\n throw new Error(\n `Inconsistent metadata for permission \"${action}:${resource}\". ` +\n `The same action+resource combination is being defined with different values:\\n` +\n inconsistencies.join(\"\\n\") +\n `\\n\\nPlease ensure all definitions of \"${action}:${resource}\" have the same name, description, and errorMessage values.`\n );\n }\n\n const mergedRoles =\n existingAuthAction.roles || transformedAction.roles\n ? [\n ...(existingAuthAction.roles || []),\n ...(transformedAction.roles || []),\n ]\n : undefined;\n\n const uniqueRoles = mergedRoles\n ? [...new Set(mergedRoles)].sort()\n : undefined;\n\n const merged: Required<AuthAction> = {\n action: existingAuthAction.action,\n resource: existingAuthAction.resource,\n roles: uniqueRoles,\n name: existingAuthAction.name ?? transformedAction.name,\n description:\n existingAuthAction.description ?? transformedAction.description,\n errorMessage:\n existingAuthAction.errorMessage ?? transformedAction.errorMessage,\n } as any;\n\n this.remove(action, resource);\n this.authActions.push(merged);\n return merged;\n } else {\n if (transformedAction.roles) {\n transformedAction.roles = [...transformedAction.roles].sort();\n }\n this.authActions.push(transformedAction);\n return transformedAction;\n }\n }\n\n remove(action: string, resource: string) {\n this.authActions = this.authActions.filter(\n (authAction) =>\n !(authAction.action === action && authAction.resource === resource)\n );\n }\n\n getAll(): AuthAction[] {\n return this.authActions;\n }\n\n getOne(action: string, resource: string): AuthAction | undefined {\n return this.authActions.find(\n (authAction) =>\n authAction.action === action && authAction.resource === resource\n );\n }\n\n private transformAccessControlToValidAuthAction(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ): Required<AuthAction> {\n const baseAuthAction: Required<AuthAction> = {\n roles:\n (accessControl &&\n (Array.isArray(accessControl)\n ? accessControl\n : typeof accessControl === \"string\"\n ? [accessControl]\n : Array.isArray(accessControl?.[action] || {})\n ? (accessControl[action] as string[])\n : (accessControl[action] as DetailedAccessControlRule)\n ?.roles)) ||\n [],\n action,\n resource,\n name: `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`,\n description: `${capitalize(kebabCase(action).replace(/-/g, \" \"))} ${capitalize(kebabCase(resource).replace(/-/g, \" \"))}`,\n errorMessage: `You cannot perform ${sentenceCase(action).toLowerCase()} for ${sentenceCase(resource).toLowerCase()}`,\n };\n\n const config = getArkosConfig();\n\n if (config?.authentication?.mode === \"dynamic\")\n delete (baseAuthAction as any).roles;\n\n if (!accessControl) return baseAuthAction;\n\n if (Array.isArray(accessControl)) return baseAuthAction;\n\n const actionRule =\n (accessControl as any) !== \"*\"\n ? (accessControl as any)[action]\n : undefined;\n\n if (config?.authentication?.mode !== \"static\")\n delete (baseAuthAction as any).roles;\n\n if (actionRule) {\n if (Array.isArray(actionRule)) {\n return baseAuthAction;\n } else if (typeof actionRule === \"object\") {\n return {\n ...baseAuthAction,\n name: actionRule.name || baseAuthAction.name,\n description: actionRule?.description || baseAuthAction.description,\n errorMessage: actionRule?.errorMessage || baseAuthAction.errorMessage,\n };\n }\n }\n\n return baseAuthAction;\n }\n\n getUniqueActions(): string[] {\n return [\n ...new Set(this.authActions.map((authAction) => authAction.action)),\n ];\n }\n\n getUniqueResources(): string[] {\n return [\n ...new Set(this.authActions.map((authAction) => authAction.resource)),\n ];\n }\n\n getByResource(resource: string): AuthAction[] | undefined {\n return this.authActions.filter(\n (authAction) => authAction.resource === resource\n );\n }\n\n getByAction(action: string): AuthAction[] {\n return this.authActions.filter(\n (authAction) => authAction.action === action\n );\n }\n\n exists(action: string, resource: string): boolean {\n return !!this.getOne(action, resource);\n }\n}\n\nconst authActionService = new AuthActionService();\n\nexport default authActionService;\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../../../src/modules/email/email.service.ts"],"names":[],"mappings":";;;;;;AAAA,4DAAsE;AACtE,+CAAuC;AACvC,yCAA8C;AAC9C,iFAAwD;AAiCxD,MAAa,YAAY;IAUvB,YAAY,MAA8B;QAT1C,gBAAW,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\"nodemailer\";\nimport { convert } from \"html-to-text\";\nimport { getArkosConfig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n subject: string;\n} & SendMailOptions;\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/reference/the-email-service-class](https://www.arkosjs.com/docs/reference/the-email-service-class)\n */\nexport class EmailService {\n transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host || !user || !pass) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST, EMAIL_USER, EMAIL_PASSWORD)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/guides/email-service\",\n }\n );\n }\n\n return {\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth: {\n user,\n pass,\n },\n name,\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) {\n const { name, ...config } = customConfig;\n return nodemailer.createTransport(config);\n }\n\n if (!this.transporter) {\n const { name, ...config } = this.getEmailConfig() || {};\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string } & Record<string, any>>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions & SendMailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification: boolean = true\n ): Promise<{ success: boolean; messageId?: string } & Record<string, any>> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress,\n text:\n options?.text ||\n (typeof options.html === \"string\" && options.html\n ? convert(options.html as string)\n : undefined),\n });\n\n return { success: true, ...info };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}
|
|
1
|
+
{"version":3,"file":"email.service.js","sourceRoot":"","sources":["../../../../src/modules/email/email.service.ts"],"names":[],"mappings":";;;;;;AAAA,4DAAsE;AACtE,+CAAuC;AACvC,yCAA8C;AAC9C,iFAAwD;AAiCxD,MAAa,YAAY;IAUvB,YAAY,MAA8B;QAT1C,gBAAW,GAAuB,IAAI,CAAC;QAC/B,iBAAY,GAAiC,IAAI,CAAC;QASxD,IAAI,MAAM,EAAE,CAAC;YACX,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC7B,CAAC;IACH,CAAC;IAUO,cAAc;QACpB,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,OAAO,IAAI,CAAC,YAAY,CAAC;QAC3B,CAAC;QAED,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;QACjD,MAAM,IAAI,GAAG,YAAY,EAAE,IAAI,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,CAAC;QAC1D,MAAM,IAAI,GACR,YAAY,EAAE,IAAI;YAClB,CAAC,OAAO,CAAC,GAAG,CAAC,UA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AAE,OAAO,EAAE,IAAI,EAAE,GAAG,IAAI,EAAE,CAAC;IACpC,CAAC;IAOM,KAAK,CAAC,gBAAgB,CAC3B,mBAAiC;QAEjC,IAAI,CAAC;YACH,MAAM,WAAW,GAAG,mBAAmB,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACjE,MAAM,WAAW,CAAC,MAAM,EAAE,CAAC;YAC3B,OAAO,IAAI,CAAC;QACd,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,gCAAgC,EAAE,KAAK,CAAC,CAAC;YACvD,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAMM,YAAY,CAAC,MAA6B;QAC/C,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;IAC1B,CAAC;IAOM,MAAM,CAAC,MAAM,CAAC,MAA6B;QAChD,OAAO,IAAI,YAAY,CAAC,MAAM,CAAC,CAAC;IAClC,CAAC;CACF;AAjKD,oCAiKC;AAED,MAAM,YAAY,GAAG,IAAI,YAAY,EAAE,CAAC;AAExC,kBAAe,YAAY,CAAC","sourcesContent":["import nodemailer, { SendMailOptions, Transporter } from \"nodemailer\";\nimport { convert } from \"html-to-text\";\nimport { getArkosConfig } from \"../../server\";\nimport AppError from \"../error-handler/utils/app-error\";\n\n/**\n * Defines the options for sending an email.\n */\nexport type EmailOptions = {\n subject: string;\n} & SendMailOptions;\n\n/**\n * Defines the authentication options for SMTP.\n */\nexport type SMTPAuthOptions = {\n user: string;\n pass: string;\n};\n\n/**\n * Defines the connection options for SMTP server.\n */\nexport type SMTPConnectionOptions = {\n host?: string;\n port?: number;\n secure?: boolean;\n auth?: SMTPAuthOptions;\n name?: string;\n};\n\n/**\n * A service class to handle email-related tasks, including sending emails.\n *\n * See the api reference [www.arkosjs.com/docs/reference/the-email-service-class](https://www.arkosjs.com/docs/reference/the-email-service-class)\n */\nexport class EmailService {\n transporter: Transporter | null = null;\n private customConfig: SMTPConnectionOptions | null = null;\n\n /**\n * Creates an instance of the EmailService class.\n *\n * @param {SMTPConnectionOptions} [config] - Optional custom SMTP configuration.\n * If provided, these settings will be used instead of the Arkos config.\n */\n constructor(config?: SMTPConnectionOptions) {\n if (config) {\n this.customConfig = config;\n }\n }\n\n /**\n * Gets the email configuration from multiple sources with priority:\n * 1. Constructor customConfig\n * 2. ArkosConfig\n * 3. Environment variables\n * @returns Configuration object with host, port, and auth details\n * @throws AppError if required email configuration is not set\n */\n private getEmailConfig(): SMTPConnectionOptions {\n if (this.customConfig) {\n return this.customConfig;\n }\n\n const { email: emailConfigs } = getArkosConfig();\n const host = emailConfigs?.host || process.env.EMAIL_HOST;\n const port =\n emailConfigs?.port ||\n (process.env.EMAIL_PORT ? parseInt(process.env.EMAIL_PORT) : undefined);\n const secure =\n emailConfigs?.secure !== undefined\n ? emailConfigs.secure\n : process.env.EMAIL_SECURE\n ? process.env.EMAIL_SECURE === \"true\"\n : undefined;\n const user = emailConfigs?.auth?.user || process.env.EMAIL_USER;\n const pass = emailConfigs?.auth?.pass || process.env.EMAIL_PASSWORD;\n const name = emailConfigs?.name || process.env.EMAIL_NAME;\n\n if (!host || !user || !pass) {\n throw new AppError(\n \"You are trying to use emailService without setting email configurations. \" +\n \"Please configure either arkosConfig.email or environment variables (EMAIL_HOST, EMAIL_USER, EMAIL_PASSWORD)\",\n 500,\n {\n docs: \"Read more about emailService at https://www.arkosjs.com/docs/guides/email-service\",\n }\n );\n }\n\n return {\n ...emailConfigs,\n host,\n port: port || 465,\n secure: secure !== undefined ? secure : true,\n auth: {\n user,\n pass,\n },\n name,\n };\n }\n\n /**\n * Gets or creates a transporter using the email configuration\n * @param customConfig Optional override connection settings (takes full priority if provided)\n * @returns A configured nodemailer transporter\n */\n private getTransporter(customConfig?: SMTPConnectionOptions): Transporter {\n if (customConfig) {\n const { name, ...config } = customConfig;\n return nodemailer.createTransport(config);\n }\n\n if (!this.transporter) {\n const { name, ...config } = this.getEmailConfig() || {};\n this.transporter = nodemailer.createTransport(config);\n }\n return this.transporter;\n }\n\n /**\n * Sends an email with the provided options.\n * Can use either the default configuration or custom connection options.\n *\n * @param {EmailOptions} options - The options for the email to be sent.\n * @param {SMTPConnectionOptions} [connectionOptions] - Optional custom connection settings.\n * @param {boolean} [skipVerification=false] - Whether to skip connection verification.\n * @returns {Promise<{ success: boolean; messageId?: string } & Record<string, any>>} Result with message ID on success.\n */\n public async send(\n options: EmailOptions & SendMailOptions,\n connectionOptions?: SMTPConnectionOptions,\n skipVerification: boolean = true\n ): Promise<{ success: boolean; messageId?: string } & Record<string, any>> {\n const config = this.getEmailConfig();\n const transporter = connectionOptions\n ? this.getTransporter(connectionOptions)\n : this.getTransporter();\n\n const fromAddress =\n options.from || connectionOptions?.auth?.user || config.auth?.user;\n\n if (connectionOptions || !skipVerification) {\n const isConnected = await this.verifyConnection(transporter);\n if (!isConnected) throw new Error(\"Failed to connect to email server\");\n }\n\n const info = await transporter.sendMail({\n ...options,\n from: fromAddress,\n text:\n options?.text ||\n (typeof options.html === \"string\" && options.html\n ? convert(options.html as string)\n : undefined),\n });\n\n return { success: true, ...info };\n }\n\n /**\n * Verifies the connection to the email server.\n * @param {Transporter} [transporterToVerify] - Optional transporter to verify.\n * @returns {Promise<boolean>} A promise that resolves to true if connection is valid.\n */\n public async verifyConnection(\n transporterToVerify?: Transporter\n ): Promise<boolean> {\n try {\n const transporter = transporterToVerify || this.getTransporter();\n await transporter.verify();\n return true;\n } catch (error) {\n console.error(\"Email Server Connection Failed\", error);\n return false;\n }\n }\n\n /**\n * Updates the custom configuration for this email service instance.\n * @param {SMTPConnectionOptions} config - The new connection options.\n */\n public updateConfig(config: SMTPConnectionOptions): void {\n this.customConfig = config;\n this.transporter = null; // Reset transporter so it will be recreated with new config\n }\n\n /**\n * Creates a new instance of EmailService with custom configuration.\n * @param {SMTPConnectionOptions} config - The connection options for the new instance.\n * @returns {EmailService} A new EmailService instance.\n */\n public static create(config: SMTPConnectionOptions): EmailService {\n return new EmailService(config);\n }\n}\n\nconst emailService = new EmailService();\n\nexport default emailService;\n"]}
|
|
@@ -14,6 +14,7 @@ const deepmerge_helper_1 = __importDefault(require("../../utils/helpers/deepmerg
|
|
|
14
14
|
const auth_service_1 = __importDefault(require("../auth/auth.service.js"));
|
|
15
15
|
const app_error_1 = __importDefault(require("../error-handler/utils/app-error.js"));
|
|
16
16
|
const get_open_api_login_html_1 = __importDefault(require("./utils/get-open-api-login-html.js"));
|
|
17
|
+
const arkos_config_helpers_1 = require("../../utils/helpers/arkos-config.helpers.js");
|
|
17
18
|
const swaggerRouter = (0, express_1.Router)();
|
|
18
19
|
function getSwaggerRouter(arkosConfig, app) {
|
|
19
20
|
const pathsFromCustomArkosRouters = (0, arkos_router_1.generateOpenAPIFromApp)(app);
|
|
@@ -22,7 +23,9 @@ function getSwaggerRouter(arkosConfig, app) {
|
|
|
22
23
|
...getSystemJsonSchemaPaths(),
|
|
23
24
|
});
|
|
24
25
|
const swaggerConfigs = (0, deepmerge_helper_1.default)(defaultSwaggerConfig, arkosConfig.swagger || {});
|
|
25
|
-
if (arkosConfig.swagger?.options?.definition?.servers &&
|
|
26
|
+
if (arkosConfig.swagger?.options?.definition?.servers &&
|
|
27
|
+
swaggerConfigs &&
|
|
28
|
+
(0, arkos_config_helpers_1.isProduction)()) {
|
|
26
29
|
swaggerConfigs.options.definition.servers =
|
|
27
30
|
arkosConfig.swagger.options.definition.servers;
|
|
28
31
|
swaggerConfigs.options.definition.servers.push(defaultSwaggerConfig.options.definition.servers[0]);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"swagger.router.js","sourceRoot":"","sources":["../../../../src/modules/swagger/swagger.router.ts"],"names":[],"mappings":";;;;;AAqBA,4CAkGC;AAED,4CA2BC;AApJD,qCAAiC;AAC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AAE;gCACN,IAAI,EAAE,QAAQ;gCACd,UAAU,EAAE;oCACV,IAAI,EAAE;wCACJ,IAAI,EAAE,OAAO;wCACb,KAAK,EAAE;4CACL,IAAI,EAAE,QAAQ;yCACf;wCACD,WAAW,EAAE,uCAAuC;qCACrD;iCACF;6BACF;yBACF;qBACF;iBACF;aACF;SACF;KACF,CAAC;IAEF,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["import { Router } from \"express\";\nimport swaggerJsdoc from \"swagger-jsdoc\";\nimport getSwaggerDefaultConfig from \"./utils/helpers/get-swagger-default-configs\";\nimport { importEsmPreventingTsTransformation } from \"../../utils/helpers/global.helpers\";\nimport { generateOpenAPIFromApp } from \"../../utils/arkos-router\";\nimport {\n ArkosConfig,\n ArkosNextFunction,\n ArkosRequest,\n ArkosResponse,\n} from \"../../exports\";\nimport deepmerge from \"../../utils/helpers/deepmerge.helper\";\nimport authService from \"../auth/auth.service\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport getOpenApiLoginHtml from \"./utils/get-open-api-login-html\";\nimport { Arkos } from \"../../types/arkos\";\nimport { OpenAPIV3 } from \"openapi-types\";\nimport { isProduction } from \"../../utils/helpers/arkos-config.helpers\";\n\nconst swaggerRouter = Router();\n\nexport function getSwaggerRouter(arkosConfig: ArkosConfig, app: Arkos): Router {\n const pathsFromCustomArkosRouters = generateOpenAPIFromApp(app);\n const defaultSwaggerConfig = getSwaggerDefaultConfig({\n ...pathsFromCustomArkosRouters,\n ...getSystemJsonSchemaPaths(),\n })!;\n\n const swaggerConfigs = deepmerge(\n defaultSwaggerConfig,\n arkosConfig.swagger || {}\n ) as ArkosConfig[\"swagger\"];\n\n if (\n arkosConfig.swagger?.options?.definition?.servers &&\n swaggerConfigs &&\n isProduction()\n ) {\n swaggerConfigs!.options!.definition!.servers =\n arkosConfig.swagger.options.definition.servers;\n\n swaggerConfigs!.options!.definition!.servers.push(\n defaultSwaggerConfig.options.definition.servers[0]\n );\n }\n\n const { definition, ...options } = swaggerConfigs?.options!;\n const swaggerSpecification = swaggerJsdoc({\n definition: definition as swaggerJsdoc.SwaggerDefinition,\n ...options,\n });\n\n const endpoint = swaggerConfigs!.endpoint!;\n\n const swaggerAuth = arkosConfig?.swagger;\n const authenticate = swaggerAuth?.authenticate !== false;\n\n if (authenticate) {\n swaggerRouter.use(\n endpoint,\n (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.path.includes(\"/auth\")) return next();\n next(\"route\"); // skip to auth chain below\n }\n );\n\n swaggerRouter.use(\n endpoint,\n authService.authenticate,\n (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (!req.user?.isSuperUser)\n return next(\n new AppError(\n \"Only super users can access API documentation in production.\",\n 403,\n \"SuperUserRequired\"\n )\n );\n next();\n },\n (\n err: AppError,\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (req.path.includes(\"/auth\")) return next();\n const message = encodeURIComponent(\n err?.message || \"Authentication required.\"\n );\n return res.redirect(\n `${arkosConfig.globalPrefix}${endpoint}/auth/login?error-message=${message}`\n );\n }\n );\n }\n\n swaggerRouter.get(\n `${endpoint}/auth/login`,\n (_: ArkosRequest, res: ArkosResponse) => {\n res.send(getOpenApiLoginHtml());\n }\n );\n\n swaggerRouter.get(\n `${endpoint}/openapi.json`,\n (_: ArkosRequest, res: ArkosResponse) => {\n res.json(swaggerSpecification);\n }\n );\n\n let scalarHandler: any = null;\n\n swaggerRouter.use(\n endpoint,\n scalarMiddleware(scalarHandler, swaggerSpecification, swaggerConfigs)\n );\n\n return swaggerRouter;\n}\n\nexport function scalarMiddleware(\n scalarHandler: any,\n swaggerSpecification: object,\n swaggerConfigs: any\n) {\n let scalarLoading: Promise<void> | null = null;\n\n return async (\n req: ArkosRequest,\n res: ArkosResponse,\n next: ArkosNextFunction\n ) => {\n if (!scalarHandler) {\n if (!scalarLoading) {\n scalarLoading = importEsmPreventingTsTransformation(\n \"@scalar/express-api-reference\"\n ).then((scalar) => {\n scalarHandler = scalar.apiReference({\n content: swaggerSpecification,\n ...swaggerConfigs?.scalarApiReferenceConfiguration,\n });\n });\n }\n await scalarLoading;\n }\n return scalarHandler(req, res, next);\n };\n}\n\nfunction getSystemJsonSchemaPaths() {\n const paths: OpenAPIV3.PathsObject = {};\n\n paths[\"/api/available-resources\"] = {\n get: {\n tags: [\"System\"],\n summary: \"Get available resources\",\n description:\n \"Returns a comprehensive list of all available API resource endpoints\",\n operationId: \"getAvailableResources\",\n responses: {\n \"200\": {\n description: \"List of available resources retrieved successfully\",\n content: {\n \"application/json\": {\n schema: {\n type: \"object\",\n properties: {\n data: {\n type: \"array\",\n items: {\n type: \"string\",\n },\n description: \"Array of available resource endpoints\",\n },\n },\n },\n },\n },\n },\n },\n },\n };\n\n return paths;\n}\n"]}
|