arkos 1.4.1-canary.1 → 1.4.1-canary.11

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 (62) hide show
  1. package/dist/cjs/modules/auth/auth.service.js +1 -1
  2. package/dist/cjs/modules/auth/auth.service.js.map +1 -1
  3. package/dist/cjs/modules/auth/utils/services/auth-action.service.js +15 -9
  4. package/dist/cjs/modules/auth/utils/services/auth-action.service.js.map +1 -1
  5. package/dist/cjs/modules/base/base.middlewares.js +10 -2
  6. package/dist/cjs/modules/base/base.middlewares.js.map +1 -1
  7. package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +27 -9
  8. package/dist/cjs/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
  9. package/dist/cjs/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js +28 -11
  10. package/dist/cjs/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js.map +1 -1
  11. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
  12. package/dist/cjs/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  13. package/dist/cjs/utils/arkos-router/index.js +19 -6
  14. package/dist/cjs/utils/arkos-router/index.js.map +1 -1
  15. package/dist/cjs/utils/cli/dev.js +1 -45
  16. package/dist/cjs/utils/cli/dev.js.map +1 -1
  17. package/dist/cjs/utils/cli/start.js +11 -8
  18. package/dist/cjs/utils/cli/start.js.map +1 -1
  19. package/dist/cjs/utils/cli/utils/cli.helpers.js +1 -1
  20. package/dist/cjs/utils/cli/utils/runtime-cli-commander.js +6 -6
  21. package/dist/cjs/utils/cli/utils/runtime-cli-commander.js.map +1 -1
  22. package/dist/cjs/utils/dotenv.helpers.js +6 -2
  23. package/dist/cjs/utils/dotenv.helpers.js.map +1 -1
  24. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js +19 -4
  25. package/dist/cjs/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  26. package/dist/cjs/utils/validate-dto.js +1 -5
  27. package/dist/cjs/utils/validate-dto.js.map +1 -1
  28. package/dist/cjs/utils/validate-schema.js +2 -7
  29. package/dist/cjs/utils/validate-schema.js.map +1 -1
  30. package/dist/esm/modules/auth/auth.service.js +1 -1
  31. package/dist/esm/modules/auth/auth.service.js.map +1 -1
  32. package/dist/esm/modules/auth/utils/services/auth-action.service.js +15 -9
  33. package/dist/esm/modules/auth/utils/services/auth-action.service.js.map +1 -1
  34. package/dist/esm/modules/base/base.middlewares.js +10 -2
  35. package/dist/esm/modules/base/base.middlewares.js.map +1 -1
  36. package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js +27 -9
  37. package/dist/esm/modules/swagger/utils/helpers/get-authentication-json-schema-paths.js.map +1 -1
  38. package/dist/esm/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js +28 -11
  39. package/dist/esm/modules/swagger/utils/helpers/get-file-upload-json-schema-paths.js.map +1 -1
  40. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js +3 -0
  41. package/dist/esm/modules/swagger/utils/helpers/missing-json-schemas-generator.js.map +1 -1
  42. package/dist/esm/utils/arkos-router/index.js +19 -6
  43. package/dist/esm/utils/arkos-router/index.js.map +1 -1
  44. package/dist/esm/utils/cli/dev.js +2 -46
  45. package/dist/esm/utils/cli/dev.js.map +1 -1
  46. package/dist/esm/utils/cli/start.js +11 -8
  47. package/dist/esm/utils/cli/start.js.map +1 -1
  48. package/dist/esm/utils/cli/utils/cli.helpers.js +1 -1
  49. package/dist/esm/utils/cli/utils/runtime-cli-commander.js +6 -6
  50. package/dist/esm/utils/cli/utils/runtime-cli-commander.js.map +1 -1
  51. package/dist/esm/utils/dotenv.helpers.js +6 -2
  52. package/dist/esm/utils/dotenv.helpers.js.map +1 -1
  53. package/dist/esm/utils/prisma/prisma-json-schema-generator.js +19 -4
  54. package/dist/esm/utils/prisma/prisma-json-schema-generator.js.map +1 -1
  55. package/dist/esm/utils/validate-dto.js +1 -2
  56. package/dist/esm/utils/validate-dto.js.map +1 -1
  57. package/dist/esm/utils/validate-schema.js +2 -4
  58. package/dist/esm/utils/validate-schema.js.map +1 -1
  59. package/dist/types/utils/arkos-router/index.d.ts +2 -1
  60. package/dist/types/utils/cli/dev.d.ts +1 -1
  61. package/dist/types/utils/cli/start.d.ts +1 -1
  62. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"prisma-json-schema-generator.js","sourceRoot":"","sources":["../../../../src/utils/prisma/prisma-json-schema-generator.ts"],"names":[],"mappings":";;;;;;AAEA,mFAAoD;AACpD,sDAG2B;AAC3B,kFAAwD;AAOxD,uGAAsG;AAetG,MAAa,yBAAyB;IAAtC;QACE,WAAM,GAAG,8BAAkB,CAAC,KAAK,EAAE,CAAC;IA8uBtC,CAAC;IAzuBC,oBAAoB,CAAC,MAA8B;QACjD,MAAM,EACJ,SAAS,EACT,WAAW,EACX,iBAAiB,GAAG;YAClB,OAAO;YACP,OAAO;YACP,QAAQ;YACR,OAAO;YACP,UAAU;YACV,gBAAgB;YAChB,QAAQ;YACR,WAAW;YACX,YAAY;YACZ,QAAQ;YACR,WAAW;YACX,YAAY;YACZ,OAAO;YACP,SAAS;YACT,UAAU;SACX,GACF,GAAG,MAAM,CAAC;QAEX,MAAM,gBAAgB,GAAG,IAAA,oCAAmB,EAAC,SAAS,CAAC,CAAC;QACxD,MAAM,YAAY,GAAG,gBAAgB,EAAE,MAAM,EAAE,MAAM,IAAI,EAAE,CAAC;QAC5D,MAAM,kBAAkB,GAAG,gBAAgB,EAAE,kBAAkB,IAAI,EAAE,CAAC;QACtE,MAAM,eAAe,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;QACtE,MAAM,YAAY,GAAG,eAAe,CAAC,QAAQ,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC,CAAC;QAEvE,IAAI,WAAW,EAAE,OAAO,EAAE,MAAM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AC;CACF;AA/uBD,8DA+uBC;AAED,MAAM,yBAAyB,GAAG,IAAI,yBAAyB,EAAE,CAAC;AAElE,kBAAe,yBAAyB,CAAC","sourcesContent":["import { ArkosConfig, RouterConfig } from \"../../exports\";\nimport { AuthPrismaQueryOptions, PrismaQueryOptions } from \"../../types\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport {\n getModuleComponents,\n ValidationFileMappingKey,\n} from \"../dynamic-loader\";\nimport prismaSchemaParser from \"./prisma-schema-parser\";\nimport {\n PrismaModel,\n PrismaField,\n JsonSchema,\n JsonSchemaProperty,\n} from \"./types\";\nimport { localValidatorFileExists } from \"../../modules/swagger/utils/helpers/swagger.router.helpers\";\n\nexport interface SchemaGenerationConfig {\n modelName: string;\n arkosConfig: ArkosConfig;\n schemasToGenerate?: ValidationFileMappingKey[];\n}\n\nexport interface GeneratedSchemas {\n [key: string]: JsonSchema;\n}\n\n/**\n * Enhanced JSON Schema generator that creates schemas based on Prisma models and query options\n */\nexport class PrismaJsonSchemaGenerator {\n schema = prismaSchemaParser.parse();\n\n /**\n * Main method to generate all schemas for a model\n */\n generateModelSchemas(config: SchemaGenerationConfig): GeneratedSchemas {\n const {\n modelName,\n arkosConfig,\n schemasToGenerate = [\n \"model\",\n \"login\",\n \"signup\",\n \"getMe\",\n \"updateMe\",\n \"updatePassword\",\n \"create\",\n \"createOne\",\n \"createMany\",\n \"update\",\n \"updateOne\",\n \"updateMany\",\n \"query\",\n \"findOne\",\n \"findMany\",\n ],\n } = config;\n\n const moduleComponents = getModuleComponents(modelName);\n const routerConfig = moduleComponents?.router?.config || {};\n const prismaQueryOptions = moduleComponents?.prismaQueryOptions || {};\n const authModuleModel = [\"auth\", \"me\", \"password\", \"signup\", \"login\"];\n const isAuthModule = authModuleModel.includes(modelName.toLowerCase());\n\n if (arkosConfig?.swagger?.strict && arkosConfig.swagger.mode !== \"prisma\")\n return {};\n\n if (routerConfig?.disable === true) return {};\n\n const model = this.schema.models.find(\n (m) => m.name.toLowerCase() === modelName.toLowerCase()\n );\n if (!model && !isAuthModule) return {};\n\n const schemas: { [key: string]: JsonSchema } = {};\n\n if (isAuthModule) {\n this.generateAuthSchemas(\n this.schema.models.find((m) => m.name.toLowerCase() === \"user\")!,\n schemas,\n arkosConfig,\n schemasToGenerate,\n prismaQueryOptions as AuthPrismaQueryOptions<any>\n );\n } else {\n if (model)\n this.generateCrudSchemas(\n model,\n schemas,\n arkosConfig,\n schemasToGenerate,\n prismaQueryOptions as PrismaQueryOptions<any>,\n routerConfig\n );\n }\n\n return { ...schemas };\n }\n\n /**\n * Generate auth-specific schemas\n */\n private generateAuthSchemas(\n model: PrismaModel,\n schemas: { [key: string]: JsonSchema },\n arkosConfig: ArkosConfig,\n schemasToGenerate: ValidationFileMappingKey[],\n queryOptions?: AuthPrismaQueryOptions<any>,\n routerConfig?: RouterConfig\n ) {\n const modelName = \"Auth\";\n\n // if no auth activated forget those json schemas\n if (!arkosConfig?.authentication) return schemas;\n\n // Login schema (input)\n if (\n schemasToGenerate.includes(\"login\") &&\n !this.isEndpointDisabled(\"login\", routerConfig) &&\n !localValidatorFileExists(\"login\", modelName, arkosConfig)\n ) {\n schemas[`LoginSchema`] = this.generateLoginSchema(arkosConfig);\n }\n\n // Signup schema (input)\n if (\n schemasToGenerate.includes(\"signup\") &&\n !this.isEndpointDisabled(\"signup\", routerConfig) &&\n !localValidatorFileExists(\"signup\", modelName, arkosConfig)\n ) {\n schemas[`SignupSchema`] = this.generateSignupSchema(\n model,\n queryOptions?.signup\n );\n }\n\n // UpdateMe schema (input)\n if (\n schemasToGenerate.includes(\"updateMe\") &&\n !this.isEndpointDisabled(\"updateMe\", routerConfig) &&\n !localValidatorFileExists(\"updateMe\", modelName, arkosConfig)\n ) {\n schemas[`UpdateMeSchema`] = this.generateUpdateMeSchema(\n model,\n queryOptions?.updateMe\n );\n }\n\n // UpdatePassword schema (input)\n if (\n schemasToGenerate.includes(\"updatePassword\") &&\n !this.isEndpointDisabled(\"updatePassword\", routerConfig) &&\n !localValidatorFileExists(\"updatePassword\", modelName, arkosConfig)\n ) {\n schemas[`UpdatePasswordSchema`] = this.generateUpdatePasswordSchema(\n model,\n queryOptions?.updatePassword\n );\n }\n\n if (\n schemasToGenerate.includes(\"getMe\") &&\n !this.isEndpointDisabled(\"getMe\", routerConfig) &&\n !localValidatorFileExists(\"getMe\", modelName, arkosConfig)\n ) {\n schemas[`GetMeSchema`] = this.generateResponseSchema(\n model,\n queryOptions?.getMe || {},\n \"findOne\"\n );\n }\n }\n\n /**\n * Generate standard CRUD schemas\n */\n private generateCrudSchemas(\n model: PrismaModel,\n schemas: { [key: string]: JsonSchema },\n arkosConfig: ArkosConfig,\n schemasToGenerate: ValidationFileMappingKey[],\n queryOptions?: PrismaQueryOptions<any>,\n routerConfig?: RouterConfig<any>\n ) {\n const modelName = model.name;\n\n const ensureBaseSchemaReference = (\n operation: string,\n modelName: string\n ) => {\n const suffix =\n arkosConfig.validation?.resolver === \"zod\" ? \"Schema\" : \"Dto\";\n\n const singleOpName = operation === \"Create\" ? \"createOne\" : \"updateOne\";\n const hasLocalValidator = localValidatorFileExists(\n singleOpName,\n modelName,\n arkosConfig\n );\n\n if (hasLocalValidator) return `${operation}${modelName}${suffix}`;\n else {\n const modelSchemaKey = `${operation}${modelName}ModelSchema`;\n\n if (!schemas[modelSchemaKey]) {\n if (operation === \"Create\") {\n schemas[modelSchemaKey] = this.generateCreateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"createOne\")\n );\n } else if (operation === \"Update\") {\n schemas[modelSchemaKey] = this.generateUpdateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n );\n }\n }\n\n return modelSchemaKey;\n }\n };\n\n if (\n schemasToGenerate.includes(\"createOne\") &&\n !this.isEndpointDisabled(\"createOne\", routerConfig) &&\n !localValidatorFileExists(\"createOne\", modelName, arkosConfig)\n ) {\n schemas[`Create${modelName}ModelSchema`] = this.generateCreateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"createOne\")\n );\n }\n\n if (\n schemasToGenerate.includes(\"createMany\") &&\n !this.isEndpointDisabled(\"createMany\", routerConfig) &&\n !localValidatorFileExists(\"createMany\", modelName, arkosConfig)\n ) {\n const baseSchemaKey = ensureBaseSchemaReference(\"Create\", modelName);\n schemas[`CreateMany${modelName}ModelSchema`] = {\n type: \"array\",\n items: { $ref: `#/components/schemas/${baseSchemaKey}` },\n };\n }\n\n if (\n schemasToGenerate.includes(\"updateOne\") &&\n !this.isEndpointDisabled(\"updateOne\", routerConfig) &&\n !localValidatorFileExists(\"updateOne\", modelName, arkosConfig)\n ) {\n schemas[`Update${modelName}ModelSchema`] = this.generateUpdateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n );\n }\n\n if (\n schemasToGenerate.includes(\"updateMany\") &&\n !this.isEndpointDisabled(\"updateMany\", routerConfig) &&\n !localValidatorFileExists(\"updateMany\", modelName, arkosConfig)\n ) {\n schemas[`UpdateMany${modelName}ModelSchema`] = this.generateUpdateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n );\n }\n if (\n schemasToGenerate.includes(\"findOne\") &&\n !this.isEndpointDisabled(\"findOne\", routerConfig) &&\n !localValidatorFileExists(\"findOne\", modelName, arkosConfig)\n ) {\n schemas[`FindOne${modelName}ModelSchema`] = this.generateResponseSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"findOne\"),\n \"findOne\"\n );\n }\n\n if (\n schemasToGenerate.includes(\"findMany\") &&\n !this.isEndpointDisabled(\"findMany\", routerConfig) &&\n !localValidatorFileExists(\"findMany\", modelName, arkosConfig)\n ) {\n schemas[`FindMany${modelName}ModelSchema`] = {\n type: \"array\",\n items: this.generateResponseSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"findMany\"),\n \"findMany\"\n ),\n };\n }\n }\n\n /**\n * Generate create schema (excludes ID, includes relation IDs only)\n */\n private generateCreateSchema(\n model: PrismaModel,\n _: Record<string, any>\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n const restrictedFields = [\"createdAt\", \"updatedAt\", \"deletedAt\", \"id\"];\n\n if (model.name.toLowerCase() === \"auth\")\n restrictedFields.push(\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"lastLoginAt\"\n );\n\n for (const field of model.fields) {\n const isForeignKey = model.fields.some(\n (_field) => _field.foreignKeyField === field.name\n );\n if (field.isId || restrictedFields.includes(field.name) || isForeignKey)\n continue;\n\n if (this.isModelRelation(field.type)) {\n if (!field.isArray) {\n const referencedModel = prismaSchemaParser.models.find(\n (_model) => _model.name === field.type\n )!;\n\n properties[field.name] = {\n type: \"object\",\n properties: {\n [field.foreignReferenceField || \"id\"]: {\n type: this.mapPrismaTypeToJsonSchema(\n referencedModel?.fields.find(\n (_field) => _field.name === field.foreignReferenceField\n )?.type || \"String\"\n ),\n },\n },\n };\n\n if (!field.isOptional && field.defaultValue === undefined)\n required.push(field.name);\n }\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n // Field is required if not optional, no default, and not array\n if (\n !field.isOptional &&\n field.defaultValue === undefined &&\n !field.isArray\n ) {\n required.push(field.name);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Generate update schema (all fields optional, includes relation IDs only)\n */\n private generateUpdateSchema(\n model: PrismaModel,\n _: Record<string, any>\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const autoFillFields = [\"createdAt\", \"updatedAt\", \"deletedAt\", \"id\"];\n\n for (const field of model.fields) {\n const isForeignKey = model.fields.some(\n (_field) => _field.foreignKeyField === field.name\n );\n if (field.isId || autoFillFields.includes(field.name) || isForeignKey)\n continue;\n\n if (this.isModelRelation(field.type)) {\n if (!field.isArray) {\n const referencedModel = prismaSchemaParser.models.find(\n (_model) => _model.name === field.type\n )!;\n\n properties[field.name] = {\n type: \"object\",\n properties: {\n [field.foreignReferenceField || \"id\"]: {\n type: this.mapPrismaTypeToJsonSchema(\n referencedModel?.fields.find(\n (_field) => _field.name === field.foreignReferenceField\n )?.type || \"String\"\n ),\n },\n },\n };\n }\n\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n }\n\n return {\n type: \"object\",\n properties,\n required: [], // All fields are optional in update\n };\n }\n\n /**\n * Generate response schema (includes nested relations based on query options)\n */\n private generateResponseSchema(\n model: PrismaModel,\n options: Record<string, any>,\n _: \"findOne\" | \"findMany\"\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n\n // Get select and include options\n const selectFields = options?.select;\n const omittedFields = options?.omit;\n const includeRelations = options?.include;\n\n for (const field of model.fields) {\n // Skip password fields\n if (field.name === \"password\") continue;\n\n // Skip ommited fields\n if (omittedFields && omittedFields[field.name]) continue;\n\n // If select is specified, only include selected fields\n if (selectFields && !selectFields[field.name]) continue;\n\n // Handle relations\n if (this.isModelRelation(field.type)) {\n // Include relation if specified in include option\n if (includeRelations?.[field.name]) {\n const relationModel = this.schema.models.find(\n (m) => m.name === field.type\n );\n\n if (relationModel) {\n const relationSchema = this.generateNestedRelationSchema(\n relationModel,\n includeRelations[field.name]\n );\n properties[field.name] = field.isArray\n ? { type: \"array\", items: relationSchema }\n : relationSchema;\n }\n }\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n // Field is required if not optional (for response schemas, we include all by default)\n if (!field.isOptional) required.push(field.name);\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Generate nested relation schema\n */\n private generateNestedRelationSchema(\n model: PrismaModel,\n includeOptions: any\n ): JsonSchemaProperty {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n\n // Handle nested select\n const selectFields = includeOptions?.select;\n const nestedIncludes = includeOptions?.include;\n\n for (const field of model.fields) {\n // Skip password fields\n if (field.name.toLowerCase().includes(\"password\")) {\n continue;\n }\n\n if (selectFields && !selectFields[field.name]) {\n continue;\n }\n\n if (this.isModelRelation(field.type)) {\n if (nestedIncludes?.[field.name]) {\n const relationModel = this.schema.models.find(\n (m) => m.name === field.type\n );\n if (relationModel) {\n const nestedSchema = this.generateNestedRelationSchema(\n relationModel,\n nestedIncludes[field.name]\n );\n properties[field.name] = field.isArray\n ? { type: \"array\", items: nestedSchema }\n : nestedSchema;\n }\n }\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n if (!field.isOptional) {\n required.push(field.name);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Auth-specific schema generators\n */\n private generateLoginSchema(arkosConfig?: ArkosConfig): JsonSchema {\n const userNameFields =\n arkosConfig?.authentication?.login?.allowedUsernames || [];\n\n // Helper function to get display name for nested fields\n const getDisplayName = (field: string) => {\n if (field.includes(\".\")) return field.split(\".\").pop() || field; // Get the part after the last dot\n return field;\n };\n\n // Base schema with password (always required)\n const baseSchema: JsonSchemaProperty = {\n type: \"object\",\n properties: {\n password: {\n type: \"string\",\n minLength: 8,\n },\n },\n required: [\"password\"],\n };\n\n // Add all username fields to properties\n userNameFields.forEach((field) => {\n const displayName = getDisplayName(field);\n baseSchema.properties![displayName] = {\n type: \"string\",\n format: \"string\",\n description: `Username field: ${field}`, // Optional: show original field path\n };\n });\n\n // At least one username field must be provided along with password\n if (userNameFields.length > 0) {\n const usernameDisplayNames = userNameFields.map(getDisplayName);\n\n return {\n ...baseSchema,\n anyOf: usernameDisplayNames.map(() => ({\n required: [...baseSchema.required!],\n })),\n };\n }\n\n return baseSchema;\n }\n private generateSignupSchema(\n model: PrismaModel,\n options?: Record<string, any>\n ): JsonSchema {\n // Similar to create but might have specific required fields\n const singupSchema = this.generateCreateSchema(model, options || {});\n\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete singupSchema?.properties?.[field];\n });\n\n return singupSchema;\n }\n\n private generateUpdateMeSchema(\n model: PrismaModel,\n options?: Record<string, any>\n ): JsonSchema {\n // Similar to update but might exclude certain fields like role, etc.\n const updateSchema = this.generateUpdateSchema(model, options || {});\n\n // Remove sensitive fields that users shouldn't update themselves\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"password\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete updateSchema?.properties?.[field];\n });\n\n return updateSchema;\n }\n\n private generateUpdatePasswordSchema(\n _: PrismaModel,\n _1?: Record<string, any>\n ): JsonSchema {\n return {\n type: \"object\",\n properties: {\n currentPassword: { type: \"string\" },\n newPassword: { type: \"string\", minLength: 8 },\n },\n required: [\"currentPassword\", \"newPassword\"],\n };\n }\n\n /**\n * Utility methods\n */\n private resolvePrismaQueryOptions(\n prismaQueryOptions?: PrismaQueryOptions<any> | AuthPrismaQueryOptions<any>,\n action?: ValidationFileMappingKey\n ): Record<string, any> {\n if (!prismaQueryOptions || !action) {\n return {};\n }\n\n const options = prismaQueryOptions as any;\n const actionOptions = options[action] || {};\n\n // Start with deprecated queryOptions (for backward compatibility)\n let mergedOptions = options.queryOptions || {};\n\n // Apply global options (replaces queryOptions)\n if (options.global)\n mergedOptions = deepmerge(mergedOptions, options.global);\n\n // Apply general operation options based on action type\n const generalOptions = this.getGeneralOptionsForAction(options, action);\n if (generalOptions)\n mergedOptions = deepmerge(mergedOptions, generalOptions);\n\n // Finally apply specific action options (highest priority)\n if (actionOptions) mergedOptions = deepmerge(mergedOptions, actionOptions);\n\n return mergedOptions;\n }\n\n /**\n * Helps in remmaping those prisma query options that combines many operations for example find, save...\n */\n private getGeneralOptionsForAction(\n options: any,\n action: ValidationFileMappingKey\n ): Record<string, any> | null {\n const actionMap: { [key: string]: string[] } = {\n find: [\"findOne\", \"findMany\"],\n create: [\"createOne\", \"createMany\"],\n update: [\"updateOne\", \"updateMany\"],\n delete: [\"deleteOne\", \"deleteMany\"],\n save: [\"createOne\", \"createMany\", \"updateOne\", \"updateMany\"],\n saveOne: [\"createOne\", \"updateOne\"],\n saveMany: [\"createMany\", \"updateMany\"],\n };\n\n for (const [optionKey, actions] of Object.entries(actionMap)) {\n if (actions.includes(action) && options[optionKey]) {\n return options[optionKey];\n }\n }\n\n return null;\n }\n\n private isEndpointDisabled(\n endpoint: string,\n routerConfig?: RouterConfig<any>\n ): boolean {\n if (!routerConfig?.disable) return false;\n\n if (typeof routerConfig.disable === \"boolean\") {\n return routerConfig.disable;\n }\n\n return (\n routerConfig.disable[endpoint as keyof typeof routerConfig.disable] ||\n false\n );\n }\n\n private isModelRelation(typeName: string): boolean {\n return this.schema.models.some((m) => m.name === typeName);\n }\n\n private convertFieldToJsonSchema(field: PrismaField): JsonSchemaProperty {\n // Reuse the existing method from the original generator\n const baseType = this.mapPrismaTypeToJsonSchema(field.type);\n const property: JsonSchemaProperty = { type: baseType };\n\n if (field.isArray) {\n property.type = \"array\";\n property.items = { type: this.mapPrismaTypeToJsonSchema(field.type) };\n }\n\n if (field.defaultValue !== undefined) {\n property.default = field.defaultValue;\n }\n\n if (field.type === \"DateTime\") {\n property.format = \"date-time\";\n }\n\n if (this.isEnum(field.type)) {\n const enumDef = this.schema.enums.find((e) => e.name === field.type);\n if (enumDef) {\n property.enum = enumDef.values;\n }\n }\n\n return property;\n }\n\n private mapPrismaTypeToJsonSchema(prismaType: string): string {\n const typeMap: { [key: string]: string } = {\n String: \"string\",\n Int: \"number\",\n Float: \"number\",\n Boolean: \"boolean\",\n DateTime: \"string\",\n Json: \"object\",\n Bytes: \"string\",\n };\n\n if (typeMap[prismaType]) return typeMap[prismaType];\n\n if (this.isEnum(prismaType)) return \"string\";\n\n if (this.isModelRelation(prismaType)) return \"object\";\n\n return \"string\";\n }\n\n private isEnum(typeName: string): boolean {\n return this.schema.enums.some((e) => e.name === typeName);\n }\n}\n\nconst prismaJsonSchemaGenerator = new PrismaJsonSchemaGenerator();\n\nexport default prismaJsonSchemaGenerator;\n"]}
