payload 4.0.0-beta.6 → 4.0.0-beta.7

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 (218) hide show
  1. package/dist/auth/baseFields/sessions.d.ts.map +1 -1
  2. package/dist/auth/baseFields/sessions.js +8 -0
  3. package/dist/auth/baseFields/sessions.js.map +1 -1
  4. package/dist/auth/createAuthToken.d.ts +30 -0
  5. package/dist/auth/createAuthToken.d.ts.map +1 -0
  6. package/dist/auth/createAuthToken.js +39 -0
  7. package/dist/auth/createAuthToken.js.map +1 -0
  8. package/dist/auth/endpoints/refresh.d.ts.map +1 -1
  9. package/dist/auth/endpoints/refresh.js +2 -1
  10. package/dist/auth/endpoints/refresh.js.map +1 -1
  11. package/dist/auth/executeAuthStrategies.d.ts.map +1 -1
  12. package/dist/auth/executeAuthStrategies.js +1 -0
  13. package/dist/auth/executeAuthStrategies.js.map +1 -1
  14. package/dist/auth/extractJWT.d.ts.map +1 -1
  15. package/dist/auth/extractJWT.js +16 -0
  16. package/dist/auth/extractJWT.js.map +1 -1
  17. package/dist/auth/loginWithCookie.d.ts.map +1 -1
  18. package/dist/auth/loginWithCookie.js +1 -0
  19. package/dist/auth/loginWithCookie.js.map +1 -1
  20. package/dist/auth/operations/local/login.d.ts.map +1 -1
  21. package/dist/auth/operations/local/login.js +1 -0
  22. package/dist/auth/operations/local/login.js.map +1 -1
  23. package/dist/auth/operations/login.d.ts +2 -0
  24. package/dist/auth/operations/login.d.ts.map +1 -1
  25. package/dist/auth/operations/login.js +10 -20
  26. package/dist/auth/operations/login.js.map +1 -1
  27. package/dist/auth/operations/refresh.d.ts +7 -0
  28. package/dist/auth/operations/refresh.d.ts.map +1 -1
  29. package/dist/auth/operations/refresh.js +160 -96
  30. package/dist/auth/operations/refresh.js.map +1 -1
  31. package/dist/auth/operations/resetPassword.d.ts.map +1 -1
  32. package/dist/auth/operations/resetPassword.js +8 -20
  33. package/dist/auth/operations/resetPassword.js.map +1 -1
  34. package/dist/auth/redeemRefreshToken.d.ts +36 -0
  35. package/dist/auth/redeemRefreshToken.d.ts.map +1 -0
  36. package/dist/auth/redeemRefreshToken.js +120 -0
  37. package/dist/auth/redeemRefreshToken.js.map +1 -0
  38. package/dist/auth/sessions.d.ts +28 -2
  39. package/dist/auth/sessions.d.ts.map +1 -1
  40. package/dist/auth/sessions.js +36 -5
  41. package/dist/auth/sessions.js.map +1 -1
  42. package/dist/auth/strategies/local/authenticate.d.ts +3 -1
  43. package/dist/auth/strategies/local/authenticate.d.ts.map +1 -1
  44. package/dist/auth/strategies/local/authenticate.js +23 -19
  45. package/dist/auth/strategies/local/authenticate.js.map +1 -1
  46. package/dist/auth/strategies/local/generatePasswordSaltHash.d.ts +14 -1
  47. package/dist/auth/strategies/local/generatePasswordSaltHash.d.ts.map +1 -1
  48. package/dist/auth/strategies/local/generatePasswordSaltHash.js +31 -15
  49. package/dist/auth/strategies/local/generatePasswordSaltHash.js.map +1 -1
  50. package/dist/auth/types.d.ts +34 -1
  51. package/dist/auth/types.d.ts.map +1 -1
  52. package/dist/auth/types.js.map +1 -1
  53. package/dist/collections/config/defaults.d.ts +2 -0
  54. package/dist/collections/config/defaults.d.ts.map +1 -1
  55. package/dist/collections/config/defaults.js +4 -0
  56. package/dist/collections/config/defaults.js.map +1 -1
  57. package/dist/collections/config/sanitize.d.ts.map +1 -1
  58. package/dist/collections/config/sanitize.js +3 -0
  59. package/dist/collections/config/sanitize.js.map +1 -1
  60. package/dist/collections/operations/create.js +11 -11
  61. package/dist/collections/operations/create.js.map +1 -1
  62. package/dist/collections/operations/renameFile.d.ts.map +1 -1
  63. package/dist/collections/operations/renameFile.js +30 -15
  64. package/dist/collections/operations/renameFile.js.map +1 -1
  65. package/dist/collections/operations/utilities/update.d.ts.map +1 -1
  66. package/dist/collections/operations/utilities/update.js +29 -40
  67. package/dist/collections/operations/utilities/update.js.map +1 -1
  68. package/dist/config/defaults.d.ts.map +1 -1
  69. package/dist/config/defaults.js +2 -1
  70. package/dist/config/defaults.js.map +1 -1
  71. package/dist/config/sanitize.d.ts.map +1 -1
  72. package/dist/config/sanitize.js +4 -0
  73. package/dist/config/sanitize.js.map +1 -1
  74. package/dist/config/types.d.ts +9 -0
  75. package/dist/config/types.d.ts.map +1 -1
  76. package/dist/config/types.js.map +1 -1
  77. package/dist/database/getLocalizedPaths.d.ts.map +1 -1
  78. package/dist/database/getLocalizedPaths.js +16 -1
  79. package/dist/database/getLocalizedPaths.js.map +1 -1
  80. package/dist/database/queryValidation/hasReadAccessToQueryPath.d.ts +17 -0
  81. package/dist/database/queryValidation/hasReadAccessToQueryPath.d.ts.map +1 -0
  82. package/dist/database/queryValidation/hasReadAccessToQueryPath.js +59 -0
  83. package/dist/database/queryValidation/hasReadAccessToQueryPath.js.map +1 -0
  84. package/dist/database/queryValidation/validateSearchParams.d.ts.map +1 -1
  85. package/dist/database/queryValidation/validateSearchParams.js +20 -23
  86. package/dist/database/queryValidation/validateSearchParams.js.map +1 -1
  87. package/dist/errors/DuplicateGlobal.d.ts.map +1 -1
  88. package/dist/errors/DuplicateGlobal.js +1 -1
  89. package/dist/errors/DuplicateGlobal.js.map +1 -1
  90. package/dist/errors/InvalidFieldName.js +1 -1
  91. package/dist/errors/InvalidFieldName.js.map +1 -1
  92. package/dist/errors/InvalidFieldRelationship.d.ts.map +1 -1
  93. package/dist/errors/InvalidFieldRelationship.js +1 -1
  94. package/dist/errors/InvalidFieldRelationship.js.map +1 -1
  95. package/dist/errors/MissingFieldInputOptions.js +1 -1
  96. package/dist/errors/MissingFieldInputOptions.js.map +1 -1
  97. package/dist/errors/ReservedFieldName.d.ts.map +1 -1
  98. package/dist/errors/ReservedFieldName.js +1 -1
  99. package/dist/errors/ReservedFieldName.js.map +1 -1
  100. package/dist/exports/internal.d.ts +1 -1
  101. package/dist/exports/internal.d.ts.map +1 -1
  102. package/dist/exports/internal.js +1 -1
  103. package/dist/exports/internal.js.map +1 -1
  104. package/dist/fields/baseFields/authorship/index.d.ts +2 -1
  105. package/dist/fields/baseFields/authorship/index.d.ts.map +1 -1
  106. package/dist/fields/baseFields/authorship/index.js +12 -5
  107. package/dist/fields/baseFields/authorship/index.js.map +1 -1
  108. package/dist/fields/hooks/afterChange/promise.d.ts.map +1 -1
  109. package/dist/fields/hooks/afterChange/promise.js +2 -1
  110. package/dist/fields/hooks/afterChange/promise.js.map +1 -1
  111. package/dist/fields/hooks/afterRead/promise.d.ts.map +1 -1
  112. package/dist/fields/hooks/afterRead/promise.js +11 -9
  113. package/dist/fields/hooks/afterRead/promise.js.map +1 -1
  114. package/dist/fields/hooks/beforeChange/index.d.ts.map +1 -1
  115. package/dist/fields/hooks/beforeChange/index.js +4 -0
  116. package/dist/fields/hooks/beforeChange/index.js.map +1 -1
  117. package/dist/fields/hooks/beforeChange/promise.d.ts.map +1 -1
  118. package/dist/fields/hooks/beforeChange/promise.js +11 -1
  119. package/dist/fields/hooks/beforeChange/promise.js.map +1 -1
  120. package/dist/fields/hooks/beforeDuplicate/promise.d.ts.map +1 -1
  121. package/dist/fields/hooks/beforeDuplicate/promise.js +7 -2
  122. package/dist/fields/hooks/beforeDuplicate/promise.js.map +1 -1
  123. package/dist/fields/hooks/beforeValidate/promise.d.ts.map +1 -1
  124. package/dist/fields/hooks/beforeValidate/promise.js +19 -2
  125. package/dist/fields/hooks/beforeValidate/promise.js.map +1 -1
  126. package/dist/fields/validations.js +3 -3
  127. package/dist/fields/validations.js.map +1 -1
  128. package/dist/globals/operations/update.d.ts.map +1 -1
  129. package/dist/globals/operations/update.js +29 -40
  130. package/dist/globals/operations/update.js.map +1 -1
  131. package/dist/index.bundled.d.ts +125 -4
  132. package/dist/index.d.ts +2 -0
  133. package/dist/index.d.ts.map +1 -1
  134. package/dist/index.js +2 -0
  135. package/dist/index.js.map +1 -1
  136. package/dist/uploads/docWithFilenameExists.d.ts +2 -1
  137. package/dist/uploads/docWithFilenameExists.d.ts.map +1 -1
  138. package/dist/uploads/docWithFilenameExists.js +19 -9
  139. package/dist/uploads/docWithFilenameExists.js.map +1 -1
  140. package/dist/uploads/downloadFileToBuffer.d.ts +11 -0
  141. package/dist/uploads/downloadFileToBuffer.d.ts.map +1 -1
  142. package/dist/uploads/downloadFileToBuffer.js +32 -21
  143. package/dist/uploads/downloadFileToBuffer.js.map +1 -1
  144. package/dist/uploads/endpoints/getFile.d.ts +2 -1
  145. package/dist/uploads/endpoints/getFile.d.ts.map +1 -1
  146. package/dist/uploads/endpoints/getFile.js +6 -1
  147. package/dist/uploads/endpoints/getFile.js.map +1 -1
  148. package/dist/uploads/fileVersioning/naming.d.ts +0 -3
  149. package/dist/uploads/fileVersioning/naming.d.ts.map +1 -1
  150. package/dist/uploads/fileVersioning/naming.js +0 -4
  151. package/dist/uploads/fileVersioning/naming.js.map +1 -1
  152. package/dist/uploads/generateFileData.d.ts.map +1 -1
  153. package/dist/uploads/generateFileData.js +77 -41
  154. package/dist/uploads/generateFileData.js.map +1 -1
  155. package/dist/uploads/generateFilePathOrURL.d.ts +3 -1
  156. package/dist/uploads/generateFilePathOrURL.d.ts.map +1 -1
  157. package/dist/uploads/generateFilePathOrURL.js +3 -2
  158. package/dist/uploads/generateFilePathOrURL.js.map +1 -1
  159. package/dist/uploads/getBaseFields.d.ts.map +1 -1
  160. package/dist/uploads/getBaseFields.js +7 -0
  161. package/dist/uploads/getBaseFields.js.map +1 -1
  162. package/dist/uploads/getFileFromUploadInstructions.d.ts.map +1 -1
  163. package/dist/uploads/getFileFromUploadInstructions.js +6 -9
  164. package/dist/uploads/getFileFromUploadInstructions.js.map +1 -1
  165. package/dist/uploads/getFileTypeIdentity.d.ts.map +1 -1
  166. package/dist/uploads/getFileTypeIdentity.js +6 -2
  167. package/dist/uploads/getFileTypeIdentity.js.map +1 -1
  168. package/dist/uploads/getSafeFilename.d.ts +3 -1
  169. package/dist/uploads/getSafeFilename.d.ts.map +1 -1
  170. package/dist/uploads/getSafeFilename.js +2 -1
  171. package/dist/uploads/getSafeFilename.js.map +1 -1
  172. package/dist/uploads/isOriginalFileRequest.d.ts +23 -0
  173. package/dist/uploads/isOriginalFileRequest.d.ts.map +1 -0
  174. package/dist/uploads/isOriginalFileRequest.js +12 -0
  175. package/dist/uploads/isOriginalFileRequest.js.map +1 -0
  176. package/dist/uploads/transformers/handleDynamicFileRequest.d.ts +2 -1
  177. package/dist/uploads/transformers/handleDynamicFileRequest.d.ts.map +1 -1
  178. package/dist/uploads/transformers/handleDynamicFileRequest.js +11 -2
  179. package/dist/uploads/transformers/handleDynamicFileRequest.js.map +1 -1
  180. package/dist/uploads/types.d.ts +13 -1
  181. package/dist/uploads/types.d.ts.map +1 -1
  182. package/dist/uploads/types.js.map +1 -1
  183. package/dist/utilities/getEntityPermissions/getEntityPermissions.d.ts.map +1 -1
  184. package/dist/utilities/getEntityPermissions/getEntityPermissions.js +5 -2
  185. package/dist/utilities/getEntityPermissions/getEntityPermissions.js.map +1 -1
  186. package/dist/utilities/getEntityPermissions/populateFieldPermissions.d.ts +4 -4
  187. package/dist/utilities/getEntityPermissions/populateFieldPermissions.d.ts.map +1 -1
  188. package/dist/utilities/getEntityPermissions/populateFieldPermissions.js +63 -32
  189. package/dist/utilities/getEntityPermissions/populateFieldPermissions.js.map +1 -1
  190. package/dist/utilities/mergeLocalizedData.d.ts +1 -1
  191. package/dist/utilities/mergeLocalizedData.d.ts.map +1 -1
  192. package/dist/utilities/mergeLocalizedData.js +6 -2
  193. package/dist/utilities/mergeLocalizedData.js.map +1 -1
  194. package/dist/utilities/sanitizePermissions.d.ts +4 -1
  195. package/dist/utilities/sanitizePermissions.d.ts.map +1 -1
  196. package/dist/utilities/sanitizePermissions.js +34 -3
  197. package/dist/utilities/sanitizePermissions.js.map +1 -1
  198. package/dist/versions/allLocalesPublicationStatus.d.ts +5 -5
  199. package/dist/versions/allLocalesPublicationStatus.d.ts.map +1 -1
  200. package/dist/versions/allLocalesPublicationStatus.js +2 -2
  201. package/dist/versions/allLocalesPublicationStatus.js.map +1 -1
  202. package/dist/versions/buildSingleLocalePublishData.d.ts +4 -4
  203. package/dist/versions/buildSingleLocalePublishData.d.ts.map +1 -1
  204. package/dist/versions/buildSingleLocalePublishData.js +8 -8
  205. package/dist/versions/buildSingleLocalePublishData.js.map +1 -1
  206. package/dist/versions/drafts/hasNonLocalizedDataChanged.d.ts +12 -0
  207. package/dist/versions/drafts/hasNonLocalizedDataChanged.d.ts.map +1 -0
  208. package/dist/versions/drafts/hasNonLocalizedDataChanged.js +165 -0
  209. package/dist/versions/drafts/hasNonLocalizedDataChanged.js.map +1 -0
  210. package/dist/versions/mergeLocalizedStatus.d.ts +9 -0
  211. package/dist/versions/mergeLocalizedStatus.d.ts.map +1 -0
  212. package/dist/versions/mergeLocalizedStatus.js +11 -0
  213. package/dist/versions/mergeLocalizedStatus.js.map +1 -0
  214. package/dist/versions/resolveLocalizedStatus.d.ts +19 -0
  215. package/dist/versions/resolveLocalizedStatus.d.ts.map +1 -0
  216. package/dist/versions/resolveLocalizedStatus.js +60 -0
  217. package/dist/versions/resolveLocalizedStatus.js.map +1 -0
  218. package/package.json +2 -2
