arkos 1.4.11-beta → 1.4.13-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/dist/cjs/components/arkos-policy/index.js +38 -0
  2. package/dist/cjs/components/arkos-policy/index.js.map +1 -0
  3. package/dist/cjs/{types/arkos-prisma-input.bak.js → components/arkos-policy/types.js} +1 -1
  4. package/dist/cjs/components/arkos-policy/types.js.map +1 -0
  5. package/dist/cjs/exports/config.js +6 -0
  6. package/dist/cjs/exports/config.js.map +1 -0
  7. package/dist/cjs/modules/auth/auth.service.js +1 -1
  8. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  9. package/dist/cjs/modules/error-handler/error-handler.controller.js +1 -1
  10. package/dist/cjs/modules/error-handler/error-handler.controller.js.map +1 -1
  11. package/dist/cjs/modules/swagger/utils/get-open-api-login-html.js +288 -0
  12. package/dist/cjs/modules/swagger/utils/get-open-api-login-html.js.map +1 -0
  13. package/dist/cjs/types/arkos-config/utils.js +3 -0
  14. package/dist/cjs/types/arkos-config/utils.js.map +1 -0
  15. package/dist/cjs/types/arkos-prisma-input.js.map +1 -1
  16. package/dist/cjs/types/arkos.js +3 -0
  17. package/dist/cjs/types/arkos.js.map +1 -0
  18. package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +152 -0
  19. package/dist/cjs/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -0
  20. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  21. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +208 -0
  22. package/dist/cjs/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -1
  23. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-multiple-components.js +143 -39
  24. package/dist/cjs/utils/cli/utils/template-generator/templates/generate-multiple-components.js.map +1 -1
  25. package/dist/cjs/utils/cli/utils/template-generator/templates/policy-template.js +51 -0
  26. package/dist/cjs/utils/cli/utils/template-generator/templates/policy-template.js.map +1 -0
  27. package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js +169 -0
  28. package/dist/cjs/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -1
  29. package/dist/cjs/utils/features/api.features.js +0 -3
  30. package/dist/cjs/utils/features/api.features.js.map +1 -1
  31. package/dist/cjs/utils/helpers/api.features.helpers.js +20 -0
  32. package/dist/cjs/utils/helpers/api.features.helpers.js.map +1 -1
  33. package/dist/cjs/utils/helpers/exit-error.js +12 -0
  34. package/dist/cjs/utils/helpers/exit-error.js.map +1 -0
  35. package/dist/cjs/utils/helpers/prisma.helpers.js +1 -2
  36. package/dist/cjs/utils/helpers/prisma.helpers.js.map +1 -1
  37. package/dist/cjs/utils/initialize-app.js +52 -0
  38. package/dist/cjs/utils/initialize-app.js.map +1 -0
  39. package/dist/cjs/utils/setup-app.js +119 -0
  40. package/dist/cjs/utils/setup-app.js.map +1 -0
  41. package/dist/esm/components/arkos-policy/index.js +32 -0
  42. package/dist/esm/components/arkos-policy/index.js.map +1 -0
  43. package/dist/esm/components/arkos-policy/types.js +2 -0
  44. package/dist/esm/components/arkos-policy/types.js.map +1 -0
  45. package/dist/esm/exports/config.js +3 -0
  46. package/dist/esm/exports/config.js.map +1 -0
  47. package/dist/esm/modules/auth/auth.service.js +1 -1
  48. package/dist/esm/modules/auth/auth.service.js.map +1 -1
  49. package/dist/esm/modules/error-handler/error-handler.controller.js +1 -1
  50. package/dist/esm/modules/error-handler/error-handler.controller.js.map +1 -1
  51. package/dist/esm/modules/swagger/utils/get-open-api-login-html.js +285 -0
  52. package/dist/esm/modules/swagger/utils/get-open-api-login-html.js.map +1 -0
  53. package/dist/esm/types/arkos-config/utils.js +2 -0
  54. package/dist/esm/types/arkos-config/utils.js.map +1 -0
  55. package/dist/esm/types/arkos-prisma-input.js.map +1 -1
  56. package/dist/esm/types/arkos.js +2 -0
  57. package/dist/esm/types/arkos.js.map +1 -0
  58. package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js +146 -0
  59. package/dist/esm/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.js.map +1 -0
  60. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  61. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js +208 -0
  62. package/dist/esm/utils/cli/utils/template-generator/templates/class-validator-dto-generator.js.map +1 -1
  63. package/dist/esm/utils/cli/utils/template-generator/templates/generate-multiple-components.js +143 -39
  64. package/dist/esm/utils/cli/utils/template-generator/templates/generate-multiple-components.js.map +1 -1
  65. package/dist/esm/utils/cli/utils/template-generator/templates/policy-template.js +45 -0
  66. package/dist/esm/utils/cli/utils/template-generator/templates/policy-template.js.map +1 -0
  67. package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js +169 -0
  68. package/dist/esm/utils/cli/utils/template-generator/templates/zod-schema-generator.js.map +1 -1
  69. package/dist/esm/utils/features/api.features.js +0 -3
  70. package/dist/esm/utils/features/api.features.js.map +1 -1
  71. package/dist/esm/utils/helpers/api.features.helpers.js +20 -0
  72. package/dist/esm/utils/helpers/api.features.helpers.js.map +1 -1
  73. package/dist/esm/utils/helpers/exit-error.js +6 -0
  74. package/dist/esm/utils/helpers/exit-error.js.map +1 -0
  75. package/dist/esm/utils/helpers/prisma.helpers.js +1 -2
  76. package/dist/esm/utils/helpers/prisma.helpers.js.map +1 -1
  77. package/dist/esm/utils/initialize-app.js +45 -0
  78. package/dist/esm/utils/initialize-app.js.map +1 -0
  79. package/dist/esm/utils/setup-app.js +113 -0
  80. package/dist/esm/utils/setup-app.js.map +1 -0
  81. package/dist/types/components/arkos-policy/index.d.ts +31 -0
  82. package/dist/types/components/arkos-policy/types.d.ts +21 -0
  83. package/dist/types/exports/config.d.ts +2 -0
  84. package/dist/types/modules/swagger/utils/get-open-api-login-html.d.ts +1 -0
  85. package/dist/types/types/arkos-config/utils.d.ts +68 -0
  86. package/dist/types/types/arkos-prisma-input.d.ts +1 -1
  87. package/dist/types/types/arkos.d.ts +31 -0
  88. package/dist/types/utils/arkos-router/utils/helpers/apply-arkos-router-proxy.d.ts +7 -0
  89. package/dist/types/utils/cli/utils/template-generator/templates/class-validator-dto-generator.d.ts +4 -0
  90. package/dist/types/utils/cli/utils/template-generator/templates/policy-template.d.ts +2 -0
  91. package/dist/types/utils/cli/utils/template-generator/templates/zod-schema-generator.d.ts +4 -0
  92. package/dist/types/utils/helpers/exit-error.d.ts +1 -0
  93. package/dist/types/utils/initialize-app.d.ts +3 -0
  94. package/dist/types/utils/setup-app.d.ts +2 -0
  95. package/package.json +55 -55
  96. package/dist/cjs/types/arkos-prisma-input.bak.js.map +0 -1
  97. package/dist/esm/types/arkos-prisma-input.bak.js +0 -2
  98. package/dist/esm/types/arkos-prisma-input.bak.js.map +0 -1
  99. package/dist/types/types/arkos-prisma-input.bak.d.ts +0 -237
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.ArkosPolicy = ArkosPolicy;
7
+ const auth_service_1 = __importDefault(require("../../modules/auth/auth.service.js"));
8
+ function ArkosPolicy(resource) {
9
+ return buildPolicy(resource, {});
10
+ }
11
+ function buildPolicy(resource, store) {
12
+ const rule = (action, config) => {
13
+ const newStore = { ...store, [action]: config };
14
+ return buildPolicy(resource, newStore);
15
+ };
16
+ const actionEntries = Object.fromEntries(Object.entries(store).flatMap(([action, config]) => {
17
+ const authEntry = {
18
+ resource,
19
+ action,
20
+ rule: config,
21
+ };
22
+ const checker = auth_service_1.default.permission(action, resource, {
23
+ [action]: config || {},
24
+ });
25
+ const canKey = `can${action.charAt(0).toUpperCase()}${action.slice(1)}`;
26
+ return [
27
+ [action, authEntry],
28
+ [canKey, checker],
29
+ ];
30
+ }));
31
+ return {
32
+ __type: "ArkosPolicy",
33
+ resource,
34
+ rule,
35
+ ...actionEntries,
36
+ };
37
+ }
38
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../src/components/arkos-policy/index.ts"],"names":[],"mappings":";;;;;AAuCA,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 { User } from \"../../types\";\nimport {\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"]}
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=arkos-prisma-input.bak.js.map
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../../src/components/arkos-policy/types.ts"],"names":[],"mappings":"","sourcesContent":["import { User } from \"../../types\";\nimport { DetailedAccessControlRule } from \"../../types/auth\";\n\nexport type ArkosPolicyRule = string[] | DetailedAccessControlRule | \"*\";\n\nexport type PolicyAuthEntry<\n TResource extends string,\n TAction extends string,\n> = {\n readonly resource: TResource;\n readonly action: TAction;\n readonly rule: ArkosPolicyRule;\n};\n\nexport type PolicyChecker = (user?: User) => Promise<boolean>;\n\ntype CanKey<TAction extends string> = `can${Capitalize<TAction>}`;\n\nexport type PolicyWithActions<\n TResource extends string,\n TActions extends string,\n> = IArkosPolicy<TResource, TActions> & {\n [K in TActions]: PolicyAuthEntry<TResource, K>;\n} & {\n [K in CanKey<TActions>]: PolicyChecker;\n};\n\nexport interface IArkosPolicy<\n TResource extends string,\n TActions extends string = never,\n> {\n readonly __type: \"ArkosPolicy\";\n readonly resource: TResource;\n\n rule<TAction extends string>(\n action: TAction,\n config?: ArkosPolicyRule\n ): PolicyWithActions<TResource, TActions | TAction>;\n}\n"]}
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.defineConfig = void 0;
4
+ const define_config_1 = require("../utils/define-config.js");
5
+ Object.defineProperty(exports, "defineConfig", { enumerable: true, get: function () { return define_config_1.defineConfig; } });
6
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../../src/exports/config.ts"],"names":[],"mappings":";;;AAAA,0DAAsD;AAE7C,6FAFA,4BAAY,OAEA","sourcesContent":["import { defineConfig } from \"../utils/define-config\";\n\nexport { defineConfig };\n"]}
@@ -92,7 +92,7 @@ class AuthService {
92
92
  }