1
+ {"version":3,"file":"prisma-json-schema-generator.js","sourceRoot":"","sources":["../../../../src/utils/prisma/prisma-json-schema-generator.ts"],"names":[],"mappings":";;;;;;AAEA,mFAAoD;AACpD,sDAG2B;AAC3B,kFAAwD;AAOxD,uGAAsG;AAetG,MAAa,yBAAyB;IAAtC;QACE,WAAM,GAAG,8BAAkB,CAAC,KAAK,EAAE,CAAC;IAuwBtC,CAAC;IAlwBC,oBAAoB,CAAC,MAA8B;QACjD,MAAM,EACJ,SAAS,EACT,WAAW,EACX,iBAAiB,GAAG;YAClB,OAAO;YACP,OAAO;YACP,QAAQ;YACR,OAAO;YACP,UAAU;YACV,gBAAgB;YAChB,QAAQ;YACR,WAAW;YACX,YAAY;YACZ,QAAQ;YACR,WAAW;YACX,YAAY;YACZ,OAAO;YACP,SAAS;YACT,UAAU;SACX,GACF,GAAG,MAAM,CAAC;QAEX,MAAM,gBAAgB,GAAG,IAAA,oCAAmB,EAAC,SAAS,CAAC,CAAC;QACxD,MAAM,YAAY,GAAG,gBAAgB,EAAE,MAAM,EAAE,MAAM,IAAI,EAAE,CAAC;QAC5D,MAAM,kBAAkB,GAAG,gBAAgB,EAAE,kBAAkB,IAAI,EAAE,CAAC;QACtE,MAAM,eAAe,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,UAAU,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;QACtE,MAAM,YAAY,GAAG,eAAe,CAAC,QAAQ,CAAC,SAAS,CAAC,WAAW,EAAE,CAAC,CAAC;QAEvE,IAAI,WAAW,EAAE,OAAO,EAAE,MAAM,IAAI,WAAW,CAAC,OAAO,CAAC,IAAI,KAAK,QAAQ;YACvE,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AC;IAClB,CAAC;IAEO,yBAAyB,CAAC,UAAkB;QAClD,MAAM,OAAO,GAA8B;YACzC,MAAM,EAAE,QAAQ;YAChB,GAAG,EAAE,QAAQ;YACb,KAAK,EAAE,QAAQ;YACf,OAAO,EAAE,SAAS;YAClB,QAAQ,EAAE,QAAQ;YAClB,IAAI,EAAE,QAAQ;YACd,KAAK,EAAE,QAAQ;SAChB,CAAC;QAEF,IAAI,OAAO,CAAC,UAAU,CAAC;YAAE,OAAO,OAAO,CAAC,UAAU,CAAC,CAAC;QAEpD,IAAI,IAAI,CAAC,MAAM,CAAC,UAAU,CAAC;YAAE,OAAO,QAAQ,CAAC;QAE7C,IAAI,IAAI,CAAC,eAAe,CAAC,UAAU,CAAC;YAAE,OAAO,QAAQ,CAAC;QAEtD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAEO,MAAM,CAAC,QAAgB;QAC7B,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;IAC5D,CAAC;CACF;AAxwBD,8DAwwBC;AAED,MAAM,yBAAyB,GAAG,IAAI,yBAAyB,EAAE,CAAC;AAElE,kBAAe,yBAAyB,CAAC","sourcesContent":["import { ArkosConfig, RouterConfig } from \"../../exports\";\nimport { AuthPrismaQueryOptions, PrismaQueryOptions } from \"../../types\";\nimport deepmerge from \"../helpers/deepmerge.helper\";\nimport {\n getModuleComponents,\n ValidationFileMappingKey,\n} from \"../dynamic-loader\";\nimport prismaSchemaParser from \"./prisma-schema-parser\";\nimport {\n PrismaModel,\n PrismaField,\n JsonSchema,\n JsonSchemaProperty,\n} from \"./types\";\nimport { localValidatorFileExists } from \"../../modules/swagger/utils/helpers/swagger.router.helpers\";\n\nexport interface SchemaGenerationConfig {\n modelName: string;\n arkosConfig: ArkosConfig;\n schemasToGenerate?: ValidationFileMappingKey[];\n}\n\nexport interface GeneratedSchemas {\n [key: string]: JsonSchema;\n}\n\n/**\n * Enhanced JSON Schema generator that creates schemas based on Prisma models and query options\n */\nexport class PrismaJsonSchemaGenerator {\n schema = prismaSchemaParser.parse();\n\n /**\n * Main method to generate all schemas for a model\n */\n generateModelSchemas(config: SchemaGenerationConfig): GeneratedSchemas {\n const {\n modelName,\n arkosConfig,\n schemasToGenerate = [\n \"model\",\n \"login\",\n \"signup\",\n \"getMe\",\n \"updateMe\",\n \"updatePassword\",\n \"create\",\n \"createOne\",\n \"createMany\",\n \"update\",\n \"updateOne\",\n \"updateMany\",\n \"query\",\n \"findOne\",\n \"findMany\",\n ],\n } = config;\n\n const moduleComponents = getModuleComponents(modelName);\n const routerConfig = moduleComponents?.router?.config || {};\n const prismaQueryOptions = moduleComponents?.prismaQueryOptions || {};\n const authModuleModel = [\"auth\", \"me\", \"password\", \"signup\", \"login\"];\n const isAuthModule = authModuleModel.includes(modelName.toLowerCase());\n\n if (arkosConfig?.swagger?.strict && arkosConfig.swagger.mode !== \"prisma\")\n return {};\n\n if (routerConfig?.disable === true) return {};\n\n const model = this.schema.models.find(\n (m) => m.name.toLowerCase() === modelName.toLowerCase()\n );\n if (!model && !isAuthModule) return {};\n\n const schemas: { [key: string]: JsonSchema } = {};\n\n if (isAuthModule) {\n this.generateAuthSchemas(\n this.schema.models.find((m) => m.name.toLowerCase() === \"user\")!,\n schemas,\n arkosConfig,\n schemasToGenerate,\n prismaQueryOptions as AuthPrismaQueryOptions<any>\n );\n } else {\n if (model)\n this.generateCrudSchemas(\n model,\n schemas,\n arkosConfig,\n schemasToGenerate,\n prismaQueryOptions as PrismaQueryOptions<any>,\n routerConfig\n );\n }\n\n return { ...schemas };\n }\n\n /**\n * Generate auth-specific schemas\n */\n private generateAuthSchemas(\n model: PrismaModel,\n schemas: { [key: string]: JsonSchema },\n arkosConfig: ArkosConfig,\n schemasToGenerate: ValidationFileMappingKey[],\n queryOptions?: AuthPrismaQueryOptions<any>,\n routerConfig?: RouterConfig\n ) {\n const modelName = \"Auth\";\n\n // if no auth activated forget those json schemas\n if (!arkosConfig?.authentication) return schemas;\n\n // Login schema (input)\n if (\n schemasToGenerate.includes(\"login\") &&\n !this.isEndpointDisabled(\"login\", routerConfig) &&\n !localValidatorFileExists(\"login\", modelName, arkosConfig)\n ) {\n schemas[`LoginSchema`] = this.generateLoginSchema(arkosConfig);\n }\n\n // Signup schema (input)\n if (\n schemasToGenerate.includes(\"signup\") &&\n !this.isEndpointDisabled(\"signup\", routerConfig) &&\n !localValidatorFileExists(\"signup\", modelName, arkosConfig)\n ) {\n schemas[`SignupSchema`] = this.generateSignupSchema(\n model,\n queryOptions?.signup\n );\n }\n\n // UpdateMe schema (input)\n if (\n schemasToGenerate.includes(\"updateMe\") &&\n !this.isEndpointDisabled(\"updateMe\", routerConfig) &&\n !localValidatorFileExists(\"updateMe\", modelName, arkosConfig)\n ) {\n schemas[`UpdateMeSchema`] = this.generateUpdateMeSchema(\n model,\n queryOptions?.updateMe\n );\n }\n\n // UpdatePassword schema (input)\n if (\n schemasToGenerate.includes(\"updatePassword\") &&\n !this.isEndpointDisabled(\"updatePassword\", routerConfig) &&\n !localValidatorFileExists(\"updatePassword\", modelName, arkosConfig)\n ) {\n schemas[`UpdatePasswordSchema`] = this.generateUpdatePasswordSchema(\n model,\n queryOptions?.updatePassword\n );\n }\n\n if (\n schemasToGenerate.includes(\"getMe\") &&\n !this.isEndpointDisabled(\"getMe\", routerConfig) &&\n !localValidatorFileExists(\"getMe\", modelName, arkosConfig)\n ) {\n schemas[`GetMeSchema`] = this.generateResponseSchema(\n model,\n queryOptions?.getMe || {},\n \"findOne\"\n );\n }\n }\n\n /**\n * Generate standard CRUD schemas\n */\n private generateCrudSchemas(\n model: PrismaModel,\n schemas: { [key: string]: JsonSchema },\n arkosConfig: ArkosConfig,\n schemasToGenerate: ValidationFileMappingKey[],\n queryOptions?: PrismaQueryOptions<any>,\n routerConfig?: RouterConfig<any>\n ) {\n const modelName = model.name;\n\n const ensureBaseSchemaReference = (\n operation: string,\n modelName: string\n ) => {\n const suffix =\n arkosConfig.validation?.resolver === \"zod\" ? \"Schema\" : \"Dto\";\n\n const singleOpName = operation === \"Create\" ? \"createOne\" : \"updateOne\";\n const hasLocalValidator = localValidatorFileExists(\n singleOpName,\n modelName,\n arkosConfig\n );\n\n if (hasLocalValidator) return `${operation}${modelName}${suffix}`;\n else {\n const modelSchemaKey = `${operation}${modelName}ModelSchema`;\n\n if (!schemas[modelSchemaKey]) {\n if (operation === \"Create\") {\n schemas[modelSchemaKey] = this.generateCreateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"createOne\")\n );\n } else if (operation === \"Update\") {\n schemas[modelSchemaKey] = this.generateUpdateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n );\n }\n }\n\n return modelSchemaKey;\n }\n };\n\n if (\n schemasToGenerate.includes(\"createOne\") &&\n !this.isEndpointDisabled(\"createOne\", routerConfig) &&\n !localValidatorFileExists(\"createOne\", modelName, arkosConfig)\n ) {\n schemas[`Create${modelName}ModelSchema`] = this.generateCreateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"createOne\")\n );\n }\n\n if (\n schemasToGenerate.includes(\"createMany\") &&\n !this.isEndpointDisabled(\"createMany\", routerConfig) &&\n !localValidatorFileExists(\"createMany\", modelName, arkosConfig)\n ) {\n const baseSchemaKey = ensureBaseSchemaReference(\"Create\", modelName);\n schemas[`CreateMany${modelName}ModelSchema`] = {\n type: \"array\",\n items: { $ref: `#/components/schemas/${baseSchemaKey}` },\n };\n }\n\n if (\n schemasToGenerate.includes(\"updateOne\") &&\n !this.isEndpointDisabled(\"updateOne\", routerConfig) &&\n !localValidatorFileExists(\"updateOne\", modelName, arkosConfig)\n ) {\n schemas[`Update${modelName}ModelSchema`] = this.generateUpdateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n );\n }\n\n if (\n schemasToGenerate.includes(\"updateMany\") &&\n !this.isEndpointDisabled(\"updateMany\", routerConfig) &&\n !localValidatorFileExists(\"updateMany\", modelName, arkosConfig)\n ) {\n schemas[`UpdateMany${modelName}ModelSchema`] = this.generateUpdateSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"updateOne\")\n );\n }\n if (\n schemasToGenerate.includes(\"findOne\") &&\n !this.isEndpointDisabled(\"findOne\", routerConfig) &&\n !localValidatorFileExists(\"findOne\", modelName, arkosConfig)\n ) {\n schemas[`FindOne${modelName}ModelSchema`] = this.generateResponseSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"findOne\"),\n \"findOne\"\n );\n }\n\n if (\n schemasToGenerate.includes(\"findMany\") &&\n !this.isEndpointDisabled(\"findMany\", routerConfig) &&\n !localValidatorFileExists(\"findMany\", modelName, arkosConfig)\n ) {\n schemas[`FindMany${modelName}ModelSchema`] = {\n type: \"array\",\n items: this.generateResponseSchema(\n model,\n this.resolvePrismaQueryOptions(queryOptions, \"findMany\"),\n \"findMany\"\n ),\n };\n }\n }\n\n /**\n * Generate create schema (excludes ID, includes relation IDs only)\n */\n private generateCreateSchema(\n model: PrismaModel,\n _: Record<string, any>\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n const restrictedFields = [\"createdAt\", \"updatedAt\", \"deletedAt\", \"id\"];\n\n if (model.name.toLowerCase() === \"auth\")\n restrictedFields.push(\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"lastLoginAt\"\n );\n\n for (const field of model.fields) {\n const isForeignKey = model.fields.some(\n (_field) => _field.foreignKeyField === field.name\n );\n if (field.isId || restrictedFields.includes(field.name) || isForeignKey)\n continue;\n\n if (this.isModelRelation(field.type)) {\n if (!field.isArray) {\n const referencedModel = prismaSchemaParser.models.find(\n (_model) => _model.name === field.type\n )!;\n\n properties[field.name] = {\n type: \"object\",\n properties: {\n [field.foreignReferenceField || \"id\"]: {\n type: this.mapPrismaTypeToJsonSchema(\n referencedModel?.fields.find(\n (_field) => _field.name === field.foreignReferenceField\n )?.type || \"String\"\n ),\n },\n },\n };\n\n if (!field.isOptional && field.defaultValue === undefined)\n required.push(field.name);\n }\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n // Field is required if not optional, no default, and not array\n if (\n !field.isOptional &&\n field.defaultValue === undefined &&\n !field.isArray\n ) {\n required.push(field.name);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Generate update schema (all fields optional, includes relation IDs only)\n */\n private generateUpdateSchema(\n model: PrismaModel,\n _: Record<string, any>\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const autoFillFields = [\"createdAt\", \"updatedAt\", \"deletedAt\", \"id\"];\n\n for (const field of model.fields) {\n const isForeignKey = model.fields.some(\n (_field) => _field.foreignKeyField === field.name\n );\n if (field.isId || autoFillFields.includes(field.name) || isForeignKey)\n continue;\n\n if (this.isModelRelation(field.type)) {\n if (!field.isArray) {\n const referencedModel = prismaSchemaParser.models.find(\n (_model) => _model.name === field.type\n )!;\n\n properties[field.name] = {\n type: \"object\",\n properties: {\n [field.foreignReferenceField || \"id\"]: {\n type: this.mapPrismaTypeToJsonSchema(\n referencedModel?.fields.find(\n (_field) => _field.name === field.foreignReferenceField\n )?.type || \"String\"\n ),\n },\n },\n };\n }\n\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n }\n\n return {\n type: \"object\",\n properties,\n required: [], // All fields are optional in update\n };\n }\n\n /**\n * Generate response schema (includes nested relations based on query options)\n */\n private generateResponseSchema(\n model: PrismaModel,\n options: Record<string, any>,\n _: \"findOne\" | \"findMany\"\n ): JsonSchema {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n\n // Get select and include options\n const selectFields = options?.select;\n const omittedFields = options?.omit;\n const includeRelations = options?.include;\n\n if (selectFields && includeRelations) {\n throw new Error(\n `Found both 'select' and 'include' in ${model.name} query options. Please use one of them.`\n );\n }\n\n for (const field of model.fields) {\n // Skip password fields\n if (field.name === \"password\") continue;\n\n // Skip ommited fields\n if (omittedFields && omittedFields[field.name]) continue;\n\n // If select is specified, only include selected fields\n if (selectFields && !selectFields[field.name]) continue;\n\n // Handle relations\n if (this.isModelRelation(field.type)) {\n // Include relation if specified in include option\n if (\n includeRelations?.[field.name] ||\n selectFields?.[field.name] ||\n omittedFields?.[field.name] === false\n ) {\n const relationModel = this.schema.models.find(\n (m) => m.name === field.type\n );\n\n if (relationModel) {\n const relationSchema = this.generateNestedRelationSchema(\n relationModel,\n includeRelations?.[field.name] ||\n selectFields?.[field.name] ||\n omittedFields?.[field.name]\n );\n properties[field.name] = field.isArray\n ? { type: \"array\", items: relationSchema }\n : relationSchema;\n }\n }\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n // Field is required if not optional (for response schemas, we include all by default)\n if (!field.isOptional) required.push(field.name);\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Generate nested relation schema\n */\n private generateNestedRelationSchema(\n model: PrismaModel,\n includeOptions: any\n ): JsonSchemaProperty {\n const properties: { [key: string]: JsonSchemaProperty } = {};\n const required: string[] = [];\n\n // Handle nested select\n const selectFields = includeOptions?.select;\n const nestedIncludes = includeOptions?.include;\n const ommittedFields = includeOptions?.omit;\n\n if (selectFields && nestedIncludes) {\n throw new Error(\n `Found both 'select' and 'include' in nested ${model.name} query options. Please use one of them.`\n );\n }\n\n for (const field of model.fields) {\n // Skip password fields\n if (field.name.toLowerCase().includes(\"password\")) {\n continue;\n }\n\n if (selectFields && !selectFields[field.name]) {\n continue;\n }\n\n if (this.isModelRelation(field.type)) {\n if (\n nestedIncludes?.[field.name] ||\n selectFields?.[field.name] ||\n ommittedFields?.[field.name] === false\n ) {\n const relationModel = this.schema.models.find(\n (m) => m.name === field.type\n );\n if (relationModel) {\n const nestedSchema = this.generateNestedRelationSchema(\n relationModel,\n nestedIncludes?.[field.name] ||\n selectFields?.[field.name] ||\n ommittedFields?.[field.name]\n );\n properties[field.name] = field.isArray\n ? { type: \"array\", items: nestedSchema }\n : nestedSchema;\n }\n }\n continue;\n }\n\n const property = this.convertFieldToJsonSchema(field);\n properties[field.name] = property;\n\n if (!field.isOptional) {\n required.push(field.name);\n }\n }\n\n return {\n type: \"object\",\n properties,\n required,\n };\n }\n\n /**\n * Auth-specific schema generators\n */\n private generateLoginSchema(arkosConfig?: ArkosConfig): JsonSchema {\n const userNameFields =\n arkosConfig?.authentication?.login?.allowedUsernames || [];\n\n // Helper function to get display name for nested fields\n const getDisplayName = (field: string) => {\n if (field.includes(\".\")) return field.split(\".\").pop() || field; // Get the part after the last dot\n return field;\n };\n\n // Base schema with password (always required)\n const baseSchema: JsonSchemaProperty = {\n type: \"object\",\n properties: {\n password: {\n type: \"string\",\n minLength: 8,\n },\n },\n required: [\"password\"],\n };\n\n // Add all username fields to properties\n userNameFields.forEach((field) => {\n const displayName = getDisplayName(field);\n baseSchema.properties![displayName] = {\n type: \"string\",\n format: \"string\",\n description: `Username field: ${field}`, // Optional: show original field path\n };\n });\n\n // At least one username field must be provided along with password\n if (userNameFields.length > 0) {\n const usernameDisplayNames = userNameFields.map(getDisplayName);\n\n return {\n ...baseSchema,\n anyOf: usernameDisplayNames.map(() => ({\n required: [...baseSchema.required!],\n })),\n };\n }\n\n return baseSchema;\n }\n private generateSignupSchema(\n model: PrismaModel,\n options?: Record<string, any>\n ): JsonSchema {\n // Similar to create but might have specific required fields\n const singupSchema = this.generateCreateSchema(model, options || {});\n\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete singupSchema?.properties?.[field];\n });\n\n return singupSchema;\n }\n\n private generateUpdateMeSchema(\n model: PrismaModel,\n options?: Record<string, any>\n ): JsonSchema {\n // Similar to update but might exclude certain fields like role, etc.\n const updateSchema = this.generateUpdateSchema(model, options || {});\n\n // Remove sensitive fields that users shouldn't update themselves\n const restrictedFields = [\n \"roles\",\n \"role\",\n \"isActive\",\n \"isStaff\",\n \"isSuperUser\",\n \"passwordChangedAt\",\n \"deletedSelfAccountAt\",\n \"password\",\n \"lastLoginAt\",\n ];\n restrictedFields.forEach((field) => {\n delete updateSchema?.properties?.[field];\n });\n\n return updateSchema;\n }\n\n private generateUpdatePasswordSchema(\n _: PrismaModel,\n _1?: Record<string, any>\n ): JsonSchema {\n return {\n type: \"object\",\n properties: {\n currentPassword: { type: \"string\" },\n newPassword: { type: \"string\", minLength: 8 },\n },\n required: [\"currentPassword\", \"newPassword\"],\n };\n }\n\n /**\n * Utility methods\n */\n private resolvePrismaQueryOptions(\n prismaQueryOptions?: PrismaQueryOptions<any> | AuthPrismaQueryOptions<any>,\n action?: ValidationFileMappingKey\n ): Record<string, any> {\n if (!prismaQueryOptions || !action) {\n return {};\n }\n\n const options = prismaQueryOptions as any;\n const actionOptions = options[action] || {};\n\n // Start with deprecated queryOptions (for backward compatibility)\n let mergedOptions = options.queryOptions || {};\n\n // Apply global options (replaces queryOptions)\n if (options.global)\n mergedOptions = deepmerge(mergedOptions, options.global);\n\n // Apply general operation options based on action type\n const generalOptions = this.getGeneralOptionsForAction(options, action);\n if (generalOptions)\n mergedOptions = deepmerge(mergedOptions, generalOptions);\n\n // Finally apply specific action options (highest priority)\n if (actionOptions) mergedOptions = deepmerge(mergedOptions, actionOptions);\n\n return mergedOptions;\n }\n\n /**\n * Helps in remmaping those prisma query options that combines many operations for example find, save...\n */\n private getGeneralOptionsForAction(\n options: any,\n action: ValidationFileMappingKey\n ): Record<string, any> | null {\n const actionMap: { [key: string]: string[] } = {\n find: [\"findOne\", \"findMany\"],\n create: [\"createOne\", \"createMany\"],\n update: [\"updateOne\", \"updateMany\"],\n delete: [\"deleteOne\", \"deleteMany\"],\n save: [\"createOne\", \"createMany\", \"updateOne\", \"updateMany\"],\n saveOne: [\"createOne\", \"updateOne\"],\n saveMany: [\"createMany\", \"updateMany\"],\n };\n\n for (const [optionKey, actions] of Object.entries(actionMap)) {\n if (actions.includes(action) && options[optionKey]) {\n return options[optionKey];\n }\n }\n\n return null;\n }\n\n private isEndpointDisabled(\n endpoint: string,\n routerConfig?: RouterConfig<any>\n ): boolean {\n if (!routerConfig?.disable) return false;\n\n if (typeof routerConfig.disable === \"boolean\") {\n return routerConfig.disable;\n }\n\n return (\n routerConfig.disable[endpoint as keyof typeof routerConfig.disable] ||\n false\n );\n }\n\n private isModelRelation(typeName: string): boolean {\n return this.schema.models.some((m) => m.name === typeName);\n }\n\n private convertFieldToJsonSchema(field: PrismaField): JsonSchemaProperty {\n // Reuse the existing method from the original generator\n const baseType = this.mapPrismaTypeToJsonSchema(field.type);\n const property: JsonSchemaProperty = { type: baseType };\n\n if (field.isArray) {\n property.type = \"array\";\n property.items = { type: this.mapPrismaTypeToJsonSchema(field.type) };\n }\n\n if (field.defaultValue !== undefined) {\n property.default = field.defaultValue;\n }\n\n if (field.type === \"DateTime\") {\n property.format = \"date-time\";\n }\n\n if (this.isEnum(field.type)) {\n const enumDef = this.schema.enums.find((e) => e.name === field.type);\n if (enumDef) {\n property.enum = enumDef.values;\n }\n }\n\n return property;\n }\n\n private mapPrismaTypeToJsonSchema(prismaType: string): string {\n const typeMap: { [key: string]: string } = {\n String: \"string\",\n Int: \"number\",\n Float: \"number\",\n Boolean: \"boolean\",\n DateTime: \"string\",\n Json: \"object\",\n Bytes: \"string\",\n };\n\n if (typeMap[prismaType]) return typeMap[prismaType];\n\n if (this.isEnum(prismaType)) return \"string\";\n\n if (this.isModelRelation(prismaType)) return \"object\";\n\n return \"string\";\n }\n\n private isEnum(typeName: string): boolean {\n return this.schema.enums.some((e) => e.name === typeName);\n }\n}\n\nconst prismaJsonSchemaGenerator = new PrismaJsonSchemaGenerator();\n\nexport default prismaJsonSchemaGenerator;\n"]}
@@ -1,17 +1,13 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.default = validateDto;
7
4
  const class_transformer_1 = require("class-transformer");