@@ -0,0 +1,120 @@
1
+ import { defaultRefreshTokenExpiration } from '../collections/config/defaults.js';
2
+ import { appendNonTrashedFilter } from '../utilities/appendNonTrashedFilter.js';
3
+ import { assertNoValidationWrite } from '../utilities/assertNoValidationWrite.js';
4
+ import { getFieldsToSign } from './getFieldsToSign.js';
5
+ import { jwtSign } from './jwt.js';
6
+ import { extendSession, removeExpiredSessions, revokeSession } from './sessions.js';
7
+ /**
8
+ * How long the refresh token from right before the latest refresh still works, in milliseconds.
9
+ * Clients that send requests in parallel can refresh twice at once.
10
+ */ const reuseInterval = 30 * 1000;
11
+ /**
12
+ * Trades a refresh token from `createAuthToken` or an earlier refresh for a new token and a new
13
+ * refresh token. Every refresh counts up the session's `refreshCount`, which the refresh token
14
+ * remembers, so a refresh token with an older count was already used. That means it was copied, and
15
+ * its session is logged out.
16
+ *
17
+ * The refresh operation uses it when it gets a refresh token. Plugins can also call it directly,
18
+ * since it needs nothing but the refresh token.
19
+ *
20
+ * @returns `null` when the refresh token is invalid, its session ended, it was reused, or its user
21
+ * is in the trash or not verified
22
+ */ export const redeemRefreshToken = async ({ collection, refreshToken, req })=>{
23
+ assertNoValidationWrite(req);
24
+ const contents = readRefreshToken({
25
+ refreshToken,
26
+ req
27
+ });
28
+ const collectionConfig = contents && req.payload.collections[contents.collection]?.config;
29
+ if (!contents || !collectionConfig || collection && collection !== contents.collection) {
30
+ return null;
31
+ }
32
+ const user = await req.payload.db.findOne({
33
+ collection: collectionConfig.slug,
34
+ req,
35
+ where: appendNonTrashedFilter({
36
+ enableTrash: Boolean(collectionConfig.trash),
37
+ trash: false,
38
+ where: {
39
+ id: {
40
+ equals: contents.userID
41
+ }
42
+ }
43
+ })
44
+ });
45
+ const session = removeExpiredSessions(user?.sessions ?? []).find(({ id })=>id === contents.sid);
46
+ // The JWT strategy wouldn't accept a token for a user who isn't verified
47
+ if (!user || !session || collectionConfig.auth.verify && !user._verified) {
48
+ return null;
49
+ }
50
+ const refreshCount = session.refreshCount ?? 0;
51
+ const refreshedAt = session.refreshedAt ? new Date(session.refreshedAt).getTime() : 0;
52
+ if (contents.refreshCount === refreshCount) {
53
+ // Refreshes at the same moment all save the same count, so their refresh tokens all stay current
54
+ session.refreshCount = refreshCount + 1;
55
+ session.refreshedAt = new Date();
56
+ // Saves the session with its new count, too
57
+ await extendSession({
58
+ collectionConfig,
59
+ req,
60
+ sessionExpiration: getRefreshTokenExpiration(collectionConfig),
61
+ sid: session.id,
62
+ user
63
+ });
64
+ } else if (contents.refreshCount !== refreshCount - 1 || Date.now() - refreshedAt >= reuseInterval) {
65
+ await revokeSession({
66
+ collectionConfig,
67
+ payload: req.payload,
68
+ req,
69
+ sid: session.id,
70
+ user
71
+ });
72
+ return null;
73
+ }
74
+ // Otherwise the client refreshed twice at once, and gets the current session again
75
+ const { exp, token } = await jwtSign({
76
+ fieldsToSign: getFieldsToSign({
77
+ collectionConfig,
78
+ email: user.email,
79
+ sid: session.id,
80
+ user
81
+ }),
82
+ secret: req.payload.secret,
83
+ tokenExpiration: collectionConfig.auth.tokenExpiration
84
+ });
85
+ return {
86
+ collectionConfig,
87
+ exp,
88
+ refreshToken: createRefreshToken({
89
+ collectionConfig,
90
+ req,
91
+ session,
92
+ userID: user.id
93
+ }),
94
+ token,
95
+ user
96
+ };
97
+ };
98
+ /** How many seconds a session with a refresh token lasts from each refresh. */ export const getRefreshTokenExpiration = (collectionConfig)=>collectionConfig.auth.refreshTokens ? collectionConfig.auth.refreshTokens.expiration : defaultRefreshTokenExpiration;
99
+ export const createRefreshToken = ({ collectionConfig, req, session, userID })=>req.payload.encrypt(JSON.stringify({
100
+ collection: collectionConfig.slug,
101
+ refreshCount: session.refreshCount ?? 0,
102
+ sid: session.id,
103
+ userID
104
+ }));
105
+ const readRefreshToken = ({ refreshToken, req })=>{
106
+ // Only the v1 format is authenticated. Older formats decrypt anything without an error.
107
+ if (!refreshToken.startsWith('v1:')) {
108
+ return undefined;
109
+ }
110
+ try {
111
+ // Only the current secret, since previous secrets can be public, like a default from source code
112
+ return JSON.parse(req.payload.decrypt(refreshToken, {
113
+ secret: req.payload.config.secret
114
+ }));
115
+ } catch {
116
+ return undefined;
117
+ }
118
+ };
119
+
120
+ //# sourceMappingURL=redeemRefreshToken.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/auth/redeemRefreshToken.ts"],"sourcesContent":["import type { SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { AuthenticatedUser, UserSession } from '../index.js'\nimport type { PayloadRequest } from '../types/index.js'\n\nimport { defaultRefreshTokenExpiration } from '../collections/config/defaults.js'\nimport { appendNonTrashedFilter } from '../utilities/appendNonTrashedFilter.js'\nimport { assertNoValidationWrite } from '../utilities/assertNoValidationWrite.js'\nimport { getFieldsToSign } from './getFieldsToSign.js'\nimport { jwtSign } from './jwt.js'\nimport { extendSession, removeExpiredSessions, revokeSession } from './sessions.js'\n\n/**\n * How long the refresh token from right before the latest refresh still works, in milliseconds.\n * Clients that send requests in parallel can refresh twice at once.\n */\nconst reuseInterval = 30 * 1000\n\n/** What a refresh token points to. It's encrypted, so clients can't read or change it. */\ntype RefreshTokenContents = {\n collection: string\n /** The session's `refreshCount` when the refresh token was created. */\n refreshCount: number\n sid: string\n userID: number | string\n}\n\n/**\n * Trades a refresh token from `createAuthToken` or an earlier refresh for a new token and a new\n * refresh token. Every refresh counts up the session's `refreshCount`, which the refresh token\n * remembers, so a refresh token with an older count was already used. That means it was copied, and\n * its session is logged out.\n *\n * The refresh operation uses it when it gets a refresh token. Plugins can also call it directly,\n * since it needs nothing but the refresh token.\n *\n * @returns `null` when the refresh token is invalid, its session ended, it was reused, or its user\n * is in the trash or not verified\n */\nexport const redeemRefreshToken = async ({\n collection,\n refreshToken,\n req,\n}: {\n /** Only accept refresh tokens of this collection. */\n collection?: string\n refreshToken: string\n req: PayloadRequest\n}): Promise<{\n collectionConfig: SanitizedCollectionConfig\n exp: number\n refreshToken: string\n token: string\n user: AuthenticatedUser\n} | null> => {\n assertNoValidationWrite(req)\n\n const contents = readRefreshToken({ refreshToken, req })\n const collectionConfig = contents && req.payload.collections[contents.collection]?.config\n\n if (!contents || !collectionConfig || (collection && collection !== contents.collection)) {\n return null\n }\n\n const user = await req.payload.db.findOne<AuthenticatedUser>({\n collection: collectionConfig.slug,\n req,\n where: appendNonTrashedFilter({\n enableTrash: Boolean(collectionConfig.trash),\n trash: false,\n where: { id: { equals: contents.userID } },\n }),\n })\n const session = removeExpiredSessions(user?.sessions ?? []).find(({ id }) => id === contents.sid)\n\n // The JWT strategy wouldn't accept a token for a user who isn't verified\n if (!user || !session || (collectionConfig.auth.verify && !user._verified)) {\n return null\n }\n\n const refreshCount = session.refreshCount ?? 0\n const refreshedAt = session.refreshedAt ? new Date(session.refreshedAt).getTime() : 0\n\n if (contents.refreshCount === refreshCount) {\n // Refreshes at the same moment all save the same count, so their refresh tokens all stay current\n session.refreshCount = refreshCount + 1\n session.refreshedAt = new Date()\n\n // Saves the session with its new count, too\n await extendSession({\n collectionConfig,\n req,\n sessionExpiration: getRefreshTokenExpiration(collectionConfig),\n sid: session.id,\n user,\n })\n } else if (\n contents.refreshCount !== refreshCount - 1 ||\n Date.now() - refreshedAt >= reuseInterval\n ) {\n await revokeSession({ collectionConfig, payload: req.payload, req, sid: session.id, user })\n\n return null\n }\n // Otherwise the client refreshed twice at once, and gets the current session again\n\n const { exp, token } = await jwtSign({\n fieldsToSign: getFieldsToSign({ collectionConfig, email: user.email!, sid: session.id, user }),\n secret: req.payload.secret,\n tokenExpiration: collectionConfig.auth.tokenExpiration,\n })\n\n return {\n collectionConfig,\n exp,\n refreshToken: createRefreshToken({ collectionConfig, req, session, userID: user.id }),\n token,\n user,\n }\n}\n\n/** How many seconds a session with a refresh token lasts from each refresh. */\nexport const getRefreshTokenExpiration = (collectionConfig: SanitizedCollectionConfig): number =>\n collectionConfig.auth.refreshTokens\n ? collectionConfig.auth.refreshTokens.expiration\n : defaultRefreshTokenExpiration\n\nexport const createRefreshToken = ({\n collectionConfig,\n req,\n session,\n userID,\n}: {\n collectionConfig: SanitizedCollectionConfig\n req: PayloadRequest\n session: UserSession\n userID: number | string\n}): string =>\n req.payload.encrypt(\n JSON.stringify({\n collection: collectionConfig.slug,\n refreshCount: session.refreshCount ?? 0,\n sid: session.id,\n userID,\n } satisfies RefreshTokenContents),\n )\n\nconst readRefreshToken = ({\n refreshToken,\n req,\n}: {\n refreshToken: string\n req: PayloadRequest\n}): RefreshTokenContents | undefined => {\n // Only the v1 format is authenticated. Older formats decrypt anything without an error.\n if (!refreshToken.startsWith('v1:')) {\n return undefined\n }\n\n try {\n // Only the current secret, since previous secrets can be public, like a default from source code\n return JSON.parse(req.payload.decrypt(refreshToken, { secret: req.payload.config.secret }))\n } catch {\n return undefined\n }\n}\n"],"names":["defaultRefreshTokenExpiration","appendNonTrashedFilter","assertNoValidationWrite","getFieldsToSign","jwtSign","extendSession","removeExpiredSessions","revokeSession","reuseInterval","redeemRefreshToken","collection","refreshToken","req","contents","readRefreshToken","collectionConfig","payload","collections","config","user","db","findOne","slug","where","enableTrash","Boolean","trash","id","equals","userID","session","sessions","find","sid","auth","verify","_verified","refreshCount","refreshedAt","Date","getTime","sessionExpiration","getRefreshTokenExpiration","now","exp","token","fieldsToSign","email","secret","tokenExpiration","createRefreshToken","refreshTokens","expiration","encrypt","JSON","stringify","startsWith","undefined","parse","decrypt"],"mappings":"AAIA,SAASA,6BAA6B,QAAQ,oCAAmC;AACjF,SAASC,sBAAsB,QAAQ,yCAAwC;AAC/E,SAASC,uBAAuB,QAAQ,0CAAyC;AACjF,SAASC,eAAe,QAAQ,uBAAsB;AACtD,SAASC,OAAO,QAAQ,WAAU;AAClC,SAASC,aAAa,EAAEC,qBAAqB,EAAEC,aAAa,QAAQ,gBAAe;AAEnF;;;CAGC,GACD,MAAMC,gBAAgB,KAAK;AAW3B;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,qBAAqB,OAAO,EACvCC,UAAU,EACVC,YAAY,EACZC,GAAG,EAMJ;IAOCV,wBAAwBU;IAExB,MAAMC,WAAWC,iBAAiB;QAAEH;QAAcC;IAAI;IACtD,MAAMG,mBAAmBF,YAAYD,IAAII,OAAO,CAACC,WAAW,CAACJ,SAASH,UAAU,CAAC,EAAEQ;IAEnF,IAAI,CAACL,YAAY,CAACE,oBAAqBL,cAAcA,eAAeG,SAASH,UAAU,EAAG;QACxF,OAAO;IACT;IAEA,MAAMS,OAAO,MAAMP,IAAII,OAAO,CAACI,EAAE,CAACC,OAAO,CAAoB;QAC3DX,YAAYK,iBAAiBO,IAAI;QACjCV;QACAW,OAAOtB,uBAAuB;YAC5BuB,aAAaC,QAAQV,iBAAiBW,KAAK;YAC3CA,OAAO;YACPH,OAAO;gBAAEI,IAAI;oBAAEC,QAAQf,SAASgB,MAAM;gBAAC;YAAE;QAC3C;IACF;IACA,MAAMC,UAAUxB,sBAAsBa,MAAMY,YAAY,EAAE,E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E,OAAO,MAAMuB,4BAA4B,CAAC3B,mBACxCA,iBAAiBmB,IAAI,CAACiB,aAAa,GAC/BpC,iBAAiBmB,IAAI,CAACiB,aAAa,CAACC,UAAU,GAC9CpD,8BAA6B;AAEnC,OAAO,MAAMkD,qBAAqB,CAAC,EACjCnC,gBAAgB,EAChBH,GAAG,EACHkB,OAAO,EACPD,MAAM,EAMP,GACCjB,IAAII,OAAO,CAACqC,OAAO,CACjBC,KAAKC,SAAS,CAAC;QACb7C,YAAYK,iBAAiBO,IAAI;QACjCe,cAAcP,QAAQO,YAAY,IAAI;QACtCJ,KAAKH,QAAQH,EAAE;QACfE;IACF,IACD;AAEH,MAAMf,mBAAmB,CAAC,EACxBH,YAAY,EACZC,GAAG,EAIJ;IACC,wFAAwF;IACxF,IAAI,CAACD,aAAa6C,UAAU,CAAC,QAAQ;QACnC,OAAOC;IACT;IAEA,IAAI;QACF,iGAAiG;QACjG,OAAOH,KAAKI,KAAK,CAAC9C,IAAII,OAAO,CAAC2C,OAAO,CAAChD,cAAc;YAAEqC,QAAQpC,IAAII,OAAO,CAACE,MAAM,CAAC8B,MAAM;QAAC;IAC1F,EAAE,OAAM;QACN,OAAOS;IACT;AACF"}
@@ -7,16 +7,42 @@ import type { Payload, PayloadRequest } from '../types/index.js';
7
7
  export declare const removeExpiredSessions: (sessions: UserSession[]) => UserSession[];
