@jmlq/auth 0.0.1-alpha.1 → 0.0.1-alpha.3

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 (361) hide show
  1. package/README.md +259 -306
  2. package/dist/application/dtos/index.d.ts +3 -0
  3. package/dist/application/dtos/index.js +19 -0
  4. package/dist/application/dtos/request/index.d.ts +4 -0
  5. package/dist/{src/application/dtos → application/dtos/request}/index.js +4 -4
  6. package/dist/{src/application/dtos/login.dto.d.ts → application/dtos/request/login.request.d.ts} +0 -4
  7. package/dist/application/dtos/request/logout.request.d.ts +3 -0
  8. package/dist/application/dtos/request/refresh-token.request.d.ts +3 -0
  9. package/dist/application/dtos/request/register-user.request.d.ts +6 -0
  10. package/dist/application/dtos/response/index.d.ts +4 -0
  11. package/dist/application/dtos/response/index.js +20 -0
  12. package/dist/application/dtos/response/login.response.d.ts +4 -0
  13. package/dist/{src/application/dtos/logout.dto.d.ts → application/dtos/response/logout.response.d.ts} +0 -3
  14. package/dist/{src/application/dtos/refresh-token.dto.d.ts → application/dtos/response/refresh-token.response.d.ts} +0 -3
  15. package/dist/application/dtos/response/register-user.response.d.ts +7 -0
  16. package/dist/application/dtos/type/index.d.ts +1 -0
  17. package/dist/{src/shared/constants → application/dtos/type}/index.js +1 -1
  18. package/dist/application/dtos/type/user-role.type.d.ts +4 -0
  19. package/dist/application/factories/auth-service.factory.d.ts +11 -0
  20. package/dist/application/factories/auth-service.factory.js +40 -0
  21. package/dist/{src/application → application}/index.d.ts +1 -0
  22. package/dist/{src/application → application}/index.js +1 -0
  23. package/dist/application/types/auth-service-factory-options.type.d.ts +5 -0
  24. package/dist/application/types/index.d.ts +1 -0
  25. package/dist/{src/infrastructure/jwt/factory → application/types}/index.js +1 -1
  26. package/dist/{src/application → application}/use-cases/login-with-password.use-case.d.ts +2 -2
  27. package/dist/{src/application → application}/use-cases/login-with-password.use-case.js +6 -5
  28. package/dist/{src/application → application}/use-cases/logout.use-case.d.ts +2 -2
  29. package/dist/{src/application → application}/use-cases/logout.use-case.js +2 -2
  30. package/dist/{src/application → application}/use-cases/refresh-token.use-case.d.ts +2 -2
  31. package/dist/{src/application → application}/use-cases/refresh-token.use-case.js +2 -2
  32. package/dist/application/use-cases/register-user.use-case.d.ts +12 -0
  33. package/dist/{src/application → application}/use-cases/register-user.use-case.js +27 -1
  34. package/dist/{src/domain → domain}/errors/auth.errors.d.ts +1 -14
  35. package/dist/{src/domain → domain}/errors/auth.errors.js +1 -15
  36. package/dist/{src/domain → domain}/index.d.ts +0 -1
  37. package/dist/{src/domain → domain}/index.js +0 -1
  38. package/dist/domain/ports/auth/index.d.ts +2 -0
  39. package/dist/domain/ports/auth/index.js +18 -0
  40. package/dist/{src/domain/ports/auth/password-hasher.d.ts → domain/ports/auth/password-hasher.port.d.ts} +1 -1
  41. package/dist/{src/domain → domain}/ports/auth/password-policy.port.d.ts +1 -1
  42. package/dist/domain/ports/index.d.ts +4 -0
  43. package/dist/{src/infrastructure/jwt → domain/ports}/index.js +3 -2
  44. package/dist/domain/ports/jwt/index.d.ts +1 -0
  45. package/dist/{src/shared/types → domain/ports/jwt}/index.js +1 -1
  46. package/dist/domain/ports/jwt/payload/index.d.ts +1 -0
  47. package/dist/domain/ports/jwt/payload/index.js +17 -0
  48. package/dist/{src/domain → domain}/ports/repository/credential.repository.d.ts +1 -1
  49. package/dist/{src/domain → domain}/ports/repository/index.d.ts +1 -1
  50. package/dist/{src/domain → domain}/ports/repository/index.js +1 -1
  51. package/dist/{src/domain/ports/repository/user.repository.d.ts → domain/ports/repository/user-repository.port.d.ts} +1 -1
  52. package/dist/domain/ports/token/index.d.ts +2 -0
  53. package/dist/domain/ports/token/index.js +18 -0
  54. package/dist/{src/domain → domain}/ports/token/token-session.port.d.ts +2 -2
  55. package/dist/{src/domain → domain}/ports/token/token.service.port.d.ts +2 -2
  56. package/dist/{src/domain → domain}/props/jwt/generate-access-token.props.d.ts +0 -2
  57. package/dist/{src/domain → domain}/props/jwt/generate-refresh-token.props.d.ts +0 -2
  58. package/dist/{src/domain/props/services → domain/props/jwt}/index.d.ts +1 -0
  59. package/dist/{src/domain/props/services → domain/props/jwt}/index.js +1 -0
  60. package/dist/{src/domain → domain}/services/password-policy.service.d.ts +2 -2
  61. package/dist/{src/infrastructure/repositories/test → in-memory}/in-memory-credential.repository.d.ts +2 -2
  62. package/dist/{src/infrastructure/repositories/test → in-memory}/in-memory-credential.repository.js +12 -2
  63. package/dist/{src/infrastructure/repositories/test → in-memory}/in-memory-user.repository.d.ts +2 -2
  64. package/dist/index.d.ts +5 -1
  65. package/dist/index.js +13 -1
  66. package/dist/infrastructure/index.js +1 -0
  67. package/dist/{src/infrastructure → infrastructure}/security/bcrypt-password-hasher.d.ts +7 -2
  68. package/dist/{src/infrastructure → infrastructure}/security/bcrypt-password-hasher.js +7 -2
  69. package/dist/{src/infrastructure → infrastructure}/services/index.d.ts +0 -1
  70. package/dist/{src/infrastructure → infrastructure}/services/index.js +0 -1
  71. package/dist/infrastructure/services/token-session.service.d.ts +22 -0
  72. package/dist/{src/infrastructure/services/default-token-session.service.js → infrastructure/services/token-session.service.js} +30 -31
  73. package/dist/infrastructure/types/auth-service-container.d.ts +14 -0
  74. package/dist/shared/index.d.ts +1 -0
  75. package/dist/{src/infrastructure/repositories → shared}/index.js +1 -1
  76. package/package.json +5 -8
  77. package/dist/examples/bcrypt-password-hasher.example.d.ts +0 -3
  78. package/dist/examples/bcrypt-password-hasher.example.js +0 -78
  79. package/dist/examples/entity-object.example.d.ts +0 -39
  80. package/dist/examples/entity-object.example.js +0 -411
  81. package/dist/examples/factory-auth-service-example.d.ts +0 -3
  82. package/dist/examples/factory-auth-service-example.js +0 -84
  83. package/dist/examples/index.example.d.ts +0 -12
  84. package/dist/examples/index.example.js +0 -171
  85. package/dist/examples/jwt-algoritm.example.d.ts +0 -47
  86. package/dist/examples/jwt-algoritm.example.js +0 -447
  87. package/dist/examples/jwt-token-generator.example.d.ts +0 -6
  88. package/dist/examples/jwt-token-generator.example.js +0 -49
  89. package/dist/examples/jwt-verifier.example.d.ts +0 -3
  90. package/dist/examples/jwt-verifier.example.js +0 -80
  91. package/dist/examples/password-policy.example.d.ts +0 -7
  92. package/dist/examples/password-policy.example.js +0 -57
  93. package/dist/examples/service-jwt-token.example.d.ts +0 -3
  94. package/dist/examples/service-jwt-token.example.js +0 -154
  95. package/dist/examples/service-token-session.example.d.ts +0 -3
  96. package/dist/examples/service-token-session.example.js +0 -139
  97. package/dist/examples/use-case-login-with-password.example.d.ts +0 -6
  98. package/dist/examples/use-case-login-with-password.example.js +0 -105
  99. package/dist/examples/use-case-logout.example.d.ts +0 -7
  100. package/dist/examples/use-case-logout.example.js +0 -134
  101. package/dist/examples/use-case-refresh-token.example.d.ts +0 -11
  102. package/dist/examples/use-case-refresh-token.example.js +0 -164
  103. package/dist/examples/use-case-register-user.example.d.ts +0 -9
  104. package/dist/examples/use-case-register-user.example.js +0 -110
  105. package/dist/src/application/dtos/index.d.ts +0 -4
  106. package/dist/src/application/dtos/register-user.dto.d.ts +0 -16
  107. package/dist/src/application/factories/auth-service.factory.d.ts +0 -5
  108. package/dist/src/application/factories/auth-service.factory.js +0 -51
  109. package/dist/src/application/use-cases/register-user.use-case.d.ts +0 -10
  110. package/dist/src/domain/errors/auth-domain-error.d.ts +0 -82
  111. package/dist/src/domain/errors/auth-domain-error.js +0 -112
  112. package/dist/src/domain/ports/auth/password-policy-config.port.js +0 -10
  113. package/dist/src/domain/ports/config/auth-config.port.d.ts +0 -19
  114. package/dist/src/domain/ports/config/auth-config.port.js +0 -3
  115. package/dist/src/domain/ports/index.d.ts +0 -9
  116. package/dist/src/domain/ports/index.js +0 -25
  117. package/dist/src/domain/ports/jwt/factory/signature-strategy-factory.port.d.ts +0 -14
  118. package/dist/src/domain/ports/jwt/signature-strategy-factory.port.d.ts +0 -14
  119. package/dist/src/domain/ports/jwt/signature-strategy.d.ts +0 -30
  120. package/dist/src/domain/ports/jwt/signature-strategy.js +0 -4
  121. package/dist/src/domain/ports/jwt/signature-strategy.port.d.ts +0 -31
  122. package/dist/src/domain/ports/jwt/signature-strategy.port.js +0 -4
  123. package/dist/src/domain/ports/jwt/strategy/signature-strategy.port.d.ts +0 -31
  124. package/dist/src/domain/ports/jwt/strategy/signature-strategy.port.js +0 -4
  125. package/dist/src/domain/props/create-payload-props.port.d.ts +0 -0
  126. package/dist/src/domain/props/create-payload-props.port.js +0 -8
  127. package/dist/src/domain/props/jwt/create-payload.props.d.ts +0 -9
  128. package/dist/src/domain/props/jwt/generate-token.props.d.ts +0 -10
  129. package/dist/src/domain/props/jwt/generate-token.props.js +0 -2
  130. package/dist/src/domain/props/jwt/index.d.ts +0 -5
  131. package/dist/src/domain/props/jwt/index.js +0 -21
  132. package/dist/src/domain/props/jwt/jwt-subject.d.ts +0 -7
  133. package/dist/src/domain/props/jwt/jwt-subject.js +0 -2
  134. package/dist/src/domain/props/services/generate-access-token.props.d.ts +0 -8
  135. package/dist/src/domain/props/services/generate-refresh-token.props.d.ts +0 -8
  136. package/dist/src/domain/services/token.service.port.d.ts +0 -9
  137. package/dist/src/index.d.ts +0 -78
  138. package/dist/src/index.js +0 -94
  139. package/dist/src/infrastructure/index.d.ts +0 -5
  140. package/dist/src/infrastructure/index.js +0 -21
  141. package/dist/src/infrastructure/jwt/factory/index.d.ts +0 -1
  142. package/dist/src/infrastructure/jwt/factory/signature-strategy.factory.d.ts +0 -21
  143. package/dist/src/infrastructure/jwt/factory/signature-strategy.factory.js +0 -61
  144. package/dist/src/infrastructure/jwt/index.d.ts +0 -3
  145. package/dist/src/infrastructure/jwt/signature-strategy.factory.d.ts +0 -21
  146. package/dist/src/infrastructure/jwt/signature-strategy.factory.js +0 -61
  147. package/dist/src/infrastructure/jwt/strategies/ecdsa-signature-strategy.d.ts +0 -47
  148. package/dist/src/infrastructure/jwt/strategies/ecdsa-signature-strategy.js +0 -124
  149. package/dist/src/infrastructure/jwt/strategies/ecdsa-signature.strategy.d.ts +0 -47
  150. package/dist/src/infrastructure/jwt/strategies/ecdsa-signature.strategy.js +0 -124
  151. package/dist/src/infrastructure/jwt/strategies/hmac-signature-strategy.d.ts +0 -54
  152. package/dist/src/infrastructure/jwt/strategies/hmac-signature-strategy.js +0 -129
  153. package/dist/src/infrastructure/jwt/strategies/hmac-signature.strategy.d.ts +0 -54
  154. package/dist/src/infrastructure/jwt/strategies/hmac-signature.strategy.js +0 -129
  155. package/dist/src/infrastructure/jwt/strategies/index.d.ts +0 -3
  156. package/dist/src/infrastructure/jwt/strategies/index.js +0 -19
  157. package/dist/src/infrastructure/jwt/strategies/rsa-signature-strategy.d.ts +0 -47
  158. package/dist/src/infrastructure/jwt/strategies/rsa-signature-strategy.js +0 -124
  159. package/dist/src/infrastructure/jwt/strategies/rsa-signature.strategy.d.ts +0 -47
  160. package/dist/src/infrastructure/jwt/strategies/rsa-signature.strategy.js +0 -124
  161. package/dist/src/infrastructure/jwt/token/actions/jwt-token-generator.d.ts +0 -57
  162. package/dist/src/infrastructure/jwt/token/actions/jwt-token-generator.js +0 -123
  163. package/dist/src/infrastructure/jwt/token/actions/jwt-token-verifier.d.ts +0 -59
  164. package/dist/src/infrastructure/jwt/token/actions/jwt-token-verifier.js +0 -100
  165. package/dist/src/infrastructure/jwt/token/index.d.ts +0 -5
  166. package/dist/src/infrastructure/jwt/token/index.js +0 -21
  167. package/dist/src/infrastructure/jwt/token/jwt-signer.d.ts +0 -33
  168. package/dist/src/infrastructure/jwt/token/jwt-signer.js +0 -46
  169. package/dist/src/infrastructure/jwt/token/jwt-token-parser.d.ts +0 -29
  170. package/dist/src/infrastructure/jwt/token/jwt-token-parser.js +0 -57
  171. package/dist/src/infrastructure/jwt/token/jwt-token-validator.d.ts +0 -32
  172. package/dist/src/infrastructure/jwt/token/jwt-token-validator.js +0 -77
  173. package/dist/src/infrastructure/jwt/token/tools/jwt-signer.d.ts +0 -33
  174. package/dist/src/infrastructure/jwt/token/tools/jwt-signer.js +0 -46
  175. package/dist/src/infrastructure/jwt/token/tools/jwt-token-parser.d.ts +0 -30
  176. package/dist/src/infrastructure/jwt/token/tools/jwt-token-parser.js +0 -57
  177. package/dist/src/infrastructure/jwt/token/tools/jwt-token-validator.d.ts +0 -32
  178. package/dist/src/infrastructure/jwt/token/tools/jwt-token-validator.js +0 -77
  179. package/dist/src/infrastructure/repositories/index.d.ts +0 -1
  180. package/dist/src/infrastructure/repositories/test/in-memory-token-session.repository.d.ts +0 -67
  181. package/dist/src/infrastructure/repositories/test/in-memory-token-session.repository.js +0 -128
  182. package/dist/src/infrastructure/services/default-token-session.service.d.ts +0 -18
  183. package/dist/src/infrastructure/services/jwt-token.service.d.ts +0 -15
  184. package/dist/src/infrastructure/services/jwt-token.service.js +0 -44
  185. package/dist/src/infrastructure/services/simple-jwt-token.service.d.ts +0 -15
  186. package/dist/src/infrastructure/services/simple-jwt-token.service.js +0 -46
  187. package/dist/src/infrastructure/services/token-session.service.d.ts +0 -24
  188. package/dist/src/infrastructure/services/token-session.service.js +0 -131
  189. package/dist/src/infrastructure/types/auth-service-container.d.ts +0 -14
  190. package/dist/src/shared/constants/index.d.ts +0 -1
  191. package/dist/src/shared/constants/jwt-algorithms.d.ts +0 -17
  192. package/dist/src/shared/constants/jwt-algorithms.js +0 -23
  193. package/dist/src/shared/encoders/base64-url-encoder.d.ts +0 -29
  194. package/dist/src/shared/encoders/base64-url-encoder.js +0 -45
  195. package/dist/src/shared/encoders/index.d.ts +0 -1
  196. package/dist/src/shared/encoders/index.js +0 -17
  197. package/dist/src/shared/index.d.ts +0 -4
  198. package/dist/src/shared/index.js +0 -20
  199. package/dist/src/shared/types/index.d.ts +0 -1
  200. package/dist/src/shared/types/jwt.d.ts +0 -25
  201. package/dist/src/shared/types/jwt.js +0 -2
  202. package/dist/src/shared/types/jwt.types.d.ts +0 -39
  203. package/dist/src/shared/types/jwt.types.js +0 -2
  204. package/dist/tests/application/factory/auth-service-factory.spec.d.ts +0 -1
  205. package/dist/tests/application/factory/auth-service-factory.spec.js +0 -97
  206. package/dist/tests/application/use-cases/login-with-password.integration.spec.d.ts +0 -1
  207. package/dist/tests/application/use-cases/login-with-password.integration.spec.js +0 -140
  208. package/dist/tests/application/use-cases/logout-use-case.spec.d.ts +0 -1
  209. package/dist/tests/application/use-cases/logout-use-case.spec.js +0 -40
  210. package/dist/tests/application/use-cases/refresh-token-use-case.spec.d.ts +0 -1
  211. package/dist/tests/application/use-cases/refresh-token-use-case.spec.js +0 -116
  212. package/dist/tests/application/use-cases/register-user.usecase.spec.d.ts +0 -1
  213. package/dist/tests/application/use-cases/register-user.usecase.spec.js +0 -151
  214. package/dist/tests/domain/entities/credential.spec.d.ts +0 -1
  215. package/dist/tests/domain/entities/credential.spec.js +0 -93
  216. package/dist/tests/domain/entities/user.spec.d.ts +0 -1
  217. package/dist/tests/domain/entities/user.spec.js +0 -93
  218. package/dist/tests/domain/object-values/email.spec.d.ts +0 -1
  219. package/dist/tests/domain/object-values/email.spec.js +0 -77
  220. package/dist/tests/domain/object-values/hashed-password.spec.d.ts +0 -1
  221. package/dist/tests/domain/object-values/hashed-password.spec.js +0 -54
  222. package/dist/tests/domain/object-values/id.spec.d.ts +0 -1
  223. package/dist/tests/domain/object-values/id.spec.js +0 -48
  224. package/dist/tests/domain/object-values/permission.spec.d.ts +0 -1
  225. package/dist/tests/domain/object-values/permission.spec.js +0 -75
  226. package/dist/tests/domain/object-values/role.spec.d.ts +0 -1
  227. package/dist/tests/domain/object-values/role.spec.js +0 -139
  228. package/dist/tests/domain/services/default-password-policy.spec.d.ts +0 -1
  229. package/dist/tests/domain/services/default-password-policy.spec.js +0 -69
  230. package/dist/tests/doman/entities/credential.spec.d.ts +0 -1
  231. package/dist/tests/doman/entities/credential.spec.js +0 -93
  232. package/dist/tests/doman/entities/user.spec.d.ts +0 -1
  233. package/dist/tests/doman/entities/user.spec.js +0 -93
  234. package/dist/tests/doman/object-values/email.spec.d.ts +0 -1
  235. package/dist/tests/doman/object-values/email.spec.js +0 -77
  236. package/dist/tests/doman/object-values/hashed-password.spec.d.ts +0 -1
  237. package/dist/tests/doman/object-values/hashed-password.spec.js +0 -54
  238. package/dist/tests/doman/object-values/id.spec.d.ts +0 -1
  239. package/dist/tests/doman/object-values/id.spec.js +0 -48
  240. package/dist/tests/doman/object-values/permission.spec.d.ts +0 -1
  241. package/dist/tests/doman/object-values/permission.spec.js +0 -75
  242. package/dist/tests/doman/object-values/role.spec.d.ts +0 -1
  243. package/dist/tests/doman/object-values/role.spec.js +0 -139
  244. package/dist/tests/helpers/make-jwt-subject.d.ts +0 -7
  245. package/dist/tests/helpers/make-jwt-subject.js +0 -16
  246. package/dist/tests/helpers/make-jwt-user.d.ts +0 -7
  247. package/dist/tests/helpers/make-jwt-user.js +0 -16
  248. package/dist/tests/helpers/make-user.d.ts +0 -2
  249. package/dist/tests/helpers/make-user.js +0 -15
  250. package/dist/tests/infrastructure/jwt/signature-strategy-factory.spec.d.ts +0 -1
  251. package/dist/tests/infrastructure/jwt/signature-strategy-factory.spec.js +0 -127
  252. package/dist/tests/infrastructure/jwt/strategies/ecdsa-signature-strategy.spec.d.ts +0 -1
  253. package/dist/tests/infrastructure/jwt/strategies/ecdsa-signature-strategy.spec.js +0 -157
  254. package/dist/tests/infrastructure/jwt/strategies/hmac-signature-strategy.spec.d.ts +0 -1
  255. package/dist/tests/infrastructure/jwt/strategies/hmac-signature-strategy.spec.js +0 -150
  256. package/dist/tests/infrastructure/jwt/strategies/rsa-signature-strategy..spec.d.ts +0 -1
  257. package/dist/tests/infrastructure/jwt/strategies/rsa-signature-strategy..spec.js +0 -156
  258. package/dist/tests/infrastructure/jwt/token/actions/jwt-token-generator.spec.d.ts +0 -1
  259. package/dist/tests/infrastructure/jwt/token/actions/jwt-token-generator.spec.js +0 -179
  260. package/dist/tests/infrastructure/jwt/token/actions/jwt-token-verifier.spec.d.ts +0 -1
  261. package/dist/tests/infrastructure/jwt/token/actions/jwt-token-verifier.spec.js +0 -142
  262. package/dist/tests/infrastructure/jwt/token/jwt-signer.spec.d.ts +0 -1
  263. package/dist/tests/infrastructure/jwt/token/jwt-signer.spec.js +0 -125
  264. package/dist/tests/infrastructure/jwt/token/jwt-token-parser.spec.d.ts +0 -1
  265. package/dist/tests/infrastructure/jwt/token/jwt-token-parser.spec.js +0 -116
  266. package/dist/tests/infrastructure/jwt/token/jwt-token-validator.spec.d.ts +0 -1
  267. package/dist/tests/infrastructure/jwt/token/jwt-token-validator.spec.js +0 -88
  268. package/dist/tests/infrastructure/jwt/token/tools/jwt-signer.spec.d.ts +0 -1
  269. package/dist/tests/infrastructure/jwt/token/tools/jwt-signer.spec.js +0 -126
  270. package/dist/tests/infrastructure/jwt/token/tools/jwt-token-parser.spec.d.ts +0 -1
  271. package/dist/tests/infrastructure/jwt/token/tools/jwt-token-parser.spec.js +0 -116
  272. package/dist/tests/infrastructure/jwt/token/tools/jwt-token-validator.spec.d.ts +0 -1
  273. package/dist/tests/infrastructure/jwt/token/tools/jwt-token-validator.spec.js +0 -88
  274. package/dist/tests/infrastructure/security/security/bcrypt-password-hasher.spec.d.ts +0 -1
  275. package/dist/tests/infrastructure/security/security/bcrypt-password-hasher.spec.js +0 -37
  276. package/dist/tests/infrastructure/services/jwt-token-service.spec.d.ts +0 -1
  277. package/dist/tests/infrastructure/services/jwt-token-service.spec.js +0 -145
  278. package/dist/tests/infrastructure/services/token-session.service.spec.d.ts +0 -1
  279. package/dist/tests/infrastructure/services/token-session.service.spec.js +0 -269
  280. package/dist/tests/shared/constants/jwt-algorithms.spec.d.ts +0 -1
  281. package/dist/tests/shared/constants/jwt-algorithms.spec.js +0 -27
  282. package/dist/tests/shared/encoders/base64-url-encoder.spec.d.ts +0 -1
  283. package/dist/tests/shared/encoders/base64-url-encoder.spec.js +0 -70
  284. package/dist/tests/shared/utils/time-parser.spec.d.ts +0 -1
  285. package/dist/tests/shared/utils/time-parser.spec.js +0 -80
  286. package/dist/utils/index.d.ts +0 -1
  287. package/dist/utils/index.js +0 -17
  288. package/dist/utils/time-parser.d.ts +0 -28
  289. package/dist/utils/time-parser.js +0 -76
  290. /package/dist/{src/application/dtos/login.dto.js → application/dtos/request/login.request.js} +0 -0
  291. /package/dist/{src/application/dtos/logout.dto.js → application/dtos/request/logout.request.js} +0 -0
  292. /package/dist/{src/application/dtos/refresh-token.dto.js → application/dtos/request/refresh-token.request.js} +0 -0
  293. /package/dist/{src/application/dtos/register-user.dto.js → application/dtos/request/register-user.request.js} +0 -0
  294. /package/dist/{src/domain/ports/auth/password-hasher.js → application/dtos/response/login.response.js} +0 -0
  295. /package/dist/{src/domain/ports/auth/password-policy.port.js → application/dtos/response/logout.response.js} +0 -0
  296. /package/dist/{src/domain/ports/jwt/factory/signature-strategy-factory.port.js → application/dtos/response/refresh-token.response.js} +0 -0
  297. /package/dist/{src/domain/ports/jwt/payload/jwt-payload.port.js → application/dtos/response/register-user.response.js} +0 -0
  298. /package/dist/{src/domain/ports/jwt/signature-strategy-factory.port.js → application/dtos/type/user-role.type.js} +0 -0
  299. /package/dist/{src/application → application}/factories/index.d.ts +0 -0
  300. /package/dist/{src/application → application}/factories/index.js +0 -0
  301. /package/dist/{src/domain/ports/repository/credential.repository.js → application/types/auth-service-factory-options.type.js} +0 -0
  302. /package/dist/{src/application → application}/use-cases/index.d.ts +0 -0
  303. /package/dist/{src/application → application}/use-cases/index.js +0 -0
  304. /package/dist/{src/domain → domain}/entities/credential.entity.d.ts +0 -0
  305. /package/dist/{src/domain → domain}/entities/credential.entity.js +0 -0
  306. /package/dist/{src/domain → domain}/entities/index.d.ts +0 -0
  307. /package/dist/{src/domain → domain}/entities/index.js +0 -0
  308. /package/dist/{src/domain → domain}/entities/user.entity.d.ts +0 -0
  309. /package/dist/{src/domain → domain}/entities/user.entity.js +0 -0
  310. /package/dist/{src/domain → domain}/errors/identity.errors.d.ts +0 -0
  311. /package/dist/{src/domain → domain}/errors/identity.errors.js +0 -0
  312. /package/dist/{src/domain → domain}/errors/index.d.ts +0 -0
  313. /package/dist/{src/domain → domain}/errors/index.js +0 -0
  314. /package/dist/{src/domain → domain}/object-values/email.d.ts +0 -0
  315. /package/dist/{src/domain → domain}/object-values/email.js +0 -0
  316. /package/dist/{src/domain → domain}/object-values/hashed-password.d.ts +0 -0
  317. /package/dist/{src/domain → domain}/object-values/hashed-password.js +0 -0
  318. /package/dist/{src/domain → domain}/object-values/id.d.ts +0 -0
  319. /package/dist/{src/domain → domain}/object-values/id.js +0 -0
  320. /package/dist/{src/domain → domain}/object-values/index.d.ts +0 -0
  321. /package/dist/{src/domain → domain}/object-values/index.js +0 -0
  322. /package/dist/{src/domain → domain}/object-values/permission.d.ts +0 -0
  323. /package/dist/{src/domain → domain}/object-values/permission.js +0 -0
  324. /package/dist/{src/domain → domain}/object-values/role.d.ts +0 -0
  325. /package/dist/{src/domain → domain}/object-values/role.js +0 -0
  326. /package/dist/{src/domain/ports/repository/user.repository.js → domain/ports/auth/password-hasher.port.js} +0 -0
  327. /package/dist/{src/domain/ports/token/token-session.port.js → domain/ports/auth/password-policy.port.js} +0 -0
  328. /package/dist/{src/domain → domain}/ports/jwt/payload/jwt-payload.port.d.ts +0 -0
  329. /package/dist/{src/domain/ports/token/token.service.port.js → domain/ports/jwt/payload/jwt-payload.port.js} +0 -0
  330. /package/dist/{src/domain/props/entities/credential.props.js → domain/ports/repository/credential.repository.js} +0 -0
  331. /package/dist/{src/domain/props/entities/user.props.js → domain/ports/repository/user-repository.port.js} +0 -0
  332. /package/dist/{src/domain/props/jwt/create-payload.props.js → domain/ports/token/token-session.port.js} +0 -0
  333. /package/dist/{src/domain/services → domain/ports/token}/token.service.port.js +0 -0
  334. /package/dist/{src/domain → domain}/props/entities/credential.props.d.ts +0 -0
  335. /package/dist/{src/domain/props/jwt/generate-access-token.props.js → domain/props/entities/credential.props.js} +0 -0
  336. /package/dist/{src/domain → domain}/props/entities/index.d.ts +0 -0
  337. /package/dist/{src/domain → domain}/props/entities/index.js +0 -0
  338. /package/dist/{src/domain → domain}/props/entities/user.props.d.ts +0 -0
  339. /package/dist/{src/domain/props/jwt/generate-refresh-token.props.js → domain/props/entities/user.props.js} +0 -0
  340. /package/dist/{src/domain → domain}/props/index.d.ts +0 -0
  341. /package/dist/{src/domain → domain}/props/index.js +0 -0
  342. /package/dist/{src/domain/props/services → domain/props/jwt}/generate-access-token.props.js +0 -0
  343. /package/dist/{src/domain/props/services → domain/props/jwt}/generate-refresh-token.props.js +0 -0
  344. /package/dist/{src/domain → domain}/props/jwt/jwt-user.d.ts +0 -0
  345. /package/dist/{src/domain → domain}/props/jwt/jwt-user.js +0 -0
  346. /package/dist/{src/domain → domain}/services/index.d.ts +0 -0
  347. /package/dist/{src/domain → domain}/services/index.js +0 -0
  348. /package/dist/{src/domain → domain}/services/password-policy.service.js +0 -0
  349. /package/dist/{src/infrastructure/repositories/test → in-memory}/in-memory-user.repository.js +0 -0
  350. /package/dist/{src/infrastructure/repositories/test → in-memory}/index.d.ts +0 -0
  351. /package/dist/{src/infrastructure/repositories/test → in-memory}/index.js +0 -0
  352. /package/dist/{src/domain/ports/auth/password-policy-config.port.d.ts → infrastructure/index.d.ts} +0 -0
  353. /package/dist/{src/infrastructure → infrastructure}/security/index.d.ts +0 -0
  354. /package/dist/{src/infrastructure → infrastructure}/security/index.js +0 -0
  355. /package/dist/{src/infrastructure → infrastructure}/types/auth-service-container.js +0 -0
  356. /package/dist/{src/infrastructure → infrastructure}/types/index.d.ts +0 -0
  357. /package/dist/{src/infrastructure → infrastructure}/types/index.js +0 -0
  358. /package/dist/{src/shared → shared}/utils/index.d.ts +0 -0
  359. /package/dist/{src/shared → shared}/utils/index.js +0 -0
  360. /package/dist/{src/shared → shared}/utils/time-parser.d.ts +0 -0
  361. /package/dist/{src/shared → shared}/utils/time-parser.js +0 -0