8
5
  const class_validator_1 = require("class-validator");
9
- const app_error_1 = __importDefault(require("../modules/error-handler/utils/app-error"));
10
6
  async function validateDto(DtoClass, data, validationOptions) {
11
7
  const dataDto = (0, class_transformer_1.plainToInstance)(DtoClass, data);
12
8
  const errors = await (0, class_validator_1.validate)(dataDto, validationOptions);
13
9
  if (errors.length > 0)
14
- throw new app_error_1.default("Invalid request body", 400, errors, "InvalidRequestBody");
10
+ throw errors;
15
11
  return dataDto;
16
12
  }
17
13
  //# sourceMappingURL=validate-dto.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-dto.js","sourceRoot":"","sources":["../../../src/utils/validate-dto.ts"],"names":[],"mappings":";;;;;AAmCA,8BAiBC;AApDD,yDAAsE;AACtE,qDAA6D;AAC7D,yFAAgE;AAiCjD,KAAK,UAAU,WAAW,CACvC,QAA6B,EAC7B,IAAyB,EACzB,iBAAoC;IAEpC,MAAM,OAAO,GAAG,IAAA,mCAAe,EAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,MAAM,IAAA,0BAAQ,EAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC;IAE1D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC;QACnB,MAAM,IAAI,mBAAQ,CAChB,sBAAsB,EACtB,GAAG,EACH,MAAM,EACN,oBAAoB,CACrB,CAAC;IAEJ,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { ClassConstructor, plainToInstance } from \"class-transformer\";\nimport { validate, ValidatorOptions } from \"class-validator\";\nimport AppError from \"../modules/error-handler/utils/app-error\";\n\n/**\n * Used to easy validate your data with class validator by passing the validator class and the data to validate, and if whished some validation options\n *\n * @param {ClassConstructor<T>} DtoClass - The DTO class you want to use to validate the data\n * @param {Record<string, any>} data - The data to validated\n * @param {ValidatorOptions} validationOptions - class-validator validation options, default {whitelist: true}\n * @returns {Promise<T> | AppError} - returns the validated data or the encountered errors.\n *\n *\n * @example\n * ```ts\n * class CreateUserDto {\n * @IsString()\n * name: string;\n *\n * @IsEmail()\n * email: string;\n * }\n *\n * async function main() {\n * const data = { name: \"Uanela Como\", email: \"invalid-email\" };\n * try {\n * const validatedUser = await validateDto(CreateUserDto, data);\n * // do something\n * } catch (error) {\n * console.error(error.message);\n * }\n * }\n * ```\n */\n\nexport default async function validateDto<T extends object>(\n DtoClass: ClassConstructor<T>,\n data: Record<string, any>,\n validationOptions?: ValidatorOptions\n): Promise<T> {\n const dataDto = plainToInstance(DtoClass, data);\n const errors = await validate(dataDto, validationOptions);\n\n if (errors.length > 0)\n throw new AppError(\n \"Invalid request body\",\n 400,\n errors,\n \"InvalidRequestBody\"\n );\n\n return dataDto;\n}\n"]}