8
8
  /**
9
9
  * Adds a session to the user and removes expired sessions
10
- * @returns The session ID (sid) if sessions are used
10
+ * @returns The session and its ID (sid) if sessions are used
11
11
  */
12
- export declare const addSessionToUser: ({ collectionConfig, payload, req, user, }: {
12
+ export declare const addSessionToUser: ({ collectionConfig, payload, req, sessionExpiration, user, }: {
13
13
  collectionConfig: SanitizedCollectionConfig;
14
14
  payload: Payload;
15
15
  req: PayloadRequest;
16
+ /**
17
+ * Seconds until the session expires.
18
+ *
19
+ * @default collectionConfig.auth.tokenExpiration
20
+ */
21
+ sessionExpiration?: number;
16
22
  user: AuthenticatedUser;
17
23
  }) => Promise<{
24
+ session?: UserSession;
18
25
  sid?: string;
19
26
  }>;
27
+ /**
28
+ * Extends the session `sid` so it lasts at least another `sessionExpiration`. Sessions that already
29
+ * last longer, like ones with a refresh token, keep their expiry, since their refresh token relies
30
+ * on it.
31
+ *
32
+ * @returns The session, or `undefined` when the user has no session with this ID
33
+ */
34
+ export declare const extendSession: ({ collectionConfig, req, sessionExpiration, sid, user, }: {
35
+ collectionConfig: SanitizedCollectionConfig;
36
+ req: PayloadRequest;
37
+ /**
38
+ * Seconds the session lasts at least, from now.
39
+ *
40
+ * @default collectionConfig.auth.tokenExpiration
41
+ */
42
+ sessionExpiration?: number;
43
+ sid: string;
44
+ user: AuthenticatedUser;
45
+ }) => Promise<undefined | UserSession>;
20
46
  export declare const revokeSession: ({ collectionConfig, payload, req, sid, user, }: {
21
47
  collectionConfig: SanitizedCollectionConfig;
22
48
  payload: Payload;
@@ -1 +1 @@
1
- {"version":3,"file":"sessions.d.ts","sourceRoot":"","sources":["../../src/auth/sessions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAA;AAC/E,OAAO,KAAK,EAAE,iBAAiB,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACvE,OAAO,KAAK,EAAE,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAA;AAIhE;;GAEG;AACH,eAAO,MAAM,qBAAqB,aAAc,WAAW,EAAE,KAAG,WAAW,EAO1E,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,gBAAgB,8CAK1B;IACD,gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,OAAO,EAAE,OAAO,CAAA;IAChB,GAAG,EAAE,cAAc,CAAA;IACnB,IAAI,EAAE,iBAAiB,CAAA;CACxB,KAAG,OAAO,CAAC;IAAE,GAAG,CAAC,EAAE,MAAM,CAAA;CAAE,CAuC3B,CAAA;AAED,eAAO,MAAM,aAAa,mDAMvB;IACD,gBAAg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gBAAgB,EAAE,yBAAyB,CAAA;IAC3C,OAAO,EAAE,OAAO,CAAA;IAChB,GAAG,EAAE,cAAc,CAAA;IACnB,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,IAAI,GAAG,IAAI,CAAA;CAClB,KAAG,OAAO,CAAC,IAAI,CAaf,CAAA"}
@@ -11,17 +11,17 @@ import { assertNoValidationWrite } from '../utilities/assertNoValidationWrite.js
11
11
  };
12
12
  /**
13
13
  * Adds a session to the user and removes expired sessions
14
- * @returns The session ID (sid) if sessions are used
15
- */ export const addSessionToUser = async ({ collectionConfig, payload, req, user })=>{
14
+ * @returns The session and its ID (sid) if sessions are used
15
+ */ export const addSessionToUser = async ({ collectionConfig, payload, req, sessionExpiration = collectionConfig.auth.tokenExpiration, user })=>{
16
16
  assertNoValidationWrite(req);
17
+ let session;
17
18
  let sid;
18
19
  if (collectionConfig.auth.useSessions) {
19
20
  // Add session to user
20
21
  sid = uuid();
21
22
  const now = new Date();
22
- const tokenExpInMs = collectionConfig.auth.tokenExpiration * 1000;
23
- const expiresAt = new Date(now.getTime() + tokenExpInMs);
24
- const session = {
23
+ const expiresAt = new Date(now.getTime() + sessionExpiration * 1000);
24
+ session = {
25
25
  id: sid,
26
26
  createdAt: now,
27
27
  expiresAt
@@ -49,9 +49,40 @@ import { assertNoValidationWrite } from '../utilities/assertNoValidationWrite.js
49
49
  user._strategy = 'local-jwt';
50
50
  }
51
51
  return {
52
+ session,
52
53
  sid
53
54
  };
54
55
  };
56
+ /**
57
+ * Extends the session `sid` so it lasts at least another `sessionExpiration`. Sessions that already
58
+ * last longer, like ones with a refresh token, keep their expiry, since their refresh token relies
59
+ * on it.
60
+ *
61
+ * @returns The session, or `undefined` when the user has no session with this ID
62
+ */ export const extendSession = async ({ collectionConfig, req, sessionExpiration = collectionConfig.auth.tokenExpiration, sid, user })=>{
63
+ assertNoValidationWrite(req);
64
+ const session = user.sessions?.find(({ id })=>id === sid);
65
+ if (!session) {
66
+ return undefined;
67
+ }
68
+ const expiresAt = new Date(Date.now() + sessionExpiration * 1000);
69
+ if (new Date(session.expiresAt) < expiresAt) {
70
+ session.expiresAt = expiresAt;
71
+ }
72
+ await req.payload.db.updateOne({
73
+ id: user.id,
74
+ collection: collectionConfig.slug,
75
+ data: {
76
+ ...user,
77
+ // Prevent updatedAt from being updated when only extending a session
78
+ sessions: removeExpiredSessions(user.sessions),
79
+ updatedAt: null
80
+ },
81
+ req,
82
+ returning: false
83
+ });
84
+ return session;
85
+ };
55
86
  export const revokeSession = async ({ collectionConfig, payload, req, sid, user })=>{
56
87
  assertNoValidationWrite(req);
57
88
  if (collectionConfig.auth.useSessions && user && user.sessions?.length) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/auth/sessions.ts"],"sourcesContent":["import { v4 as uuid } from 'uuid'\n\nimport type { SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { AuthenticatedUser, User, UserSession } from '../index.js'\nimport type { Payload, PayloadRequest } from '../types/index.js'\n\nimport { assertNoValidationWrite } from '../utilities/assertNoValidationWrite.js'\n\n/**\n * Removes expired sessions from an array of sessions\n */\nexport const removeExpiredSessions = (sessions: UserSession[]): UserSession[] => {\n const now = new Date()\n\n return sessions.filter(({ expiresAt }) => {\n const expiry = expiresAt instanceof Date ? expiresAt : new Date(expiresAt)\n return expiry > now\n })\n}\n\n/**\n * Adds a session to the user and removes expired sessions\n * @returns The session ID (sid) if sessions are used\n */\nexport const addSessionToUser = async ({\n collectionConfig,\n payload,\n req,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n payload: Payload\n req: PayloadRequest\n user: AuthenticatedUser\n}): Promise<{ sid?: string }> => {\n assertNoValidationWrite(req)\n\n let sid: string | undefined\n if (collectionConfig.auth.useSessions) {\n // Add session to user\n sid = uuid()\n const now = new Date()\n const tokenExpInMs = collectionConfig.auth.tokenExpiration * 1000\n const expiresAt = new Date(now.getTime() + tokenExpInMs)\n\n const session = { id: sid, createdAt: now, expiresAt }\n\n if (!user.sessions?.length) {\n user.sessions = [session]\n } else {\n user.sessions = removeExpiredSessions(user.sessions)\n user.sessions.push(session)\n }\n\n await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: {\n ...user,\n // Prevent updatedAt from being updated when only adding a session\n updatedAt: null,\n },\n req,\n returning: false,\n })\n\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n }\n\n return {\n sid,\n }\n}\n\nexport const revokeSession = async ({\n collectionConfig,\n payload,\n req,\n sid,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n payload: Payload\n req: PayloadRequest\n sid: string\n user: null | User\n}): Promise<void> => {\n assertNoValidationWrite(req)\n\n if (collectionConfig.auth.useSessions && user && user.sessions?.length) {\n user.sessions = user.sessions.filter((session) => session.id !== sid)\n await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: user,\n req,\n returning: false,\n })\n }\n}\n"],"names":["v4","uuid","assertNoValidationWrite","removeExpiredSessions","sessions","now","Date","filter","expiresAt","expiry","addSessionToUser","collectionConfig","payload","req","user","sid","auth","useSessions","tokenExpInMs","tokenExpiration","getTime","session","id","createdAt","length","push","db","updateOne","collection","slug","data","updatedAt","returning","_strategy","revokeSession"],"mappings":"AAAA,SAASA,MAAMC,IAAI,QAAQ,OAAM;AAMjC,SAASC,uBAAuB,QAAQ,0CAAyC;AAEjF;;CAEC,GACD,OAAO,MAAMC,wBAAwB,CAACC;IACpC,MAAMC,MAAM,IAAIC;IAEhB,OAAOF,SAASG,MAAM,CAAC,CAAC,EAAEC,SAAS,EAAE;QACnC,MAAMC,SAASD,qBAAqBF,OAAOE,YAAY,IAAIF,KAAKE;QAChE,OAAOC,SAASJ;IAClB;AACF,EAAC;AAED;;;CAGC,GACD,OAAO,MAAMK,mBAAmB,OAAO,EACrCC,gBAAgB,EAChBC,OAAO,EACPC,GAAG,EACHC,IAAI,EAML;IACCZ,wBAAwBW;IAExB,IAAIE;IACJ,IAAIJ,iBAAiBK,IAAI,CAACC,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"version":3,"sources":["../../src/auth/sessions.ts"],"sourcesContent":["import { v4 as uuid } from 'uuid'\n\nimport type { SanitizedCollectionConfig } from '../collections/config/types.js'\nimport type { AuthenticatedUser, User, UserSession } from '../index.js'\nimport type { Payload, PayloadRequest } from '../types/index.js'\n\nimport { assertNoValidationWrite } from '../utilities/assertNoValidationWrite.js'\n\n/**\n * Removes expired sessions from an array of sessions\n */\nexport const removeExpiredSessions = (sessions: UserSession[]): UserSession[] => {\n const now = new Date()\n\n return sessions.filter(({ expiresAt }) => {\n const expiry = expiresAt instanceof Date ? expiresAt : new Date(expiresAt)\n return expiry > now\n })\n}\n\n/**\n * Adds a session to the user and removes expired sessions\n * @returns The session and its ID (sid) if sessions are used\n */\nexport const addSessionToUser = async ({\n collectionConfig,\n payload,\n req,\n sessionExpiration = collectionConfig.auth.tokenExpiration,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n payload: Payload\n req: PayloadRequest\n /**\n * Seconds until the session expires.\n *\n * @default collectionConfig.auth.tokenExpiration\n */\n sessionExpiration?: number\n user: AuthenticatedUser\n}): Promise<{ session?: UserSession; sid?: string }> => {\n assertNoValidationWrite(req)\n\n let session: undefined | UserSession\n let sid: string | undefined\n if (collectionConfig.auth.useSessions) {\n // Add session to user\n sid = uuid()\n const now = new Date()\n const expiresAt = new Date(now.getTime() + sessionExpiration * 1000)\n\n session = { id: sid, createdAt: now, expiresAt }\n\n if (!user.sessions?.length) {\n user.sessions = [session]\n } else {\n user.sessions = removeExpiredSessions(user.sessions)\n user.sessions.push(session)\n }\n\n await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: {\n ...user,\n // Prevent updatedAt from being updated when only adding a session\n updatedAt: null,\n },\n req,\n returning: false,\n })\n\n user.collection = collectionConfig.slug\n user._strategy = 'local-jwt'\n }\n\n return {\n session,\n sid,\n }\n}\n\n/**\n * Extends the session `sid` so it lasts at least another `sessionExpiration`. Sessions that already\n * last longer, like ones with a refresh token, keep their expiry, since their refresh token relies\n * on it.\n *\n * @returns The session, or `undefined` when the user has no session with this ID\n */\nexport const extendSession = async ({\n collectionConfig,\n req,\n sessionExpiration = collectionConfig.auth.tokenExpiration,\n sid,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n req: PayloadRequest\n /**\n * Seconds the session lasts at least, from now.\n *\n * @default collectionConfig.auth.tokenExpiration\n */\n sessionExpiration?: number\n sid: string\n user: AuthenticatedUser\n}): Promise<undefined | UserSession> => {\n assertNoValidationWrite(req)\n\n const session = user.sessions?.find(({ id }) => id === sid)\n\n if (!session) {\n return undefined\n }\n\n const expiresAt = new Date(Date.now() + sessionExpiration * 1000)\n\n if (new Date(session.expiresAt) < expiresAt) {\n session.expiresAt = expiresAt\n }\n\n await req.payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: {\n ...user,\n // Prevent updatedAt from being updated when only extending a session\n sessions: removeExpiredSessions(user.sessions!),\n updatedAt: null,\n },\n req,\n returning: false,\n })\n\n return session\n}\n\nexport const revokeSession = async ({\n collectionConfig,\n payload,\n req,\n sid,\n user,\n}: {\n collectionConfig: SanitizedCollectionConfig\n payload: Payload\n req: PayloadRequest\n sid: string\n user: null | User\n}): Promise<void> => {\n assertNoValidationWrite(req)\n\n if (collectionConfig.auth.useSessions && user && user.sessions?.length) {\n user.sessions = user.sessions.filter((session) => session.id !== sid)\n await payload.db.updateOne({\n id: user.id,\n collection: collectionConfig.slug,\n data: user,\n req,\n returning: false,\n })\n }\n}\n"],"names":["v4","uuid","assertNoValidationWrite","removeExpiredSessions","sessions","now","Date","filter","expiresAt","expiry","addSessionToUser","collectionConfig","payload","req","sessionExpiration","auth","tokenExpiration","user","session","sid","useSessions","getTime","id","createdAt","length","push","db","updateOne","collection","slug","data","updatedAt","returning","_strategy","extendSession","find","undefined","revokeSession"],"mappings":"AAAA,SAASA,MAAMC,IAAI,QAAQ,OAAM;AAMjC,SAASC,uBAAuB,QAAQ,0CAAyC;AAEjF;;CAEC,GACD,OAAO,MA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iBI,IAAI,CAACC,eAAe,EACzDG,GAAG,EACHF,IAAI,EAYL;IACCf,wBAAwBW;IAExB,MAAMK,UAAUD,KAAKb,QAAQ,EAAE+B,KAAK,CAAC,EAAEb,EAAE,EAAE,GAAKA,OAAOH;IAEvD,IAAI,CAACD,SAAS;QACZ,OAAOkB;IACT;IAEA,MAAM5B,YAAY,IAAIF,KAAKA,KAAKD,GAAG,KAAKS,oBAAoB;IAE5D,IAAI,IAAIR,KAAKY,QAAQV,SAAS,IAAIA,WAAW;QAC3CU,QAAQV,SAAS,GAAGA;IACtB;IAEA,MAAMK,IAAID,OAAO,CAACc,EAAE,CAACC,SAAS,CAAC;QAC7BL,IAAIL,KAAKK,EAAE;QACXM,YAAYjB,iBAAiBkB,IAAI;QACjCC,MAAM;YACJ,GAAGb,IAAI;YACP,qEAAqE;YACrEb,UAAUD,sBAAsBc,KAAKb,QAAQ;YAC7C2B,WAAW;QACb;QACAlB;QACAmB,WAAW;IACb;IAEA,OAAOd;AACT,EAAC;AAED,OAAO,MAAMmB,gBAAgB,OAAO,EAClC1B,gBAAgB,EAChBC,OAAO,EACPC,GAAG,EACHM,GAAG,EACHF,IAAI,EAOL;IACCf,wBAAwBW;IAExB,IAAIF,iBAAiBI,IAAI,CAACK,WAAW,IAAIH,QAAQA,KAAKb,QAAQ,EAAEoB,QAAQ;QACtEP,KAAKb,QAAQ,GAAGa,KAAKb,QAAQ,CAACG,MAAM,CAAC,CAACW,UAAYA,QAAQI,EAAE,KAAKH;QACjE,MAAMP,QAAQc,EAAE,CAACC,SAAS,CAAC;YACzBL,IAAIL,KAAKK,EAAE;YACXM,YAAYjB,iBAAiBkB,IAAI;YACjCC,MAAMb;YACNJ;YACAmB,WAAW;QACb;IACF;AACF,EAAC"}
@@ -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,4 +1,5 @@
1
1
  import type { SanitizedCollectionConfig } from '../../../collections/config/types.js';
2
+ import type { SanitizedConfig } from '../../../config/types.js';
2
3
  import type { PayloadRequest } from '../../../types/index.js';
3
4
  type PasswordHashParameters = {
4
5
  hash: string;
@@ -11,11 +12,23 @@ type Args = {
11
12
  password: string;
12
13
  req: PayloadRequest;
13
14
  };
15
+ type PasswordHashIterations = SanitizedConfig['auth']['passwordHashIterations'];
16
+ export declare const supportedPasswordHashIterations: number[];
14
17
  export declare const generatePasswordSaltHash: ({ collection, isPasswordAuthenticated, password: passwordToSet, req, }: Args) => Promise<{
15
18
  hash: string;
16
19
  salt: string;
17
20
  }>;
18
21
  export declare const getPasswordHashParameters: (hash: string) => PasswordHashParameters;
19
- export declare const isCurrentPasswordHash: (hash: unknown) => hash is string;
22
+ export declare const isCurrentPasswordHash: ({ hash, passwordHashIterations, }: {
23
+ hash: string;
24
+ passwordHashIterations: PasswordHashIterations;
25
+ }) => boolean;
26
+ export declare const isUnsupportedIterationsError: (err: unknown) => boolean;
27
+ export declare function pbkdf2Promisified({ iterations, keyLength, password, salt, }: {
28
+ iterations: number;
29
+ keyLength: number;
30
+ password: string;
31
+ salt: string;
32
+ }): Promise<Buffer>;
20
33
  export {};
21
34
  //# sourceMappingURL=generatePasswordSaltHash.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"generatePasswordSaltHash.d.ts","sourceRoot":"","sources":["../../../../src/auth/strategies/local/generatePasswordSaltHash.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAA;AACrF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAK7D,KAAK,sBAAsB,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAA;IACZ,UAAU,EAAE,MAAM,CAAA;IAClB,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,KAAK,IAAI,GAAG;IACV,UAAU,EAAE,yBAAyB,CAAA;IACrC,uBAAuB,CAAC,EAAE,OAAO,CAAA;IACjC,QAAQ,EAAE,MAAM,CAAA;IAChB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAQD,eAAO,MAAM,wBAAwB,2EAKlC,IAAI,KAAG,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAmC/C,CAAA;AAED,eAAO,MAAM,yBAAyB,SAAU,MAAM,KAAG,sBAcxD,CAAA;AAED,eAAO,MAAM,qBAAqB,SAAU,OAAO,KAAG,IAAI,IAAI,MACU,CAAA"}
1
+ {"version":3,"file":"generatePasswordSaltHash.d.ts","sourceRoot":"","sources":["../../../../src/auth/strategies/local/generatePasswordSaltHash.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,sCAAsC,CAAA;AACrF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAA;AAC/D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAA;AAK7D,KAAK,sBAAsB,GAAG;IAC5B,IAAI,EAAE,MAAM,CAAA;IACZ,UAAU,EAAE,MAAM,CAAA;IAClB,SAAS,EAAE,MAAM,CAAA;CAClB,CAAA;AAED,KAAK,IAAI,GAAG;IACV,UAAU,EAAE,yBAAyB,CAAA;IACrC,uBAAuB,CAAC,EAAE,OAAO,CAAA;IACjC,QAAQ,EAAE,MAAM,CAAA;IAChB,GAAG,EAAE,cAAc,CAAA;CACpB,CAAA;AAED,KAAK,sBAAsB,GAAG,eAAe,CAAC,MAAM,CAAC,CAAC,wBAAwB,CAAC,CAAA;AAQ/E,eAAO,MAAM,+BAA+B,UAAgD,CAAA;AAK5F,eAAO,MAAM,wBAAwB,2EAKlC,IAAI,KAAG,OAAO,CAAC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAiD/C,CAAA;AAED,eAAO,MAAM,yBAAyB,SAAU,MAAM,KAAG,sBAgBxD,CAAA;AAED,eAAO,MAAM,qBAAqB,sCAG/B;IACD,IAAI,EAAE,MAAM,CAAA;IACZ,sBAAsB,EAAE,sBAAsB,CAAA;CAC/C,KAAG,OAAwE,CAAA;AAS5E,eAAO,MAAM,4BAA4B,QAAS,OAAO,KAAG,OACF,CAAA;AAE1D,wBAAgB,iBAAiB,CAAC,EAChC,UAAU,EACV,SAAS,EACT,QAAQ,EACR,IAAI,GACL,EAAE;IACD,UAAU,EAAE,MAAM,CAAA;IAClB,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAA;IAChB,IAAI,EAAE,MAAM,CAAA;CACb,GAAG,OAAO,CAAC,MAAM,CAAC,CAMlB"}
@@ -1,9 +1,14 @@
1
1
  import crypto from 'crypto';
2
- import { ValidationError } from '../../../errors/index.js';
2
+ import { InvalidConfiguration, ValidationError } from '../../../errors/index.js';
3
3
  import { password } from '../../../fields/validations.js';
4
- const currentPasswordHashPrefix = 'pbkdf2-sha256-v1:';
5
- const currentPasswordHashIterations = 600000;
6
- const currentPasswordHashKeyLength = 32;
4
+ // Each supported iteration count has its own fixed prefix, so a stored hash
5
+ // can be verified whichever count is configured
6
+ const passwordHashPrefixes = {
7
+ 100000: 'pbkdf2-sha256-100k-v1:',
8
+ 600000: 'pbkdf2-sha256-v1:'
9
+ };
10
+ export const supportedPasswordHashIterations = Object.keys(passwordHashPrefixes).map(Number);
11
+ const passwordHashKeyLength = 32;
7
12
  const legacyPasswordHashIterations = 25000;
8
13
  const legacyPasswordHashKeyLength = 512;
9
14
  export const generatePasswordSaltHash = async ({ collection, isPasswordAuthenticated, password: passwordToSet, req })=>{
@@ -36,27 +41,36 @@ export const generatePasswordSaltHash = async ({ collection, isPasswordAuthentic
36
41
  });
37
42
  }
38
43
  }
44
+ const { passwordHashIterations } = req.payload.config.auth;
39
45
  const saltBuffer = await randomBytes();
40
46
  const salt = saltBuffer.toString('hex');
41
47
  const hashRaw = await pbkdf2Promisified({
42
- iterations: currentPasswordHashIterations,
43
- keyLength: currentPasswordHashKeyLength,
48
+ iterations: passwordHashIterations,
49
+ keyLength: passwordHashKeyLength,
44
50
  password: passwordToSet,
45
51
  salt
52
+ }).catch((err)=>{
53
+ if (isUnsupportedIterationsError(err)) {
54
+ const configHint = passwordHashIterations === 100000 ? '' : ' Set `auth.passwordHashIterations` to 100000 in your Payload Config.';
55
+ throw new InvalidConfiguration(`This environment does not support ${passwordHashIterations} PBKDF2 iterations for password hashing.${configHint}`);
56
+ }
57
+ throw err;
46
58
  });
47
- const hash = `${currentPasswordHashPrefix}${hashRaw.toString('hex')}`;
59
+ const hash = `${passwordHashPrefixes[passwordHashIterations]}${hashRaw.toString('hex')}`;
48
60
  return {
49
61
  hash,
50
62
  salt
51
63
  };
52
64
  };
53
65
  export const getPasswordHashParameters = (hash)=>{
54
- if (isCurrentPasswordHash(hash)) {
55
- return {
56
- hash: hash.slice(currentPasswordHashPrefix.length),
57
- iterations: currentPasswordHashIterations,
58
- keyLength: currentPasswordHashKeyLength
59
- };
66
+ for (const [iterations, prefix] of Object.entries(passwordHashPrefixes)){
67
+ if (hash.startsWith(prefix)) {
68
+ return {
69
+ hash: hash.slice(prefix.length),
70
+ iterations: Number(iterations),
71
+ keyLength: passwordHashKeyLength
72
+ };
73
+ }
60
74
  }
61
75
  return {
62
76
  hash,
@@ -64,11 +78,13 @@ export const getPasswordHashParameters = (hash)=>{
64
78
  keyLength: legacyPasswordHashKeyLength
65
79
  };
66
80
  };
67
- export const isCurrentPasswordHash = (hash)=>typeof hash === 'string' && hash.startsWith(currentPasswordHashPrefix);
81
+ export const isCurrentPasswordHash = ({ hash, passwordHashIterations })=>hash.startsWith(passwordHashPrefixes[passwordHashIterations]);
68
82
  function randomBytes() {
69
83
  return new Promise((resolve, reject)=>crypto.randomBytes(32, (err, saltBuffer)=>err ? reject(err) : resolve(saltBuffer)));
70
84
  }
71
- function pbkdf2Promisified({ iterations, keyLength, password, salt }) {
85
+ // Environments such as Cloudflare Workers reject iteration counts above their limit
86
+ export const isUnsupportedIterationsError = (err)=>err instanceof Error && err.name === 'NotSupportedError';
87
+ export function pbkdf2Promisified({ iterations, keyLength, password, salt }) {
72
88
  return new Promise((resolve, reject)=>crypto.pbkdf2(password, salt, iterations, keyLength, 'sha256', (err, hashRaw)=>err ? reject(err) : resolve(hashRaw)));
73
89
  }
74
90
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/auth/strategies/local/generatePasswordSaltHash.ts"],"sourcesContent":["import crypto from 'crypto'\n\nimport type { SanitizedCollectionConfig } from '../../../collections/config/types.js'\nimport type { PayloadRequest } from '../../../types/index.js'\n\nimport { ValidationError } from '../../../errors/index.js'\nimport { password } from '../../../fields/validations.js'\n\ntype PasswordHashParameters = {\n hash: string\n iterations: number\n keyLength: number\n}\n\ntype Args = {\n collection: SanitizedCollectionConfig\n isPasswordAuthenticated?: boolean\n password: string\n req: PayloadRequest\n}\n\nconst currentPasswordHashPrefix = 'pbkdf2-sha256-v1:'\nconst currentPasswordHashIterations = 600000\nconst currentPasswordHashKeyLength = 32\nconst legacyPasswordHashIterations = 25000\nconst legacyPasswordHashKeyLength = 512\n\nexport const generatePasswordSaltHash = async ({\n collection,\n isPasswordAuthenticated,\n password: passwordToSet,\n req,\n}: Args): Promise<{ hash: string; salt: string }> => {\n if (!isPasswordAuthenticated) {\n const validationResult = password(passwordToSet, {\n name: 'password',\n type: 'text',\n blockData: {},\n data: {},\n event: 'submit',\n path: ['password'],\n preferences: { fields: {} },\n req,\n required: true,\n siblingData: {},\n })\n\n if (typeof validationResult === 'string') {\n throw new ValidationError({\n collection: collection?.slug,\n errors: [{ message: validationResult, path: 'password' }],\n })\n }\n }\n\n const saltBuffer = await randomBytes()\n const salt = saltBuffer.toString('hex')\n\n const hashRaw = await pbkdf2Promisified({\n iterations: currentPasswordHashIterations,\n keyLength: currentPasswordHashKeyLength,\n password: passwordToSet,\n salt,\n })\n const hash = `${currentPasswordHashPrefix}${hashRaw.toString('hex')}`\n\n return { hash, salt }\n}\n\nexport const getPasswordHashParameters = (hash: string): PasswordHashParameters => {\n if (isCurrentPasswordHash(hash)) {\n return {\n hash: hash.slice(currentPasswordHashPrefix.length),\n iterations: currentPasswordHashIterations,\n keyLength: currentPasswordHashKeyLength,\n }\n }\n\n return {\n hash,\n iterations: legacyPasswordHashIterations,\n keyLength: legacyPasswordHashKeyLength,\n }\n}\n\nexport const isCurrentPasswordHash = (hash: unknown): hash is string =>\n typeof hash === 'string' && hash.startsWith(currentPasswordHashPrefix)\n\nfunction randomBytes(): Promise<Buffer> {\n return new Promise((resolve, reject) =>\n crypto.randomBytes(32, (err, saltBuffer) => (err ? reject(err) : resolve(saltBuffer))),\n )\n}\n\nfunction pbkdf2Promisified({\n iterations,\n keyLength,\n password,\n salt,\n}: {\n iterations: number\n keyLength: number\n password: string\n salt: string\n}): Promise<Buffer> {\n return new Promise((resolve, reject) =>\n crypto.pbkdf2(password, salt, iterations, keyLength, 'sha256', (err, hashRaw) =>\n err ? reject(err) : resolve(hashRaw),\n ),\n )\n}\n"],"names":["crypto","ValidationError","password","currentPasswordHashPrefix","currentPasswordHashIterations","currentPasswordHashKeyLength","legacyPasswordHashIterations","legacyPasswordHashKeyLength","generatePasswordSaltHash","collection","isPasswordAuthenticated","passwordToSet","req","validationResult","name","type","blockData","data","event","path","preferences","fields","required","siblingData","slug","errors","message","saltBuffer","randomBytes","salt","toString","hashRaw","pbkdf2Promisified","iterations","keyLength","hash","getPasswordHashParameters","isCurrentPasswordHash","slice","length","startsWith","Promise","resolve","reject","err","pbkdf2"],"mappings":"AAAA,OAAOA,YAAY,SAAQ;AAK3B,SAASC,eAAe,QAAQ,2BAA0B;AAC1D,SAASC,QAAQ,QAAQ,iCAAgC;AAezD,MAAMC,4BAA4B;AAClC,MAAMC,gCAAgC;AACtC,MAAMC,+BAA+B;AACrC,MAAMC,+BAA+B;AACrC,MAAMC,8BAA8B;AAEpC,OAAO,MAAMC,2BAA2B,OAAO,EAC7CC,UAAU,EACVC,uBAAuB,EACvBR,UAAUS,aAAa,EACvBC,GAAG,EACE;IACL,IAAI,CAACF,yBAAyB;QAC5B,MAAMG,mBAAmBX,SAASS,eAAe;YAC/CG,MAAM;YACNC,MAAM;YACNC,WAAW,CAAC;YACZC,MAAM,CAAC;YACPC,OAAO;YACPC,MAAM;gBAAC;aAAW;YAClBC,aAAa;gBAAEC,QAAQ,CAAC;YAAE;YAC1BT;YACAU,UAAU;YACVC,aAAa,CAAC;QAChB;QAEA,IAAI,OAAOV,qBAAqB,UAAU;YACxC,MAAM,IAAIZ,gBAAgB;gBACxBQ,YAAYA,YAAYe;gBACxBC,QAAQ;oBAAC;wBAAEC,SAASb;wBAAkBM,MAAM;oBAAW;iBAAE;YAC3D;QACF;IACF;IAEA,MAAMQ,aAAa,MAAMC;IACzB,MAAMC,OAAOF,WAAWG,QAAQ,CAAC;IAEjC,MAAMC,UAAU,MAAMC,kBAAkB;QACtCC,YAAY7B;QACZ8B,WAAW7B;QACXH,UAAUS;QACVkB;IACF;IACA,MAAMM,OAAO,GAAGhC,4BAA4B4B,QAAQD,QAAQ,CAAC,QAAQ;IAErE,OAAO;QAAEK;QAAMN;IAAK;AACtB,EAAC;AAED,OAAO,MAAMO,4BAA4B,CAACD;IACxC,IAAIE,sBAAsBF,OAAO;QAC/B,OAAO;YACLA,MAAMA,KAAKG,KAAK,CAACnC,0BAA0BoC,MAAM;YACjDN,YAAY7B;YACZ8B,WAAW7B;QACb;IACF;IAEA,OAAO;QACL8B;QACAF,YAAY3B;QACZ4B,WAAW3B;IACb;AACF,EAAC;AAED,OAAO,MAAM8B,wBAAwB,CAACF,OACpC,OAAOA,SAAS,YAAYA,KAAKK,UAAU,CAACrC,2BAA0B;AAExE,SAASyB;IACP,OAAO,IAAIa,QAAQ,CAACC,SAASC,SAC3B3C,OAAO4B,WAAW,CAAC,IAAI,CAACgB,KAAKjB,aAAgBiB,MAAMD,OAAOC,OAAOF,QAAQf;AAE7E;AAEA,SAASK,kBAAkB,EACzBC,UAAU,EACVC,SAAS,EACThC,QAAQ,EACR2B,IAAI,EAML;IACC,OAAO,IAAIY,QAAQ,CAACC,SAASC,SAC3B3C,OAAO6C,MAAM,CAAC3C,UAAU2B,MAAMI,YAAYC,WAAW,UAAU,CAACU,KAAKb,UACnEa,MAAMD,OAAOC,OAAOF,QAAQX;AAGlC"}
1
+ {"version":3,"sources":["../../../../src/auth/strategies/local/generatePasswordSaltHash.ts"],"sourcesContent":["import crypto from 'crypto'\n\nimport type { SanitizedCollectionConfig } from '../../../collections/config/types.js'\nimport type { SanitizedConfig } from '../../../config/types.js'\nimport type { PayloadRequest } from '../../../types/index.js'\n\nimport { InvalidConfiguration, ValidationError } from '../../../errors/index.js'\nimport { password } from '../../../fields/validations.js'\n\ntype PasswordHashParameters = {\n hash: string\n iterations: number\n keyLength: number\n}\n\ntype Args = {\n collection: SanitizedCollectionConfig\n isPasswordAuthenticated?: boolean\n password: string\n req: PayloadRequest\n}\n\ntype PasswordHashIterations = SanitizedConfig['auth']['passwordHashIterations']\n\n// Each supported iteration count has its own fixed prefix, so a stored hash\n// can be verified whichever count is configured\nconst passwordHashPrefixes: Record<PasswordHashIterations, string> = {\n 100000: 'pbkdf2-sha256-100k-v1:',\n 600000: 'pbkdf2-sha256-v1:',\n}\nexport const supportedPasswordHashIterations = Object.keys(passwordHashPrefixes).map(Number)\nconst passwordHashKeyLength = 32\nconst legacyPasswordHashIterations = 25000\nconst legacyPasswordHashKeyLength = 512\n\nexport const generatePasswordSaltHash = async ({\n collection,\n isPasswordAuthenticated,\n password: passwordToSet,\n req,\n}: Args): Promise<{ hash: string; salt: string }> => {\n if (!isPasswordAuthenticated) {\n const validationResult = password(passwordToSet, {\n name: 'password',\n type: 'text',\n blockData: {},\n data: {},\n event: 'submit',\n path: ['password'],\n preferences: { fields: {} },\n req,\n required: true,\n siblingData: {},\n })\n\n if (typeof validationResult === 'string') {\n throw new ValidationError({\n collection: collection?.slug,\n errors: [{ message: validationResult, path: 'password' }],\n })\n }\n }\n\n const { passwordHashIterations } = req.payload.config.auth\n const saltBuffer = await randomBytes()\n const salt = saltBuffer.toString('hex')\n\n const hashRaw = await pbkdf2Promisified({\n iterations: passwordHashIterations,\n keyLength: passwordHashKeyLength,\n password: passwordToSet,\n salt,\n }).catch((err: unknown) => {\n if (isUnsupportedIterationsError(err)) {\n const configHint =\n passwordHashIterations === 100000\n ? ''\n : ' Set `auth.passwordHashIterations` to 100000 in your Payload Config.'\n\n throw new InvalidConfiguration(\n `This environment does not support ${passwordHashIterations} PBKDF2 iterations for password hashing.${configHint}`,\n )\n }\n\n throw err\n })\n const hash = `${passwordHashPrefixes[passwordHashIterations]}${hashRaw.toString('hex')}`\n\n return { hash, salt }\n}\n\nexport const getPasswordHashParameters = (hash: string): PasswordHashParameters => {\n for (const [iterations, prefix] of Object.entries(passwordHashPrefixes)) {\n if (hash.startsWith(prefix)) {\n return {\n hash: hash.slice(prefix.length),\n iterations: Number(iterations),\n keyLength: passwordHashKeyLength,\n }\n }\n }\n\n return {\n hash,\n iterations: legacyPasswordHashIterations,\n keyLength: legacyPasswordHashKeyLength,\n }\n}\n\nexport const isCurrentPasswordHash = ({\n hash,\n passwordHashIterations,\n}: {\n hash: string\n passwordHashIterations: PasswordHashIterations\n}): boolean => hash.startsWith(passwordHashPrefixes[passwordHashIterations])\n\nfunction randomBytes(): Promise<Buffer> {\n return new Promise((resolve, reject) =>\n crypto.randomBytes(32, (err, saltBuffer) => (err ? reject(err) : resolve(saltBuffer))),\n )\n}\n\n// Environments such as Cloudflare Workers reject iteration counts above their limit\nexport const isUnsupportedIterationsError = (err: unknown): boolean =>\n err instanceof Error && err.name === 'NotSupportedError'\n\nexport function pbkdf2Promisified({\n iterations,\n keyLength,\n password,\n salt,\n}: {\n iterations: number\n keyLength: number\n password: string\n salt: string\n}): Promise<Buffer> {\n return new Promise((resolve, reject) =>\n crypto.pbkdf2(password, salt, iterations, keyLength, 'sha256', (err, hashRaw) =>\n err ? reject(err) : resolve(hashRaw),\n ),\n )\n}\n"],"names":["crypto","InvalidConfiguration","ValidationError","password","passwordHashPrefixes","supportedPasswordHashIterations","Object","keys","map","Number","passwordHashKeyLength","legacyPasswordHashIterations","legacyPasswordHashKeyLength","generatePasswordSaltHash","collection","isPasswordAuthenticated","passwordToSet","req","validationResult","name","type","blockData","data","event","path","preferences","fields","required","siblingData","slug","errors","message","passwordHashIterations","payload","config","auth","saltBuffer","randomBytes","salt","toString","hashRaw","pbkdf2Promisified","iterations","keyLength","catch","err","isUnsupportedIterationsError","configHint","hash","getPasswordHashParameters","prefix","entries","startsWith","slice","length","isCurrentPasswordHash","Promise","resolve","reject","Error","pbkdf2"],"mappings":"AAAA,OAAOA,YAAY,SAAQ;AAM3B,SAASC,oBAAoB,EAAEC,eAAe,QAAQ,2BAA0B;AAChF,SAASC,QAAQ,QAAQ,iCAAgC;AAiBzD,4EAA4E;AAC5E,gDAAgD;AAChD,MAAMC,uBAA+D;IACnE,QAAQ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;AACtB,EAAC;AAED,OAAO,MAAMW,4BAA4B,CAACD;IACxC,KAAK,MAAM,CAACN,YAAYQ,OAAO,IAAI5C,OAAO6C,OAAO,CAAC/C,sBAAuB;QACvE,IAAI4C,KAAKI,UAAU,CAACF,SAAS;YAC3B,OAAO;gBACLF,MAAMA,KAAKK,KAAK,CAACH,OAAOI,MAAM;gBAC9BZ,YAAYjC,OAAOiC;gBACnBC,WAAWjC;YACb;QACF;IACF;IAEA,OAAO;QACLsC;QACAN,YAAY/B;QACZgC,WAAW/B;IACb;AACF,EAAC;AAED,OAAO,MAAM2C,wBAAwB,CAAC,EACpCP,IAAI,EACJhB,sBAAsB,EAIvB,GAAcgB,KAAKI,UAAU,CAAChD,oBAAoB,CAAC4B,uBAAuB,EAAC;AAE5E,SAASK;IACP,OAAO,IAAImB,QAAQ,CAACC,SAASC,SAC3B1D,OAAOqC,WAAW,CAAC,IAAI,CAACQ,KAAKT,aAAgBS,MAAMa,OAAOb,OAAOY,QAAQrB;AAE7E;AAEA,oFAAoF;AACpF,OAAO,MAAMU,+BAA+B,CAACD,MAC3CA,eAAec,SAASd,IAAI1B,IAAI,KAAK,oBAAmB;AAE1D,OAAO,SAASsB,kBAAkB,EAChCC,UAAU,EACVC,SAAS,EACTxC,QAAQ,EACRmC,IAAI,EAML;IACC,OAAO,IAAIkB,QAAQ,CAACC,SAASC,SAC3B1D,OAAO4D,MAAM,CAACzD,UAAUmC,MAAMI,YAAYC,WAAW,UAAU,CAACE,KAAKL,UACnEK,MAAMa,OAAOb,OAAOY,QAAQjB;AAGlC"}
@@ -129,6 +129,13 @@ export type UserSession = {
129
129
  createdAt?: Date | null | string;
130
130
  expiresAt: Date | string;
131
131
  id: string;
132
+ /**
133
+ * How many times the session was refreshed with a refresh token. Refresh tokens remember it, so
134
+ * the latest one can be told apart from older ones.
135
+ */
136
+ refreshCount?: null | number;
137
+ /** When the session was last refreshed with a refresh token. */
138
+ refreshedAt?: Date | null | string;
132
139
  };
133
140
  type GenerateVerifyEmailHTML<TUser = any> = (args: {
134
141
  req: PayloadRequest;
@@ -250,6 +257,29 @@ export interface IncomingAuthType {
250
257
  * Only allow a user to attempt logging in X amount of times. Automatically locks out a user from authenticating if this limit is passed. Set to 0 to disable.
251
258
  */
252
259
  maxLoginAttempts?: number;
260
+ /**
261
+ * Lets clients stay logged in after their token expires. Logins also return a refresh token,
262
+ * which the refresh operation trades for a new token and a new refresh token. Each refresh token
263
+ * is meant to be used once. The one from right before still works for 30 seconds after a refresh,
264
+ * for clients that refresh twice at once. When a used one comes back otherwise, its session is
265
+ * logged out. Requires `useSessions`.
266
+ *
267
+ * Refresh tokens don't expire on their own. They work as long as their login session, which lasts
268
+ * `expiration` from the last refresh instead of `tokenExpiration`.
269
+ *
270
+ * @default false
271
+ * @link https://payloadcms.com/docs/authentication/overview#refresh-tokens
272
+ */
273
+ refreshTokens?: {
274
+ /**
275
+ * How many seconds a login session with a refresh token lasts without a refresh, which is
276
+ * how long its refresh token can be used. Every refresh starts this time again. The token
277
+ * itself still expires after `tokenExpiration`.
278
+ *
279
+ * @default 2592000 (30 days)
280
+ */
281
+ expiration?: number;
282
+ } | boolean;
253
283
  /***
254
284
  * Set to true if you want to remove the token from the returned authentication API responses such as login or refresh.
255
285
  */
@@ -295,9 +325,12 @@ export type VerifyConfig = {
295
325
  generateEmailHTML?: GenerateVerifyEmailHTML;
296
326
  generateEmailSubject?: GenerateVerifyEmailSubject;
297
327
  };
298
- export interface Auth extends Omit<IncomingAuthType, 'cookies' | 'forgotPassword' | 'lockTime' | 'loginWithUsername' | 'maxLoginAttempts' | 'strategies' | 'tokenExpiration' | 'useSessions' | 'verify'>, Required<Pick<IncomingAuthType, 'forgotPassword' | 'lockTime' | 'maxLoginAttempts' | 'strategies' | 'tokenExpiration' | 'useSessions' | 'verify'>> {
328
+ export interface Auth extends Omit<IncomingAuthType, 'cookies' | 'forgotPassword' | 'lockTime' | 'loginWithUsername' | 'maxLoginAttempts' | 'refreshTokens' | 'strategies' | 'tokenExpiration' | 'useSessions' | 'verify'>, Required<Pick<IncomingAuthType, 'forgotPassword' | 'lockTime' | 'maxLoginAttempts' | 'strategies' | 'tokenExpiration' | 'useSessions' | 'verify'>> {
299
329
  cookies: Pick<AuthCookies, 'domain'> & Required<Pick<AuthCookies, 'sameSite' | 'secure'>>;
300
330
  loginWithUsername: false | Required<LoginWithUsernameOptions>;
331
+ refreshTokens: {
332
+ expiration: number;
333
+ } | false;
301
334
  }
302
335
  export declare function hasWhereAccessResult(result: boolean | Where): result is Where;
303
336
  export {};