payload 3.92.0 → 3.93.0

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 (161) hide show
  1. package/dist/auth/operations/login.d.ts.map +1 -1
  2. package/dist/auth/operations/login.js +2 -1
  3. package/dist/auth/operations/login.js.map +1 -1
  4. package/dist/auth/operations/resetPassword.d.ts.map +1 -1
  5. package/dist/auth/operations/resetPassword.js +52 -2
  6. package/dist/auth/operations/resetPassword.js.map +1 -1
  7. package/dist/auth/strategies/local/authenticate.d.ts +3 -1
  8. package/dist/auth/strategies/local/authenticate.d.ts.map +1 -1
  9. package/dist/auth/strategies/local/authenticate.js +23 -19
  10. package/dist/auth/strategies/local/authenticate.js.map +1 -1
  11. package/dist/auth/strategies/local/authenticate.spec.js +91 -7
  12. package/dist/auth/strategies/local/authenticate.spec.js.map +1 -1
  13. package/dist/auth/strategies/local/generatePasswordSaltHash.d.ts +14 -1
  14. package/dist/auth/strategies/local/generatePasswordSaltHash.d.ts.map +1 -1
  15. package/dist/auth/strategies/local/generatePasswordSaltHash.js +31 -15
  16. package/dist/auth/strategies/local/generatePasswordSaltHash.js.map +1 -1
  17. package/dist/auth/strategies/local/generatePasswordSaltHash.spec.js +76 -0
  18. package/dist/auth/strategies/local/generatePasswordSaltHash.spec.js.map +1 -0
  19. package/dist/collections/operations/create.js +8 -8
  20. package/dist/collections/operations/create.js.map +1 -1
  21. package/dist/collections/operations/utilities/update.d.ts.map +1 -1
  22. package/dist/collections/operations/utilities/update.js +31 -26
  23. package/dist/collections/operations/utilities/update.js.map +1 -1
  24. package/dist/config/defaults.d.ts.map +1 -1
  25. package/dist/config/defaults.js +3 -2
  26. package/dist/config/defaults.js.map +1 -1
  27. package/dist/config/sanitize.d.ts.map +1 -1
  28. package/dist/config/sanitize.js +4 -0
  29. package/dist/config/sanitize.js.map +1 -1
  30. package/dist/config/types.d.ts +10 -1
  31. package/dist/config/types.d.ts.map +1 -1
  32. package/dist/config/types.js.map +1 -1
  33. package/dist/database/getLocalizedPaths.d.ts.map +1 -1
  34. package/dist/database/getLocalizedPaths.js +15 -2
  35. package/dist/database/getLocalizedPaths.js.map +1 -1
  36. package/dist/database/queryValidation/hasReadAccessToQueryPath.d.ts +20 -0
  37. package/dist/database/queryValidation/hasReadAccessToQueryPath.d.ts.map +1 -0
  38. package/dist/database/queryValidation/hasReadAccessToQueryPath.js +86 -0
  39. package/dist/database/queryValidation/hasReadAccessToQueryPath.js.map +1 -0
  40. package/dist/database/queryValidation/validateSearchParams.d.ts.map +1 -1
  41. package/dist/database/queryValidation/validateSearchParams.js +28 -34
  42. package/dist/database/queryValidation/validateSearchParams.js.map +1 -1
  43. package/dist/errors/DuplicateGlobal.d.ts.map +1 -1
  44. package/dist/errors/DuplicateGlobal.js +1 -1
  45. package/dist/errors/DuplicateGlobal.js.map +1 -1
  46. package/dist/errors/InvalidFieldName.js +1 -1
  47. package/dist/errors/InvalidFieldName.js.map +1 -1
  48. package/dist/errors/InvalidFieldRelationship.d.ts.map +1 -1
  49. package/dist/errors/InvalidFieldRelationship.js +1 -1
  50. package/dist/errors/InvalidFieldRelationship.js.map +1 -1
  51. package/dist/errors/MissingFieldInputOptions.js +1 -1
  52. package/dist/errors/MissingFieldInputOptions.js.map +1 -1
  53. package/dist/errors/ReservedFieldName.d.ts.map +1 -1
  54. package/dist/errors/ReservedFieldName.js +1 -1
  55. package/dist/errors/ReservedFieldName.js.map +1 -1
  56. package/dist/fields/getBlockFromField.d.ts +8 -0
  57. package/dist/fields/getBlockFromField.d.ts.map +1 -0
  58. package/dist/fields/getBlockFromField.js +6 -0
  59. package/dist/fields/getBlockFromField.js.map +1 -0
  60. package/dist/fields/hooks/afterChange/promise.d.ts.map +1 -1
  61. package/dist/fields/hooks/afterChange/promise.js +6 -1
  62. package/dist/fields/hooks/afterChange/promise.js.map +1 -1
  63. package/dist/fields/hooks/afterRead/promise.d.ts.map +1 -1
  64. package/dist/fields/hooks/afterRead/promise.js +17 -8
  65. package/dist/fields/hooks/afterRead/promise.js.map +1 -1
  66. package/dist/fields/hooks/beforeChange/promise.d.ts.map +1 -1
  67. package/dist/fields/hooks/beforeChange/promise.js +26 -1
  68. package/dist/fields/hooks/beforeChange/promise.js.map +1 -1
  69. package/dist/fields/hooks/beforeDuplicate/promise.d.ts.map +1 -1
  70. package/dist/fields/hooks/beforeDuplicate/promise.js +28 -17
  71. package/dist/fields/hooks/beforeDuplicate/promise.js.map +1 -1
  72. package/dist/fields/hooks/beforeValidate/promise.d.ts.map +1 -1
  73. package/dist/fields/hooks/beforeValidate/promise.js +6 -1
  74. package/dist/fields/hooks/beforeValidate/promise.js.map +1 -1
  75. package/dist/fields/validations.js +3 -3
  76. package/dist/fields/validations.js.map +1 -1
  77. package/dist/fields/validations.spec.js +16 -0
  78. package/dist/fields/validations.spec.js.map +1 -1
  79. package/dist/globals/operations/update.d.ts.map +1 -1
  80. package/dist/globals/operations/update.js +31 -26
  81. package/dist/globals/operations/update.js.map +1 -1
  82. package/dist/index.bundled.d.ts +25 -2
  83. package/dist/index.d.ts +1 -0
  84. package/dist/index.d.ts.map +1 -1
  85. package/dist/index.js +1 -0
  86. package/dist/index.js.map +1 -1
  87. package/dist/uploads/assertClientUploadAllowed.spec.js +29 -0
  88. package/dist/uploads/assertClientUploadAllowed.spec.js.map +1 -1
  89. package/dist/uploads/cropImage.d.ts.map +1 -1
  90. package/dist/uploads/cropImage.js +4 -2
  91. package/dist/uploads/cropImage.js.map +1 -1
  92. package/dist/uploads/generateFileData.d.ts.map +1 -1
  93. package/dist/uploads/generateFileData.js +24 -3
  94. package/dist/uploads/generateFileData.js.map +1 -1
  95. package/dist/uploads/getExternalFile.d.ts +11 -0
  96. package/dist/uploads/getExternalFile.d.ts.map +1 -1
  97. package/dist/uploads/getExternalFile.js +32 -21
  98. package/dist/uploads/getExternalFile.js.map +1 -1
  99. package/dist/uploads/getFileFromClientUpload.d.ts +6 -0
  100. package/dist/uploads/getFileFromClientUpload.d.ts.map +1 -1
  101. package/dist/uploads/getFileFromClientUpload.js +6 -0
  102. package/dist/uploads/getFileFromClientUpload.js.map +1 -1
  103. package/dist/uploads/getFileFromClientUpload.spec.js +30 -1
  104. package/dist/uploads/getFileFromClientUpload.spec.js.map +1 -1
  105. package/dist/uploads/getFileTypeIdentity.d.ts.map +1 -1
  106. package/dist/uploads/getFileTypeIdentity.js +6 -2
  107. package/dist/uploads/getFileTypeIdentity.js.map +1 -1
  108. package/dist/uploads/getFileTypeIdentity.spec.js +16 -0
  109. package/dist/uploads/getFileTypeIdentity.spec.js.map +1 -1
  110. package/dist/utilities/getEntityPermissions/getEntityPermissions.d.ts.map +1 -1
  111. package/dist/utilities/getEntityPermissions/getEntityPermissions.js +5 -2
  112. package/dist/utilities/getEntityPermissions/getEntityPermissions.js.map +1 -1
  113. package/dist/utilities/getEntityPermissions/populateFieldPermissions.d.ts +4 -4
  114. package/dist/utilities/getEntityPermissions/populateFieldPermissions.d.ts.map +1 -1
  115. package/dist/utilities/getEntityPermissions/populateFieldPermissions.js +63 -31
  116. package/dist/utilities/getEntityPermissions/populateFieldPermissions.js.map +1 -1
  117. package/dist/utilities/mergeLocalizedData.d.ts +4 -4
  118. package/dist/utilities/mergeLocalizedData.d.ts.map +1 -1
  119. package/dist/utilities/mergeLocalizedData.js +24 -20
  120. package/dist/utilities/mergeLocalizedData.js.map +1 -1
  121. package/dist/utilities/mergeLocalizedData.spec.js +89 -22
  122. package/dist/utilities/mergeLocalizedData.spec.js.map +1 -1
  123. package/dist/utilities/sanitizePermissions.d.ts +5 -2
  124. package/dist/utilities/sanitizePermissions.d.ts.map +1 -1
  125. package/dist/utilities/sanitizePermissions.js +38 -4
  126. package/dist/utilities/sanitizePermissions.js.map +1 -1
  127. package/dist/utilities/sanitizePermissions.spec.js +118 -20
  128. package/dist/utilities/sanitizePermissions.spec.js.map +1 -1
  129. package/dist/versions/allLocalesPublicationStatus.d.ts +5 -5
  130. package/dist/versions/allLocalesPublicationStatus.d.ts.map +1 -1
  131. package/dist/versions/allLocalesPublicationStatus.js +2 -2
  132. package/dist/versions/allLocalesPublicationStatus.js.map +1 -1
  133. package/dist/versions/drafts/hasNonLocalizedDataChanged.d.ts +12 -0
  134. package/dist/versions/drafts/hasNonLocalizedDataChanged.d.ts.map +1 -0
  135. package/dist/versions/drafts/hasNonLocalizedDataChanged.js +165 -0
  136. package/dist/versions/drafts/hasNonLocalizedDataChanged.js.map +1 -0
  137. package/dist/versions/drafts/hasNonLocalizedDataChanged.spec.js +860 -0
  138. package/dist/versions/drafts/hasNonLocalizedDataChanged.spec.js.map +1 -0
  139. package/dist/versions/mergeLocalizedStatus.d.ts +9 -0
  140. package/dist/versions/mergeLocalizedStatus.d.ts.map +1 -0
  141. package/dist/versions/mergeLocalizedStatus.js +11 -0
  142. package/dist/versions/mergeLocalizedStatus.js.map +1 -0
  143. package/dist/versions/mergeLocalizedStatus.spec.js +52 -0
  144. package/dist/versions/mergeLocalizedStatus.spec.js.map +1 -0
  145. package/dist/versions/migrations/localizeStatus/sql/down.d.ts.map +1 -1
  146. package/dist/versions/migrations/localizeStatus/sql/down.js +74 -119
  147. package/dist/versions/migrations/localizeStatus/sql/down.js.map +1 -1
  148. package/dist/versions/migrations/localizeStatus/sql/migrateMainCollection.d.ts.map +1 -1
  149. package/dist/versions/migrations/localizeStatus/sql/migrateMainCollection.js +19 -28
  150. package/dist/versions/migrations/localizeStatus/sql/migrateMainCollection.js.map +1 -1
  151. package/dist/versions/migrations/localizeStatus/sql/migrateMainGlobal.d.ts.map +1 -1
  152. package/dist/versions/migrations/localizeStatus/sql/migrateMainGlobal.js +17 -26
  153. package/dist/versions/migrations/localizeStatus/sql/migrateMainGlobal.js.map +1 -1
  154. package/dist/versions/migrations/localizeStatus/sql/up.d.ts.map +1 -1
  155. package/dist/versions/migrations/localizeStatus/sql/up.js +48 -90
  156. package/dist/versions/migrations/localizeStatus/sql/up.js.map +1 -1
  157. package/dist/versions/resolveLocalizedStatus.d.ts +19 -0
  158. package/dist/versions/resolveLocalizedStatus.d.ts.map +1 -0
  159. package/dist/versions/resolveLocalizedStatus.js +60 -0
  160. package/dist/versions/resolveLocalizedStatus.js.map +1 -0
  161. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"login.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/login.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gCAAgC,EAChC,UAAU,EACV,sBAAsB,EACvB,MAAM,mCAAmC,CAAA;AAC1C,OAAO,KAAK,EAAE,kBAAkB,EAAa,MAAM,gBAAgB,CAAA;AACnE,OAAO,KAAK,EAAE,cAAc,EAAS,MAAM,sBAAsB,CAAA;AAyBjE,MAAM,MAAM,WAAW,CAAC,KAAK,SAAS,kBAAkB,IAAI;IAC1D,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,IAAI,CAAC,EAAE,sBAAsB,CAAC,KAAK,CAAC,CAAA;CACrC,CAAA;AAED,MAAM,MAAM,SAAS,CAAC,KAAK,SAAS,kBAAkB,IAAI;IACxD,UAAU,EAAE,UAAU,CAAA;IACtB,IAAI,EAAE,gCAAgC,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,CAAA;IACtD,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,cAAc,CAAC,EAAE,OAAO,CAAA;IACxB,GAAG,EAAE,cAAc,CAAA;IACnB,gBAAgB,CAAC,EAAE,OAAO,CAAA;CAC3B,CAAA;AAED,KAAK,wBAAwB,CAAC,KAAK,SAAS,kBAAkB,IAAI;IAChE,qBAAqB,CAAC,EAAE,OAAO,CAAA;IAC/B,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,EAAE,sBAAsB,CAAC,KAAK,CAAC,CAAA;CACpC,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,oBAAoB,GAAI,KAAK,SAAS,kBAAkB,yCAIlE,wBAAwB,CAAC,KAAK,CAAC,SAQjC,CAAA;AAED,eAAO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,GAAU,KAAK,SAAS,kBAAkB,gBACrD,SAAS,CAAC,KAAK,CAAC,KAC7B,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,CA2W5B,CAAA"}