1
+ {"version":3,"file":"validate-dto.js","sourceRoot":"","sources":["../../../src/utils/validate-dto.ts"],"names":[],"mappings":";;AAkCA,8BAWC;AA7CD,yDAAsE;AACtE,qDAA6D;AAiC9C,KAAK,UAAU,WAAW,CACvC,QAA6B,EAC7B,IAAyB,EACzB,iBAAoC;IAEpC,MAAM,OAAO,GAAG,IAAA,mCAAe,EAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;IAChD,MAAM,MAAM,GAAG,MAAM,IAAA,0BAAQ,EAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC;IAE1D,IAAI,MAAM,CAAC,MAAM,GAAG,CAAC;QAAE,MAAM,MAAM,CAAC;IAEpC,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import { ClassConstructor, plainToInstance } from \"class-transformer\";\nimport { validate, ValidatorOptions } from \"class-validator\";\n\n/**\n * Used to easy validate your data with class validator by passing the validator class and the data to validate, and if whished some validation options\n *\n * @param {ClassConstructor<T>} DtoClass - The DTO class you want to use to validate the data\n * @param {Record<string, any>} data - The data to validated\n * @param {ValidatorOptions} validationOptions - class-validator validation options, default {whitelist: true}\n * @returns {Promise<T> | AppError} - returns the validated data or the encountered errors.\n *\n *\n * @example\n * ```ts\n * class CreateUserDto {\n * @IsString()\n * name: string;\n *\n * @IsEmail()\n * email: string;\n * }\n *\n * async function main() {\n * const data = { name: \"Uanela Como\", email: \"invalid-email\" };\n * try {\n * const validatedUser = await validateDto(CreateUserDto, data);\n * // do something\n * } catch (error) {\n * console.error(error.message);\n * }\n * }\n * ```\n */\n\nexport default async function validateDto<T extends object>(\n DtoClass: ClassConstructor<T>,\n data: Record<string, any>,\n validationOptions?: ValidatorOptions\n): Promise<T> {\n const dataDto = plainToInstance(DtoClass, data);\n const errors = await validate(dataDto, validationOptions);\n\n if (errors.length > 0) throw errors;\n\n return dataDto;\n}\n"]}
@@ -1,15 +1,10 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.default = validateSchema;
7
- const app_error_1 = __importDefault(require("../modules/error-handler/utils/app-error"));
8
4
  async function validateSchema(schema, data, options) {
9
5
  const result = schema.safeParse(data);
10
- if (!result.success) {
11
- throw new app_error_1.default("Invalid request body", 400, result.error.format(), "InvalidRequestBody");
12
- }
6
+ if (!result.success)
7
+ throw result.error;
13
8
  return result.data;
14
9
  }