93
93
  userChangedPasswordAfter(user, JWTTimestamp) {
94
94
  if (user.passwordChangedAt) {
95
- const convertedTimestamp = parseInt(String(user.passwordChangedAt.getTime() / 1000), 10);
95
+ const convertedTimestamp = parseInt(String(new Date(user.passwordChangedAt).getTime() / 1000), 10);
96
96
  return JWTTimestamp < convertedTimestamp;
97
97
  }
98
98
  return false;
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":";;;;;;AAAA,gEAAgD;AAChD,wDAA8B;AAE9B,qFAA4D;AAC5D,iFAAwD;AACxD,+DAAoD;AACpD,yCAA8C;AAC9C,sEAA6C;AAC7C,uEAAuE;AAavE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AACrE,mFAGkD;AAKlD,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QAqbrD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,IAAI,IAAA,8CAAuB,GAAE;gBAC3B,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;YAC5D,IAAI,EAAE,CAAC;QACT,CAAC,CACF,CAAC;IAuFJ,CAAC;IAxgBC,YAAY,CACV,EAAmB,EACnB,SAA+B,EAC/B,MAAe;QAEf,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,IAAA,uBAAc,GA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GAAE;gBAC1B,MAAM,KAAK,CACT,2FAA2F,CAC5F,CAAC;YAEJ,IAAI,CAAC,IAAA,8CAAuB,GAAE;gBAAE,OAAO,KAAK,CAAC;YAC7C,IAAI,CAAC,IAAI;gBAAE,MAAM,uCAAkB,CAAC;YACpC,IAAI,IAAI,EAAE,WAAW;gBAAE,OAAO,IAAI,CAAC;YAEnC,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,SAAS,EAAE,CAAC;gBAChD,OAAO,MAAM,IAAI,CAAC,yBAAyB,CAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC1E,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,IAAI,CAAC,aAAa,IAAI,2BAAU,CAAC,QAAQ,CAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC;oBAC5D,aAAa,GAAG,IAAA,oCAAmB,EAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC,EAAE,WAAW;wBACnE,EAAE,aAAa,CAAC;gBAEpB,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AAthBD,kCAshBC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure: (() => {\n 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 };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles: string[] = [];\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = Array.isArray(accessControl[action])\n ? accessControl[action]\n : accessControl[action].roles || [];\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return !!userRoles.some((role: string) => authorizedRoles.includes(role));\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call 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) throw loginRequiredError;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n {},\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (isAuthenticationEnabled())\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any> | 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;AAavE,qFAA2E;AAC3E,+DAA6E;AAC7E,+CAAgD;AAChD,mEAGoC;AACpC,+FAAqE;AACrE,mFAGkD;AAKlD,MAAa,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QAqbrD,iBAAY,GAAG,IAAA,qBAAU,EACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,IAAI,IAAA,8CAAuB,GAAE;gBAC3B,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;YAC5D,IAAI,EAAE,CAAC;QACT,CAAC,CACF,CAAC;IAuFJ,CAAC;IAxgBC,YAAY,CACV,EAAmB,EACnB,SAA+B,EAC/B,MAAe;QAEf,MAAM,EAAE,cAAc,EAAE,OAAO,EAAE,GAAG,IAAA,uBAAc,GAAE,CAAC;QAErD,IACE,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;YAClC,CAAC,OAAO,CAAC,GAAG,CAAC,UAAU;YACvB,CAAC,OAAO,EAAE,GAAG,EAAE,MAAM;YAErB,MAAM,IAAI,mBAAQ,CAChB,mCAAmC,EACnC,GAAG,EACH,wBAAwB,CACzB,CAAC;QAEJ,MAAM;YACJ,MAAM;gBACN,OAAO,EAAE,GAAG,EAAE,MAAM;gBACpB,OAAO,CAAC,GAAG,CAAC,UAAU;gBACtB,mBA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,IAAI,CAAC,yBAAyB,CAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC1E,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,IAAI,CAAC,aAAa,IAAI,2BAAU,CAAC,QAAQ,CAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC;oBAC5D,aAAa,GAAG,IAAA,oCAAmB,EAAC,IAAA,iBAAS,EAAC,QAAQ,CAAC,CAAC,EAAE,WAAW;wBACnE,EAAE,aAAa,CAAC;gBAEpB,OAAO,CACL,CAAC,CAAC,aAAa;oBACf,IAAI,CAAC,wBAAwB,CAAC,IAAW,EAAE,MAAM,EAAE,aAAa,CAAC,CAClE,CAAC;YACJ,CAAC;YACD,OAAO,KAAK,CAAC;QACf,CAAC,CAAC;IACJ,CAAC;CACF;AAthBD,kCAshBC;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,kBAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration, toMs } from \"./utils/helpers/auth.controller.helpers\";\nimport { appModules, getModuleComponents } from \"../../utils/dynamic-loader\";\nimport { kebabCase } from \"../../exports/utils\";\nimport {\n invaliAuthTokenError,\n loginRequiredError,\n} from \"./utils/auth-error-objects\";\nimport authActionService from \"./utils/services/auth-action.service\";\nimport {\n isAuthenticationEnabled,\n isUsingAuthentication,\n} from \"../../utils/helpers/arkos-config.helpers\";\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nexport class AuthService {\n /**\n * Object containing a combination of actions per resource, tracked by each set of calls of `authService.handleAccessControl`, this can be accessed through the `authService` object or through the endpoint\n */\n actionsPerResource: Record<string, Set<string>> = {};\n\n /**\n * Signs a JWT token for the user.\n *\n * @param {number | string} id - The unique identifier of the user to generate the token for.\n * @param {string | number} [expiresIn] - The expiration time for the token. Defaults to environment variable `JWT_EXPIRES_IN`.\n * @param {string} [secret] - The secret key used to sign the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {string} The signed JWT token.\n */\n signJwtToken(\n id: number | string,\n expiresIn?: MsDuration | number,\n secret?: string\n ): string {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret on production!\",\n 500,\n \"MissingJWTOnProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n expiresIn = (expiresIn ||\n configs?.jwt?.expiresIn ||\n process.env.JWT_EXPIRES_IN ||\n arkosEnv.JWT_EXPIRES_IN) as keyof SignOptions[\"expiresIn\"];\n\n return jwt.sign({ id }, secret, {\n expiresIn: expiresIn as MsDuration,\n });\n }\n\n /**\n * Retrieves cookie configuration options for JWT authentication.\n *\n * Merges configuration from multiple sources in order of precedence:\n * 1. Arkos configuration file\n * 2. Environment variables\n * 3. Request properties (for secure flag)\n * 4. Default fallback values\n *\n * @param req - ArkosRequest object used to determine if the connection is secure\n * @returns Cookie options object with expires, httpOnly, secure, and sameSite properties\n *\n * @example\n * ```typescript\n * const cookieOptions = authService.getJwtCookieOptions(req);\n * res.cookie('jwt', token, cookieOptions);\n * ```\n */\n getJwtCookieOptions(req: ArkosRequest) {\n const arkosConfig = getArkosConfig();\n const authConfigs = arkosConfig?.authentication;\n\n if (!req)\n throw new Error(\"Missing req object in order get jwt cookie options\");\n\n const sameSite =\n authConfigs?.jwt?.cookie?.sameSite ||\n (process.env.JWT_COOKIE_SAME_SITE as\n | \"none\"\n | \"lax\"\n | \"strict\"\n | undefined) ||\n \"lax\";\n\n return {\n expires: new Date(\n Date.now() +\n Number(\n toMs(\n authConfigs?.jwt?.expiresIn ||\n (process.env.JWT_EXPIRES_IN as MsDuration) ||\n (arkosEnv.JWT_EXPIRES_IN as MsDuration)\n )\n )\n ),\n httpOnly:\n authConfigs?.jwt?.cookie?.httpOnly ??\n (process.env.JWT_COOKIE_HTTP_ONLY !== undefined\n ? process.env.JWT_COOKIE_HTTP_ONLY === \"true\"\n : undefined) ??\n true,\n secure: (() => {\n 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 };\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 /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles: string[] = [];\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = Array.isArray(accessControl[action])\n ? accessControl[action]\n : accessControl[action].roles || [];\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return !!userRoles.some((role: string) => authorizedRoles.includes(role));\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n if (!isAuthenticationEnabled())\n throw Error(\n \"ValidationError: Trying to call 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) throw loginRequiredError;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n {},\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (isAuthenticationEnabled())\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any> | 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"]}
@@ -85,8 +85,8 @@ function errorHandler(err, req, res, _) {
85
85
  error = errorControllerHelper.handleVersionMismatchError(err);
86
86
  if (process.env.ARKOS_BUILD !== "true")
87
87
  return sendDevelopmentError({
88
- ...error,
89
88
  message: error.message,
89
+ ...error,
90
90
  stack: err.stack,
91
91
  originalError: err,
92
92
  }, req, res);
@@ -1 +1 @@
1
- {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAsEC;AAxFD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,CAAC;IAEF,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM;QAAE,OAAO,KAAK,EAAE,KAAK,CAAC;IAE5D,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,cAAc,EAAE,CAAC;IACjD,IAAI,GAAG,CAAC,IAAI,KAAK,mBAAmB;QAClC,KAAK,GAAG,qBAAqB,CAAC,gBAAgB,EAAE,CAAC;IAEnD,IAAI,GAAG,CAAC,IAAI,KAAK,6BAA6B;QAC5C,KAAK,GAAG,qBAAqB,CAAC,iCAAiC,CAAC,GAAG,CAAC,CAAC;IACvE,IAAI,GAAG,CAAC,IAAI,KAAK,iCAAiC;QAChD,KAAK,GAAG,qBAAqB,CAAC,qCAAqC,CAAC,GAAG,CAAC,CAAC;IAC3E,IAAI,GAAG,CAAC,IAAI,KAAK,OAAO;QACtB,KAAK,GAAG,qBAAqB,CAAC,yBAAyB,CAAC,GAA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AAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n ...error,\n message: error.message,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message:\n err.message?.split?.(\"\\n\")[err.message?.split?.(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split?.(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (process.env.ARKOS_BUILD !== \"true\") {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
1
+ {"version":3,"file":"error-handler.controller.js","sourceRoot":"","sources":["../../../../src/modules/error-handler/error-handler.controller.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,+BAsEC;AAxFD,qFAAuE;AACvE,yCAAsC;AAiBtC,SAAwB,YAAY,CAClC,GAAa,EACb,GAAY,EACZ,GAAa,EACb,CAAe;IAEf,OAAO,CAAC,KAAK,CAAC,yBAAyB,EAAE,GAAG,CAAC,CAAC;IAE9C,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,IAAI,GAAG,CAAC;IACvC,GAAG,CAAC,MAAM,GAAG,GAAG,CAAC,MAAM,IAAI,OAAO,CAAC;IAEnC,IAAI,KAAK,GAAQ;QACf,GAAG,GAAG;QACN,OAAO,EAAE,GAAG,CAAC,OAAO;QACpB,KAAK,EAAE,GAAG,EAAE,KAAK,IAAI,SAAS;KAC/B,CAAC;IAEF,IAAI,O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,EAAE,uBAAuB;YAC9B,OAAO,EAAE,GAAG,CAAC,OAAO;YACpB,IAAI,EAAE,SAAS;SAChB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IAED,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC;QAC9B,KAAK,EAAE,uBAAuB;QAC9B,OAAO,EAAE,gDAAgD;KAC1D,CAAC,CAAC;AACL,CAAC;AAWD,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;IACzB,IAAI,OAAO,CAAC,GAAG,CAAC,WAAW,KAAK,MAAM,EAAE,CAAC;QACvC,OAAO,CAAC,IAAI,EAAE,CAAC;IACjB,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,KAAK,CAAC,2DAA2D,CAAC,CAAC;QAE3E,eAAM,CAAC,KAAK,CAAC,GAAG,EAAE;YAChB,OAAO,CAAC,KAAK,CAAC,uBAAuB,CAAC,CAAC;YACvC,OAAO,CAAC,IAAI,EAAE,CAAC;QACjB,CAAC,CAAC,CAAC;IACL,CAAC;AACH,CAAC,CAAC,CAAC","sourcesContent":["import { NextFunction, Request, Response } from \"express\";\nimport AppError from \"./utils/app-error\";\nimport * as errorControllerHelper from \"./utils/error-handler.helpers\";\nimport { server } from \"../../server\";\n\n/**\n * Error handling middleware for Express.\n *\n * This middleware function handles all errors in the Express application.\n * It checks for the environment (development or production) and sends appropriate error responses\n * based on whether the environment is production or not. It also maps specific errors such as\n * JWT errors, Prisma client errors, and database-related errors to specific helper functions for handling.\n *\n * @param {AppError} err - The error object thrown by the application.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n * @param {NextFunction} _ - The next middleware function in the chain.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nexport default function errorHandler(\n err: AppError,\n req: Request,\n res: Response,\n _: NextFunction\n): void {\n console.error(\"[\\x1b[31mError\\x1b[0m]:\", err);\n\n err.statusCode = err.statusCode || 500;\n err.status = err.status || \"error\";\n\n let error: any = {\n ...err,\n message: err.message,\n stack: err?.stack || undefined,\n };\n\n if (process.env.ARKOS_BUILD === \"true\") delete error?.stack;\n\n if (err.name === \"JsonWebTokenError\")\n error = errorControllerHelper.handleJWTError();\n if (err.name === \"TokenExpiredError\")\n error = errorControllerHelper.handleJWTExpired();\n\n if (err.name === \"PrismaClientValidationError\")\n error = errorControllerHelper.handlePrismaClientValidationError(err);\n if (err.name === \"PrismaClientInitializationError\")\n error = errorControllerHelper.handlePrismaClientInitializationError(err);\n if (err.code === \"P1000\")\n error = errorControllerHelper.handleAuthenticationError(err);\n if (err.code === \"P1001\")\n error = errorControllerHelper.handleServerNotReachableError(err);\n if (err.code === \"P1002\")\n error = errorControllerHelper.handleConnectionTimeoutError(err);\n if (err.code === \"P1003\")\n error = errorControllerHelper.handleDatabaseNotFoundError(err);\n if (err.code === \"P2000\")\n error = errorControllerHelper.handleFieldValueTooLargeError(err);\n if (err.code === \"P2001\")\n error = errorControllerHelper.handleRecordNotFoundError(err);\n if (err.code === \"P2002\")\n error = errorControllerHelper.handleUniqueConstraintError(err);\n if (err.code === \"P2003\")\n error = errorControllerHelper.handleForeignKeyConstraintError(err);\n if (err.code === \"P2004\")\n error = errorControllerHelper.handleConstraintFailedError(err);\n if (err.code === \"P2025\")\n error = errorControllerHelper.handleNonExistingRecord(err);\n if (err.code === \"P3000\")\n error = errorControllerHelper.handleSchemaCreationFailedError(err);\n if (err.code === \"P3001\")\n error = errorControllerHelper.handleMigrationAlreadyAppliedError(err);\n if (err.code === \"P3002\")\n error = errorControllerHelper.handleMigrationScriptFailedError(err);\n if (err.code === \"P3003\")\n error = errorControllerHelper.handleVersionMismatchError(err);\n\n if (process.env.ARKOS_BUILD !== \"true\")\n return sendDevelopmentError(\n {\n message: error.message,\n ...error,\n stack: err.stack,\n originalError: err,\n },\n req,\n res\n );\n\n sendProductionError(error, req, res);\n}\n\n/**\n * Sends a detailed error response in development mode.\n *\n * In development, the error response includes full error details, including\n * the stack trace and the complete error message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendDevelopmentError(err: any, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\"))\n res.status(err.statusCode).json({\n ...err,\n message:\n err.message?.split?.(\"\\n\")[err.message?.split?.(\"\\n\").length - 1],\n stack: err?.originalError?.stack?.split?.(\"\\n\"),\n });\n else\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n });\n}\n\n/**\n * Sends a generic error response in production mode.\n *\n * In production, sensitive error details (such as stack traces) are not exposed\n * to the client. Only operational errors are shown with a generic message.\n *\n * @param {AppError} err - The error object.\n * @param {Request} req - The Express request object.\n * @param {Response} res - The Express response object.\n *\n * @returns {void} - Sends the response with the error details to the client.\n */\nfunction sendProductionError(err: AppError, req: Request, res: Response): void {\n if (req.originalUrl.startsWith(\"/api\")) {\n if (err.isOperational)\n res.status(err.statusCode).json({\n status: err.status,\n message: err.message,\n meta: err.meta || {},\n code: err.code || \"Unknown\",\n });\n else\n res.status(500).json({\n status: \"error\",\n message: \"Internal server error, please try again later.\",\n code: \"Unknown\",\n meta: {},\n });\n\n return;\n }\n\n if (err.isOperational) {\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: err.message,\n code: \"Unknown\",\n });\n return;\n }\n\n res.status(err.statusCode).json({\n title: \"Internal server error\",\n message: \"Internal server error, please try again later.\",\n });\n}\n\n/**\n * Gracefully handles process termination by listening for SIGTERM signal.\n *\n * - In production and staging environments, it will log a shutdown message\n * and attempt to close the server gracefully.\n * - In development or non-production environments, it will immediately exit the process.\n *\n * @returns {void}\n */\nprocess.on(\"SIGTERM\", () => {\n if (process.env.ARKOS_BUILD !== \"true\") {\n process.exit();\n } else {\n console.error(\"SIGTERM RECEIVED in Production. Shutting down gracefully!\");\n\n server.close(() => {\n console.error(\"Process terminated!!!\");\n process.exit();\n });\n }\n});\n"]}
@@ -0,0 +1,288 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = getOpenApiLoginHtml;
4
+ const server_1 = require("../../../server.js");
5
+ function formatFieldLabel(field) {
6
+ const last = field.split(".").pop();
7
+ return last
8
+ .replace(/([A-Z])/g, " $1")
9
+ .replace(/^./, (c) => c.toUpperCase())
10
+ .trim();
11
+ }
12
+ function getOpenApiLoginHtml() {
13
+ const arkosConfig = (0, server_1.getArkosConfig)();
14
+ const theme = arkosConfig?.swagger?.scalarApiReferenceConfiguration?.theme || "default";
15
+ const allowedUsernames = arkosConfig?.authentication?.login?.allowedUsernames
16
+ ?.length
17
+ ? arkosConfig.authentication.login.allowedUsernames
18
+ : ["username"];
19
+ const themeColors = {
20
+ default: { bg: "#0f0f0f", surface: "#1a1a1a", border: "#2e2e2e" },
21
+ moon: { bg: "#0f1117", surface: "#1c1e26", border: "#2e3040" },
22
+ purple: { bg: "#0d0d14", surface: "#1a1a2e", border: "#2e2e4a" },
23
+ solarized: { bg: "#002b36", surface: "#073642", border: "#124652" },
24
+ bluePlanet: { bg: "#070b14", surface: "#0d1424", border: "#1a2540" },
25
+ saturn: { bg: "#0a0a0f", surface: "#16161f", border: "#28283a" },
26
+ kepler: { bg: "#0a0f0a", surface: "#141f14", border: "#253525" },
27
+ mars: { bg: "#0f0a08", surface: "#1f1410", border: "#352520" },
28
+ deepSpace: { bg: "#0a0a0a", surface: "#121212", border: "#3a3a3a" },
29
+ };
30
+ const colors = themeColors[theme] ?? themeColors["default"];
31
+ const firstLabel = formatFieldLabel(allowedUsernames[0]);
32
+ const showSelect = allowedUsernames.length > 1;
33
+ const title = arkosConfig?.swagger?.options?.definition?.info?.title ||
34
+ "Arkos.js OpenAPI Documentation";
35
+ return `<!DOCTYPE html>
36
+ <html lang="en">
37
+ <head>
38
+ <meta charset="UTF-8">
39
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
40
+ <title>${title}</title>
41
+ <style>
42
+ * { margin: 0; padding: 0; box-sizing: border-box; }
43
+
44
+ body {
45
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
46
+ min-height: 100vh;
47
+ display: flex;
48
+ align-items: center;
49
+ justify-content: center;
50
+ background-color: ${colors.bg};
51
+ padding: 8px;
52
+ }
53
+
54
+ .login-container {
55
+ background-color: ${colors.surface};
56
+ padding: 40px;
57
+ border: 1px solid ${colors.border};
58
+ border-radius: 8px;
59
+ width: 100%;
60
+ max-width: 400px;
61
+ }
62
+
63
+ h1 {
64
+ color: #ffffff;
65
+ text-align: center;
66
+ margin-bottom: 30px;
67
+ font-size: 24px;
68
+ font-weight: 600;
69
+ }
70
+
71
+ h2 {
72
+ color: #ffffff;
73
+ text-align: center;
74
+ margin-bottom: 20px;
75
+ font-size: 16px;
76
+ font-weight: 500;
77
+ }
78
+
79
+ .form-group {
80
+ margin-bottom: 20px;
81
+ }
82
+
83
+ label {
84
+ display: block;
85
+ color: #ffffff;
86
+ margin-bottom: 8px;
87
+ font-size: 14px;
88
+ font-weight: 500;
89
+ }
90
+
91
+ input[type="text"],
92
+ input[type="password"] {
93
+ width: 100%;
94
+ padding: 12px 16px;
95
+ background-color: ${colors.bg};
96
+ border: 1px solid ${colors.border};
97
+ border-radius: 4px;
98
+ color: #ffffff;
99
+ font-size: 14px;
100
+ transition: border-color 0.3s;
101
+ }
102
+
103
+ select {
104
+ width: 100%;
105
+ padding: 12px 16px;
106
+ background-color: ${colors.bg};
107
+ border: 1px solid ${colors.border};
108
+ border-radius: 4px;
109
+ color: #ffffff;
110
+ font-size: 14px;
111
+ transition: border-color 0.3s;
112
+ appearance: none;
113
+ -webkit-appearance: none;
114
+ -moz-appearance: none;
115
+ cursor: pointer;
116
+ /* custom arrow */
117
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23ffffff' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
118
+ background-repeat: no-repeat;
119
+ background-position: right 16px center;
120
+ }
121
+
122
+ input[type="text"]:focus,
123
+ input[type="password"]:focus,
124
+ select:focus {
125
+ outline: none;
126
+ border-color: #ffffff;
127
+ }
128
+
129
+ input[type="text"]::placeholder,
130
+ input[type="password"]::placeholder {
131
+ color: #666666;
132
+ }
133
+
134
+ select option {
135
+ background-color: ${colors.surface};
136
+ color: #ffffff;
137
+ }
138
+
139
+ .login-button {
140
+ width: 100%;
141
+ padding: 12px;
142
+ background-color: #ffffff;
143
+ color: #1a1a1a;
144
+ border: none;
145
+ border-radius: 4px;
146
+ font-size: 16px;
147
+ font-weight: 600;
148
+ cursor: pointer;
149
+ transition: background-color 0.3s;
150
+ }
151
+
152
+ .login-button:hover { background-color: #e0e0e0; }
153
+ .login-button:active { transform: translateY(1px); }
154
+ .login-button:disabled { background-color: #666666; cursor: not-allowed; }
155
+
156
+ .error-message {
157
+ color: #ff6b6b;
158
+ font-size: 14px;
159
+ margin-top: 10px;
160
+ text-align: center;
161
+ display: none;
162
+ }
163
+
164
+ .error-message.show { display: block; }
165
+ </style>
166
+ </head>
167
+ <body>
168
+ <div class="login-container">
169
+ <h1>${title}</h1>
170
+ <h2>Login</h2>
171
+ <form id="loginForm">
172
+
173
+ ${showSelect
174
+ ? `
175
+ <div class="form-group">
176
+ <label for="usernameSelect">Login With</label>
177
+ <select id="usernameSelect">
178
+ ${allowedUsernames
179
+ .map((f) => `
180
+ <option value="${f}">${formatFieldLabel(f)}</option>
181
+ `)
182
+ .join("")}
183
+ </select>
184
+ </div>
185
+ `
186
+ : ""}
187
+
188
+ <div class="form-group">
189
+ <label id="usernameLabel" for="usernameField">${firstLabel}</label>
190
+ <input
191
+ type="text"
192
+ id="usernameField"
193
+ placeholder="Enter your ${firstLabel.toLowerCase()}"
194
+ required
195
+ >
196
+ </div>
197
+
198
+ <div class="form-group">
199
+ <label for="password">Password</label>
200
+ <input
201
+ type="password"
202
+ id="password"
203
+ placeholder="Enter your password"
204
+ required
205
+ >
206
+ </div>
207
+
208
+ <button type="submit" class="login-button" id="loginButton">Login</button>
209
+ <div class="error-message" id="errorMessage"></div>
210
+
211
+ </form>
212
+ </div>
213
+
214
+ <script>
215
+ const usernameLabel = document.getElementById('usernameLabel');
216
+ const usernameField = document.getElementById('usernameField');
217
+ const usernameSelect = document.getElementById('usernameSelect');
218
+ const loginButton = document.getElementById('loginButton');
219
+ const errorMessage = document.getElementById('errorMessage');
220
+
221
+ function formatFieldLabel(field) {
222
+ const last = field.split('.').pop();
223
+ return last
224
+ .replace(/([A-Z])/g, ' $1')
225
+ .replace(/^./, c => c.toUpperCase())
226
+ .trim();
227
+ }
228
+
229
+ if (usernameSelect) {
230
+ usernameSelect.addEventListener('change', () => {
231
+ const label = formatFieldLabel(usernameSelect.value);
232
+ usernameLabel.textContent = label;
233
+ usernameField.placeholder = \`Enter your \${label.toLowerCase()}\`;
234
+ });
235
+ }
236
+
237
+ const params = new URLSearchParams(window.location.search);
238
+ const urlErrorMessage = params.get('error-message');
239
+ if (urlErrorMessage) {
240
+ errorMessage.textContent = decodeURIComponent(urlErrorMessage);
241
+ errorMessage.classList.add('show');
242
+ }
243
+
244
+ document.getElementById('loginForm').addEventListener('submit', async (e) => {
245
+ e.preventDefault();
246
+
247
+ const selectedField = usernameSelect ? usernameSelect.value : '${allowedUsernames[0]}';
248
+ const password = document.getElementById('password').value;
249
+
250
+ errorMessage.classList.remove('show');
251
+ errorMessage.textContent = '';
252
+ loginButton.disabled = true;
253
+ loginButton.textContent = '...';
254
+
255
+ try {
256
+ const selectedField = usernameSelect ? usernameSelect.value : '${allowedUsernames[0]}';
257
+ const fieldKey = selectedField.split('.').pop(); // last segment only as body key
258
+
259
+ const response = await fetch(\`/api/auth/login?usernameField=\${selectedField}\`, {
260
+ method: 'POST',
261
+ headers: { 'Content-Type': 'application/json' },
262
+ body: JSON.stringify({
263
+ [fieldKey]: usernameField.value,
264
+ password,
265
+ }),
266
+ });
267
+
268
+ const data = await response.json();
269
+
270
+ if (response.ok) {
271
+ window.location.href = '/api/docs';
272
+ } else {
273
+ errorMessage.textContent = data.message || 'Login failed';
274
+ errorMessage.classList.add('show');
275
+ }
276
+ } catch {
277
+ errorMessage.textContent = 'An error occurred. Please try again.';
278
+ errorMessage.classList.add('show');
279
+ } finally {
280
+ loginButton.disabled = false;
281
+ loginButton.textContent = 'Login';
282
+ }
283
+ });
284
+ </script>
285
+ </body>
286
+ </html>`;
287
+ }
288
+ //# sourceMappingURL=get-open-api-login-html.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"get-open-api-login-html.js","sourceRoot":"","sources":["../../../../../src/modules/swagger/utils/get-open-api-login-html.ts"],"names":[],"mappings":";;AAUA,sCAkSC;AA5SD,4CAAiD;AAEjD,SAAS,gBAAgB,CAAC,KAAa;IACrC,MAAM,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,EAAG,CAAC;IACrC,OAAO,IAAI;SACR,OAAO,CAAC,UAAU,EAAE,KAAK,CAAC;SAC1B,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC;SACrC,IAAI,EAAE,CAAC;AACZ,CAAC;AAED,SAAwB,mBAAmB;IACzC,MAAM,WAAW,GAAG,IAAA,uBAAc,GAAE,CAAC;IAErC,MAAM,KAAK,GACT,WAAW,EAAE,OAAO,EAAE,+BAA+B,EAAE,KAAK,IAAI,SAAS,CAAC;IAE5E,MAAM,gBAAgB,GAAG,WAAW,EAAE,cAAc,EAAE,KAAK,EAAE,gBAAgB;QAC3E,EAAE,MAAM;QACR,CAAC,CAAC,WAAW,CAAC,cAAc,CAAC,KAAK,CAAC,gBAAgB;QACnD,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;IAEjB,MAAM,WAAW,GAGb;QACF,OAAO,EAAE,EAAE,EAAE,EAAE,SAAS,EAAE,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE;Q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AC,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;0BAsCb,MAAM,CAAC,EAAE;0BACT,MAAM,CAAC,MAAM;;;;;;;;;;0BAUb,MAAM,CAAC,EAAE;0BACT,MAAM,CAAC,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;0BA4Bb,MAAM,CAAC,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAkC9B,KAAK;;;;QAKP,UAAU;QACR,CAAC,CAAC;;;;YAIA,gBAAgB;aACf,GAAG,CACF,CAAC,CAAC,EAAE,EAAE,CAAC;2BACM,CAAC,KAAK,gBAAgB,CAAC,CAAC,CAAC;WACzC,CACE;aACA,IAAI,CAAC,EAAE,CAAC;;;OAGd;QACG,CAAC,CAAC,EACN;;;wDAGkD,UAAU;;;;oCAI9B,UAAU,CAAC,WAAW,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;uEAsDW,gBAAgB,CAAC,CAAC,CAAC;;;;;;;;;yEASjB,gBAAgB,CAAC,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;QA8BpF,CAAC;AACT,CAAC","sourcesContent":["import { getArkosConfig } from \"../../../server\";\n\nfunction formatFieldLabel(field: string): string {\n const last = field.split(\".\").pop()!;\n return last\n .replace(/([A-Z])/g, \" $1\")\n .replace(/^./, (c) => c.toUpperCase())\n .trim();\n}\n\nexport default function getOpenApiLoginHtml() {\n const arkosConfig = getArkosConfig();\n\n const theme =\n arkosConfig?.swagger?.scalarApiReferenceConfiguration?.theme || \"default\";\n\n const allowedUsernames = arkosConfig?.authentication?.login?.allowedUsernames\n ?.length\n ? arkosConfig.authentication.login.allowedUsernames\n : [\"username\"];\n\n const themeColors: Record<\n string,\n { bg: string; surface: string; border: string }\n > = {\n default: { bg: \"#0f0f0f\", surface: \"#1a1a1a\", border: \"#2e2e2e\" },\n moon: { bg: \"#0f1117\", surface: \"#1c1e26\", border: \"#2e3040\" },\n purple: { bg: \"#0d0d14\", surface: \"#1a1a2e\", border: \"#2e2e4a\" },\n solarized: { bg: \"#002b36\", surface: \"#073642\", border: \"#124652\" },\n bluePlanet: { bg: \"#070b14\", surface: \"#0d1424\", border: \"#1a2540\" },\n saturn: { bg: \"#0a0a0f\", surface: \"#16161f\", border: \"#28283a\" },\n kepler: { bg: \"#0a0f0a\", surface: \"#141f14\", border: \"#253525\" },\n mars: { bg: \"#0f0a08\", surface: \"#1f1410\", border: \"#352520\" },\n deepSpace: { bg: \"#0a0a0a\", surface: \"#121212\", border: \"#3a3a3a\" },\n };\n\n const colors = themeColors[theme] ?? themeColors[\"default\"];\n\n const firstLabel = formatFieldLabel(allowedUsernames[0]);\n const showSelect = allowedUsernames.length > 1;\n const title =\n arkosConfig?.swagger?.options?.definition?.info?.title ||\n \"Arkos.js OpenAPI Documentation\";\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${title}</title>\n <style>\n * { margin: 0; padding: 0; box-sizing: border-box; }\n\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n min-height: 100vh;\n display: flex;\n align-items: center;\n justify-content: center;\n background-color: ${colors.bg};\n padding: 8px;\n }\n\n .login-container {\n background-color: ${colors.surface};\n padding: 40px;\n border: 1px solid ${colors.border};\n border-radius: 8px;\n width: 100%;\n max-width: 400px;\n }\n\n h1 {\n color: #ffffff;\n text-align: center;\n margin-bottom: 30px;\n font-size: 24px;\n font-weight: 600;\n }\n\n h2 {\n color: #ffffff;\n text-align: center;\n margin-bottom: 20px;\n font-size: 16px;\n font-weight: 500;\n }\n\n .form-group {\n margin-bottom: 20px;\n }\n\n label {\n display: block;\n color: #ffffff;\n margin-bottom: 8px;\n font-size: 14px;\n font-weight: 500;\n }\n\n input[type=\"text\"],\n input[type=\"password\"] {\n width: 100%;\n padding: 12px 16px;\n background-color: ${colors.bg};\n border: 1px solid ${colors.border};\n border-radius: 4px;\n color: #ffffff;\n font-size: 14px;\n transition: border-color 0.3s;\n }\n\n select {\n width: 100%;\n padding: 12px 16px;\n background-color: ${colors.bg};\n border: 1px solid ${colors.border};\n border-radius: 4px;\n color: #ffffff;\n font-size: 14px;\n transition: border-color 0.3s;\n appearance: none;\n -webkit-appearance: none;\n -moz-appearance: none;\n cursor: pointer;\n /* custom arrow */\n background-image: url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%23ffffff' d='M6 8L1 3h10z'/%3E%3C/svg%3E\");\n background-repeat: no-repeat;\n background-position: right 16px center;\n }\n\n input[type=\"text\"]:focus,\n input[type=\"password\"]:focus,\n select:focus {\n outline: none;\n border-color: #ffffff;\n }\n\n input[type=\"text\"]::placeholder,\n input[type=\"password\"]::placeholder {\n color: #666666;\n }\n\n select option {\n background-color: ${colors.surface};\n color: #ffffff;\n }\n\n .login-button {\n width: 100%;\n padding: 12px;\n background-color: #ffffff;\n color: #1a1a1a;\n border: none;\n border-radius: 4px;\n font-size: 16px;\n font-weight: 600;\n cursor: pointer;\n transition: background-color 0.3s;\n }\n\n .login-button:hover { background-color: #e0e0e0; }\n .login-button:active { transform: translateY(1px); }\n .login-button:disabled { background-color: #666666; cursor: not-allowed; }\n\n .error-message {\n color: #ff6b6b;\n font-size: 14px;\n margin-top: 10px;\n text-align: center;\n display: none;\n }\n\n .error-message.show { display: block; }\n </style>\n</head>\n<body>\n <div class=\"login-container\">\n <h1>${title}</h1>\n <h2>Login</h2>\n <form id=\"loginForm\">\n\n ${\n showSelect\n ? `\n <div class=\"form-group\">\n <label for=\"usernameSelect\">Login With</label>\n <select id=\"usernameSelect\">\n ${allowedUsernames\n .map(\n (f) => `\n <option value=\"${f}\">${formatFieldLabel(f)}</option>\n `\n )\n .join(\"\")}\n </select>\n </div>\n `\n : \"\"\n }\n\n <div class=\"form-group\">\n <label id=\"usernameLabel\" for=\"usernameField\">${firstLabel}</label>\n <input\n type=\"text\"\n id=\"usernameField\"\n placeholder=\"Enter your ${firstLabel.toLowerCase()}\"\n required\n >\n </div>\n\n <div class=\"form-group\">\n <label for=\"password\">Password</label>\n <input\n type=\"password\"\n id=\"password\"\n placeholder=\"Enter your password\"\n required\n >\n </div>\n\n <button type=\"submit\" class=\"login-button\" id=\"loginButton\">Login</button>\n <div class=\"error-message\" id=\"errorMessage\"></div>\n\n </form>\n </div>\n\n <script>\n const usernameLabel = document.getElementById('usernameLabel');\n const usernameField = document.getElementById('usernameField');\n const usernameSelect = document.getElementById('usernameSelect');\n const loginButton = document.getElementById('loginButton');\n const errorMessage = document.getElementById('errorMessage');\n\n function formatFieldLabel(field) {\n const last = field.split('.').pop();\n return last\n .replace(/([A-Z])/g, ' $1')\n .replace(/^./, c => c.toUpperCase())\n .trim();\n }\n\n if (usernameSelect) {\n usernameSelect.addEventListener('change', () => {\n const label = formatFieldLabel(usernameSelect.value);\n usernameLabel.textContent = label;\n usernameField.placeholder = \\`Enter your \\${label.toLowerCase()}\\`;\n });\n }\n\n const params = new URLSearchParams(window.location.search);\n const urlErrorMessage = params.get('error-message');\n if (urlErrorMessage) {\n errorMessage.textContent = decodeURIComponent(urlErrorMessage);\n errorMessage.classList.add('show');\n }\n\n document.getElementById('loginForm').addEventListener('submit', async (e) => {\n e.preventDefault();\n\n const selectedField = usernameSelect ? usernameSelect.value : '${allowedUsernames[0]}';\n const password = document.getElementById('password').value;\n\n errorMessage.classList.remove('show');\n errorMessage.textContent = '';\n loginButton.disabled = true;\n loginButton.textContent = '...';\n\n try {\n const selectedField = usernameSelect ? usernameSelect.value : '${allowedUsernames[0]}';\n const fieldKey = selectedField.split('.').pop(); // last segment only as body key\n\n const response = await fetch(\\`/api/auth/login?usernameField=\\${selectedField}\\`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n [fieldKey]: usernameField.value,\n password,\n }),\n });\n\n const data = await response.json();\n\n if (response.ok) {\n window.location.href = '/api/docs';\n } else {\n errorMessage.textContent = data.message || 'Login failed';\n errorMessage.classList.add('show');\n }\n } catch {\n errorMessage.textContent = 'An error occurred. Please try again.';\n errorMessage.classList.add('show');\n } finally {\n loginButton.disabled = false;\n loginButton.textContent = 'Login';\n }\n });\n </script>\n</body>\n</html>`;\n}\n"]}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../src/types/arkos-config/utils.ts"],"names":[],"mappings":"","sourcesContent":["import { ArkosRequest } from \"..\";\nimport { AccessAction, DetailedAccessControlRule } from \"../auth\";\n\n/** Context passed to `before` hooks of `authenticate`. */\nexport interface AuthenticateBeforeHookContext {\n /** The incoming request object. */\n req: ArkosRequest;\n /** Bypasses core logic and jumps directly to `after` hooks. */\n skip: () => void;\n}\n\n/** Context passed to `after` hooks of `authenticate`. */\nexport interface AuthenticateAfterHookContext {\n /** The incoming request object. */\n req: ArkosRequest;\n}\n\n/** Context passed to `onError` hooks of `authenticate`. */\nexport interface AuthenticateErrorHookContext {\n /** The incoming request object. */\n req: ArkosRequest;\n /** The error thrown during authentication. */\n error: unknown;\n /** Suppresses the error and jumps to `after` hooks. */\n skip: () => void;\n}\n\nexport type AuthenticateHookHandler = (\n ctx: AuthenticateBeforeHookContext\n) => void | Promise<void>;\n\nexport type AuthenticateAfterHookHandler = (\n ctx: AuthenticateAfterHookContext\n) => void | Promise<void>;\n\nexport type AuthenticateErrorHookHandler = (\n ctx: AuthenticateErrorHookContext\n) => void | Promise<void>;\n\n/** Context passed to `before` hooks of `authorize`. */\nexport interface AuthorizeBeforeHookContext {\n /** The incoming request object. */\n req: ArkosRequest;\n /** The action being authorized (e.g. `\"Create\"`, `\"Delete\"`). */\n action: AccessAction;\n /** The resource being accessed in kebab-case (e.g. `\"post\"`, `\"cart-item\"`). */\n resource: string;\n /** The access control rule for this action. */\n rule?: string[] | DetailedAccessControlRule | \"*\";\n /** Bypasses core logic and jumps directly to `after` hooks. */\n skip: () => void;\n}\n\n/** Context passed to `after` hooks of `authorize`. */\nexport interface AuthorizeAfterHookContext {\n /** The incoming request object. */\n req: ArkosRequest;\n /** The action that was authorized (e.g. `\"Create\"`, `\"Delete\"`). */\n action: AccessAction;\n /** The resource that was accessed in kebab-case (e.g. `\"post\"`, `\"cart-item\"`). */\n resource: string;\n /** The access control rule that was applied. */\n rule?: string[] | DetailedAccessControlRule | \"*\";\n}\n\n/** Context passed to `onError` hooks of `authorize`. */\nexport interface AuthorizeErrorHookContext {\n /** The incoming request object. */\n req: ArkosRequest;\n /** The error thrown during authorization. */\n error: unknown;\n /** The action being authorized (e.g. `\"Create\"`, `\"Delete\"`). */\n action: AccessAction;\n /** The resource being accessed in kebab-case (e.g. `\"post\"`, `\"cart-item\"`). */\n resource: string;\n /** The access control rule for this action. */\n rule?: string[] | DetailedAccessControlRule | \"*\";\n /** Suppresses the error and jumps to `after` hooks. */\n skip: () => void;\n}\n\nexport type AuthorizeHookHandler = (\n ctx: AuthorizeBeforeHookContext\n) => void | Promise<void>;\n\nexport type AuthorizeAfterHookHandler = (\n ctx: AuthorizeAfterHookContext\n) => void | Promise<void>;\n\nexport type AuthorizeErrorHookHandler = (\n ctx: AuthorizeErrorHookContext\n) => void | Promise<void>;\n"]}