@@ -1,40 +0,0 @@
1
- "use strict";
2
- // tests/application/use-cases/logout.usecase.spec.ts
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- const application_1 = require("src/application");
5
- const domain_1 = require("../../../src/domain");
6
- describe("LogoutUseCase", () => {
7
- let tokenSessionMock;
8
- let useCase;
9
- beforeEach(() => {
10
- tokenSessionMock = {
11
- revokeSession: jest.fn(),
12
- };
13
- // Solo necesitamos revokeSession para este caso de uso,
14
- // así que casteamos al tipo completo de ITokenSession.
15
- useCase = new application_1.LogoutUseCase(tokenSessionMock);
16
- });
17
- it("debería cerrar sesión correctamente cuando revokeSession no lanza error", async () => {
18
- // Arrange
19
- const request = { refreshToken: "valid-refresh-token" };
20
- tokenSessionMock.revokeSession.mockResolvedValueOnce(); // Promise<void>
21
- // Act
22
- const response = await useCase.execute(request);
23
- // Assert
24
- expect(tokenSessionMock.revokeSession).toHaveBeenCalledTimes(1);
25
- expect(tokenSessionMock.revokeSession).toHaveBeenCalledWith("valid-refresh-token");
26
- expect(response).toEqual({
27
- success: true,
28
- message: "Successfully logged out",
29
- });
30
- });
31
- it("debería lanzar LogoutError cuando revokeSession lanza un error", async () => {
32
- // Arrange
33
- const request = { refreshToken: "invalid-refresh-token" };
34
- tokenSessionMock.revokeSession.mockRejectedValueOnce(new Error("Some low-level error"));
35
- // Act & Assert
36
- await expect(useCase.execute(request)).rejects.toEqual(new domain_1.LogoutError("Failed to logout: invalid refresh token"));
37
- expect(tokenSessionMock.revokeSession).toHaveBeenCalledTimes(1);
38
- expect(tokenSessionMock.revokeSession).toHaveBeenCalledWith("invalid-refresh-token");
39
- });
40
- });
@@ -1,116 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const application_1 = require("src/application");
4
- const refresh_token_use_case_1 = require("src/application/use-cases/refresh-token.use-case");
5
- const domain_1 = require("src/domain");
6
- const infrastructure_1 = require("src/infrastructure");
7
- const shared_1 = require("src/shared");
8
- describe("RefreshTokenUseCase", () => {
9
- let userRepo;
10
- let credentialRepo;
11
- let passwordHasher;
12
- let jwtSigner;
13
- let tokenGenerator;
14
- let tokenSessionService;
15
- const jwtConfig = {
16
- accessTokenSecret: "access_secret_key_123",
17
- refreshTokenSecret: "refresh_secret_key_123",
18
- accessTokenExpirationMs: 1000 * 60 * 15, // 15 minutos
19
- refreshTokenExpirationMs: 1000 * 60 * 60 * 24, // 1 día,
20
- algorithm: "HS256",
21
- };
22
- // Hash válido de "Password123!" (cost 10)
23
- const VALID_BCRYPT = "$2b$10$CwTycUXWue0Thq9StjUM0uJ8rS8o9VZqvE8G9W9C6q7CwTycUXWu2";
24
- beforeEach(() => {
25
- userRepo = new infrastructure_1.InMemoryUserRepository();
26
- credentialRepo = new infrastructure_1.InMemoryCredentialRepository();
27
- passwordHasher = new infrastructure_1.BcryptPasswordHasher();
28
- jwtSigner = new infrastructure_1.JwtSigner(new shared_1.Base64UrlEncoder());
29
- // 👇 Ajuste: orden típico (signer, encoder). Mantén tu firma real si difiere.
30
- tokenGenerator = new infrastructure_1.JwtTokenGenerator(new shared_1.Base64UrlEncoder(), jwtSigner);
31
- // TokenSessionJWT implementa ITokenSession
32
- class TokenSessionJWT {
33
- constructor(tokenGen, credentialRepo) {
34
- this.tokenGen = tokenGen;
35
- this.credentialRepo = credentialRepo;
36
- }
37
- validateSession(_accessToken) {
38
- throw new Error("Method not implemented.");
39
- }
40
- async createSession(user) {
41
- const accessToken = this.tokenGen.generateAccessToken({
42
- user: {
43
- id: user.id.getValue(),
44
- email: user.email.toString(),
45
- roles: user.roles.map((r) => ({ role: r.getValuePublic().role })),
46
- },
47
- config: jwtConfig,
48
- });
49
- const refreshToken = this.tokenGen.generateRefreshToken({
50
- user: {
51
- id: user.id.getValue(),
52
- email: user.email.toString(),
53
- roles: user.roles.map((r) => ({ role: r.getValuePublic().role })),
54
- },
55
- config: jwtConfig,
56
- });
57
- const credential = new domain_1.Credential({
58
- userId: new domain_1.Id(user.id.getValue()),
59
- accessToken,
60
- refreshToken,
61
- expiresAt: new Date(Date.now() + jwtConfig.accessTokenExpirationMs),
62
- createdAt: new Date(),
63
- });
64
- await this.credentialRepo.save(credential);
65
- return credential;
66
- }
67
- async refreshSession(refreshToken) {
68
- const found = await this.credentialRepo.findByRefreshToken(refreshToken);
69
- if (!found)
70
- throw new domain_1.InvalidOrExpiredRefreshTokenError();
71
- // ✅ (opcional) rotar: revocar el refresh anterior para evitar reutilización
72
- await this.credentialRepo.deleteByRefreshToken(refreshToken);
73
- const user = new domain_1.User({
74
- id: new domain_1.Id(found.userId.getValue()),
75
- email: new domain_1.Email("user@example.com"),
76
- roles: [new domain_1.Role("USER")],
77
- password: new domain_1.HashedPassword(VALID_BCRYPT),
78
- isActive: true,
79
- createdAt: new Date(),
80
- updatedAt: new Date(),
81
- });
82
- return this.createSession(user);
83
- }
84
- async revokeSession(refreshToken) {
85
- await this.credentialRepo.deleteByRefreshToken(refreshToken);
86
- }
87
- }
88
- tokenSessionService = new TokenSessionJWT(tokenGenerator, credentialRepo);
89
- });
90
- it("debería crear un usuario, loguearlo y refrescar su token", async () => {
91
- // 1️⃣ Registrar usuario
92
- const passwordPolicy = new domain_1.DefaultPasswordPolicy();
93
- const registerUser = new application_1.RegisterUserUseCase(userRepo, passwordHasher, passwordPolicy);
94
- const email = "user@example.com";
95
- const password = "Password123!";
96
- const roles = [{ role: "USER" }];
97
- await registerUser.execute({ email, password, roles });
98
- // 2️⃣ Loguear usuario
99
- const login = new application_1.LoginWithPasswordUseCase(userRepo, passwordHasher, tokenSessionService);
100
- const loginResponse = await login.execute({ email, password });
101
- expect(loginResponse.accessToken).toBeDefined();
102
- expect(loginResponse.refreshToken).toBeDefined();
103
- // 3️⃣ Refrescar Token
104
- const refreshTokenUseCase = new refresh_token_use_case_1.RefreshTokenUseCase(tokenSessionService);
105
- const refreshed = await refreshTokenUseCase.execute({
106
- refreshToken: loginResponse.refreshToken,
107
- });
108
- expect(refreshed.accessToken).toBeDefined();
109
- expect(refreshed.refreshToken).toBeDefined();
110
- expect(refreshed.refreshToken).not.toEqual(loginResponse.refreshToken);
111
- });
112
- it("debería lanzar InvalidOrExpiredRefreshTokenError si el token no existe", async () => {
113
- const refreshTokenUseCase = new refresh_token_use_case_1.RefreshTokenUseCase(tokenSessionService);
114
- await expect(refreshTokenUseCase.execute({ refreshToken: "invalid.token" })).rejects.toThrow(domain_1.InvalidOrExpiredRefreshTokenError);
115
- });
116
- });
@@ -1,151 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const application_1 = require("src/application");
4
- const domain_1 = require("src/domain");
5
- describe("RegisterUserUseCase", () => {
6
- let userRepository;
7
- let passwordHasher;
8
- let passwordPolicy;
9
- let useCase;
10
- beforeEach(() => {
11
- userRepository = {
12
- findByEmail: jest.fn(),
13
- save: jest.fn(),
14
- // agrega otros métodos del repo si existen, con jest.fn()
15
- };
16
- passwordHasher = {
17
- hash: jest.fn(),
18
- };
19
- passwordPolicy = {
20
- validateStrength: jest.fn(),
21
- getRequirements: jest.fn(),
22
- };
23
- useCase = new application_1.RegisterUserUseCase(userRepository, passwordHasher, passwordPolicy);
24
- jest.clearAllMocks();
25
- });
26
- it("debería lanzar PasswordPolicyViolationError si la contraseña no cumple la política", async () => {
27
- const weakPasswordErrors = ["Too short", "No number"];
28
- passwordPolicy.validateStrength.mockReturnValue({
29
- isValid: false,
30
- errors: weakPasswordErrors,
31
- });
32
- const request = {
33
- email: "test@example.com",
34
- password: "weak",
35
- roles: [],
36
- };
37
- await expect(useCase.execute(request)).rejects.toBeInstanceOf(domain_1.PasswordPolicyViolationError);
38
- expect(passwordPolicy.validateStrength).toHaveBeenCalledWith(request.password);
39
- expect(userRepository.findByEmail).not.toHaveBeenCalled();
40
- expect(passwordHasher.hash).not.toHaveBeenCalled();
41
- expect(userRepository.save).not.toHaveBeenCalled();
42
- });
43
- it("debería lanzar EmailAlreadyInUseError si el email ya existe", async () => {
44
- passwordPolicy.validateStrength.mockReturnValue({
45
- isValid: true,
46
- errors: [],
47
- });
48
- // No necesitamos un User real, basta con algo truthy
49
- const existingUser = {};
50
- userRepository.findByEmail.mockResolvedValue(existingUser);
51
- const request = {
52
- email: "used@example.com",
53
- password: "StrongP@ss1",
54
- roles: [],
55
- };
56
- await expect(useCase.execute(request)).rejects.toBeInstanceOf(domain_1.EmailAlreadyInUseError);
57
- expect(passwordPolicy.validateStrength).toHaveBeenCalledWith(request.password);
58
- expect(userRepository.findByEmail).toHaveBeenCalledTimes(1);
59
- expect(passwordHasher.hash).not.toHaveBeenCalled();
60
- expect(userRepository.save).not.toHaveBeenCalled();
61
- });
62
- it("debería registrar un usuario, guardar en el repositorio y retornar la respuesta correcta", async () => {
63
- passwordPolicy.validateStrength.mockReturnValue({
64
- isValid: true,
65
- errors: [],
66
- });
67
- userRepository.findByEmail.mockResolvedValue(null);
68
- const hashedPassword = "hashed-password-123";
69
- passwordHasher.hash.mockResolvedValue(hashedPassword);
70
- const request = {
71
- email: "newuser@example.com",
72
- password: "StrongP@ss1",
73
- roles: [
74
- {
75
- role: "ADMIN",
76
- permissions: ["user.read", "user.write"],
77
- },
78
- ],
79
- };
80
- // Fake user que retornará User.create
81
- const fakeUserIdValue = "generated-user-id";
82
- const fakePublicRoles = [
83
- {
84
- role: "ADMIN",
85
- permissions: ["user.read", "user.write"],
86
- },
87
- ];
88
- const fakeUser = {
89
- id: {
90
- getValue: jest.fn().mockReturnValue(fakeUserIdValue),
91
- },
92
- roles: [
93
- {
94
- getValuePublic: jest.fn().mockReturnValue(fakePublicRoles[0]),
95
- },
96
- ],
97
- isActive: true,
98
- };
99
- const createSpy = jest
100
- .spyOn(domain_1.User, "create")
101
- .mockReturnValue(fakeUser);
102
- const result = await useCase.execute(request);
103
- // Validar interacción con passwordPolicy y repos
104
- expect(passwordPolicy.validateStrength).toHaveBeenCalledWith(request.password);
105
- expect(userRepository.findByEmail).toHaveBeenCalledTimes(1);
106
- expect(passwordHasher.hash).toHaveBeenCalledWith(request.password);
107
- // Validar que se llama User.create con los argumentos esperados
108
- expect(createSpy).toHaveBeenCalledWith(request.email, expect.arrayContaining([
109
- expect.objectContaining({}), // aquí solo validamos que se pasó al menos un Role
110
- ]), hashedPassword);
111
- // Validar que se persiste el usuario
112
- expect(userRepository.save).toHaveBeenCalledWith(fakeUser);
113
- const expectedResponse = {
114
- id: fakeUserIdValue,
115
- roles: fakePublicRoles,
116
- isActive: true,
117
- };
118
- expect(result).toEqual(expectedResponse);
119
- });
120
- it("debería permitir registrar usuario sin roles (array vacío por defecto)", async () => {
121
- passwordPolicy.validateStrength.mockReturnValue({
122
- isValid: true,
123
- errors: [],
124
- });
125
- userRepository.findByEmail.mockResolvedValue(null);
126
- const hashedPassword = "hashed-no-roles";
127
- passwordHasher.hash.mockResolvedValue(hashedPassword);
128
- const request = {
129
- email: "noroles@example.com",
130
- password: "StrongP@ss1",
131
- // roles: undefined
132
- };
133
- const fakeUser = {
134
- id: {
135
- getValue: jest.fn().mockReturnValue("no-roles-id"),
136
- },
137
- roles: [],
138
- isActive: true,
139
- };
140
- jest.spyOn(domain_1.User, "create").mockReturnValue(fakeUser);
141
- const result = await useCase.execute(request);
142
- expect(userRepository.findByEmail).toHaveBeenCalledTimes(1);
143
- expect(passwordHasher.hash).toHaveBeenCalledWith(request.password);
144
- expect(userRepository.save).toHaveBeenCalledWith(fakeUser);
145
- expect(result).toEqual({
146
- id: "no-roles-id",
147
- roles: [],
148
- isActive: true,
149
- });
150
- });
151
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,93 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const credential_entity_1 = require("../../../src/domain/entities/credential.entity");
4
- const object_values_1 = require("../../../src/domain/object-values");
5
- describe("Credential", () => {
6
- const ACCESS = "access.jwt.token.mock";
7
- const REFRESH = "refresh.jwt.token.mock";
8
- beforeAll(() => {
9
- // Controlamos el tiempo del sistema para pruebas deterministas
10
- jest.useFakeTimers();
11
- });
12
- afterAll(() => {
13
- // Restauramos el tiempo real
14
- jest.useRealTimers();
15
- });
16
- test("create(): crea credenciales válidas con timestamps correctos", () => {
17
- const now = new Date("2025-01-01T10:00:00.000Z");
18
- jest.setSystemTime(now);
19
- const userId = new object_values_1.Id("user-123");
20
- const expiresAt = new Date(now.getTime() + 60 * 60 * 1000); // +1h
21
- const cred = credential_entity_1.Credential.create(userId, ACCESS, REFRESH, expiresAt);
22
- expect(cred.userId.equals(userId)).toBe(true);
23
- expect(cred.accessToken).toBe(ACCESS);
24
- expect(cred.refreshToken).toBe(REFRESH);
25
- // createdAt debe ser ~ now, y expiresAt exactamente el pasado
26
- expect(cred.createdAt.toISOString()).toBe(now.toISOString());
27
- expect(cred.expiresAt.toISOString()).toBe(expiresAt.toISOString());
28
- // Estado
29
- expect(cred.isExpired()).toBe(false);
30
- expect(cred.isValid()).toBe(true);
31
- });
32
- test("isExpired(): expira cuando now > expiresAt", () => {
33
- const base = new Date("2025-01-01T10:00:00.000Z");
34
- const expires = new Date("2025-01-01T10:10:00.000Z");
35
- jest.setSystemTime(base);
36
- const cred = credential_entity_1.Credential.create(new object_values_1.Id("u-1"), ACCESS, REFRESH, expires);
37
- // Antes de expirar
38
- jest.setSystemTime(new Date("2025-01-01T10:09:59.000Z"));
39
- expect(cred.isExpired()).toBe(false);
40
- expect(cred.isValid()).toBe(true);
41
- // Justo en el borde (now === expiresAt) → NO está expirado (usa >, no >=)
42
- jest.setSystemTime(new Date("2025-01-01T10:10:00.000Z"));
43
- expect(cred.isExpired()).toBe(false);
44
- expect(cred.isValid()).toBe(true);
45
- // Después de expirar
46
- jest.setSystemTime(new Date("2025-01-01T10:10:01.000Z"));
47
- expect(cred.isExpired()).toBe(true);
48
- expect(cred.isValid()).toBe(false);
49
- });
50
- test("getters de Date devuelven copias (no exponen estado interno)", () => {
51
- const now = new Date("2025-01-01T12:00:00.000Z");
52
- jest.setSystemTime(now);
53
- const expires = new Date(now.getTime() + 5 * 60 * 1000); // +5m
54
- const cred = credential_entity_1.Credential.create(new object_values_1.Id("u-2"), ACCESS, REFRESH, expires);
55
- const createdAtCopy = cred.createdAt;
56
- const expiresAtCopy = cred.expiresAt;
57
- // Mutamos las copias
58
- createdAtCopy.setFullYear(1999);
59
- expiresAtCopy.setFullYear(1999);
60
- // El estado interno debe mantenerse intacto
61
- expect(cred.createdAt.toISOString()).toBe(now.toISOString());
62
- expect(cred.expiresAt.toISOString()).toBe(expires.toISOString());
63
- });
64
- test("reconstitute(): reconstruye desde props sin alterar valores", () => {
65
- const propsNow = new Date("2025-02-02T08:00:00.000Z");
66
- const propsExp = new Date("2025-02-02T09:00:00.000Z");
67
- const userId = new object_values_1.Id("user-xyz");
68
- const cred = credential_entity_1.Credential.reconstitute({
69
- userId,
70
- accessToken: ACCESS,
71
- refreshToken: REFRESH,
72
- createdAt: propsNow,
73
- expiresAt: propsExp,
74
- });
75
- expect(cred.userId.equals(userId)).toBe(true);
76
- expect(cred.accessToken).toBe(ACCESS);
77
- expect(cred.refreshToken).toBe(REFRESH);
78
- expect(cred.createdAt.toISOString()).toBe(propsNow.toISOString());
79
- expect(cred.expiresAt.toISOString()).toBe(propsExp.toISOString());
80
- expect(cred.isExpired()).toBe(false);
81
- expect(cred.isValid()).toBe(true);
82
- });
83
- test("soporta IDs generados", () => {
84
- const id = object_values_1.Id.generate();
85
- const exp = new Date(Date.now() + 1000);
86
- const cred = credential_entity_1.Credential.create(id, ACCESS, REFRESH, exp);
87
- // Simple smoke tests
88
- expect(typeof cred.userId.getValue).toBe("function");
89
- expect(cred.accessToken).toBe(ACCESS);
90
- expect(cred.refreshToken).toBe(REFRESH);
91
- expect(cred.isValid()).toBe(true);
92
- });
93
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,93 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const domain_1 = require("src/domain");
4
- describe("User (Entity)", () => {
5
- // Genera la cola EXACTA de 53 caracteres válidos para bcrypt
6
- const makeBcrypt = (cost = 10) => `$2b$${String(cost).padStart(2, "0")}$${"A".repeat(53)}`;
7
- let mockId;
8
- let mockEmail;
9
- let mockPassword;
10
- let mockRole;
11
- let baseDate;
12
- let baseProps;
13
- beforeEach(() => {
14
- mockId = new domain_1.Id("user-123");
15
- mockEmail = new domain_1.Email("test@example.com");
16
- mockPassword = new domain_1.HashedPassword(makeBcrypt(10)); // ✅ válido: $2b$10$ + 53 chars
17
- mockRole = new domain_1.Role("admin", [domain_1.Permission.create("read:*")]);
18
- baseDate = new Date("2025-01-01T00:00:00.000Z");
19
- baseProps = {
20
- id: mockId,
21
- email: mockEmail,
22
- roles: [mockRole],
23
- password: mockPassword,
24
- isActive: true,
25
- createdAt: baseDate,
26
- updatedAt: baseDate,
27
- };
28
- });
29
- describe("constructor & getters", () => {
30
- it("crea correctamente una instancia con todas las propiedades", () => {
31
- const user = new domain_1.User(baseProps);
32
- expect(user.id).toBe(mockId);
33
- expect(user.email).toBe(mockEmail);
34
- expect(user.roles).toEqual([mockRole]);
35
- expect(user.password).toBe(mockPassword);
36
- expect(user.isActive).toBe(true);
37
- expect(user.createdAt).toEqual(baseDate);
38
- expect(user.updatedAt).toEqual(baseDate);
39
- });
40
- it("devuelve nuevas instancias de fecha (copia defensiva)", () => {
41
- const user = new domain_1.User(baseProps);
42
- const c1 = user.createdAt;
43
- const c2 = user.createdAt;
44
- const u1 = user.updatedAt;
45
- const u2 = user.updatedAt;
46
- expect(c1).not.toBe(c2);
47
- expect(u1).not.toBe(u2);
48
- expect(c1.getTime()).toBe(c2.getTime());
49
- expect(u1.getTime()).toBe(u2.getTime());
50
- });
51
- });
52
- describe("business methods", () => {
53
- it("activate() cambia isActive a true y actualiza updatedAt", () => {
54
- const user = new domain_1.User({ ...baseProps, isActive: false });
55
- const before = user.updatedAt.getTime();
56
- user.activate();
57
- expect(user.isActive).toBe(true);
58
- expect(user.updatedAt.getTime()).toBeGreaterThan(before);
59
- });
60
- it("deactivate() cambia isActive a false y actualiza updatedAt", () => {
61
- const user = new domain_1.User({ ...baseProps, isActive: true });
62
- const before = user.updatedAt.getTime();
63
- user.deactivate();
64
- expect(user.isActive).toBe(false);
65
- expect(user.updatedAt.getTime()).toBeGreaterThan(before);
66
- });
67
- it("canLogin() refleja el estado activo", () => {
68
- expect(new domain_1.User({ ...baseProps, isActive: true }).canLogin()).toBe(true);
69
- expect(new domain_1.User({ ...baseProps, isActive: false }).canLogin()).toBe(false);
70
- });
71
- });
72
- describe("factory methods", () => {
73
- it("create() genera valores válidos", () => {
74
- const roles = [new domain_1.Role("user")];
75
- const user = domain_1.User.create("person@example.com", roles, makeBcrypt(12));
76
- expect(user).toBeInstanceOf(domain_1.User);
77
- expect(user.id).toBeInstanceOf(domain_1.Id);
78
- expect(user.email.getValue()).toBe("person@example.com");
79
- expect(user.roles).toEqual(roles);
80
- expect(user.password).toBeInstanceOf(domain_1.HashedPassword);
81
- expect(user.isActive).toBe(true);
82
- expect(user.createdAt).toBeInstanceOf(Date);
83
- expect(user.updatedAt).toBeInstanceOf(Date);
84
- });
85
- it("reconstitute() reconstruye desde props", () => {
86
- const user = domain_1.User.reconstitute(baseProps);
87
- expect(user.id).toBe(mockId);
88
- expect(user.email).toBe(mockEmail);
89
- expect(user.roles[0]).toBe(mockRole);
90
- expect(user.password).toBe(mockPassword);
91
- });
92
- });
93
- });
@@ -1 +0,0 @@
1
- export {};
@@ -1,77 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const errors_1 = require("src/domain/errors");
4
- const email_1 = require("src/domain/object-values/email");
5
- describe("Email Value Object", () => {
6
- // 1️⃣ Casos válidos
7
- describe("creación válida", () => {
8
- test("crea correctamente un email bien formado", () => {
9
- const email = new email_1.Email("User@Test.COM");
10
- expect(email.getValue()).toBe("user@test.com");
11
- });
12
- test("elimina espacios al inicio y final y convierte a minúsculas", () => {
13
- const email = new email_1.Email(" MyMail@Example.COM ");
14
- expect(email.getValue()).toBe("mymail@example.com");
15
- });
16
- test("toString devuelve el mismo valor normalizado", () => {
17
- const email = new email_1.Email("Example@Mail.COM");
18
- expect(email.toString()).toBe("example@mail.com");
19
- });
20
- });
21
- // 2️⃣ Casos inválidos de formato
22
- describe("formato inválido", () => {
23
- test("lanza InvalidEmailError si falta el símbolo '@'", () => {
24
- expect(() => new email_1.Email("invalidemail.com")).toThrow(errors_1.InvalidEmailError);
25
- });
26
- test("lanza InvalidEmailError si falta dominio", () => {
27
- expect(() => new email_1.Email("user@")).toThrow(errors_1.InvalidEmailError);
28
- });
29
- test("lanza InvalidEmailError si falta usuario", () => {
30
- expect(() => new email_1.Email("@domain.com")).toThrow(errors_1.InvalidEmailError);
31
- });
32
- test("lanza InvalidEmailError si el dominio no tiene punto", () => {
33
- expect(() => new email_1.Email("user@domain")).toThrow(errors_1.InvalidEmailError);
34
- });
35
- test("lanza InvalidEmailError si hay caracteres inválidos", () => {
36
- expect(() => new email_1.Email("user@@domain.com")).toThrow(errors_1.InvalidEmailError);
37
- expect(() => new email_1.Email("user domain@com")).toThrow(errors_1.InvalidEmailError);
38
- });
39
- test("lanza InvalidEmailError si excede 254 caracteres", () => {
40
- const longLocalPart = "a".repeat(245);
41
- const tooLong = `${longLocalPart}@example.com`;
42
- expect(() => new email_1.Email(tooLong)).toThrow(errors_1.InvalidEmailError);
43
- });
44
- });
45
- // 3️⃣ Igualdad
46
- describe("equals", () => {
47
- test("devuelve true si los valores normalizados coinciden", () => {
48
- const a = new email_1.Email("User@Test.com");
49
- const b = new email_1.Email("user@test.com");
50
- expect(a.equals(b)).toBe(true);
51
- });
52
- test("devuelve false si los valores son distintos", () => {
53
- const a = new email_1.Email("user1@test.com");
54
- const b = new email_1.Email("user2@test.com");
55
- expect(a.equals(b)).toBe(false);
56
- });
57
- });
58
- // 4️⃣ Robustez ante espacios y casos mixtos
59
- describe("normalización", () => {
60
- test("ignora espacios extra y respeta minúsculas", () => {
61
- const email = new email_1.Email(" TestUser@Example.COM ");
62
- expect(email.getValue()).toBe("testuser@example.com");
63
- });
64
- });
65
- // 5️⃣ Mensaje de error (opcional)
66
- describe("mensaje de error", () => {
67
- test("incluye el valor original en el mensaje del InvalidEmailError", () => {
68
- try {
69
- new email_1.Email("bad-email");
70
- }
71
- catch (err) {
72
- expect(err).toBeInstanceOf(errors_1.InvalidEmailError);
73
- expect(err.message).toMatch(/bad-email/);
74
- }
75
- });
76
- });
77
- });
@@ -1,54 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const errors_1 = require("../../../src/domain/errors");
4
- const hashed_password_1 = require("../../../src/domain/object-values/hashed-password");
5
- // Tests para HashedPassword
6
- describe("HashedPassword", () => {
7
- // Genera la cola de 53 caracteres válidos para bcrypt
8
- const makePayload = (c = "A") => c.repeat(53);
9
- // Genera un hash bcrypt válido con cost y prefijo dados
10
- const makeHash = (cost, prefix = "2b") => `$${prefix}$${String(cost).padStart(2, "0")}$${makePayload()}`;
11
- // Casos de prueba
12
- it("lanza error si el hash es null", () => {
13
- // Prueba para null
14
- expect(() => new hashed_password_1.HashedPassword(null)).toThrow(new errors_1.InvalidHashedPasswordError("Hashed password cannot be null or undefined"));
15
- });
16
- // Prueba para undefined
17
- it("lanza error si el hash es undefined", () => {
18
- expect(() => new hashed_password_1.HashedPassword(undefined)).toThrow(new errors_1.InvalidHashedPasswordError("Hashed password cannot be null or undefined"));
19
- });
20
- // Prueba para cadena vacía
21
- it("lanza error si el hash está vacío", () => {
22
- expect(() => new hashed_password_1.HashedPassword(" ")).toThrow(new errors_1.InvalidHashedPasswordError("Hashed password cannot be empty"));
23
- });
24
- // Prueba para formato inválido
25
- it("lanza error si el hash no tiene formato bcrypt válido", () => {
26
- // Falta un carácter (52 en lugar de 53) → rompe el regex
27
- const invalidFormat = `$2b$10$${"A".repeat(52)}`;
28
- // Ejecutar prueba
29
- expect(() => new hashed_password_1.HashedPassword(invalidFormat)).toThrow(new errors_1.InvalidHashedPasswordError("Invalid bcrypt hash format"));
30
- });
31
- // Prueba para cost factor inválido (menor a 4)
32
- it("lanza error si el cost factor es menor a 4", () => {
33
- // Generar hash con cost factor 3
34
- const lowCost = makeHash(3); // "03"
35
- // Ejecutar prueba
36
- expect(() => new hashed_password_1.HashedPassword(lowCost)).toThrow(new errors_1.InvalidHashedPasswordError("Invalid bcrypt cost factor"));
37
- });
38
- // Prueba para cost factor inválido (mayor a 31)
39
- it("lanza error si el cost factor es mayor a 31", () => {
40
- const highCost = makeHash(32); // "32"
41
- // Ejecutar prueba
42
- expect(() => new hashed_password_1.HashedPassword(highCost)).toThrow(new errors_1.InvalidHashedPasswordError("Invalid bcrypt cost factor"));
43
- });
44
- it("crea instancia válida con hash correcto", () => {
45
- const valid = makeHash(10); // dentro de [4..31]
46
- const hashed = new hashed_password_1.HashedPassword(valid);
47
- expect(hashed.value).toBe(valid);
48
- });
49
- it("trimea espacios y sigue válido", () => {
50
- const valid = ` ${makeHash(12)} `;
51
- const hashed = new hashed_password_1.HashedPassword(valid);
52
- expect(hashed.value).toBe(valid.trim());
53
- });
54
- });
@@ -1 +0,0 @@
1
- export {};