15
10
  //# sourceMappingURL=validate-schema.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate-schema.js","sourceRoot":"","sources":["../../../src/utils/validate-schema.ts"],"names":[],"mappings":";;;;;AA4BA,iCAeC;AA1CD,yFAAgE;AA2BjD,KAAK,UAAU,cAAc,CAC1C,MAAoB,EACpB,IAAa,EACb,OAAa;IAEb,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IACtC,IAAI,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;QACpB,MAAM,IAAI,mBAAQ,CAChB,sBAAsB,EACtB,GAAG,EACH,MAAM,CAAC,KAAK,CAAC,MAAM,EAAE,EACrB,oBAAoB,CACrB,CAAC;IACJ,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC;AACrB,CAAC","sourcesContent":["import { ZodSchema } from \"zod\";\nimport AppError from \"../modules/error-handler/utils/app-error\";\n\n/**\n * Validates data using a Zod schema and throws an AppError if validation fails.\n *\n * @param {ZodSchema} schema - The Zod schema to validate against.\n * @param {unknown} data - The data to validate.\n * @returns {Promise<any>} - The validated data or throws an AppError on failure.\n *\n * @example\n * ```typescript\n * const userSchema = z.object({\n * name: z.string(),\n * email: z.string().email()\n * });\n *\n * async function main() {\n * const data = { name: \"Uanela Como\", email: \"invalid-email\" };\n * try {\n * const validatedUser = await validateSchema(userSchema, data);\n * // do something\n * } catch (error) {\n * console.error(error.message);\n * }\n * }\n * ```\n */\nexport default async function validateSchema<T>(\n schema: ZodSchema<T>,\n data: unknown,\n options?: any\n): Promise<T> {\n const result = schema.safeParse(data);\n if (!result.success) {\n throw new AppError(\n \"Invalid request body\",\n 400,\n result.error.format(),\n \"InvalidRequestBody\"\n );\n }\n return result.data;\n}\n"]}