@@ -164,7 +164,8 @@ export const loginOperation = async (incomingArgs)=>{
164
164
  const authenticatedSalt = user.salt;
165
165
  const authResult = await authenticateLocalStrategy({
166
166
  doc: user,
167
- password
167
+ password,
168
+ passwordHashIterations: payload.config.auth.passwordHashIterations
168
169
  });
169
170
  user = sanitizeInternalFields(user);
170
171
  const maxLoginAttemptsEnabled = args.collection.config.auth.maxLoginAttempts > 0;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/auth/operations/login.ts"],"sourcesContent":["import type {\n AuthOperationsFromCollectionSlug,\n Collection,\n DataFromCollectionSlug,\n} from '../../collections/config/types.js'\nimport type { AuthCollectionSlug, TypedUser } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'\nimport {\n AuthenticationError,\n LockedAuth,\n UnverifiedEmail,\n ValidationError,\n} from '../../errors/index.js'\nimport { commitTransaction, Forbidden, initTransaction } from '../../index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.js'\nimport { applyUserReadAccess } from '../applyUserReadAccess.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { getLoginOptions } from '../getLoginOptions.js'\nimport { isUserLocked } from '../isUserLocked.js'\nimport { jwtSign } from '../jwt.js'\nimport { addSessionToUser, revokeSession } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { generatePasswordSaltHash } from '../strategies/local/generatePasswordSaltHash.js'\nimport { incrementLoginAttempts } from '../strategies/local/incrementLoginAttempts.js'\nimport { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js'\n\nexport type LoginResult<TSlug extends AuthCollectionSlug> = {\n exp?: number\n token?: string\n user?: DataFromCollectionSlug<TSlug>\n}\n\nexport type Arguments<TSlug extends AuthCollectionSlug> = {\n collection: Collection\n data: AuthOperationsFromCollectionSlug<TSlug>['login']\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n}\n\ntype CheckLoginPermissionArgs<TSlug extends AuthCollectionSlug> = {\n loggingInWithUsername?: boolean\n req: PayloadRequest\n user: DataFromCollectionSlug<TSlug>\n}\n\n/**\n * Throws an error if the user is locked or does not exist.\n * This does not check the login attempts, only the lock status. Whoever increments login attempts\n * is responsible for locking the user properly, not whoever checks the login permission.\n */\nexport const checkLoginPermission = <TSlug extends AuthCollectionSlug>({\n loggingInWithUsername,\n req,\n user,\n}: CheckLoginPermissionArgs<TSlug>) => {\n if (!user) {\n throw new AuthenticationError(req.t, Boolean(loggingInWithUsername))\n }\n\n if (isUserLocked(new Date(user.lockUntil))) {\n throw new LockedAuth(req.t)\n }\n}\n\nexport const loginOperation = async <TSlug extends AuthCollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<LoginResult<TSlug>> => {\n let args = incomingArgs\n\n if (args.collection.config.auth.disableLocalStrategy) {\n throw new Forbidden(args.req.t)\n }\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'login',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess = false,\n req,\n req: {\n payload,\n payload: { secret },\n },\n showHiddenFields,\n } = args\n\n // /////////////////////////////////////\n // Login\n // /////////////////////////////////////\n\n const { email: unsanitizedEmail, password } = data\n const loginWithUsername = collectionConfig.auth.loginWithUsername\n\n const sanitizedEmail =\n typeof unsanitizedEmail === 'string' ? unsanitizedEmail.toLowerCase().trim() : null\n const sanitizedUsername =\n 'username' in data && typeof data?.username === 'string'\n ? data.username.toLowerCase().trim()\n : null\n\n const { canLoginWithEmail, canLoginWithUsername } = getLoginOptions(loginWithUsername)\n\n // cannot login with email, did not provide username\n if (!canLoginWithEmail && !sanitizedUsername) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'username' }],\n })\n }\n\n // cannot login with username, did not provide email\n if (!canLoginWithUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'email' }],\n })\n }\n\n // can login with either email or username, did not provide either\n if (!sanitizedUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [\n { message: req.i18n.t('validation:required'), path: 'email' },\n { message: req.i18n.t('validation:required'), path: 'username' },\n ],\n })\n }\n\n // did not provide password for login\n if (typeof password !== 'string' || password.trim() === '') {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'password' }],\n })\n }\n\n let whereConstraint: Where = {}\n const emailConstraint: Where = {\n email: {\n equals: sanitizedEmail,\n },\n }\n const usernameConstraint: Where = {\n username: {\n equals: sanitizedUsername,\n },\n }\n\n if (canLoginWithEmail && canLoginWithUsername && (sanitizedUsername || sanitizedEmail)) {\n if (sanitizedUsername) {\n whereConstraint = {\n or: [\n usernameConstraint,\n {\n email: {\n equals: sanitizedUsername,\n },\n },\n ],\n }\n } else {\n whereConstraint = {\n or: [\n emailConstraint,\n {\n username: {\n equals: sanitizedEmail,\n },\n },\n ],\n }\n }\n } else if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = emailConstraint\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = usernameConstraint\n }\n\n // Exclude trashed users\n whereConstraint = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash: false,\n where: whereConstraint,\n })\n\n let user = (await payload.db.findOne<TypedUser>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })) as TypedUser\n\n checkLoginPermission({\n loggingInWithUsername: Boolean(canLoginWithUsername && sanitizedUsername),\n req,\n user,\n })\n\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const authenticatedHash = user.hash\n const authenticatedSalt = user.salt\n const authResult = await authenticateLocalStrategy({ doc: user, password })\n user = sanitizeInternalFields(user)\n\n const maxLoginAttemptsEnabled = args.collection.config.auth.maxLoginAttempts > 0\n\n if (!authResult) {\n if (maxLoginAttemptsEnabled) {\n await incrementLoginAttempts({\n collection: collectionConfig,\n payload: req.payload,\n user,\n })\n\n // Re-check login permissions and max attempts after incrementing attempts, in case parallel updates occurred\n checkLoginPermission({\n loggingInWithUsername: Boolean(canLoginWithUsername && sanitizedUsername),\n req,\n user,\n })\n }\n\n throw new AuthenticationError(req.t)\n }\n\n if (collectionConfig.auth.verify && user._verified === false) {\n throw new UnverifiedEmail({ t: req.t })\n }\n\n // Authentication successful - start transaction for remaining operations\n const shouldCommit = await initTransaction(args.req)\n let sid: string | undefined\n\n try {\n /*\n * Correct password accepted - re‑check that the account didn't\n * get locked by parallel bad attempts in the meantime.\n */\n if (maxLoginAttemptsEnabled) {\n const { lockUntil, loginAttempts } = (await payload.db.findOne<TypedUser>({\n collection: collectionConfig.slug,\n req,\n select: {\n lockUntil: true,\n loginAttempts: true,\n },\n where: { id: { equals: user.id } },\n }))!\n\n user.lockUntil = lockUntil\n user.loginAttempts = loginAttempts\n\n checkLoginPermission({\n req,\n user,\n })\n }\n\n const fieldsToSignArgs: Parameters<typeof getFieldsToSign>[0] = {\n collectionConfig,\n email: sanitizedEmail!,\n user,\n }\n\n const session = await addSessionToUser({\n collectionConfig,\n payload,\n req,\n user,\n })\n sid = session.sid\n\n if (sid) {\n fieldsToSignArgs.sid = sid\n }\n\n if (\n authResult.shouldUpdatePasswordHash &&\n typeof authenticatedHash === 'string' &&\n typeof authenticatedSalt === 'string'\n ) {\n try {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n isPasswordAuthenticated: true,\n password,\n req,\n })\n\n await payload.db.updateOne({\n collection: collectionConfig.slug,\n data: { hash, salt },\n req,\n select: { id: true },\n where: {\n id: { equals: user.id },\n hash: { equals: authenticatedHash },\n salt: { equals: authenticatedSalt },\n },\n })\n } catch (err) {\n // Rehashing is opportunistic and is retried on the next login, so a failure here\n // must not reject an otherwise valid login or discard the session already created\n payload.logger.error({ err, msg: 'Failed to update the stored password hash' })\n }\n }\n\n const fieldsToSign = getFieldsToSign(fieldsToSignArgs)\n\n if (maxLoginAttemptsEnabled) {\n await resetLoginAttempts({\n collection: collectionConfig,\n doc: user,\n payload: req.payload,\n req,\n })\n }\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeLogin?.length) {\n for (const hook of collectionConfig.hooks.beforeLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user,\n })) || user\n }\n }\n\n const { exp, token } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = user\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterLogin?.length) {\n for (const hook of collectionConfig.hooks.afterLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n token,\n user,\n })) || user\n }\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n const userWithReadAccess = await applyUserReadAccess({\n collection: collectionConfig,\n depth: depth!,\n overrideAccess,\n req,\n showHiddenFields: showHiddenFields!,\n user,\n })\n\n let result: LoginResult<TSlug> = {\n exp,\n token,\n user: userWithReadAccess,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'login',\n overrideAccess: args.overrideAccess!,\n result,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result\n } catch (error: unknown) {\n if (sid) {\n await revokeSession({\n collectionConfig,\n payload,\n req,\n sid,\n user,\n })\n }\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["buildAfterOperation","buildBeforeOperation","AuthenticationError","LockedAuth","UnverifiedEmail","ValidationError","commitTransaction","Forbidden","initTransaction","appendNonTrashedFilter","killTransaction","sanitizeInternalFields","applyUserReadAccess","getFieldsToSign","getLoginOptions","isUserLocked","jwtSign","addSessionToUser","revokeSession","authenticateLocalStrategy","generatePasswordSaltHash","incrementLoginAttempts","resetLoginAttempts","checkLoginPermission","loggingInWithUsername","req","user","t","Boolean","Date","lockUntil","loginOperation","incomingArgs","args","collection","config","auth","disableLocalStrategy","operation","overrideAccess","collectionConfig","data","depth","payload","secret","showHiddenFields","email","unsanitizedEmail","password","loginWithUsername","sanitizedEmail","toLowerCase","trim","sanitizedUsername","username","canLoginWithEmail","canLoginWithUsername","slug","errors","message","i18n","path","whereConstraint","emailConstraint","equals","usernameConstraint","or","enableTrash","trash","where","db","findOne","_strategy","authenticatedHash","hash","authenticatedSalt","salt","authResult","doc","maxLoginAttemptsEnabled","maxLoginAttempts","verify","_verified","shouldCommit","sid","loginAttempts","select","id","fieldsToSignArgs","session","shouldUpdatePasswordHash","isPasswordAuthenticated","updateOne","err","logger","error","msg","fieldsToSign","hooks","beforeLogin","length","hook","context","exp","token","tokenExpiration","afterLogin","userWithReadAccess","result"],"mappings":"AAQA,SAASA,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SACEC,mBAAmB,EACnBC,UAAU,EACVC,eAAe,EACfC,eAAe,QACV,wBAAuB;AAC9B,SAASC,iBAAiB,EAAEC,SAAS,EAAEC,eAAe,QAAQ,iBAAgB;AAC9E,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,eAAe,QAAQ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sE;IACR;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../src/auth/operations/login.ts"],"sourcesContent":["import type {\n AuthOperationsFromCollectionSlug,\n Collection,\n DataFromCollectionSlug,\n} from '../../collections/config/types.js'\nimport type { AuthCollectionSlug, TypedUser } from '../../index.js'\nimport type { PayloadRequest, Where } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'\nimport {\n AuthenticationError,\n LockedAuth,\n UnverifiedEmail,\n ValidationError,\n} from '../../errors/index.js'\nimport { commitTransaction, Forbidden, initTransaction } from '../../index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { sanitizeInternalFields } from '../../utilities/sanitizeInternalFields.js'\nimport { applyUserReadAccess } from '../applyUserReadAccess.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { getLoginOptions } from '../getLoginOptions.js'\nimport { isUserLocked } from '../isUserLocked.js'\nimport { jwtSign } from '../jwt.js'\nimport { addSessionToUser, revokeSession } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { generatePasswordSaltHash } from '../strategies/local/generatePasswordSaltHash.js'\nimport { incrementLoginAttempts } from '../strategies/local/incrementLoginAttempts.js'\nimport { resetLoginAttempts } from '../strategies/local/resetLoginAttempts.js'\n\nexport type LoginResult<TSlug extends AuthCollectionSlug> = {\n exp?: number\n token?: string\n user?: DataFromCollectionSlug<TSlug>\n}\n\nexport type Arguments<TSlug extends AuthCollectionSlug> = {\n collection: Collection\n data: AuthOperationsFromCollectionSlug<TSlug>['login']\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n showHiddenFields?: boolean\n}\n\ntype CheckLoginPermissionArgs<TSlug extends AuthCollectionSlug> = {\n loggingInWithUsername?: boolean\n req: PayloadRequest\n user: DataFromCollectionSlug<TSlug>\n}\n\n/**\n * Throws an error if the user is locked or does not exist.\n * This does not check the login attempts, only the lock status. Whoever increments login attempts\n * is responsible for locking the user properly, not whoever checks the login permission.\n */\nexport const checkLoginPermission = <TSlug extends AuthCollectionSlug>({\n loggingInWithUsername,\n req,\n user,\n}: CheckLoginPermissionArgs<TSlug>) => {\n if (!user) {\n throw new AuthenticationError(req.t, Boolean(loggingInWithUsername))\n }\n\n if (isUserLocked(new Date(user.lockUntil))) {\n throw new LockedAuth(req.t)\n }\n}\n\nexport const loginOperation = async <TSlug extends AuthCollectionSlug>(\n incomingArgs: Arguments<TSlug>,\n): Promise<LoginResult<TSlug>> => {\n let args = incomingArgs\n\n if (args.collection.config.auth.disableLocalStrategy) {\n throw new Forbidden(args.req.t)\n }\n\n // /////////////////////////////////////\n // beforeOperation - Collection\n // /////////////////////////////////////\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'login',\n overrideAccess: args.overrideAccess!,\n })\n\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess = false,\n req,\n req: {\n payload,\n payload: { secret },\n },\n showHiddenFields,\n } = args\n\n // /////////////////////////////////////\n // Login\n // /////////////////////////////////////\n\n const { email: unsanitizedEmail, password } = data\n const loginWithUsername = collectionConfig.auth.loginWithUsername\n\n const sanitizedEmail =\n typeof unsanitizedEmail === 'string' ? unsanitizedEmail.toLowerCase().trim() : null\n const sanitizedUsername =\n 'username' in data && typeof data?.username === 'string'\n ? data.username.toLowerCase().trim()\n : null\n\n const { canLoginWithEmail, canLoginWithUsername } = getLoginOptions(loginWithUsername)\n\n // cannot login with email, did not provide username\n if (!canLoginWithEmail && !sanitizedUsername) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'username' }],\n })\n }\n\n // cannot login with username, did not provide email\n if (!canLoginWithUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'email' }],\n })\n }\n\n // can login with either email or username, did not provide either\n if (!sanitizedUsername && !sanitizedEmail) {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [\n { message: req.i18n.t('validation:required'), path: 'email' },\n { message: req.i18n.t('validation:required'), path: 'username' },\n ],\n })\n }\n\n // did not provide password for login\n if (typeof password !== 'string' || password.trim() === '') {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: req.i18n.t('validation:required'), path: 'password' }],\n })\n }\n\n let whereConstraint: Where = {}\n const emailConstraint: Where = {\n email: {\n equals: sanitizedEmail,\n },\n }\n const usernameConstraint: Where = {\n username: {\n equals: sanitizedUsername,\n },\n }\n\n if (canLoginWithEmail && canLoginWithUsername && (sanitizedUsername || sanitizedEmail)) {\n if (sanitizedUsername) {\n whereConstraint = {\n or: [\n usernameConstraint,\n {\n email: {\n equals: sanitizedUsername,\n },\n },\n ],\n }\n } else {\n whereConstraint = {\n or: [\n emailConstraint,\n {\n username: {\n equals: sanitizedEmail,\n },\n },\n ],\n }\n }\n } else if (canLoginWithEmail && sanitizedEmail) {\n whereConstraint = emailConstraint\n } else if (canLoginWithUsername && sanitizedUsername) {\n whereConstraint = usernameConstraint\n }\n\n // Exclude trashed users\n whereConstraint = appendNonTrashedFilter({\n enableTrash: collectionConfig.trash,\n trash: false,\n where: whereConstraint,\n })\n\n let user = (await payload.db.findOne<TypedUser>({\n collection: collectionConfig.slug,\n req,\n where: whereConstraint,\n })) as TypedUser\n\n checkLoginPermission({\n loggingInWithUsername: Boolean(canLoginWithUsername && sanitizedUsername),\n req,\n user,\n })\n\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const authenticatedHash = user.hash\n const authenticatedSalt = user.salt\n const authResult = await authenticateLocalStrategy({\n doc: user,\n password,\n passwordHashIterations: payload.config.auth.passwordHashIterations,\n })\n user = sanitizeInternalFields(user)\n\n const maxLoginAttemptsEnabled = args.collection.config.auth.maxLoginAttempts > 0\n\n if (!authResult) {\n if (maxLoginAttemptsEnabled) {\n await incrementLoginAttempts({\n collection: collectionConfig,\n payload: req.payload,\n user,\n })\n\n // Re-check login permissions and max attempts after incrementing attempts, in case parallel updates occurred\n checkLoginPermission({\n loggingInWithUsername: Boolean(canLoginWithUsername && sanitizedUsername),\n req,\n user,\n })\n }\n\n throw new AuthenticationError(req.t)\n }\n\n if (collectionConfig.auth.verify && user._verified === false) {\n throw new UnverifiedEmail({ t: req.t })\n }\n\n // Authentication successful - start transaction for remaining operations\n const shouldCommit = await initTransaction(args.req)\n let sid: string | undefined\n\n try {\n /*\n * Correct password accepted - re‑check that the account didn't\n * get locked by parallel bad attempts in the meantime.\n */\n if (maxLoginAttemptsEnabled) {\n const { lockUntil, loginAttempts } = (await payload.db.findOne<TypedUser>({\n collection: collectionConfig.slug,\n req,\n select: {\n lockUntil: true,\n loginAttempts: true,\n },\n where: { id: { equals: user.id } },\n }))!\n\n user.lockUntil = lockUntil\n user.loginAttempts = loginAttempts\n\n checkLoginPermission({\n req,\n user,\n })\n }\n\n const fieldsToSignArgs: Parameters<typeof getFieldsToSign>[0] = {\n collectionConfig,\n email: sanitizedEmail!,\n user,\n }\n\n const session = await addSessionToUser({\n collectionConfig,\n payload,\n req,\n user,\n })\n sid = session.sid\n\n if (sid) {\n fieldsToSignArgs.sid = sid\n }\n\n if (\n authResult.shouldUpdatePasswordHash &&\n typeof authenticatedHash === 'string' &&\n typeof authenticatedSalt === 'string'\n ) {\n try {\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n isPasswordAuthenticated: true,\n password,\n req,\n })\n\n await payload.db.updateOne({\n collection: collectionConfig.slug,\n data: { hash, salt },\n req,\n select: { id: true },\n where: {\n id: { equals: user.id },\n hash: { equals: authenticatedHash },\n salt: { equals: authenticatedSalt },\n },\n })\n } catch (err) {\n // Rehashing is opportunistic and is retried on the next login, so a failure here\n // must not reject an otherwise valid login or discard the session already created\n payload.logger.error({ err, msg: 'Failed to update the stored password hash' })\n }\n }\n\n const fieldsToSign = getFieldsToSign(fieldsToSignArgs)\n\n if (maxLoginAttemptsEnabled) {\n await resetLoginAttempts({\n collection: collectionConfig,\n doc: user,\n payload: req.payload,\n req,\n })\n }\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeLogin?.length) {\n for (const hook of collectionConfig.hooks.beforeLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user,\n })) || user\n }\n }\n\n const { exp, token } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = user\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterLogin?.length) {\n for (const hook of collectionConfig.hooks.afterLogin) {\n user =\n (await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n token,\n user,\n })) || user\n }\n }\n\n // /////////////////////////////////////\n // afterRead - Fields\n // /////////////////////////////////////\n\n const userWithReadAccess = await applyUserReadAccess({\n collection: collectionConfig,\n depth: depth!,\n overrideAccess,\n req,\n showHiddenFields: showHiddenFields!,\n user,\n })\n\n let result: LoginResult<TSlug> = {\n exp,\n token,\n user: userWithReadAccess,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'login',\n overrideAccess: args.overrideAccess!,\n result,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n // /////////////////////////////////////\n // Return results\n // /////////////////////////////////////\n\n return result\n } catch (error: unknown) {\n if (sid) {\n await revokeSession({\n collectionConfig,\n payload,\n req,\n sid,\n user,\n })\n }\n await killTransaction(args.req)\n throw error\n }\n}\n"],"names":["buildAfterOperation","buildBeforeOperation","AuthenticationError","LockedAuth","UnverifiedEmail","ValidationError","commitTransaction","Forbidden","initTransaction","appendNonTrashedFilter","killTransaction","sanitizeInternalFields","applyUserReadAccess","getFieldsToSign","getLoginOptions","isUserLocked","jwtSign","addSessionToUser","revokeSession","authenticateLocalStrategy","generatePasswordSaltHash","incrementLoginAttempts","resetLoginAttempts","checkLoginPermission","loggingInWithUsername","req","user","t","Boolean","Date","lockUntil","loginOperation","incomingArgs","args","collection","config","auth","disableLocalStrategy","operation","overrideAccess","collectionConfig","data","depth","payload","secret","showHiddenFields","email","unsanitizedEmail","password","loginWithUsername","sanitizedEmail","toLowerCase","trim","sanitizedUsername","username","canLoginWithEmail","canLoginWithUsername","slug","errors","message","i18n","path","whereConstraint","emailConstraint","equals","usernameConstraint","or","enableTrash","trash","where","db","findOne","_strategy","authenticatedHash","hash","authenticatedSalt","salt","authResult","doc","passwordHashIterations","maxLoginAttemptsEnabled","maxLoginAttempts","verify","_verified","shouldCommit","sid","loginAttempts","select","id","fieldsToSignArgs","session","shouldUpdatePasswordHash","isPasswordAuthenticated","updateOne","err","logger","error","msg","fieldsToSign","hooks","beforeLogin","length","hook","context","exp","token","tokenExpiration","afterLogin","userWithReadAccess","result"],"mappings":"AAQA,SAASA,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SACEC,mBAAmB,EACnBC,UAAU,EACVC,eAAe,EACfC,eAAe,QACV,wBAAuB;AAC9B,SAASC,iBAAiB,EAAEC,SAAS,EAAEC,eAAe,QAAQ,iBAAgB;AAC9E,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,mBAAmB,QAAQ,4BAA2B;AAC/D,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,YAAY,QAAQ,qBAAoB;AACjD,SAASC,OAAO,QAAQ,YAAW;AACnC,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,iBAAgB;AAChE,SAASC,yBAAyB,QAAQ,sCAAqC;AAC/E,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B,wCAAwC;QAExC,IAAIc,iBAAiB2D,KAAK,EAAEQ,YAAYN,QAAQ;YAC9C,KAAK,MAAMC,QAAQ9D,iBAAiB2D,KAAK,CAACQ,UAAU,CAAE;gBACpDjF,OACE,AAAC,MAAM4E,KAAK;oBACVpE,YAAYD,KAAKC,UAAU,EAAEC;oBAC7BoE,SAAStE,KAAKR,GAAG,CAAC8E,OAAO;oBACzB9E,KAAKQ,KAAKR,GAAG;oBACbgF;oBACA/E;gBACF,MAAOA;YACX;QACF;QAEA,wCAAwC;QACxC,qBAAqB;QACrB,wCAAwC;QAExC,MAAMkF,qBAAqB,MAAMhG,oBAAoB;YACnDsB,YAAYM;YACZE,OAAOA;YACPH;YACAd;YACAoB,kBAAkBA;YAClBnB;QACF;QAEA,IAAImF,SAA6B;YAC/BL;YACAC;YACA/E,MAAMkF;QACR;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCC,SAAS,MAAM7G,oBAAoB;YACjCiC;YACAC,YAAYD,KAAKC,UAAU,EAAEC;YAC7BG,WAAW;YACXC,gBAAgBN,KAAKM,cAAc;YACnCsE;QACF;QAEA,IAAIzB,cAAc;YAChB,MAAM9E,kBAAkBmB;QAC1B;QAEA,wCAAwC;QACxC,iBAAiB;QACjB,wCAAwC;QAExC,OAAOoF;IACT,EAAE,OAAOb,OAAgB;QACvB,IAAIX,KAAK;YACP,MAAMnE,cAAc;gBAClBsB;gBACAG;gBACAlB;gBACA4D;gBACA3D;YACF;QACF;QACA,MAAMhB,gBAAgBuB,KAAKR,GAAG;QAC9B,MAAMuE;IACR;AACF,EAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"resetPassword.d.ts","sourceRoot":"","sources":["../../../src/auth/operations/resetPassword.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAA0B,MAAM,mCAAmC,CAAA;AAC3F,OAAO,KAAK,EAAE,kBAAkB,EAAa,MAAM,gBAAgB,CAAA;AACnE,OAAO,KAAK,E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KAAK,SAAS,kBAAkB,QACrE,SAAS,KACd,OAAO,CAAC,MAAM,CAiPhB,CAAA"}
@@ -1,7 +1,7 @@
1
1
  import { status as httpStatus } from 'http-status';
2
2
  import { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js';
3
3
  import { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js';
4
- import { APIError, Forbidden } from '../../errors/index.js';
4
+ import { APIError, Forbidden, ValidationError } from '../../errors/index.js';
5
5
  import { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js';
6
6
  import { commitTransaction } from '../../utilities/commitTransaction.js';
7
7
  import { initTransaction } from '../../utilities/initTransaction.js';
@@ -53,6 +53,13 @@ export const resetPasswordOperation = async (args)=>{
53
53
  if (!user) {
54
54
  throw new APIError('Token is either invalid or has expired.', httpStatus.FORBIDDEN);
55
55
  }
56
+ await validatePasswordField({
57
+ collectionConfig,
58
+ overrideAccess,
59
+ password: data.password,
60
+ req,
61
+ user
62
+ });
56
63
  // TODO: replace this method
57
64
  const { hash, salt } = await generatePasswordSaltHash({
58
65
  collection: collectionConfig,
@@ -99,7 +106,8 @@ export const resetPasswordOperation = async (args)=>{
99
106
  });
100
107
  await authenticateLocalStrategy({
101
108
  doc,
102
- password: data.password
109
+ password: data.password,
110
+ passwordHashIterations: payload.config.auth.passwordHashIterations
103
111
  });
104
112
  user = doc;
105
113
  user.collection = collectionConfig.slug;
@@ -196,5 +204,47 @@ export const resetPasswordOperation = async (args)=>{
196
204
  throw error;
197
205
  }
198
206
  };
207
+ /**
208
+ * Runs the `password` field override's validation, which `payload.db.updateOne` skips.
209
+ */ async function validatePasswordField({ collectionConfig, overrideAccess, password, req, user }) {
210
+ const passwordField = collectionConfig.flattenedFields.find((field)=>field.name === 'password');
211
+ if (!passwordField || !('validate' in passwordField) || !passwordField.validate) {
212
+ return;
213
+ }
214
+ const validate = passwordField.validate;
215
+ const dataToValidate = {
216
+ ...user,
217
+ password
218
+ };
219
+ const validationResult = await validate(password, {
220
+ ...passwordField,
221
+ id: user.id,
222
+ blockData: {},
223
+ collectionSlug: collectionConfig.slug,
224
+ data: dataToValidate,
225
+ event: 'submit',
226
+ operation: 'update',
227
+ overrideAccess,
228
+ path: [
229
+ 'password'
230
+ ],
231
+ preferences: {
232
+ fields: {}
233
+ },
234
+ req,
235
+ siblingData: dataToValidate
236
+ });
237
+ if (typeof validationResult === 'string') {
238
+ throw new ValidationError({
239
+ collection: collectionConfig.slug,
240
+ errors: [
241
+ {
242
+ message: validationResult,
243
+ path: 'password'
244
+ }
245
+ ]
246
+ });
247
+ }
248
+ }
199
249
 
200
250
  //# sourceMappingURL=resetPassword.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/auth/operations/resetPassword.ts"],"sourcesContent":["import { status as httpStatus } from 'http-status'\n\nimport type { Collection, DataFromCollectionSlug } from '../../collections/config/types.js'\nimport type { AuthCollectionSlug, TypedUser } from '../../index.js'\nimport type { PayloadRequest } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'\nimport { APIError, Forbidden } from '../../errors/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { applyUserReadAccess } from '../applyUserReadAccess.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { jwtSign } from '../jwt.js'\nimport { addSessionToUser, revokeSession } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { generatePasswordSaltHash } from '../strategies/local/generatePasswordSaltHash.js'\n\nexport type Result = {\n token?: string\n user: Record<string, unknown>\n}\n\nexport type Arguments = {\n collection: Collection\n data: {\n password: string\n token: string\n }\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n}\n\nexport const resetPasswordOperation = async <TSlug extends AuthCollectionSlug>(\n args: Arguments,\n): Promise<Result> => {\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess = false,\n req: {\n payload: { secret },\n payload,\n },\n req,\n } = args\n\n if (\n !Object.prototype.hasOwnProperty.call(data, 'token') ||\n !Object.prototype.hasOwnProperty.call(data, 'password')\n ) {\n throw new APIError('Missing required data.', httpStatus.BAD_REQUEST)\n }\n\n if (collectionConfig.auth.disableLocalStrategy) {\n throw new Forbidden(req.t)\n }\n\n let sid: string | undefined\n let sessionUser: null | TypedUser = null\n\n try {\n const shouldCommit = await initTransaction(req)\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'resetPassword',\n overrideAccess,\n })\n\n // /////////////////////////////////////\n // Reset Password\n // /////////////////////////////////////\n\n const where = appendNonTrashedFilter({\n enableTrash: Boolean(collectionConfig.trash),\n trash: false,\n where: {\n resetPasswordExpiration: { greater_than: new Date().toISOString() },\n resetPasswordToken: { equals: data.token },\n },\n })\n\n let user = await payload.db.findOne<TypedUser>({\n collection: collectionConfig.slug,\n req,\n where,\n })\n\n if (!user) {\n throw new APIError('Token is either invalid or has expired.', httpStatus.FORBIDDEN)\n }\n\n // TODO: replace this method\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password: data.password,\n req,\n })\n\n user.salt = salt\n user.hash = hash\n\n user.resetPasswordExpiration = new Date().toISOString()\n\n if (collectionConfig.auth.maxLoginAttempts > 0) {\n user.lockUntil = null\n user.loginAttempts = 0\n }\n\n if (collectionConfig.auth.verify) {\n user._verified = Boolean(user._verified)\n }\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n await hook({\n collection: args.collection?.config,\n context: req.context,\n data: user,\n operation: 'update',\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // Update new password\n // /////////////////////////////////////\n\n // Ensure updatedAt date is always updated\n user.updatedAt = new Date().toISOString()\n\n if (collectionConfig.auth.useSessions) {\n user.sessions = []\n }\n\n const doc = await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: user,\n req,\n })\n\n await authenticateLocalStrategy({ doc, password: data.password })\n\n user = doc as TypedUser\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const fieldsToSignArgs: Parameters<typeof getFieldsToSign>[0] = {\n collectionConfig,\n email: user.email!,\n user,\n }\n\n const session = await addSessionToUser({\n collectionConfig,\n payload,\n req,\n user,\n })\n\n sessionUser = user\n sid = session.sid\n\n if (sid) {\n fieldsToSignArgs.sid = sid\n }\n\n const fieldsToSign = getFieldsToSign(fieldsToSignArgs)\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeLogin?.length) {\n for (const hook of collectionConfig.hooks.beforeLogin) {\n user = ((await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user,\n })) || user) as NonNullable<TypedUser>\n }\n }\n\n const { token } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = user\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterLogin?.length) {\n for (const hook of collectionConfig.hooks.afterLogin) {\n user = ((await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n token,\n user,\n })) || user) as NonNullable<TypedUser>\n }\n }\n\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const userWithReadAccess = await applyUserReadAccess({\n collection: collectionConfig,\n depth: depth!,\n overrideAccess,\n req,\n showHiddenFields: false,\n user,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n token,\n user: userWithReadAccess,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'resetPassword',\n overrideAccess,\n result,\n })\n\n return result\n } catch (error: unknown) {\n if (sid) {\n await revokeSession({\n collectionConfig,\n payload,\n req,\n sid,\n user: sessionUser,\n })\n }\n await killTransaction(req)\n throw error\n }\n}\n"],"names":["status","httpStatus","buildAfterOperation","buildBeforeOperation","APIError","Forbidden","appendNonTrashedFilter","commitTransaction","initTransaction","killTransaction","applyUserReadAccess","getFieldsToSign","jwtSign","addSessionToUser","revokeSession","authenticateLocalStrategy","generatePasswordSaltHash","resetPasswordOperation","args","collection","config","collectionConfig","data","depth","overrideAccess","req","payload","secret","Object","prototype","hasOwnProperty","call","BAD_REQUEST","auth","disableLocalStrategy","t","sid","sessionUser","shouldCommit","operation","where","enableTrash","Boolean","trash","resetPasswordExpiration","greater_than","Date","toISOString","resetPasswordToken","equals","token","user","db","findOne","slug","FORBIDDEN","hash","salt","password","maxLoginAttempts","lockUntil","loginAttempts","verify","_verified","hooks","beforeValidate","length","hook","context","updatedAt","useSessions","sessions","doc","updateOne","id","_strategy","fieldsToSignArgs","email","session","fieldsToSign","beforeLogin","tokenExpiration","afterLogin","userWithReadAccess","showHiddenFields","result","error"],"mappings":"AAAA,SAASA,UAAUC,UAAU,QAAQ,cAAa;AAMlD,SAASC,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SAASC,QAAQ,EAAEC,SAAS,QAAQ,wBAAuB;AAC3D,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,mBAAmB,QAAQ,4BAA2B;AAC/D,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,OAAO,QAAQ,YAAW;AACnC,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,iBAAgB;AA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AAI;QACvCH,KAAKwB,SAAS,GAAG;QAEjB,MAAMQ,qBAAqB,MAAMzE,oBAAoB;YACnDS,YAAYE;YACZE,OAAOA;YACPC;YACAC;YACA2D,kBAAkB;YAClBjC;QACF;QAEA,IAAIb,cAAc;YAChB,MAAM/B,kBAAkBkB;QAC1B;QAEA,IAAI4D,SAA2D;YAC7DnC;YACAC,MAAMgC;QACR;QAEA,wCAAwC;QACxC,8BAA8B;QAC9B,wCAAwC;QAExCE,SAAS,MAAMnF,oBAAoB;YACjCgB;YACAC,YAAYD,KAAKC,UAAU,EAAEC;YAC7BmB,WAAW;YACXf;YACA6D;QACF;QAEA,OAAOA;IACT,EAAE,OAAOC,OAAgB;QACvB,IAAIlD,KAAK;YACP,MAAMtB,cAAc;gBAClBO;gBACAK;gBACAD;gBACAW;gBACAe,MAAMd;YACR;QACF;QACA,MAAM5B,gBAAgBgB;QACtB,MAAM6D;IACR;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../src/auth/operations/resetPassword.ts"],"sourcesContent":["import { status as httpStatus } from 'http-status'\n\nimport type {\n Collection,\n DataFromCollectionSlug,\n SanitizedCollectionConfig,\n} from '../../collections/config/types.js'\nimport type { Validate } from '../../fields/config/types.js'\nimport type { AuthCollectionSlug, TypedUser } from '../../index.js'\nimport type { PayloadRequest } from '../../types/index.js'\n\nimport { buildAfterOperation } from '../../collections/operations/utilities/buildAfterOperation.js'\nimport { buildBeforeOperation } from '../../collections/operations/utilities/buildBeforeOperation.js'\nimport { APIError, Forbidden, ValidationError } from '../../errors/index.js'\nimport { appendNonTrashedFilter } from '../../utilities/appendNonTrashedFilter.js'\nimport { commitTransaction } from '../../utilities/commitTransaction.js'\nimport { initTransaction } from '../../utilities/initTransaction.js'\nimport { killTransaction } from '../../utilities/killTransaction.js'\nimport { applyUserReadAccess } from '../applyUserReadAccess.js'\nimport { getFieldsToSign } from '../getFieldsToSign.js'\nimport { jwtSign } from '../jwt.js'\nimport { addSessionToUser, revokeSession } from '../sessions.js'\nimport { authenticateLocalStrategy } from '../strategies/local/authenticate.js'\nimport { generatePasswordSaltHash } from '../strategies/local/generatePasswordSaltHash.js'\n\nexport type Result = {\n token?: string\n user: Record<string, unknown>\n}\n\nexport type Arguments = {\n collection: Collection\n data: {\n password: string\n token: string\n }\n depth?: number\n overrideAccess?: boolean\n req: PayloadRequest\n}\n\nexport const resetPasswordOperation = async <TSlug extends AuthCollectionSlug>(\n args: Arguments,\n): Promise<Result> => {\n const {\n collection: { config: collectionConfig },\n data,\n depth,\n overrideAccess = false,\n req: {\n payload: { secret },\n payload,\n },\n req,\n } = args\n\n if (\n !Object.prototype.hasOwnProperty.call(data, 'token') ||\n !Object.prototype.hasOwnProperty.call(data, 'password')\n ) {\n throw new APIError('Missing required data.', httpStatus.BAD_REQUEST)\n }\n\n if (collectionConfig.auth.disableLocalStrategy) {\n throw new Forbidden(req.t)\n }\n\n let sid: string | undefined\n let sessionUser: null | TypedUser = null\n\n try {\n const shouldCommit = await initTransaction(req)\n\n args = await buildBeforeOperation({\n args,\n collection: args.collection.config,\n operation: 'resetPassword',\n overrideAccess,\n })\n\n // /////////////////////////////////////\n // Reset Password\n // /////////////////////////////////////\n\n const where = appendNonTrashedFilter({\n enableTrash: Boolean(collectionConfig.trash),\n trash: false,\n where: {\n resetPasswordExpiration: { greater_than: new Date().toISOString() },\n resetPasswordToken: { equals: data.token },\n },\n })\n\n let user = await payload.db.findOne<TypedUser>({\n collection: collectionConfig.slug,\n req,\n where,\n })\n\n if (!user) {\n throw new APIError('Token is either invalid or has expired.', httpStatus.FORBIDDEN)\n }\n\n await validatePasswordField({\n collectionConfig,\n overrideAccess,\n password: data.password,\n req,\n user,\n })\n\n // TODO: replace this method\n const { hash, salt } = await generatePasswordSaltHash({\n collection: collectionConfig,\n password: data.password,\n req,\n })\n\n user.salt = salt\n user.hash = hash\n\n user.resetPasswordExpiration = new Date().toISOString()\n\n if (collectionConfig.auth.maxLoginAttempts > 0) {\n user.lockUntil = null\n user.loginAttempts = 0\n }\n\n if (collectionConfig.auth.verify) {\n user._verified = Boolean(user._verified)\n }\n\n // /////////////////////////////////////\n // beforeValidate - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeValidate?.length) {\n for (const hook of collectionConfig.hooks.beforeValidate) {\n await hook({\n collection: args.collection?.config,\n context: req.context,\n data: user,\n operation: 'update',\n req,\n })\n }\n }\n\n // /////////////////////////////////////\n // Update new password\n // /////////////////////////////////////\n\n // Ensure updatedAt date is always updated\n user.updatedAt = new Date().toISOString()\n\n if (collectionConfig.auth.useSessions) {\n user.sessions = []\n }\n\n const doc = await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: user,\n req,\n })\n\n await authenticateLocalStrategy({\n doc,\n password: data.password,\n passwordHashIterations: payload.config.auth.passwordHashIterations,\n })\n\n user = doc as TypedUser\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const fieldsToSignArgs: Parameters<typeof getFieldsToSign>[0] = {\n collectionConfig,\n email: user.email!,\n user,\n }\n\n const session = await addSessionToUser({\n collectionConfig,\n payload,\n req,\n user,\n })\n\n sessionUser = user\n sid = session.sid\n\n if (sid) {\n fieldsToSignArgs.sid = sid\n }\n\n const fieldsToSign = getFieldsToSign(fieldsToSignArgs)\n\n // /////////////////////////////////////\n // beforeLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.beforeLogin?.length) {\n for (const hook of collectionConfig.hooks.beforeLogin) {\n user = ((await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n user,\n })) || user) as NonNullable<TypedUser>\n }\n }\n\n const { token } = await jwtSign({\n fieldsToSign,\n secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n req.user = user\n\n // /////////////////////////////////////\n // afterLogin - Collection\n // /////////////////////////////////////\n\n if (collectionConfig.hooks?.afterLogin?.length) {\n for (const hook of collectionConfig.hooks.afterLogin) {\n user = ((await hook({\n collection: args.collection?.config,\n context: args.req.context,\n req: args.req,\n token,\n user,\n })) || user) as NonNullable<TypedUser>\n }\n }\n\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n\n const userWithReadAccess = await applyUserReadAccess({\n collection: collectionConfig,\n depth: depth!,\n overrideAccess,\n req,\n showHiddenFields: false,\n user,\n })\n\n if (shouldCommit) {\n await commitTransaction(req)\n }\n\n let result: { user: DataFromCollectionSlug<TSlug> } & Result = {\n token,\n user: userWithReadAccess,\n }\n\n // /////////////////////////////////////\n // afterOperation - Collection\n // /////////////////////////////////////\n\n result = await buildAfterOperation({\n args,\n collection: args.collection?.config,\n operation: 'resetPassword',\n overrideAccess,\n result,\n })\n\n return result\n } catch (error: unknown) {\n if (sid) {\n await revokeSession({\n collectionConfig,\n payload,\n req,\n sid,\n user: sessionUser,\n })\n }\n await killTransaction(req)\n throw error\n }\n}\n\n/**\n * Runs the `password` field override's validation, which `payload.db.updateOne` skips.\n */\nasync function validatePasswordField({\n collectionConfig,\n overrideAccess,\n password,\n req,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n overrideAccess: boolean\n password: string\n req: PayloadRequest\n user: TypedUser\n}): Promise<void> {\n const passwordField = collectionConfig.flattenedFields.find((field) => field.name === 'password')\n\n if (!passwordField || !('validate' in passwordField) || !passwordField.validate) {\n return\n }\n\n const validate = passwordField.validate as Validate<string>\n const dataToValidate = { ...user, password }\n\n const validationResult = await validate(password, {\n ...passwordField,\n id: user.id,\n blockData: {},\n collectionSlug: collectionConfig.slug,\n data: dataToValidate,\n event: 'submit',\n operation: 'update',\n overrideAccess,\n path: ['password'],\n preferences: { fields: {} },\n req,\n siblingData: dataToValidate,\n })\n\n if (typeof validationResult === 'string') {\n throw new ValidationError({\n collection: collectionConfig.slug,\n errors: [{ message: validationResult, path: 'password' }],\n })\n }\n}\n"],"names":["status","httpStatus","buildAfterOperation","buildBeforeOperation","APIError","Forbidden","ValidationError","appendNonTrashedFilter","commitTransaction","initTransaction","killTransaction","applyUserReadAccess","getFieldsToSign","jwtSign","addSessionToUser","revokeSession","authenticateLocalStrategy","generatePasswordSaltHash","resetPasswordOperation","args","collection","config","collectionConfig","data","depth","overrideAccess","req","payload","secret","Object","prototype","hasOwnProperty","call","BAD_REQUEST","auth","disableLocalStrategy","t","sid","sessionUser","shouldCommit","operation","where","enableTrash","Boolean","trash","resetPasswordExpiration","greater_than","Date","toISOString","resetPasswordToken","equals","token","user","db","findOne","slug","FORBIDDEN","validatePasswordField","password","hash","salt","maxLoginAttempts","lockUntil","loginAttempts","verify","_verified","hooks","beforeValidate","length","hook","context","updatedAt","useSessions","sessions","doc","updateOne","id","passwordHashIterations","_strategy","fieldsToSignArgs","email","session","fieldsToSign","beforeLogin","tokenExpiration","afterLogin","userWithReadAccess","showHiddenFields","result","error","passwordField","flattenedFields","find","field","name","validate","dataToValidate","validationResult","blockData","collectionSlug","event","path","preferences","fields","siblingData","errors","message"],"mappings":"AAAA,SAASA,UAAUC,UAAU,QAAQ,cAAa;AAWlD,SAASC,mBAAmB,QAAQ,gEAA+D;AACnG,SAASC,oBAAoB,QAAQ,iEAAgE;AACrG,SAASC,QAAQ,EAAEC,SAAS,EAAEC,eAAe,QAAQ,wBAAuB;AAC5E,SAASC,sBAAsB,QAAQ,4CAA2C;AAClF,SAASC,iBAAiB,QAAQ,uCAAsC;AACxE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,eAAe,QAAQ,qCAAoC;AACpE,SAASC,mBAAmB,QAAQ,4BAA2B;AAC/D,SAASC,eAAe,QAAQ,wBAAuB;AACvD,SAASC,OAAO,QAAQ,YAAW;AACnC,SAASC,gBAAgB,EAAEC,aAAa,QAAQ,iBAAgB;AAChE,SAASC,yBAAyB,QAAQ,sCAAqC;AAC/E,SAASC,wBAAwB,QAAQ,kDAAiD;AAkB1F,OAAO,MAAMC,yBAAyB,OACpCC;IAEA,MAAM,EACJC,YAAY,EAAEC,QAAQC,gBAAgB,EAAE,EACxCC,IAAI,EACJC,KAAK,EACLC,iBAAiB,KAAK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qBAAqB,UAAU;QACxC,MAAM,IAAI3F,gBAAgB;YACxBc,YAAYE,iBAAiBiC,IAAI;YACjCkD,QAAQ;gBAAC;oBAAEC,SAAST;oBAAkBI,MAAM;gBAAW;aAAE;QAC3D;IACF;AACF"}
@@ -1,4 +1,5 @@
1
1
  import type { TypeWithID } from '../../../collections/config/types.js';
2
+ import type { SanitizedConfig } from '../../../config/types.js';
2
3
  type Doc = Record<string, unknown> & TypeWithID;
3
4
  type AuthenticationResult = {
4
5
  doc: Doc;
@@ -7,7 +8,8 @@ type AuthenticationResult = {
7
8
  type Args = {
8
9
  doc: Doc;
9
10
  password: string;
11
+ passwordHashIterations: SanitizedConfig['auth']['passwordHashIterations'];
10
12
  };
11
- export declare const authenticateLocalStrategy: ({ doc, password, }: Args) => Promise<AuthenticationResult | null>;
13
+ export declare const authenticateLocalStrategy: ({ doc, password, passwordHashIterations, }: Args) => Promise<AuthenticationResult | null>;
12
14
  export {};
13
15
  //# sourceMappingURL=authenticate.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"authenticate.d.ts","sourceRoot":"","sources":["../../../../src/auth/strategies/local/authenticate.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sCAAsC,CAAA;AAItE,KAAK,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,UAAU,CAAA;AAE/C,KAAK,oBAAoB,GAAG;IAC1B,GAAG,EAAE,GAAG,CAAA;IACR,wBAAwB,EAAE,OAAO,CAAA;CAClC,CAAA;AAED,KAAK,IAAI,GAAG;IACV,GAAG,EAAE,GAAG,CAAA;IACR,QAAQ,EAAE,MAAM,CAAA;CACjB,CAAA;AAED,eAAO,MAAM,yBAAyB,uBAGnC,IAAI,KAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAmC5C,CAAA"}
1
+ {"version":3,"file":"authenticate.d.ts","sourceRoot":"","sources":["../../../../src/auth/strategies/local/authenticate.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sCAAsC,CAAA;AACtE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAU/D,KAAK,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,UAAU,CAAA;AAE/C,KAAK,oBAAoB,GAAG;IAC1B,GAAG,EAAE,GAAG,CAAA;IACR,wBAAwB,EAAE,OAAO,CAAA;CAClC,CAAA;AAED,KAAK,IAAI,GAAG;IACV,GAAG,EAAE,GAAG,CAAA;IACR,QAAQ,EAAE,MAAM,CAAA;IAChB,sBAAsB,EAAE,eAAe,CAAC,MAAM,CAAC,CAAC,wBAAwB,CAAC,CAAA;CAC1E,CAAA;AAED,eAAO,MAAM,yBAAyB,+CAInC,IAAI,KAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CA+B5C,CAAA"}
@@ -1,31 +1,35 @@
1
1
  // @ts-strict-ignore
2
2
  import crypto from 'crypto';
3
- import { getPasswordHashParameters, isCurrentPasswordHash } from './generatePasswordSaltHash.js';
4
- export const authenticateLocalStrategy = async ({ doc, password })=>{
3
+ import { InvalidConfiguration } from '../../../errors/index.js';
4
+ import { getPasswordHashParameters, isCurrentPasswordHash, isUnsupportedIterationsError, pbkdf2Promisified } from './generatePasswordSaltHash.js';
5
+ export const authenticateLocalStrategy = async ({ doc, password, passwordHashIterations })=>{
5
6
  try {
6
7
  const { hash, salt } = doc;
7
8
  if (typeof salt === 'string' && typeof hash === 'string') {
8
9
  const { hash: storedHash, iterations, keyLength } = getPasswordHashParameters(hash);
9
- const res = await new Promise((resolve, reject)=>{
10
- crypto.pbkdf2(password, salt, iterations, keyLength, 'sha256', (e, hashBuffer)=>{
11
- if (e) {
12
- reject(e);
13
- }
14
- const storedHashBuffer = Buffer.from(storedHash, 'hex');
15
- if (hashBuffer.length === storedHashBuffer.length && crypto.timingSafeEqual(hashBuffer, storedHashBuffer)) {
16
- resolve({
17
- doc,
18
- shouldUpdatePasswordHash: !isCurrentPasswordHash(hash)
19
- });
20
- } else {
21
- reject(new Error('Invalid password'));
22
- }
23
- });
10
+ const hashBuffer = await pbkdf2Promisified({
11
+ iterations,
12
+ keyLength,
13
+ password,
14
+ salt
24
15
  });
25
- return res;
16
+ const storedHashBuffer = Buffer.from(storedHash, 'hex');
17
+ if (hashBuffer.length === storedHashBuffer.length && crypto.timingSafeEqual(hashBuffer, storedHashBuffer)) {
18
+ return {
19
+ doc,
20
+ shouldUpdatePasswordHash: !isCurrentPasswordHash({
21
+ hash,
22
+ passwordHashIterations
23
+ })
24
+ };
25
+ }
26
26
  }
27
27
  return null;
28
- } catch (ignore) {
28
+ } catch (err) {
29
+ // Without this error, the failed login would count against the user's login attempts
30
+ if (isUnsupportedIterationsError(err)) {
31
+ throw new InvalidConfiguration("This environment does not support the PBKDF2 iterations of this user's stored password hash. The user must reset their password.");
32
+ }
29
33
  return null;
30
34
  }
31
35
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/auth/strategies/local/authenticate.ts"],"sourcesContent":["// @ts-strict-ignore\nimport crypto from 'crypto'\n\nimport type { TypeWithID } from '../../../collections/config/types.js'\n\nimport { getPasswordHashParameters, isCurrentPasswordHash } from './generatePasswordSaltHash.js'\n\ntype Doc = Record<string, unknown> & TypeWithID\n\ntype AuthenticationResult = {\n doc: Doc\n shouldUpdatePasswordHash: boolean\n}\n\ntype Args = {\n doc: Doc\n password: string\n}\n\nexport const authenticateLocalStrategy = async ({\n doc,\n password,\n}: Args): Promise<AuthenticationResult | null> => {\n try {\n const { hash, salt } = doc\n\n if (typeof salt === 'string' && typeof hash === 'string') {\n const { hash: storedHash, iterations, keyLength } = getPasswordHashParameters(hash)\n const res = await new Promise<AuthenticationResult | null>((resolve, reject) => {\n crypto.pbkdf2(password, salt, iterations, keyLength, 'sha256', (e, hashBuffer) => {\n if (e) {\n reject(e)\n }\n\n const storedHashBuffer = Buffer.from(storedHash, 'hex')\n\n if (\n hashBuffer.length === storedHashBuffer.length &&\n crypto.timingSafeEqual(hashBuffer, storedHashBuffer)\n ) {\n resolve({\n doc,\n shouldUpdatePasswordHash: !isCurrentPasswordHash(hash),\n })\n } else {\n reject(new Error('Invalid password'))\n }\n })\n })\n\n return res\n }\n\n return null\n } catch (ignore) {\n return null\n }\n}\n"],"names":["crypto","getPasswordHashParameters","isCurrentPasswordHash","authenticateLocalStrategy","doc","password","hash","salt","storedHash","iterations","keyLength","res","Promise","resolve","reject","pbkdf2","e","hashBuffer","storedHashBuffer","Buffer","from","length","timingSafeEqual","shouldUpdatePasswordHash","Error","ignore"],"mappings":"AAAA,oBAAoB;AACpB,OAAOA,YAAY,SAAQ;AAI3B,SAASC,yBAAyB,EAAEC,qBAAqB,QAAQ,gCAA+B;AAchG,OAAO,MAAMC,4BAA4B,OAAO,EAC9CC,GAAG,EACHC,QAAQ,EACH;IACL,IAAI;QACF,MAAM,EAAEC,IAAI,EAAEC,IAAI,EAAE,GAAGH;QAEvB,IAAI,OAAOG,SAAS,YAAY,OAAOD,SAAS,UAAU;YACxD,MAAM,EAAEA,MAAME,UAAU,EAAEC,UAAU,EAAEC,SAAS,EAAE,GAAGT,0BAA0BK;YAC9E,MAAMK,MAAM,MAAM,IAAIC,QAAqC,CAACC,SAASC;gBACnEd,OAAOe,MAAM,CAACV,UAAUE,MAAME,YAAYC,WAAW,UAAU,CAACM,GAAGC;oBACjE,IAAID,GAAG;wBACLF,OAAOE;oBACT;oBAEA,MAAME,mBAAmBC,OAAOC,IAAI,CAACZ,YAAY;oBAEjD,IACES,WAAWI,MAAM,KAAKH,iBAAiBG,MAAM,IAC7CrB,OAAOsB,eAAe,CAACL,YAAYC,mBACnC;wBACAL,QAAQ;4BACNT;4BACAmB,0BAA0B,CAACrB,sBAAsBI;wBACnD;oBACF,OAAO;wBACLQ,OAAO,IAAIU,MAAM;oBACnB;gBACF;YACF;YAEA,OAAOb;QACT;QAEA,OAAO;IACT,EAAE,OAAOc,QAAQ;QACf,OAAO;IACT;AACF,EAAC"}
1
+ {"version":3,"sources":["../../../../src/auth/strategies/local/authenticate.ts"],"sourcesContent":["// @ts-strict-ignore\nimport crypto from 'crypto'\n\nimport type { TypeWithID } from '../../../collections/config/types.js'\nimport type { SanitizedConfig } from '../../../config/types.js'\n\nimport { InvalidConfiguration } from '../../../errors/index.js'\nimport {\n getPasswordHashParameters,\n isCurrentPasswordHash,\n isUnsupportedIterationsError,\n pbkdf2Promisified,\n} from './generatePasswordSaltHash.js'\n\ntype Doc = Record<string, unknown> & TypeWithID\n\ntype AuthenticationResult = {\n doc: Doc\n shouldUpdatePasswordHash: boolean\n}\n\ntype Args = {\n doc: Doc\n password: string\n passwordHashIterations: SanitizedConfig['auth']['passwordHashIterations']\n}\n\nexport const authenticateLocalStrategy = async ({\n doc,\n password,\n passwordHashIterations,\n}: Args): Promise<AuthenticationResult | null> => {\n try {\n const { hash, salt } = doc\n\n if (typeof salt === 'string' && typeof hash === 'string') {\n const { hash: storedHash, iterations, keyLength } = getPasswordHashParameters(hash)\n const hashBuffer = await pbkdf2Promisified({ iterations, keyLength, password, salt })\n const storedHashBuffer = Buffer.from(storedHash, 'hex')\n\n if (\n hashBuffer.length === storedHashBuffer.length &&\n crypto.timingSafeEqual(hashBuffer, storedHashBuffer)\n ) {\n return {\n doc,\n shouldUpdatePasswordHash: !isCurrentPasswordHash({ hash, passwordHashIterations }),\n }\n }\n }\n\n return null\n } catch (err) {\n // Without this error, the failed login would count against the user's login attempts\n if (isUnsupportedIterationsError(err)) {\n throw new InvalidConfiguration(\n \"This environment does not support the PBKDF2 iterations of this user's stored password hash. The user must reset their password.\",\n )\n }\n\n return null\n }\n}\n"],"names":["crypto","InvalidConfiguration","getPasswordHashParameters","isCurrentPasswordHash","isUnsupportedIterationsError","pbkdf2Promisified","authenticateLocalStrategy","doc","password","passwordHashIterations","hash","salt","storedHash","iterations","keyLength","hashBuffer","storedHashBuffer","Buffer","from","length","timingSafeEqual","shouldUpdatePasswordHash","err"],"mappings":"AAAA,oBAAoB;AACpB,OAAOA,YAAY,SAAQ;AAK3B,SAASC,oBAAoB,QAAQ,2BAA0B;AAC/D,SACEC,yBAAyB,EACzBC,qBAAqB,EACrBC,4BAA4B,EAC5BC,iBAAiB,QACZ,gCAA+B;AAetC,OAAO,MAAMC,4BAA4B,OAAO,EAC9CC,GAAG,EACHC,QAAQ,EACRC,sBAAsB,EACjB;IACL,IAAI;QACF,MAAM,EAAEC,IAAI,EAAEC,IAAI,EAAE,GAAGJ;QAEvB,IAAI,OAAOI,SAAS,YAAY,OAAOD,SAAS,UAAU;YACxD,MAAM,EAAEA,MAAME,UAAU,EAAEC,UAAU,EAAEC,SAAS,EAAE,GAAGZ,0BAA0BQ;YAC9E,MAAMK,aAAa,MAAMV,kBAAkB;gBAAEQ;gBAAYC;gBAAWN;gBAAUG;YAAK;YACnF,MAAMK,mBAAmBC,OAAOC,IAAI,CAACN,YAAY;YAEjD,IACEG,WAAWI,MAAM,KAAKH,iBAAiBG,MAAM,IAC7CnB,OAAOoB,eAAe,CAACL,YAAYC,mBACnC;gBACA,OAAO;oBACLT;oBACAc,0BAA0B,CAAClB,sBAAsB;wBAAEO;wBAAMD;oBAAuB;gBAClF;YACF;QACF;QAEA,OAAO;IACT,EAAE,OAAOa,KAAK;QACZ,qFAAqF;QACrF,IAAIlB,6BAA6BkB,MAAM;YACrC,MAAM,IAAIrB,qBACR;QAEJ;QAEA,OAAO;IACT;AACF,EAAC"}
@@ -1,5 +1,6 @@
1
1
  import crypto from 'crypto';
2
- import { describe, expect, it } from 'vitest';
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+ import { InvalidConfiguration } from '../../../errors/InvalidConfiguration.js';
3
4
  import { authenticateLocalStrategy } from './authenticate.js';
4
5
  const generateExistingHashAndSalt = (password)=>{
5
6
  const salt = crypto.randomBytes(32).toString('hex');
@@ -18,6 +19,9 @@ const generateCurrentHashAndSalt = (password)=>{
18
19
  };
19
20
  };
20
21
  describe('authenticateLocalStrategy', ()=>{
22
+ afterEach(()=>{
23
+ vi.restoreAllMocks();
24
+ });
21
25
  it('should return doc for an existing password hash', async ()=>{
22
26
  const password = 'test-password';
23
27
  const { hash, salt } = generateExistingHashAndSalt(password);
@@ -28,7 +32,8 @@ describe('authenticateLocalStrategy', ()=>{
28
32
  };
29
33
  const result = await authenticateLocalStrategy({
30
34
  doc,
31
- password
35
+ password,
36
+ passwordHashIterations: 600000
32
37
  });
33
38
  expect(result).toEqual({
34
39
  doc,
@@ -45,13 +50,88 @@ describe('authenticateLocalStrategy', ()=>{
45
50
  };
46
51
  const result = await authenticateLocalStrategy({
47
52
  doc,
48
- password
53
+ password,
54
+ passwordHashIterations: 600000
49
55
  });
50
56
  expect(result).toEqual({
51
57
  doc,
52
58
  shouldUpdatePasswordHash: false
53
59
  });
54
60
  });
61
+ it('should flag a 600k password hash for rehash when configured for 100000 iterations', async ()=>{
62
+ const password = 'test-password';
63
+ const { hash, salt } = generateCurrentHashAndSalt(password);
64
+ const doc = {
65
+ id: 1,
66
+ hash,
67
+ salt
68
+ };
69
+ const result = await authenticateLocalStrategy({
70
+ doc,
71
+ password,
72
+ passwordHashIterations: 100000
73
+ });
74
+ expect(result).toEqual({
75
+ doc,
76
+ shouldUpdatePasswordHash: true
77
+ });
78
+ });
79
+ it('should flag a legacy password hash for rehash when configured for 100000 iterations', async ()=>{
80
+ const password = 'test-password';
81
+ const { hash, salt } = generateExistingHashAndSalt(password);
82
+ const doc = {
83
+ id: 1,
84
+ hash,
85
+ salt
86
+ };
87
+ const result = await authenticateLocalStrategy({
88
+ doc,
89
+ password,
90
+ passwordHashIterations: 100000
91
+ });
92
+ expect(result).toEqual({
93
+ doc,
94
+ shouldUpdatePasswordHash: true
95
+ });
96
+ });
97
+ it('should return null when hashing fails', async ()=>{
98
+ // Calls back on a later tick like the real crypto.pbkdf2, so an error thrown
99
+ // inside the callback is not caught by authenticateLocalStrategy
100
+ vi.spyOn(crypto, 'pbkdf2').mockImplementation((...args)=>{
101
+ const callback = args.at(-1);
102
+ process.nextTick(()=>callback(new Error('Unsupported iteration count')));
103
+ });
104
+ const { hash, salt } = generateCurrentHashAndSalt('test-password');
105
+ const doc = {
106
+ id: 1,
107
+ hash,
108
+ salt
109
+ };
110
+ const result = await authenticateLocalStrategy({
111
+ doc,
112
+ password: 'test-password',
113
+ passwordHashIterations: 600000
114
+ });
115
+ expect(result).toBeNull();
116
+ });
117
+ it('should throw an InvalidConfiguration error when the environment does not support the stored hash iterations', async ()=>{
118
+ // Matches the error Cloudflare Workers throws for more than 100,000 iterations
119
+ vi.spyOn(crypto, 'pbkdf2').mockImplementation((...args)=>{
120
+ const callback = args.at(-1);
121
+ process.nextTick(()=>callback(new DOMException('Pbkdf2 failed: iteration counts above 100000 are not supported (requested 600000).', 'NotSupportedError')));
122
+ });
123
+ const { hash, salt } = generateCurrentHashAndSalt('test-password');
124
+ const doc = {
125
+ id: 1,
126
+ hash,
127
+ salt
128
+ };
129
+ await expect(authenticateLocalStrategy({
130
+ doc,
131
+ password: 'test-password',
132
+ passwordHashIterations: 100000
133
+ })).rejects.toThrow(InvalidConfiguration);
134
+ });
55
135
  it('should return null when password is invalid', async ()=>{
56
136
  const { hash, salt } = generateExistingHashAndSalt('correct-password');
57
137
  const doc = {
@@ -61,7 +141,8 @@ describe('authenticateLocalStrategy', ()=>{
61
141
  };
62
142
  const result = await authenticateLocalStrategy({
63
143
  doc,
64
- password: 'wrong-password'
144
+ password: 'wrong-password',
145
+ passwordHashIterations: 600000
65
146
  });
66
147
  expect(result).toBeNull();
67
148
  });
@@ -73,7 +154,8 @@ describe('authenticateLocalStrategy', ()=>{
73
154
  };
74
155
  const result = await authenticateLocalStrategy({
75
156
  doc,
76
- password: 'test-password'
157
+ password: 'test-password',
158
+ passwordHashIterations: 600000
77
159
  });
78
160
  expect(result).toBeNull();
79
161
  });
@@ -85,7 +167,8 @@ describe('authenticateLocalStrategy', ()=>{
85
167
  };
86
168
  const result = await authenticateLocalStrategy({
87
169
  doc,
88
- password: 'test-password'
170
+ password: 'test-password',
171
+ passwordHashIterations: 600000
89
172
  });
90
173
  expect(result).toBeNull();
91
174
  });
@@ -101,7 +184,8 @@ describe('authenticateLocalStrategy', ()=>{
101
184
  };
102
185
  const result = await authenticateLocalStrategy({
103
186
  doc,
104
- password
187
+ password,
188
+ passwordHashIterations: 600000
105
189
  });
106
190
  expect(result).toBeNull();
107
191
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/auth/strategies/local/authenticate.spec.ts"],"sourcesContent":["import crypto from 'crypto'\n\nimport { describe, expect, it } from 'vitest'\n\nimport { authenticateLocalStrategy } from './authenticate.js'\n\nconst generateExistingHashAndSalt = (password: string): { hash: string; salt: string } => {\n const salt = crypto.randomBytes(32).toString('hex')\n const hash = crypto.pbkdf2Sync(password, salt, 25000, 512, 'sha256').toString('hex')\n return { hash, salt }\n}\n\nconst generateCurrentHashAndSalt = (password: string): { hash: string; salt: string } => {\n const salt = crypto.randomBytes(32).toString('hex')\n const hash = crypto.pbkdf2Sync(password, salt, 600000, 32, 'sha256').toString('hex')\n\n return { hash: `pbkdf2-sha256-v1:${hash}`, salt }\n}\n\ndescribe('authenticateLocalStrategy', () => {\n it('should return doc for an existing password hash', async () => {\n const password = 'test-password'\n const { hash, salt } = generateExistingHashAndSalt(password)\n const doc = { id: 1, hash, salt }\n\n const result = await authenticateLocalStrategy({ doc, password })\n\n expect(result).toEqual({ doc, shouldUpdatePasswordHash: true })\n })\n\n it('should return doc for a current password hash', async () => {\n const password = 'test-password'\n const { hash, salt } = generateCurrentHashAndSalt(password)\n const doc = { id: 1, hash, salt }\n\n const result = await authenticateLocalStrategy({ doc, password })\n\n expect(result).toEqual({ doc, shouldUpdatePasswordHash: false })\n })\n\n it('should return null when password is invalid', async () => {\n const { hash, salt } = generateExistingHashAndSalt('correct-password')\n const doc = { id: 1, hash, salt }\n\n const result = await authenticateLocalStrategy({ doc, password: 'wrong-password' })\n\n expect(result).toBeNull()\n })\n\n it('should return null when salt is missing', async () => {\n const { hash } = generateExistingHashAndSalt('test-password')\n const doc = { id: 1, hash }\n\n const result = await authenticateLocalStrategy({ doc, password: 'test-password' })\n\n expect(result).toBeNull()\n })\n\n it('should return null when hash is missing', async () => {\n const { salt } = generateExistingHashAndSalt('test-password')\n const doc = { id: 1, salt }\n\n const result = await authenticateLocalStrategy({ doc, password: 'test-password' })\n\n expect(result).toBeNull()\n })\n\n it('should return null when hash has different length (tampered)', async () => {\n const password = 'test-password'\n const { salt } = generateExistingHashAndSalt(password)\n // Truncated hash - different length than an existing hash derives\n const shortHash = 'abcd1234'\n const doc = { id: 1, hash: shortHash, salt }\n\n const result = await authenticateLocalStrategy({ doc, password })\n\n expect(result).toBeNull()\n })\n})\n"],"names":["crypto","describe","expect","it","authenticateLocalStrategy","generateExistingHashAndSalt","password","salt","randomBytes","toString","hash","pbkdf2Sync","generateCurrentHashAndSalt","doc","id","result","toEqual","shouldUpdatePasswordHash","toBeNull","shortHash"],"mappings":"AAAA,OAAOA,YAAY,SAAQ;AAE3B,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAQ;AAE7C,SAASC,yBAAyB,QAAQ,oBAAmB;AAE7D,MAAMC,8BAA8B,CAACC;IACnC,MAAMC,OAAOP,OAAOQ,WAAW,CAAC,IAAIC,QAAQ,CAAC;IAC7C,MAAMC,OAAOV,OAAOW,UAAU,CAACL,UAAUC,MAAM,OAAO,KAAK,UAAUE,QAAQ,CAAC;IAC9E,OAAO;QAAEC;QAAMH;IAAK;AACtB;AAEA,MAAMK,6BAA6B,CAACN;IAClC,MAAMC,OAAOP,OAAOQ,WAAW,CAAC,IAAIC,QAAQ,CAAC;IAC7C,MAAMC,OAAOV,OAAOW,UAAU,CAACL,UAAUC,MAAM,QAAQ,IAAI,UAAUE,QAAQ,CAAC;IAE9E,OAAO;QAAEC,MAAM,CAAC,iBAAiB,EAAEA,MAAM;QAAEH;IAAK;AAClD;AAEAN,SAAS,6BAA6B;IACpCE,GA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zB;IAEAf,GAAG,gEAAgE;QACjE,MAAMG,WAAW;QACjB,MAAM,EAAEC,IAAI,EAAE,GAAGF,4BAA4BC;QAC7C,kEAAkE;QAClE,MAAMa,YAAY;QAClB,MAAMN,MAAM;YAAEC,IAAI;YAAGJ,MAAMS;YAAWZ;QAAK;QAE3C,MAAMQ,SAAS,MAAMX,0BAA0B;YAAES;YAAKP;QAAS;QAE/DJ,OAAOa,QAAQG,QAAQ;IACzB;AACF"}
1
+ {"version":3,"sources":["../../../../src/auth/strategies/local/authenticate.spec.ts"],"sourcesContent":["import crypto from 'crypto'\n\nimport { afterEach, describe, expect, it, vi } from 'vitest'\n\nimport { InvalidConfiguration } from '../../../errors/InvalidConfiguration.js'\nimport { authenticateLocalStrategy } from './authenticate.js'\n\nconst generateExistingHashAndSalt = (password: string): { hash: string; salt: string } => {\n const salt = crypto.randomBytes(32).toString('hex')\n const hash = crypto.pbkdf2Sync(password, salt, 25000, 512, 'sha256').toString('hex')\n return { hash, salt }\n}\n\nconst generateCurrentHashAndSalt = (password: string): { hash: string; salt: string } => {\n const salt = crypto.randomBytes(32).toString('hex')\n const hash = crypto.pbkdf2Sync(password, salt, 600000, 32, 'sha256').toString('hex')\n\n return { hash: `pbkdf2-sha256-v1:${hash}`, salt }\n}\n\ndescribe('authenticateLocalStrategy', () => {\n afterEach(() => {\n vi.restoreAllMocks()\n })\n\n it('should return doc for an existing password hash', async () => {\n const password = 'test-password'\n const { hash, salt } = generateExistingHashAndSalt(password)\n const doc = { id: 1, hash, salt }\n\n const result = await authenticateLocalStrategy({\n doc,\n password,\n passwordHashIterations: 600000,\n })\n\n expect(result).toEqual({ doc, shouldUpdatePasswordHash: true })\n })\n\n it('should return doc for a current password hash', async () => {\n const password = 'test-password'\n const { hash, salt } = generateCurrentHashAndSalt(password)\n const doc = { id: 1, hash, salt }\n\n const result = await authenticateLocalStrategy({\n doc,\n password,\n passwordHashIterations: 600000,\n })\n\n expect(result).toEqual({ doc, shouldUpdatePasswordHash: false })\n })\n\n it('should flag a 600k password hash for rehash when configured for 100000 iterations', async () => {\n const password = 'test-password'\n const { hash, salt } = generateCurrentHashAndSalt(password)\n const doc = { id: 1, hash, salt }\n\n const result = await authenticateLocalStrategy({\n doc,\n password,\n passwordHashIterations: 100000,\n })\n\n expect(result).toEqual({ doc, shouldUpdatePasswordHash: true })\n })\n\n it('should flag a legacy password hash for rehash when configured for 100000 iterations', async () => {\n const password = 'test-password'\n const { hash, salt } = generateExistingHashAndSalt(password)\n const doc = { id: 1, hash, salt }\n\n const result = await authenticateLocalStrategy({\n doc,\n password,\n passwordHashIterations: 100000,\n })\n\n expect(result).toEqual({ doc, shouldUpdatePasswordHash: true })\n })\n\n it('should return null when hashing fails', async () => {\n // Calls back on a later tick like the real crypto.pbkdf2, so an error thrown\n // inside the callback is not caught by authenticateLocalStrategy\n vi.spyOn(crypto, 'pbkdf2').mockImplementation(((...args: unknown[]) => {\n const callback = args.at(-1) as (err: Error, derivedKey?: Buffer) => void\n\n process.nextTick(() => callback(new Error('Unsupported iteration count')))\n }) as typeof crypto.pbkdf2)\n const { hash, salt } = generateCurrentHashAndSalt('test-password')\n const doc = { id: 1, hash, salt }\n\n const result = await authenticateLocalStrategy({\n doc,\n password: 'test-password',\n passwordHashIterations: 600000,\n })\n\n expect(result).toBeNull()\n })\n\n it('should throw an InvalidConfiguration error when the environment does not support the stored hash iterations', async () => {\n // Matches the error Cloudflare Workers throws for more than 100,000 iterations\n vi.spyOn(crypto, 'pbkdf2').mockImplementation(((...args: unknown[]) => {\n const callback = args.at(-1) as (err: Error) => void\n\n process.nextTick(() =>\n callback(\n new DOMException(\n 'Pbkdf2 failed: iteration counts above 100000 are not supported (requested 600000).',\n 'NotSupportedError',\n ),\n ),\n )\n }) as typeof crypto.pbkdf2)\n const { hash, salt } = generateCurrentHashAndSalt('test-password')\n const doc = { id: 1, hash, salt }\n\n await expect(\n authenticateLocalStrategy({\n doc,\n password: 'test-password',\n passwordHashIterations: 100000,\n }),\n ).rejects.toThrow(InvalidConfiguration)\n })\n\n it('should return null when password is invalid', async () => {\n const { hash, salt } = generateExistingHashAndSalt('correct-password')\n const doc = { id: 1, hash, salt }\n\n const result = await authenticateLocalStrategy({\n doc,\n password: 'wrong-password',\n passwordHashIterations: 600000,\n })\n\n expect(result).toBeNull()\n })\n\n it('should return null when salt is missing', async () => {\n const { hash } = generateExistingHashAndSalt('test-password')\n const doc = { id: 1, hash }\n\n const result = await authenticateLocalStrategy({\n doc,\n password: 'test-password',\n passwordHashIterations: 600000,\n })\n\n expect(result).toBeNull()\n })\n\n it('should return null when hash is missing', async () => {\n const { salt } = generateExistingHashAndSalt('test-password')\n const doc = { id: 1, salt }\n\n const result = await authenticateLocalStrategy({\n doc,\n password: 'test-password',\n passwordHashIterations: 600000,\n })\n\n expect(result).toBeNull()\n })\n\n it('should return null when hash has different length (tampered)', async () => {\n const password = 'test-password'\n const { salt } = generateExistingHashAndSalt(password)\n // Truncated hash - different length than an existing hash derives\n const shortHash = 'abcd1234'\n const doc = { id: 1, hash: shortHash, salt }\n\n const result = await authenticateLocalStrategy({\n doc,\n password,\n passwordHashIterations: 600000,\n })\n\n expect(result).toBeNull()\n })\n})\n"],"names":["crypto","afterEach","describe","expect","it","vi","InvalidConfiguration","authenticateLocalStrategy","generateExistingHashAndSalt","password","salt","randomBytes","toString","hash","pbkdf2Sync","generateCurrentHashAndSalt","restoreAllMocks","doc","id","result","passwordHashIterations","toEqual","shouldUpdatePasswordHash","spyOn","mockImplementation","args","callback","at","process","nextTick","Error","toBeNull","DOMException","rejects","toThrow","shortHash"],"mappings":"AAAA,OAAOA,YAAY,SAAQ;AAE3B,SAASC,SAAS,EAAEC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,EAAEC,EAAE,QAAQ,SAAQ;AAE5D,SAASC,oBAAoB,QAAQ,0CAAyC;AAC9E,SAASC,yBAAyB,QAAQ,oBAAmB;AAE7D,MAAMC,8BAA8B,CAACC;IACnC,MAAMC,OAAOV,OAAOW,W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