1
+ {"version":3,"file":"validate-schema.js","sourceRoot":"","sources":["../../../src/utils/validate-schema.ts"],"names":[],"mappings":";;AA2BA,iCAQC;AARc,KAAK,UAAU,cAAc,CAC1C,MAAoB,EACpB,IAAa,EACb,OAAa;IAEb,MAAM,MAAM,GAAG,MAAM,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC;IACtC,IAAI,CAAC,MAAM,CAAC,OAAO;QAAE,MAAM,MAAM,CAAC,KAAK,CAAC;IACxC,OAAO,MAAM,CAAC,IAAI,CAAC;AACrB,CAAC","sourcesContent":["import { ZodSchema } from \"zod\";\n\n/**\n * Validates data using a Zod schema and throws an AppError if validation fails.\n *\n * @param {ZodSchema} schema - The Zod schema to validate against.\n * @param {unknown} data - The data to validate.\n * @returns {Promise<any>} - The validated data or throws an AppError on failure.\n *\n * @example\n * ```typescript\n * const userSchema = z.object({\n * name: z.string(),\n * email: z.string().email()\n * });\n *\n * async function main() {\n * const data = { name: \"Uanela Como\", email: \"invalid-email\" };\n * try {\n * const validatedUser = await validateSchema(userSchema, data);\n * // do something\n * } catch (error) {\n * console.error(error.message);\n * }\n * }\n * ```\n */\nexport default async function validateSchema<T>(\n schema: ZodSchema<T>,\n data: unknown,\n options?: any\n): Promise<T> {\n const result = schema.safeParse(data);\n if (!result.success) throw result.error;\n return result.data;\n}\n"]}
@@ -170,7 +170,7 @@ export class AuthService {
170
170
  }
171
171
  async getAuthenticatedUser(req) {
172
172
  if (!isAuthenticationEnabled())
173
- return null;
173
+ throw Error("ValidationError: Trying to call getAuthenticatedUser without setting up authentication");
174
174
  const prisma = getPrismaInstance();
175
175
  let token;
176
176
  if (req?.headers?.authorization &&
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":"AAAA,OAAO,GAAoB,MAAM,cAAc,CAAC;AAChD,OAAO,MAAM,MAAM,UAAU,CAAC;AAE9B,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,QAAQ,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAavE,OAAO,EAAc,IAAI,EAAE,MAAM,yCAAyC,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EACL,oBAA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F,CAAC;QAEJ,iBAAiB,CAAC,GAAG,CAAC,MAAM,EAAE,QAAQ,EAAE,aAAa,CAAC,CAAC;QAEvD,OAAO,KAAK,EAAE,IAAqC,EAAoB,EAAE;YAEvE,MAAM,OAAO,GAAG,cAAc,EAAE,CAAC;YACjC,IAAI,CAAC,qBAAqB,EAAE;gBAC1B,MAAM,KAAK,CACT,2FAA2F,CAC5F,CAAC;YAEJ,IAAI,CAAC,IAAI;gBAAE,MAAM,kBAAkB,CAAC;YACpC,IAAI,IAAI,CAAC,WAAW;gBAAE,OAAO,IAAI,CAAC;YAElC,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,SAAS,EAAE,CAAC;gBAChD,OAAO,MAAM,IAAI,CAAC,yBAAyB,CAAC,IAAI,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC;YAC1E,CAAC;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,IAAI,CAAC,aAAa,IAAI,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;oBAC5D,aAAa,GAAG,mBAAmB,CAAC,SAAS,CAAC,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;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,eAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration, 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 authConfigs?.jwt?.cookie?.secure ??\n (process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\" ||\n sameSite === \"none\"),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles: string[] = [];\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = Array.isArray(accessControl[action])\n ? accessControl[action]\n : accessControl[action].roles || [];\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return !!userRoles.some((role: string) => authorizedRoles.includes(role));\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n if (!isAuthenticationEnabled()) return null;\n\n const prisma = getPrismaInstance();\n\n let token: string | undefined;\n\n if (\n req?.headers?.authorization &&\n req?.headers?.authorization.startsWith(\"Bearer\")\n ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) throw loginRequiredError;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n {},\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (isAuthenticationEnabled())\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any> | undefined): Promise<boolean> => {\n // getArkosConfig must not be called the same time as arkos.init()\n const configs = getArkosConfig();\n if (!isUsingAuthentication())\n throw Error(\n \"Validation Error: Trying to use authService.permission without setting up authentication.\"\n );\n\n if (!user) throw loginRequiredError;\n if (user.isSuperUser) return true;\n\n if (configs?.authentication?.mode === \"dynamic\") {\n return await this.checkDynamicAccessControl(user?.id, action, resource);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl && appModules.includes(kebabCase(resource)))\n accessControl = getModuleComponents(kebabCase(resource))?.authConfigs\n ?.accessControl;\n\n return (\n !!accessControl &&\n this.checkStaticAccessControl(user as any, action, accessControl)\n );\n }\n return false;\n };\n }\n}\n\n/**\n * Handles various authentication-related tasks such as JWT signing, password hashing, and verifying user credentials.\n */\nconst authService = new AuthService();\n\nexport default authService;\n"]}
1
+ {"version":3,"file":"auth.service.js","sourceRoot":"","sources":["../../../../src/modules/auth/auth.service.ts"],"names":[],"mappings":"AAAA,OAAO,GAAoB,MAAM,cAAc,CAAC;AAChD,OAAO,MAAM,MAAM,UAAU,CAAC;AAE9B,OAAO,UAAU,MAAM,oCAAoC,CAAC;AAC5D,OAAO,QAAQ,MAAM,kCAAkC,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAC9C,OAAO,QAAQ,MAAM,uBAAuB,CAAC;AAC7C,OAAO,EAAE,iBAAiB,EAAE,MAAM,oCAAoC,CAAC;AAavE,OAAO,EAAc,IAAI,EAAE,MAAM,yCAAyC,CAAC;AAC3E,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAC7E,OAAO,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChD,OAAO,EACL,oBAAoB,EACpB,kBAAkB,GACnB,MAAM,4BAA4B,CAAC;AACpC,OAAO,iBAAiB,MAAM,sCAAsC,CAAC;AACrE,OAAO,EACL,uBAAuB,EACvB,qBAAqB,GACtB,MAAM,0CAA0C,CAAC;AAKlD,MAAM,OAAO,WAAW;IAAxB;QAIE,uBAAkB,GAAgC,EAAE,CAAC;QA8arD,iBAAY,GAAG,UAAU,CACvB,KAAK,EAAE,GAAiB,EAAE,CAAgB,EAAE,IAAuB,EAAE,EAAE;YACrE,IAAI,uBAAuB,EAAE;gBAC3B,GAAG,CAAC,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,oBAAoB,CAAC,GAAG,CAAC,CAAS,CAAC;YAC5D,IAAI,EAAE,CAAC;QACT,CAAC,CACF,CAAC;IAsFJ,CAAC;IAhgBC,YAAY,CACV,EAAmB,EACnB,SAA+B,EAC/B,MAAe;QAEf,MAAM,EAAE,c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C;iBAAM,IAAI,OAAO,EAAE,cAAc,EAAE,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACtD,IAAI,CAAC,aAAa,IAAI,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;oBAC5D,aAAa,GAAG,mBAAmB,CAAC,SAAS,CAAC,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;AAKD,MAAM,WAAW,GAAG,IAAI,WAAW,EAAE,CAAC;AAEtC,eAAe,WAAW,CAAC","sourcesContent":["import jwt, { SignOptions } from \"jsonwebtoken\";\nimport bcrypt from \"bcryptjs\";\nimport { User } from \"../../types\";\nimport catchAsync from \"../error-handler/utils/catch-async\";\nimport AppError from \"../error-handler/utils/app-error\";\nimport { callNext } from \"../base/base.middlewares\";\nimport { getArkosConfig } from \"../../server\";\nimport arkosEnv from \"../../utils/arkos-env\";\nimport { getPrismaInstance } from \"../../utils/helpers/prisma.helpers\";\nimport {\n ArkosRequest,\n ArkosResponse,\n ArkosNextFunction,\n ArkosRequestHandler,\n} from \"../../types\";\nimport {\n AuthJwtPayload,\n AccessAction,\n AccessControlConfig,\n AuthenticationControlConfig,\n} from \"../../types/auth\";\nimport { MsDuration, 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 authConfigs?.jwt?.cookie?.secure ??\n (process.env.JWT_COOKIE_SECURE === \"true\" ||\n req.secure ||\n req.headers[\"x-forwarded-proto\"] === \"https\" ||\n sameSite === \"none\"),\n sameSite,\n };\n }\n\n /**\n * Is used by default internally by Arkos under `BaseService` class to check if the password is already hashed.\n *\n * This was just added to prevent unwanted errors when someone just forgets that the `BaseService` class will automatically hash the password field using `authService.hashPassword` by default.\n *\n * So now before `BaseService` hashes it will test it.\n *\n *\n * @param password The password to be tested if is hashed\n * @returns\n */\n isPasswordHashed(password: string) {\n return !Number.isNaN(bcrypt.getRounds(password) * 1);\n }\n\n /**\n * Compares a candidate password with the stored user password to check if they match.\n *\n * @param {string} candidatePassword - The password provided by the user during login.\n * @param {string} userPassword - The password stored in the database.\n * @returns {Promise<boolean>} Returns true if the passwords match, otherwise false.\n */\n async isCorrectPassword(\n candidatePassword: string,\n userPassword: string\n ): Promise<boolean> {\n return await bcrypt.compare(candidatePassword, userPassword);\n }\n\n /**\n * Hashes a plain text password using bcrypt.\n *\n * @param {string} password - The password to be hashed.\n * @returns {Promise<string>} Returns the hashed password.\n */\n async hashPassword(password: string): Promise<string> {\n return await bcrypt.hash(password, 12);\n }\n\n /**\n * Checks if a password is strong, requiring uppercase, lowercase, and numeric characters as the default.\n *\n * **NB**: You must pay attention when using custom validation with zod or class-validator, try to use the same regex always.\n *\n * **Note**: You can define it when calling arkos.init()\n * ```ts\n * arkos.init({\n * authentication: {\n * passwordValidation:{ regex: /your-desired-regex/, message: 'password must contain...'}\n * }\n * })\n * ```\n *\n * @param {string} password - The password to check.\n * @returns {boolean} Returns true if the password meets the strength criteria, otherwise false.\n */\n public isPasswordStrong(password: string): boolean {\n const initAuthConfigs = getArkosConfig()?.authentication;\n\n const strongPasswordRegex =\n initAuthConfigs?.passwordValidation?.regex ||\n /^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).+$/;\n return strongPasswordRegex.test(password);\n }\n\n /**\n * Checks if a user has changed their password after the JWT was issued.\n *\n * @param {User} user - The user object containing the passwordChangedAt field.\n * @param {number} JWTTimestamp - The timestamp when the JWT was issued.\n * @returns {boolean} Returns true if the user changed their password after the JWT was issued, otherwise false.\n */\n userChangedPasswordAfter(user: User, JWTTimestamp: number): boolean {\n if (user.passwordChangedAt) {\n const convertedTimestamp = parseInt(\n String(user.passwordChangedAt.getTime() / 1000),\n 10\n );\n\n return JWTTimestamp < convertedTimestamp;\n }\n return false;\n }\n\n /**\n * Verifies the authenticity of a JWT token.\n *\n * @param {string} token - The JWT token to verify.\n * @param {string} [secret] - The secret key used to verify the token. Defaults to environment variable `JWT_SECRET`.\n * @returns {Promise<AuthJwtPayload>} Returns the decoded JWT payload if the token is valid.\n * @throws {Error} Throws an error if the token is invalid or expired.\n */\n async verifyJwtToken(\n token: string,\n secret?: string\n ): Promise<AuthJwtPayload> {\n const { authentication: configs } = getArkosConfig();\n\n if (\n process.env.ARKOS_BUILD === \"true\" &&\n !process.env.JWT_SECRET &&\n !configs?.jwt?.secret\n )\n throw new AppError(\n \"Missing JWT secret in production\",\n 500,\n \"MissingJWTSecretInProduction\"\n );\n\n secret =\n secret ||\n configs?.jwt?.secret ||\n process.env.JWT_SECRET ||\n arkosEnv.JWT_SECRET;\n\n return new Promise((resolve, reject) => {\n jwt.verify(token, secret, (err, decoded) => {\n if (err) reject(err);\n else resolve(decoded as AuthJwtPayload);\n });\n });\n }\n\n /**\n * Checks if a user has permission for a specific action using static access control rules.\n * Validates user roles against predefined access control configuration.\n *\n * @param user - The user object containing role or roles field\n * @param action - The action being performed\n * @param accessControl - Access control configuration (array of roles or object with action-role mappings)\n * @returns True if user has permission, false otherwise\n * @throws Error if user doesn't have role/roles field\n */\n protected checkStaticAccessControl(\n user: User,\n action: string,\n accessControl: AccessControlConfig\n ) {\n if (!user?.role && !user.roles)\n throw Error(\n \"Validation Error: In order to use static authentication user needs at least role field or roles for multiple roles.\"\n );\n\n let authorizedRoles: string[] = [];\n\n if (Array.isArray(accessControl)) authorizedRoles = accessControl;\n else if (accessControl[action])\n authorizedRoles = Array.isArray(accessControl[action])\n ? accessControl[action]\n : accessControl[action].roles || [];\n\n const userRoles = Array.isArray(user?.roles) ? user.roles : [user.role];\n\n return !!userRoles.some((role: string) => authorizedRoles.includes(role));\n }\n\n /**\n * Checks if a user has permission for a specific action and resource using dynamic access control.\n * Queries the database to verify user's role permissions.\n *\n * @param userId - The unique identifier of the user\n * @param action - The action being performed\n * @param resource - The resource being accessed\n * @returns Promise resolving to true if user has permission, false otherwise\n */\n protected async checkDynamicAccessControl(\n userId: string,\n action: string,\n resource: string\n ) {\n const prisma = getPrismaInstance();\n return !!(await prisma.userRole.findFirst({\n where: {\n userId,\n role: {\n permissions: {\n some: {\n resource,\n action,\n },\n },\n },\n },\n select: { id: true },\n }));\n }\n\n /**\n * Middleware function to handle access control based on user roles and permissions.\n *\n * @param {AccessAction} action - The action being performed (e.g., create, update, delete, view).\n * @param {string} resource - The resource name that the action is being performed on (e.g., \"User\", \"Post\").\n * @param {AccessControlConfig} accessControl - The access control configuration.\n * @returns {ArkosRequestHandler} The middleware function that checks if the user has permission to perform the action.\n */\n handleAccessControl(\n action: AccessAction,\n resource: string,\n accessControl?: AccessControlConfig\n ): ArkosRequestHandler {\n if (\n !accessControl &&\n appModules.some(\n (appModule) => kebabCase(appModule) === kebabCase(resource)\n )\n )\n accessControl = getModuleComponents(resource)?.authConfigs?.accessControl;\n\n authActionService.add(action, resource, accessControl);\n\n return catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (req.user) {\n const user = req.user as User;\n const configs = getArkosConfig();\n\n if (user.isSuperUser) {\n next();\n return;\n }\n\n const notEnoughPermissionsError = new AppError(\n \"You do not have permission to perfom this action\",\n 403,\n {},\n \"NotEnoughPermissions\"\n );\n\n if (configs?.authentication?.mode === \"dynamic\") {\n const hasPermission = await this.checkDynamicAccessControl(\n user.id,\n action,\n resource\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n } else if (configs?.authentication?.mode === \"static\") {\n if (!accessControl) return next(notEnoughPermissionsError);\n\n const hasPermission = this.checkStaticAccessControl(\n user,\n action,\n accessControl\n );\n\n if (!hasPermission) return next(notEnoughPermissionsError);\n }\n }\n\n next();\n }\n );\n }\n\n /**\n * Processes the cookies or authoriation token and returns the user.\n * @param req\n * @returns {Promise<User | null>} - if authentication is turned off in arkosConfig it returns null\n * @throws {AppError} Throws an error if the token is invalid or the user is not logged in.\n */\n async getAuthenticatedUser(req: ArkosRequest): Promise<User | null> {\n 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 ) {\n token = req?.headers?.authorization.split(\" \")[1];\n } else if (req?.cookies?.arkos_access_token !== \"no-token\" && req.cookies) {\n token = req?.cookies?.arkos_access_token;\n }\n\n if (!token) throw loginRequiredError;\n\n let decoded: AuthJwtPayload | undefined;\n\n try {\n decoded = await this.verifyJwtToken(token);\n } catch (err) {\n throw invaliAuthTokenError;\n }\n\n if (!decoded?.id) throw invaliAuthTokenError;\n const user: any | null = await (prisma as any).user.findUnique({\n where: { id: String(decoded.id) },\n });\n\n if (!user)\n throw new AppError(\n \"The user belonging to this token does no longer exists\",\n 401,\n {},\n \"UserNoLongerExists\"\n );\n\n if (\n this.userChangedPasswordAfter(user, decoded.iat!) &&\n !req.path?.includes?.(\"logout\")\n )\n throw new AppError(\n \"User recently changed password! Please log in again.\",\n 401,\n {},\n \"PasswordChanged\"\n );\n\n req.accessToken = token;\n return user;\n }\n\n /**\n * Middleware function to authenticate the user based on the JWT token.\n *\n * @param {ArkosRequest} req - The request object.\n * @param {ArkosResponse} res - The response object.\n * @param {ArkosNextFunction} next - The next middleware function to be called.\n * @returns {void}\n */\n authenticate = catchAsync(\n async (req: ArkosRequest, _: ArkosResponse, next: ArkosNextFunction) => {\n if (isAuthenticationEnabled())\n req.user = (await this.getAuthenticatedUser(req)) as User;\n next();\n }\n );\n\n /**\n * Handles authentication control by checking the `authenticationControl` configuration in the `authConfigs`.\n *\n * @param {ControllerActions} action - The action being performed (e.g., create, update, delete, view).\n * @param {AuthenticationControlConfig} authenticationControl - The authentication configuration object.\n * @returns {ArkosRequestHandler} The middleware function that checks if authentication is required.\n */\n handleAuthenticationControl(\n action: AccessAction,\n authenticationControl?: AuthenticationControlConfig | undefined\n ): ArkosRequestHandler {\n if (authenticationControl && typeof authenticationControl === \"object\") {\n if (authenticationControl[action] === false) return callNext;\n else if (authenticationControl[action] === true) return this.authenticate;\n } else return this.authenticate;\n\n return this.authenticate;\n }\n\n /**\n * Creates a permission checker function for a specific action and resource.\n *\n * PS: This method should be called during application initialization to build permission validators.\n *\n * @see {@link https://www.arkosjs.com/docs/advanced-guide/fine-grained-access-control}\n *\n * @param action - The action to check permission for (e.g., 'View', 'Create', 'Delete')\n * @param resource - The resource being accessed, must be in kebabCase (e.g., 'user', 'cart-item', 'order')\n * @param accessControl - Access control rules (required for static authentication mode), and it is automatically loaded for known modules such as all prisma models, auth and file-upload.\n * @returns A function that takes a user object and returns a boolean indicating permission status\n *\n * @example\n * ```typescript\n * const hasViewProductPermission = await authService.permission('View', 'product');\n *\n * // Later in handler:\n * const canAccess = await hasViewProductPermission(user);\n * if (canAccess) {\n * // User has permission\n * }\n * ```\n */\n permission(\n action: string,\n resource: string,\n accessControl?: AccessControlConfig\n ) {\n // Check if called during request handling (deep call stack indicates handler execution)\n const stack = new Error().stack;\n\n if (stack?.includes(\"node_modules/express/lib/router/index.js\"))\n throw new Error(\n \"authService.permission() should be called during application initialization level.\"\n );\n\n authActionService.add(action, resource, accessControl);\n\n return async (user: Record<string, any> | 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 (!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"]}
@@ -19,19 +19,25 @@ class AuthActionService {
19
19
  const existingAuthAction = this.getOne(action, resource);
20
20
  if (existingAuthAction) {
21
21
  const inconsistencies = [];
22
- if (existingAuthAction.name !== transformedAction.name &&
23
- existingAuthAction.name !== undefined &&
24
- transformedAction.name !== undefined) {
22
+ const defaultName = `${capitalize(kebabCase(action).replace(/-/g, " "))} ${capitalize(kebabCase(resource).replace(/-/g, " "))}`;
23
+ const defaultDescription = `${capitalize(kebabCase(action).replace(/-/g, " "))} ${capitalize(kebabCase(resource).replace(/-/g, " "))}`;
24
+ const defaultErrorMessage = "You do not have permission to perform this operation";
25
+ const isNonDefault = (value, defaultValue) => {
26
+ return value !== undefined && value !== defaultValue;
27
+ };
28
+ if (isNonDefault(existingAuthAction.name, defaultName) &&
29
+ isNonDefault(transformedAction.name, defaultName) &&
30
+ existingAuthAction.name !== transformedAction.name) {
25
31
  inconsistencies.push(` - name: "${existingAuthAction.name}" vs "${transformedAction.name}"`);
26
32
  }
27
- if (existingAuthAction.description !== transformedAction.description &&
28
- existingAuthAction.description !== undefined &&
29
- transformedAction.description !== undefined) {
33
+ if (isNonDefault(existingAuthAction.description, defaultDescription) &&
34
+ isNonDefault(transformedAction.description, defaultDescription) &&
35
+ existingAuthAction.description !== transformedAction.description) {
30
36
  inconsistencies.push(` - description: "${existingAuthAction.description}" vs "${transformedAction.description}"`);
31
37
  }
32
- if (existingAuthAction.errorMessage !== transformedAction.errorMessage &&
33
- existingAuthAction.errorMessage !== undefined &&
34
- transformedAction.errorMessage !== undefined) {
38
+ if (isNonDefault(existingAuthAction.errorMessage, defaultErrorMessage) &&
39
+ isNonDefault(transformedAction.errorMessage, defaultErrorMessage) &&
40
+ existingAuthAction.errorMessage !== transformedAction.errorMessage) {
35
41
  inconsistencies.push(` - errorMessage: "${existingAuthAction.errorMessage}" vs "${transformedAction.errorMessage}"`);
36
42
  }
37
43
  if (inconsistencies.length > 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"auth-action.service.js","sourceRoot":"","sources":["../../../../../../src/modules/auth/utils/services/auth-action.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAKtD,OAAO,EAAE,cAAc,EAAE,MAAM,gDAAgD,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,wCAAwC,CAAC;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,CAA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AI,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,eAAe,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 if (\n existingAuthAction.name !== transformedAction.name &&\n existingAuthAction.name !== undefined &&\n transformedAction.name !== undefined\n ) {\n inconsistencies.push(\n ` - name: \"${existingAuthAction.name}\" vs \"${transformedAction.name}\"`\n );\n }\n\n if (\n existingAuthAction.description !== transformedAction.description &&\n existingAuthAction.description !== undefined &&\n transformedAction.description !== undefined\n ) {\n inconsistencies.push(\n ` - description: \"${existingAuthAction.description}\" vs \"${transformedAction.description}\"`\n );\n }\n\n if (\n existingAuthAction.errorMessage !== transformedAction.errorMessage &&\n existingAuthAction.errorMessage !== undefined &&\n transformedAction.errorMessage !== undefined\n ) {\n inconsistencies.push(\n ` - errorMessage: \"${existingAuthAction.errorMessage}\" vs \"${transformedAction.errorMessage}\"`\n );\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 = accessControl[action];\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":["../../../../../../src/modules/auth/utils/services/auth-action.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AAKtD,OAAO,EAAE,cAAc,EAAE,MAAM,gDAAgD,CAAC;AAChF,OAAO,EAAE,UAAU,EAAE,MAAM,wCAAwC,CAAC;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;IA+LJ,CAAC;IA7LC,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,eAAe,GAAa,EAAE,CAAC;YAErC,MAAM,WAAW,GAAG,GAAG,UAAU,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,IAAI,UAAU,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CAAC;YAChI,MAAM,kBAAkB,GAAG,GAAG,UAAU,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,IAAI,UAAU,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC,EAAE,CA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AC,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,eAAe,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 = accessControl[action];\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"]}
@@ -6,6 +6,7 @@ import validateSchema from "../../utils/validate-schema.js";
6
6
  import { resolvePrismaQueryOptions } from "./utils/helpers/base.middlewares.helpers.js";
7
7
  import { capitalize } from "../../utils/helpers/text.helpers.js";
8
8
  import { isClass, isZodSchema } from "../../utils/dynamic-loader.js";
9
+ import { pascalCase } from "../../exports/utils/index.js";
9
10
  export function callNext(_, _1, next) {
10
11
  next();
11
12
  }
@@ -190,7 +191,7 @@ export function validateRequestInputs(routeConfig) {
190
191
  });
191
192
  return catchAsync(async (req, _, next) => {
192
193
  for (const key of validatorsKey) {
193
- const reqInput = Object.keys(req[key]).length > 0;
194
+ const reqInput = Object.keys(req[key] || {}).length > 0;
194
195
  const validator = validators?.[key];
195
196
  const notAllowedInputError = new AppError(`Request ${key} is not allowed on this route`, 400, `Request${capitalize(key)}NotAllowed`, { [key]: req[key] });
196
197
  if (((typeof validators === "boolean" && validators === false) ||
@@ -200,7 +201,14 @@ export function validateRequestInputs(routeConfig) {
200
201
  if (strictValidation && !validator && reqInput)
201
202
  throw notAllowedInputError;
202
203
  if (validator)
203
- req[key] = await validatorFn(validator, req[key], arkosConfig.validation?.validationOptions);
204
+ try {
205
+ req[key] = await validatorFn(validator, req[key], arkosConfig.validation?.validationOptions);
206
+ }
207
+ catch (err) {
208
+ throw new AppError(`Invalid request ${key}`, 400, `InvalidRequest${pascalCase(key)}`, (err &&
209
+ (validationConfig?.resolver === "zod" ? err.format() : err)) ||
210
+ {});
211
+ }
204
212
  }
205
213
  next();
206
214
  });