@warlock.js/auth 5.52.0 → 5.53.1

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 (118) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/esm/contracts/index.d.mts +2 -2
  3. package/esm/contracts/providers.d.mts +53 -0
  4. package/esm/contracts/providers.d.mts.map +1 -1
  5. package/esm/contracts/types.d.mts +53 -0
  6. package/esm/contracts/types.d.mts.map +1 -1
  7. package/esm/contracts/types.mjs.map +1 -1
  8. package/esm/errors/index.d.mts +2 -1
  9. package/esm/errors/index.mjs +2 -1
  10. package/esm/errors/provider-account-link-blocked.error.d.mts +16 -0
  11. package/esm/errors/provider-account-link-blocked.error.d.mts.map +1 -0
  12. package/esm/errors/provider-account-link-blocked.error.mjs +22 -0
  13. package/esm/errors/provider-account-link-blocked.error.mjs.map +1 -0
  14. package/esm/index.d.mts +3 -2
  15. package/esm/index.mjs +2 -1
  16. package/esm/middleware/auth.middleware.mjs +1 -1
  17. package/esm/middleware/auth.middleware.mjs.map +1 -1
  18. package/esm/middleware/login-throttle.middleware.d.mts +38 -8
  19. package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
  20. package/esm/middleware/login-throttle.middleware.mjs +93 -29
  21. package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
  22. package/esm/models/access-token/access-token.model.d.mts +14 -3
  23. package/esm/models/access-token/access-token.model.d.mts.map +1 -1
  24. package/esm/models/access-token/access-token.model.mjs +15 -8
  25. package/esm/models/access-token/access-token.model.mjs.map +1 -1
  26. package/esm/models/auth.model.d.mts +8 -0
  27. package/esm/models/auth.model.d.mts.map +1 -1
  28. package/esm/models/auth.model.mjs +3 -0
  29. package/esm/models/auth.model.mjs.map +1 -1
  30. package/esm/models/one-time-token/one-time-token.model.d.mts +7 -2
  31. package/esm/models/one-time-token/one-time-token.model.d.mts.map +1 -1
  32. package/esm/models/one-time-token/one-time-token.model.mjs +8 -7
  33. package/esm/models/one-time-token/one-time-token.model.mjs.map +1 -1
  34. package/esm/models/refresh-token/refresh-token.model.d.mts +15 -3
  35. package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
  36. package/esm/models/refresh-token/refresh-token.model.mjs +17 -12
  37. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  38. package/esm/otp/otp.d.mts +5 -1
  39. package/esm/otp/otp.d.mts.map +1 -1
  40. package/esm/otp/otp.mjs +18 -3
  41. package/esm/otp/otp.mjs.map +1 -1
  42. package/esm/passkeys/passkey-authentication.mjs +2 -2
  43. package/esm/passkeys/passkey-authentication.mjs.map +1 -1
  44. package/esm/passkeys/passkey-registration.d.mts.map +1 -1
  45. package/esm/passkeys/passkey-registration.mjs +2 -2
  46. package/esm/passkeys/passkey-registration.mjs.map +1 -1
  47. package/esm/providers/apple-provider.d.mts +2 -0
  48. package/esm/providers/apple-provider.d.mts.map +1 -1
  49. package/esm/providers/apple-provider.mjs +4 -1
  50. package/esm/providers/apple-provider.mjs.map +1 -1
  51. package/esm/providers/discord-provider.d.mts +2 -0
  52. package/esm/providers/discord-provider.d.mts.map +1 -1
  53. package/esm/providers/discord-provider.mjs +7 -1
  54. package/esm/providers/discord-provider.mjs.map +1 -1
  55. package/esm/providers/facebook-provider.d.mts +2 -0
  56. package/esm/providers/facebook-provider.d.mts.map +1 -1
  57. package/esm/providers/facebook-provider.mjs +10 -2
  58. package/esm/providers/facebook-provider.mjs.map +1 -1
  59. package/esm/providers/github-provider.d.mts +2 -0
  60. package/esm/providers/github-provider.d.mts.map +1 -1
  61. package/esm/providers/github-provider.mjs +19 -10
  62. package/esm/providers/github-provider.mjs.map +1 -1
  63. package/esm/providers/linkedin-provider.d.mts +2 -0
  64. package/esm/providers/linkedin-provider.d.mts.map +1 -1
  65. package/esm/providers/linkedin-provider.mjs +4 -1
  66. package/esm/providers/linkedin-provider.mjs.map +1 -1
  67. package/esm/providers/provider-timeout.mjs +17 -0
  68. package/esm/providers/provider-timeout.mjs.map +1 -0
  69. package/esm/providers/resolve-provider-user.mjs +21 -1
  70. package/esm/providers/resolve-provider-user.mjs.map +1 -1
  71. package/esm/providers/x-provider.d.mts +2 -0
  72. package/esm/providers/x-provider.d.mts.map +1 -1
  73. package/esm/providers/x-provider.mjs +7 -1
  74. package/esm/providers/x-provider.mjs.map +1 -1
  75. package/esm/services/auth-config.mjs +65 -6
  76. package/esm/services/auth-config.mjs.map +1 -1
  77. package/esm/services/auth-cookie-names.mjs +49 -0
  78. package/esm/services/auth-cookie-names.mjs.map +1 -0
  79. package/esm/services/auth-events.d.mts +4 -0
  80. package/esm/services/auth-events.d.mts.map +1 -1
  81. package/esm/services/auth-events.mjs.map +1 -1
  82. package/esm/services/auth.service.d.mts +8 -0
  83. package/esm/services/auth.service.d.mts.map +1 -1
  84. package/esm/services/auth.service.mjs +146 -20
  85. package/esm/services/auth.service.mjs.map +1 -1
  86. package/esm/services/jwt.d.mts.map +1 -1
  87. package/esm/services/jwt.mjs +92 -10
  88. package/esm/services/jwt.mjs.map +1 -1
  89. package/esm/services/password-reset.d.mts +5 -0
  90. package/esm/services/password-reset.d.mts.map +1 -1
  91. package/esm/services/password-reset.mjs +15 -1
  92. package/esm/services/password-reset.mjs.map +1 -1
  93. package/esm/services/resolve-request-user.d.mts.map +1 -1
  94. package/esm/services/resolve-request-user.mjs +17 -3
  95. package/esm/services/resolve-request-user.mjs.map +1 -1
  96. package/esm/session/page-session.d.mts.map +1 -1
  97. package/esm/session/page-session.mjs +5 -3
  98. package/esm/session/page-session.mjs.map +1 -1
  99. package/esm/utils/auth-error-codes.d.mts +8 -1
  100. package/esm/utils/auth-error-codes.d.mts.map +1 -1
  101. package/esm/utils/auth-error-codes.mjs +7 -0
  102. package/esm/utils/auth-error-codes.mjs.map +1 -1
  103. package/esm/utils/token-digest.mjs +47 -0
  104. package/esm/utils/token-digest.mjs.map +1 -0
  105. package/esm/utils/token-expiry.d.mts +3 -1
  106. package/esm/utils/token-expiry.d.mts.map +1 -1
  107. package/esm/utils/token-expiry.mjs +7 -2
  108. package/esm/utils/token-expiry.mjs.map +1 -1
  109. package/llms-full.txt +70 -30
  110. package/llms.txt +2 -2
  111. package/package.json +9 -9
  112. package/skills/auth-basics/SKILL.md +9 -0
  113. package/skills/customize-token-storage/SKILL.md +10 -10
  114. package/skills/login-with-providers/SKILL.md +14 -3
  115. package/skills/manage-tokens/SKILL.md +6 -0
  116. package/skills/protect-routes/SKILL.md +5 -0
  117. package/skills/throttle-login-attempts/SKILL.md +23 -17
  118. package/skills/verify-email-and-reset-password/SKILL.md +3 -0
@@ -6,6 +6,8 @@ import { createSigner, createVerifier } from "fast-jwt";
6
6
  //#region ../../packages/auth/src/services/jwt.ts
7
7
  const getSecretKey = () => authConfig.accessToken.secret();
8
8
  const getAlgorithm = () => authConfig.accessToken.algorithm();
9
+ const getIssuer = () => authConfig.accessToken.issuer();
10
+ const getAudience = () => authConfig.accessToken.audience();
9
11
  const getRefreshSecretKey = () => authConfig.refreshToken.secret() || getSecretKey();
10
12
  const ACCESS_TOKEN_TYPE = "access";
11
13
  const REFRESH_TOKEN_TYPE = "refresh";
@@ -91,17 +93,73 @@ function withRequiredClaims(callerClaims) {
91
93
  if (!callerClaims?.length) return REQUIRED_CLAIMS;
92
94
  return [.../* @__PURE__ */ new Set([...callerClaims, ...REQUIRED_CLAIMS])];
93
95
  }
96
+ /**
97
+ * One prepared signer/verifier per token kind, rebuilt only when the settings
98
+ * that shape it change. Building one validates options and prepares the key
99
+ * (a PEM key is parsed), which is wasted work when it happens on every
100
+ * authenticated request with settings that never change.
101
+ */
102
+ const prepared = /* @__PURE__ */ new Map();
103
+ function preparedFor(slot, settings, build) {
104
+ const fingerprint = JSON.stringify(settings);
105
+ const current = prepared.get(slot);
106
+ if (current && current.fingerprint === fingerprint) return current.value;
107
+ const value = build();
108
+ prepared.set(slot, {
109
+ fingerprint,
110
+ value
111
+ });
112
+ return value;
113
+ }
114
+ /** Whether the caller passed only the options the prepared instances are keyed on. */
115
+ function onlyKeyedOptions(options, allowed = []) {
116
+ return Object.keys(options).every((name) => allowed.includes(name));
117
+ }
118
+ /**
119
+ * Issuer/audience claims stamped on signed tokens, from
120
+ * `auth.accessToken.issuer` / `auth.accessToken.audience` (both optional).
121
+ */
122
+ function issuedClaims() {
123
+ const iss = getIssuer();
124
+ const aud = getAudience();
125
+ return {
126
+ ...iss !== void 0 ? { iss } : {},
127
+ ...aud !== void 0 ? { aud } : {}
128
+ };
129
+ }
130
+ /**
131
+ * Verifier options that require the configured issuer/audience. A configured
132
+ * claim is also REQUIRED, so a token signed before it was set (which has none)
133
+ * is rejected rather than slipping past the check.
134
+ */
135
+ function expectedClaims() {
136
+ const iss = getIssuer();
137
+ const aud = getAudience();
138
+ return {
139
+ ...iss !== void 0 ? { allowedIss: iss } : {},
140
+ ...aud !== void 0 ? { allowedAud: aud } : {},
141
+ required: [...iss !== void 0 ? ["iss"] : [], ...aud !== void 0 ? ["aud"] : []]
142
+ };
143
+ }
94
144
  const jwt = {
95
145
  /**
96
146
  * Generate a new JWT token for the user.
97
147
  * @param payload The payload to encode in the JWT token.
98
148
  */
99
149
  async generate(payload, { key = getSecretKey(), algorithm = getAlgorithm(), ...options } = {}) {
100
- return await createSigner({
150
+ const claims = issuedClaims();
151
+ const build = () => createSigner({
101
152
  key,
153
+ ...claims,
102
154
  ...options,
103
155
  algorithm
104
- })({
156
+ });
157
+ return (onlyKeyedOptions(options, ["expiresIn"]) ? preparedFor("sign:access", {
158
+ key,
159
+ algorithm,
160
+ claims,
161
+ expiresIn: options.expiresIn
162
+ }, build) : build())({
105
163
  jti: randomUUID(),
106
164
  ...payload,
107
165
  tokenType: ACCESS_TOKEN_TYPE
@@ -113,12 +171,20 @@ const jwt = {
113
171
  * @returns The decoded token payload if verification is successful.
114
172
  */
115
173
  async verify(token, { key = getSecretKey(), algorithms = [getAlgorithm()], requiredClaims, ...options } = {}) {
116
- const decoded = await createVerifier({
174
+ const { required, ...expected } = expectedClaims();
175
+ const build = () => createVerifier({
117
176
  key,
177
+ ...expected,
118
178
  ...options,
119
179
  algorithms,
120
- requiredClaims: withRequiredClaims(requiredClaims)
121
- })(token);
180
+ requiredClaims: withRequiredClaims([...requiredClaims ?? [], ...required])
181
+ });
182
+ const decoded = await (requiredClaims === void 0 && onlyKeyedOptions(options) ? preparedFor("verify:access", {
183
+ key,
184
+ algorithms,
185
+ expected,
186
+ required
187
+ }, build) : build())(token);
122
188
  assertTokenType(decoded, ACCESS_TOKEN_TYPE);
123
189
  return decoded;
124
190
  },
@@ -126,12 +192,20 @@ const jwt = {
126
192
  * Generate a new refresh token for the user.
127
193
  */
128
194
  async generateRefreshToken(payload, { key = getRefreshSecretKey(), expiresIn, algorithm = getAlgorithm(), ...options } = {}) {
129
- return createSigner({
195
+ const claims = issuedClaims();
196
+ const build = () => createSigner({
130
197
  key,
131
198
  expiresIn,
132
199
  algorithm,
200
+ ...claims,
133
201
  ...options
134
- })({
202
+ });
203
+ return (onlyKeyedOptions(options) ? preparedFor("sign:refresh", {
204
+ key,
205
+ algorithm,
206
+ claims,
207
+ expiresIn
208
+ }, build) : build())({
135
209
  jti: randomUUID(),
136
210
  ...payload,
137
211
  tokenType: REFRESH_TOKEN_TYPE
@@ -141,12 +215,20 @@ const jwt = {
141
215
  * Verify the given refresh token.
142
216
  */
143
217
  async verifyRefreshToken(token, { key = getRefreshSecretKey(), algorithms = [getAlgorithm()], requiredClaims, ...options } = {}) {
144
- const decoded = await createVerifier({
218
+ const { required, ...expected } = expectedClaims();
219
+ const build = () => createVerifier({
145
220
  key,
146
221
  algorithms,
222
+ ...expected,
147
223
  ...options,
148
- requiredClaims: withRequiredClaims(requiredClaims)
149
- })(token);
224
+ requiredClaims: withRequiredClaims([...requiredClaims ?? [], ...required])
225
+ });
226
+ const decoded = await (requiredClaims === void 0 && onlyKeyedOptions(options) ? preparedFor("verify:refresh", {
227
+ key,
228
+ algorithms,
229
+ expected,
230
+ required
231
+ }, build) : build())(token);
150
232
  assertTokenType(decoded, REFRESH_TOKEN_TYPE);
151
233
  return decoded;
152
234
  }
@@ -1 +1 @@
1
- {"version":3,"file":"jwt.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/jwt.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { createSigner, createVerifier, type SignerOptions, type VerifierOptions } from \"fast-jwt\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport { authConfig } from \"./auth-config\";\n\nconst getSecretKey = () => authConfig.accessToken.secret();\nconst getAlgorithm = () => authConfig.accessToken.algorithm();\n\n// Refresh tokens may declare their own secret; when unset/empty we fall back to\n// the access-token secret (the documented optional behavior).\nconst getRefreshSecretKey = () => authConfig.refreshToken.secret() || getSecretKey();\n\n/**\n * Token class. Stamped as the `tokenType` claim on every signed token and\n * checked on verify so an access token can never be accepted where a refresh\n * token is expected (and vice versa) — even when both share the same secret\n * under the documented refresh-secret fallback. Legacy tokens minted before\n * this claim existed carry no `tokenType` and remain accepted; a *mismatched*\n * type is always rejected.\n */\nexport type TokenType = \"access\" | \"refresh\";\n\nconst ACCESS_TOKEN_TYPE: TokenType = \"access\";\nconst REFRESH_TOKEN_TYPE: TokenType = \"refresh\";\n\n/**\n * Error codes that mean \"the credential itself is bad\", as opposed to \"this\n * server could not check it\". This is an ALLOWLIST and must stay one. The codes\n * deliberately left out — `FAST_JWT_INVALID_KEY`, `FAST_JWT_MISSING_KEY`,\n * `FAST_JWT_KEY_FETCHING_ERROR`, `FAST_JWT_INVALID_OPTION`,\n * `FAST_JWT_VERIFY_ERROR`, and `FAST_JWT_SIGN_ERROR` — describe a broken\n * server, not a broken token, and so does every unknown future code.\n */\nconst INVALID_CREDENTIAL_ERROR_CODES = new Set<string>([\n \"FAST_JWT_MALFORMED\",\n \"FAST_JWT_INVALID_SIGNATURE\",\n \"FAST_JWT_MISSING_SIGNATURE\",\n \"FAST_JWT_INVALID_ALGORITHM\",\n \"FAST_JWT_EXPIRED\",\n \"FAST_JWT_INACTIVE\",\n // How a token carrying no `exp` is rejected — `jwt.verify` forces `exp` into\n // `requiredClaims`, so this code IS the missing-deadline guard firing.\n \"FAST_JWT_MISSING_REQUIRED_CLAIM\",\n \"FAST_JWT_INVALID_CLAIM_VALUE\",\n \"FAST_JWT_INVALID_CLAIM_TYPE\",\n \"FAST_JWT_INVALID_CRIT_HEADER\",\n \"FAST_JWT_INVALID_TYPE\",\n \"FAST_JWT_INVALID_PAYLOAD\",\n AuthErrorCodes.InvalidTokenType,\n]);\n\n/**\n * Only coded credential failures become authentication misses. Plain errors,\n * including missing-secret configuration failures, propagate to the central\n * server-error path instead of reading as \"everyone's token is bad\".\n */\nexport function isInvalidCredentialError(error: unknown): boolean {\n const code = (error as { code?: unknown } | null | undefined)?.code;\n\n return typeof code === \"string\" && INVALID_CREDENTIAL_ERROR_CODES.has(code);\n}\n\n/**\n * A `tokenType` claim that does not match what the caller expects. This IS a\n * bad credential (an access-token cookie can only hold a refresh token\n * through an app bug) — but unlike `fast-jwt`'s own rejections it was\n * previously a plain `Error`, unclassifiable by a caller that wants to answer\n * 401 without string-matching a message that could reword on any release.\n * `code` mirrors how `fast-jwt`'s `TokenError` carries its own code, so a\n * caller can classify both through `isInvalidCredentialError` above.\n */\nexport class TokenTypeError extends Error {\n readonly code = AuthErrorCodes.InvalidTokenType;\n\n constructor(expected: TokenType, actual: string) {\n super(`Invalid token type: expected \"${expected}\", received \"${actual}\".`);\n this.name = \"TokenTypeError\";\n }\n}\n\n/**\n * Reject the token when its `tokenType` claim is present and does not match the\n * expected class. Absent claim ⇒ legacy token, accepted (backward compatible).\n */\nfunction assertTokenType(decoded: unknown, expected: TokenType): void {\n const actual = (decoded as { tokenType?: unknown } | null | undefined)?.tokenType;\n\n if (typeof actual === \"string\" && actual !== expected) {\n throw new TokenTypeError(expected, actual);\n }\n}\n\n/**\n * Claims no token may be missing, whatever the caller asks for.\n *\n * A JWT with no `exp` is not \"a token with a long life\" — it is a credential\n * with *no* life, because a verifier with no deadline to check simply succeeds,\n * forever (measured against `fast-jwt@6.2.4`: a token with no `exp` verifies\n * unchanged at `clockTimestamp` + 100 years). Nothing in this package can mint\n * one as of 4.12.0, but tokens minted by an earlier version are already in the\n * wild, so the rejection lives on the *verify* side where it catches a token\n * from any version, including one signed by a service this package never ran.\n *\n * There is no legitimate source to preserve: an app that wants a token that\n * effectively never expires sets `expiresIn: NO_EXPIRATION` (`\"100y\"`), which\n * mints a real `exp` roughly a century out (measured: `ms(\"100y\")` ⇒\n * `3155760000000`, `exp - iat` ⇒ `3155760000` seconds). \"No deadline\" and \"a\n * distant deadline\" are different things, and only the second one is asked for.\n */\nconst REQUIRED_CLAIMS = [\"exp\"];\n\n/**\n * Union the caller's `requiredClaims` with the mandatory ones — a caller may\n * add requirements, never drop them.\n */\nfunction withRequiredClaims(callerClaims?: string[]): string[] {\n if (!callerClaims?.length) return REQUIRED_CLAIMS;\n\n return [...new Set([...callerClaims, ...REQUIRED_CLAIMS])];\n}\n\nexport const jwt = {\n /**\n * Generate a new JWT token for the user.\n * @param payload The payload to encode in the JWT token.\n */\n async generate(\n payload: any,\n {\n key = getSecretKey(),\n algorithm = getAlgorithm(),\n ...options\n }: SignerOptions & { key?: string } = {},\n ): Promise<string> {\n // Create a signer function with predefined options\n const sign = createSigner({ key, ...options, algorithm });\n\n const token = await sign({ jti: randomUUID(), ...payload, tokenType: ACCESS_TOKEN_TYPE });\n return token;\n },\n\n /**\n * Verify the given token.\n * @param token The JWT token to verify.\n * @returns The decoded token payload if verification is successful.\n */\n async verify<T = unknown>(\n token: string,\n {\n key = getSecretKey(),\n algorithms = [getAlgorithm()],\n requiredClaims,\n ...options\n }: VerifierOptions & { key?: string } = {},\n ): Promise<T> {\n const verify = createVerifier({\n key,\n ...options,\n algorithms,\n requiredClaims: withRequiredClaims(requiredClaims),\n });\n\n const decoded = await verify(token as string);\n\n assertTokenType(decoded, ACCESS_TOKEN_TYPE);\n\n return decoded;\n },\n\n /**\n * Generate a new refresh token for the user.\n */\n async generateRefreshToken(\n payload: any,\n {\n key = getRefreshSecretKey(),\n expiresIn,\n algorithm = getAlgorithm(),\n ...options\n }: SignerOptions & { key?: string } = {},\n ): Promise<string> {\n const sign = createSigner({ key, expiresIn, algorithm, ...options });\n return sign({ jti: randomUUID(), ...payload, tokenType: REFRESH_TOKEN_TYPE });\n },\n\n /**\n * Verify the given refresh token.\n */\n async verifyRefreshToken<T = unknown>(\n token: string,\n {\n key = getRefreshSecretKey(),\n algorithms = [getAlgorithm()],\n requiredClaims,\n ...options\n }: VerifierOptions & { key?: string } = {},\n ): Promise<T> {\n const verify = createVerifier({\n key,\n algorithms,\n ...options,\n requiredClaims: withRequiredClaims(requiredClaims),\n });\n\n const decoded = await verify(token);\n\n assertTokenType(decoded, REFRESH_TOKEN_TYPE);\n\n return decoded;\n },\n};\n"],"mappings":";;;;;;AAKA,MAAM,qBAAqB,WAAW,YAAY,OAAO;AACzD,MAAM,qBAAqB,WAAW,YAAY,UAAU;AAI5D,MAAM,4BAA4B,WAAW,aAAa,OAAO,KAAK,aAAa;AAYnF,MAAM,oBAA+B;AACrC,MAAM,qBAAgC;;;;;;;;;AAUtC,MAAM,iDAAiC,IAAI,IAAY;CACrD;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;;AAEF,CAAC;;;;;;AAOD,SAAgB,yBAAyB,OAAyB;CAChE,MAAM,OAAQ,OAAiD;CAE/D,OAAO,OAAO,SAAS,YAAY,+BAA+B,IAAI,IAAI;AAC5E;;;;;;;;;;AAWA,IAAa,iBAAb,cAAoC,MAAM;CAGxC,YAAY,UAAqB,QAAgB;EAC/C,MAAM,iCAAiC,SAAS,eAAe,OAAO,GAAG;;EACzE,KAAK,OAAO;CACd;AACF;;;;;AAMA,SAAS,gBAAgB,SAAkB,UAA2B;CACpE,MAAM,SAAU,SAAwD;CAExE,IAAI,OAAO,WAAW,YAAY,WAAW,UAC3C,MAAM,IAAI,eAAe,UAAU,MAAM;AAE7C;;;;;;;;;;;;;;;;;;AAmB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
1
+ {"version":3,"file":"jwt.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/jwt.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { createSigner, createVerifier, type SignerOptions, type VerifierOptions } from \"fast-jwt\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\nimport { authConfig } from \"./auth-config\";\n\nconst getSecretKey = () => authConfig.accessToken.secret();\nconst getAlgorithm = () => authConfig.accessToken.algorithm();\nconst getIssuer = () => authConfig.accessToken.issuer();\nconst getAudience = () => authConfig.accessToken.audience();\n\n// Refresh tokens may declare their own secret; when unset/empty we fall back to\n// the access-token secret (the documented optional behavior).\nconst getRefreshSecretKey = () => authConfig.refreshToken.secret() || getSecretKey();\n\n/**\n * Token class. Stamped as the `tokenType` claim on every signed token and\n * checked on verify so an access token can never be accepted where a refresh\n * token is expected (and vice versa) — even when both share the same secret\n * under the documented refresh-secret fallback. Legacy tokens minted before\n * this claim existed carry no `tokenType` and remain accepted; a *mismatched*\n * type is always rejected.\n */\nexport type TokenType = \"access\" | \"refresh\";\n\nconst ACCESS_TOKEN_TYPE: TokenType = \"access\";\nconst REFRESH_TOKEN_TYPE: TokenType = \"refresh\";\n\n/**\n * Error codes that mean \"the credential itself is bad\", as opposed to \"this\n * server could not check it\". This is an ALLOWLIST and must stay one. The codes\n * deliberately left out — `FAST_JWT_INVALID_KEY`, `FAST_JWT_MISSING_KEY`,\n * `FAST_JWT_KEY_FETCHING_ERROR`, `FAST_JWT_INVALID_OPTION`,\n * `FAST_JWT_VERIFY_ERROR`, and `FAST_JWT_SIGN_ERROR` — describe a broken\n * server, not a broken token, and so does every unknown future code.\n */\nconst INVALID_CREDENTIAL_ERROR_CODES = new Set<string>([\n \"FAST_JWT_MALFORMED\",\n \"FAST_JWT_INVALID_SIGNATURE\",\n \"FAST_JWT_MISSING_SIGNATURE\",\n \"FAST_JWT_INVALID_ALGORITHM\",\n \"FAST_JWT_EXPIRED\",\n \"FAST_JWT_INACTIVE\",\n // How a token carrying no `exp` is rejected — `jwt.verify` forces `exp` into\n // `requiredClaims`, so this code IS the missing-deadline guard firing.\n \"FAST_JWT_MISSING_REQUIRED_CLAIM\",\n \"FAST_JWT_INVALID_CLAIM_VALUE\",\n \"FAST_JWT_INVALID_CLAIM_TYPE\",\n \"FAST_JWT_INVALID_CRIT_HEADER\",\n \"FAST_JWT_INVALID_TYPE\",\n \"FAST_JWT_INVALID_PAYLOAD\",\n AuthErrorCodes.InvalidTokenType,\n]);\n\n/**\n * Only coded credential failures become authentication misses. Plain errors,\n * including missing-secret configuration failures, propagate to the central\n * server-error path instead of reading as \"everyone's token is bad\".\n */\nexport function isInvalidCredentialError(error: unknown): boolean {\n const code = (error as { code?: unknown } | null | undefined)?.code;\n\n return typeof code === \"string\" && INVALID_CREDENTIAL_ERROR_CODES.has(code);\n}\n\n/**\n * A `tokenType` claim that does not match what the caller expects. This IS a\n * bad credential (an access-token cookie can only hold a refresh token\n * through an app bug) — but unlike `fast-jwt`'s own rejections it was\n * previously a plain `Error`, unclassifiable by a caller that wants to answer\n * 401 without string-matching a message that could reword on any release.\n * `code` mirrors how `fast-jwt`'s `TokenError` carries its own code, so a\n * caller can classify both through `isInvalidCredentialError` above.\n */\nexport class TokenTypeError extends Error {\n readonly code = AuthErrorCodes.InvalidTokenType;\n\n constructor(expected: TokenType, actual: string) {\n super(`Invalid token type: expected \"${expected}\", received \"${actual}\".`);\n this.name = \"TokenTypeError\";\n }\n}\n\n/**\n * Reject the token when its `tokenType` claim is present and does not match the\n * expected class. Absent claim ⇒ legacy token, accepted (backward compatible).\n */\nfunction assertTokenType(decoded: unknown, expected: TokenType): void {\n const actual = (decoded as { tokenType?: unknown } | null | undefined)?.tokenType;\n\n if (typeof actual === \"string\" && actual !== expected) {\n throw new TokenTypeError(expected, actual);\n }\n}\n\n/**\n * Claims no token may be missing, whatever the caller asks for.\n *\n * A JWT with no `exp` is not \"a token with a long life\" — it is a credential\n * with *no* life, because a verifier with no deadline to check simply succeeds,\n * forever (measured against `fast-jwt@6.2.4`: a token with no `exp` verifies\n * unchanged at `clockTimestamp` + 100 years). Nothing in this package can mint\n * one as of 4.12.0, but tokens minted by an earlier version are already in the\n * wild, so the rejection lives on the *verify* side where it catches a token\n * from any version, including one signed by a service this package never ran.\n *\n * There is no legitimate source to preserve: an app that wants a token that\n * effectively never expires sets `expiresIn: NO_EXPIRATION` (`\"100y\"`), which\n * mints a real `exp` roughly a century out (measured: `ms(\"100y\")` ⇒\n * `3155760000000`, `exp - iat` ⇒ `3155760000` seconds). \"No deadline\" and \"a\n * distant deadline\" are different things, and only the second one is asked for.\n */\nconst REQUIRED_CLAIMS = [\"exp\"];\n\n/**\n * Union the caller's `requiredClaims` with the mandatory ones — a caller may\n * add requirements, never drop them.\n */\nfunction withRequiredClaims(callerClaims?: string[]): string[] {\n if (!callerClaims?.length) return REQUIRED_CLAIMS;\n\n return [...new Set([...callerClaims, ...REQUIRED_CLAIMS])];\n}\n\ntype Sign = (payload: Record<string, unknown>) => Promise<string> | string;\ntype Verify = (token: string) => Promise<unknown> | unknown;\n\n/**\n * One prepared signer/verifier per token kind, rebuilt only when the settings\n * that shape it change. Building one validates options and prepares the key\n * (a PEM key is parsed), which is wasted work when it happens on every\n * authenticated request with settings that never change.\n */\nconst prepared = new Map<string, { fingerprint: string; value: Sign | Verify }>();\n\nfunction preparedFor<T extends Sign | Verify>(\n slot: string,\n settings: Record<string, unknown>,\n build: () => T,\n): T {\n const fingerprint = JSON.stringify(settings);\n const current = prepared.get(slot);\n\n if (current && current.fingerprint === fingerprint) return current.value as T;\n\n const value = build();\n prepared.set(slot, { fingerprint, value });\n\n return value;\n}\n\n/** Whether the caller passed only the options the prepared instances are keyed on. */\nfunction onlyKeyedOptions(options: object, allowed: string[] = []): boolean {\n return Object.keys(options).every((name) => allowed.includes(name));\n}\n\n/**\n * Issuer/audience claims stamped on signed tokens, from\n * `auth.accessToken.issuer` / `auth.accessToken.audience` (both optional).\n */\nfunction issuedClaims(): { iss?: string; aud?: string | string[] } {\n const iss = getIssuer();\n const aud = getAudience();\n\n return {\n ...(iss !== undefined ? { iss } : {}),\n ...(aud !== undefined ? { aud } : {}),\n };\n}\n\n/**\n * Verifier options that require the configured issuer/audience. A configured\n * claim is also REQUIRED, so a token signed before it was set (which has none)\n * is rejected rather than slipping past the check.\n */\nfunction expectedClaims(): {\n allowedIss?: string;\n allowedAud?: string | string[];\n required: string[];\n} {\n const iss = getIssuer();\n const aud = getAudience();\n\n return {\n ...(iss !== undefined ? { allowedIss: iss } : {}),\n ...(aud !== undefined ? { allowedAud: aud } : {}),\n required: [...(iss !== undefined ? [\"iss\"] : []), ...(aud !== undefined ? [\"aud\"] : [])],\n };\n}\n\nexport const jwt = {\n /**\n * Generate a new JWT token for the user.\n * @param payload The payload to encode in the JWT token.\n */\n async generate(\n payload: any,\n {\n key = getSecretKey(),\n algorithm = getAlgorithm(),\n ...options\n }: SignerOptions & { key?: string } = {},\n ): Promise<string> {\n const claims = issuedClaims();\n const build = () => createSigner({ key, ...claims, ...options, algorithm }) as Sign;\n const sign = onlyKeyedOptions(options, [\"expiresIn\"])\n ? preparedFor(\"sign:access\", { key, algorithm, claims, expiresIn: options.expiresIn }, build)\n : build();\n\n return sign({ jti: randomUUID(), ...payload, tokenType: ACCESS_TOKEN_TYPE });\n },\n\n /**\n * Verify the given token.\n * @param token The JWT token to verify.\n * @returns The decoded token payload if verification is successful.\n */\n async verify<T = unknown>(\n token: string,\n {\n key = getSecretKey(),\n algorithms = [getAlgorithm()],\n requiredClaims,\n ...options\n }: VerifierOptions & { key?: string } = {},\n ): Promise<T> {\n const { required, ...expected } = expectedClaims();\n const build = () =>\n createVerifier({\n key,\n ...expected,\n ...options,\n algorithms,\n requiredClaims: withRequiredClaims([...(requiredClaims ?? []), ...required]),\n }) as Verify;\n const verify =\n requiredClaims === undefined && onlyKeyedOptions(options)\n ? preparedFor(\"verify:access\", { key, algorithms, expected, required }, build)\n : build();\n\n const decoded = (await verify(token)) as T;\n\n assertTokenType(decoded, ACCESS_TOKEN_TYPE);\n\n return decoded;\n },\n\n /**\n * Generate a new refresh token for the user.\n */\n async generateRefreshToken(\n payload: any,\n {\n key = getRefreshSecretKey(),\n expiresIn,\n algorithm = getAlgorithm(),\n ...options\n }: SignerOptions & { key?: string } = {},\n ): Promise<string> {\n const claims = issuedClaims();\n const build = () => createSigner({ key, expiresIn, algorithm, ...claims, ...options }) as Sign;\n const sign = onlyKeyedOptions(options)\n ? preparedFor(\"sign:refresh\", { key, algorithm, claims, expiresIn }, build)\n : build();\n\n return sign({ jti: randomUUID(), ...payload, tokenType: REFRESH_TOKEN_TYPE });\n },\n\n /**\n * Verify the given refresh token.\n */\n async verifyRefreshToken<T = unknown>(\n token: string,\n {\n key = getRefreshSecretKey(),\n algorithms = [getAlgorithm()],\n requiredClaims,\n ...options\n }: VerifierOptions & { key?: string } = {},\n ): Promise<T> {\n const { required, ...expected } = expectedClaims();\n const build = () =>\n createVerifier({\n key,\n algorithms,\n ...expected,\n ...options,\n requiredClaims: withRequiredClaims([...(requiredClaims ?? []), ...required]),\n }) as Verify;\n const verify =\n requiredClaims === undefined && onlyKeyedOptions(options)\n ? preparedFor(\"verify:refresh\", { key, algorithms, expected, required }, build)\n : build();\n\n const decoded = (await verify(token)) as T;\n\n assertTokenType(decoded, REFRESH_TOKEN_TYPE);\n\n return decoded;\n },\n};\n"],"mappings":";;;;;;AAKA,MAAM,qBAAqB,WAAW,YAAY,OAAO;AACzD,MAAM,qBAAqB,WAAW,YAAY,UAAU;AAC5D,MAAM,kBAAkB,WAAW,YAAY,OAAO;AACtD,MAAM,oBAAoB,WAAW,YAAY,SAAS;AAI1D,MAAM,4BAA4B,WAAW,aAAa,OAAO,KAAK,aAAa;AAYnF,MAAM,oBAA+B;AACrC,MAAM,qBAAgC;;;;;;;;;AAUtC,MAAM,iDAAiC,IAAI,IAAY;CACrD;CACA;CACA;CACA;CACA;CACA;CAGA;CACA;CACA;CACA;CACA;CACA;;AAEF,CAAC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EAE1C,OAAO;CACT;;;;CAKA,MAAM,qBACJ,SACA,EACE,MAAM,oBAAoB,GAC1B,WACA,YAAY,aAAa,GACzB,GAAG,YACiC,CAAC,GACtB;EACjB,MAAM,SAAS,aAAa;EAC5B,MAAM,cAAc,aAAa;GAAE;GAAK;GAAW;GAAW,GAAG;GAAQ,GAAG;EAAQ,CAAC;EAKrF,QAJa,iBAAiB,OAAO,IACjC,YAAY,gBAAgB;GAAE;GAAK;GAAW;GAAQ;EAAU,GAAG,KAAK,IACxE,MAAM,EAEC,CAAC;GAAE,KAAK,WAAW;GAAG,GAAG;GAAS,WAAW;EAAmB,CAAC;CAC9E;;;;CAKA,MAAM,mBACJ,OACA,EACE,MAAM,oBAAoB,GAC1B,aAAa,CAAC,aAAa,CAAC,GAC5B,gBACA,GAAG,YACmC,CAAC,GAC7B;EACZ,MAAM,EAAE,UAAU,GAAG,aAAa,eAAe;EACjD,MAAM,cACJ,eAAe;GACb;GACA;GACA,GAAG;GACH,GAAG;GACH,gBAAgB,mBAAmB,CAAC,GAAI,kBAAkB,CAAC,GAAI,GAAG,QAAQ,CAAC;EAC7E,CAAC;EAMH,MAAM,UAAW,OAJf,mBAAmB,UAAa,iBAAiB,OAAO,IACpD,YAAY,kBAAkB;GAAE;GAAK;GAAY;GAAU;EAAS,GAAG,KAAK,IAC5E,MAAM,EAEiB,CAAC,KAAK;EAEnC,gBAAgB,SAAS,kBAAkB;EAE3C,OAAO;CACT;AACF"}
@@ -9,6 +9,11 @@ import { ChildModel } from "@warlock.js/cascade";
9
9
  * **Anti-enumeration:** resolves `undefined` whether or not the account exists
10
10
  * — an unknown identifier simply sends nothing. Notification availability is
11
11
  * checked before the lookup, so a misconfigured app fails identically for both.
12
+ * The notification is sent in the background: awaiting it (an SMTP round trip
13
+ * for a known account, nothing for an unknown one) would let response timing
14
+ * reveal which accounts exist. A send that fails is logged and emitted as
15
+ * `password.resetDeliveryFailed`; set `auth.passwordReset.awaitDelivery: true`
16
+ * to wait for it (and receive its error) instead.
12
17
  *
13
18
  * @throws NotificationsUnavailableError when `@warlock.js/notifications` is not installed or not configured.
14
19
  *
@@ -1 +1 @@
1
- {"version":3,"file":"password-reset.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/services/password-reset.ts"],"mappings":";;;;;;;;;;;;;;;;;;wBAwDsB,qBAAqB,UAAU,MACnD,OAAO,WAAW,IAClB,qBACC;;;;;;;;;;;wBAmCmB,cAAc,eAAe,sBAAsB,QAAQ"}
1
+ {"version":3,"file":"password-reset.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/services/password-reset.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;wBA8DsB,qBAAqB,UAAU,MACnD,OAAO,WAAW,IAClB,qBACC;;;;;;;;;;;wBAgDmB,cAAc,eAAe,sBAAsB,QAAQ"}
@@ -3,6 +3,7 @@ import { authEvents } from "./auth-events.mjs";
3
3
  import { authService } from "./auth.service.mjs";
4
4
  import { consumeOneTimeToken, issueOneTimeToken } from "./one-time-tokens.mjs";
5
5
  import { resolveTokenNotification } from "./token-notifications.mjs";
6
+ import { log } from "@warlock.js/logger";
6
7
 
7
8
  //#region ../../packages/auth/src/services/password-reset.ts
8
9
  /**
@@ -35,6 +36,11 @@ async function writePassword(user, plainPassword) {
35
36
  * **Anti-enumeration:** resolves `undefined` whether or not the account exists
36
37
  * — an unknown identifier simply sends nothing. Notification availability is
37
38
  * checked before the lookup, so a misconfigured app fails identically for both.
39
+ * The notification is sent in the background: awaiting it (an SMTP round trip
40
+ * for a known account, nothing for an unknown one) would let response timing
41
+ * reveal which accounts exist. A send that fails is logged and emitted as
42
+ * `password.resetDeliveryFailed`; set `auth.passwordReset.awaitDelivery: true`
43
+ * to wait for it (and receive its error) instead.
38
44
  *
39
45
  * @throws NotificationsUnavailableError when `@warlock.js/notifications` is not installed or not configured.
40
46
  *
@@ -50,10 +56,18 @@ async function requestPasswordReset(Model, identifier) {
50
56
  const { token, expiresAt } = await issueOneTimeToken(user, "password-reset", authConfig.passwordReset.expiresInMs(), true);
51
57
  authEvents.emit("password.resetRequested", user, token);
52
58
  const url = authConfig.passwordReset.url()?.(token, user);
53
- await notification.send(user, {
59
+ const delivery = Promise.resolve().then(() => notification.send(user, {
54
60
  token,
55
61
  expiresAt,
56
62
  ...url ? { url } : {}
63
+ }));
64
+ if (authConfig.passwordReset.awaitDelivery()) {
65
+ await delivery;
66
+ return;
67
+ }
68
+ delivery.catch((error) => {
69
+ log.error("auth", "password-reset", error);
70
+ authEvents.emit("password.resetDeliveryFailed", user, error);
57
71
  });
58
72
  }
59
73
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"password-reset.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/password-reset.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport type { Auth } from \"../models/auth.model\";\nimport { authConfig } from \"./auth-config\";\nimport { authEvents } from \"./auth-events\";\nimport { authService } from \"./auth.service\";\nimport { consumeOneTimeToken, issueOneTimeToken } from \"./one-time-tokens\";\nimport { resolveTokenNotification } from \"./token-notifications\";\n\n/**\n * Default password writer. Login verifies with `authService.verifyPassword`,\n * so that is the authority on what \"stored correctly\" means:\n *\n * 1. Save `hashPassword(plain)` — right for a model that stores what it's given.\n * 2. If that no longer verifies, the model hashed on save (core's\n * `useHashedPassword()`), double-hashing it: save the plaintext so the\n * model's own transformer hashes it once.\n * 3. Still not verifiable ⇒ throw. Never leave a reset that \"succeeded\" with a\n * password nobody can log in with.\n *\n * The first write is always a hash, so a model without a transformer never\n * has plaintext written.\n */\nasync function writePassword(user: Auth, plainPassword: string): Promise<void> {\n await user.merge({ password: await authService.hashPassword(plainPassword) } as never).save();\n\n if (await authService.verifyPassword(plainPassword, user.string(\"password\") ?? \"\")) return;\n\n await user.merge({ password: plainPassword } as never).save();\n\n const stored = user.string(\"password\") ?? \"\";\n\n if (stored !== plainPassword && (await authService.verifyPassword(plainPassword, stored))) {\n return;\n }\n\n throw new Error(\n \"@warlock.js/auth: resetPassword could not store a password that verifies — \" +\n \"set `auth.passwordReset.setPassword` to write it the way your user model expects.\",\n );\n}\n\n/**\n * Start a password reset for the account whose `auth.passwordReset.identifierField`\n * (default `email`) equals `identifier`: invalidate the account's unused reset\n * tokens, issue a new one, and send it through the reset notification.\n *\n * **Anti-enumeration:** resolves `undefined` whether or not the account exists\n * — an unknown identifier simply sends nothing. Notification availability is\n * checked before the lookup, so a misconfigured app fails identically for both.\n *\n * @throws NotificationsUnavailableError when `@warlock.js/notifications` is not installed or not configured.\n *\n * @example\n * await requestPasswordReset(User, request.input(\"email\"));\n * return response.success({ message: \"If the account exists, we sent a reset link.\" });\n */\nexport async function requestPasswordReset<T extends Auth>(\n Model: ChildModel<T>,\n identifier: string,\n): Promise<void> {\n const notification = await resolveTokenNotification(\"password-reset\");\n\n if (typeof identifier !== \"string\" || identifier.length === 0) return;\n\n const user = (await Model.first({\n [authConfig.passwordReset.identifierField()]: identifier,\n })) as T | null;\n\n if (!user) return;\n\n const { token, expiresAt } = await issueOneTimeToken(\n user,\n \"password-reset\",\n authConfig.passwordReset.expiresInMs(),\n true,\n );\n\n authEvents.emit(\"password.resetRequested\", user, token);\n\n const url = authConfig.passwordReset.url()?.(token, user);\n\n await notification.send(user, { token, expiresAt, ...(url ? { url } : {}) });\n}\n\n/**\n * Complete a password reset: consume the token, store the new password, then\n * revoke every access token, refresh token and cookie session the user holds\n * (`authService.revokeAllTokens`). Resolves to the user.\n *\n * Validate password strength BEFORE calling this — the token is consumed first.\n *\n * @throws InvalidOneTimeTokenError for an unknown, verification-purpose,\n * expired, superseded or already-used token.\n */\nexport async function resetPassword(token: string, newPassword: string): Promise<Auth> {\n const user = await consumeOneTimeToken(token, \"password-reset\");\n\n const setPassword = authConfig.passwordReset.setPassword();\n\n if (setPassword) {\n await setPassword(user, newPassword);\n } else {\n await writePassword(user, newPassword);\n }\n\n await authService.revokeAllTokens(user);\n\n authEvents.emit(\"password.reset\", user);\n\n return user;\n}\n"],"mappings":";;;;;;;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OAAO;AACT"}
1
+ {"version":3,"file":"password-reset.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/password-reset.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport { log } from \"@warlock.js/logger\";\nimport type { Auth } from \"../models/auth.model\";\nimport { authConfig } from \"./auth-config\";\nimport { authEvents } from \"./auth-events\";\nimport { authService } from \"./auth.service\";\nimport { consumeOneTimeToken, issueOneTimeToken } from \"./one-time-tokens\";\nimport { resolveTokenNotification } from \"./token-notifications\";\n\n/**\n * Default password writer. Login verifies with `authService.verifyPassword`,\n * so that is the authority on what \"stored correctly\" means:\n *\n * 1. Save `hashPassword(plain)` — right for a model that stores what it's given.\n * 2. If that no longer verifies, the model hashed on save (core's\n * `useHashedPassword()`), double-hashing it: save the plaintext so the\n * model's own transformer hashes it once.\n * 3. Still not verifiable ⇒ throw. Never leave a reset that \"succeeded\" with a\n * password nobody can log in with.\n *\n * The first write is always a hash, so a model without a transformer never\n * has plaintext written.\n */\nasync function writePassword(user: Auth, plainPassword: string): Promise<void> {\n await user.merge({ password: await authService.hashPassword(plainPassword) } as never).save();\n\n if (await authService.verifyPassword(plainPassword, user.string(\"password\") ?? \"\")) return;\n\n await user.merge({ password: plainPassword } as never).save();\n\n const stored = user.string(\"password\") ?? \"\";\n\n if (stored !== plainPassword && (await authService.verifyPassword(plainPassword, stored))) {\n return;\n }\n\n throw new Error(\n \"@warlock.js/auth: resetPassword could not store a password that verifies — \" +\n \"set `auth.passwordReset.setPassword` to write it the way your user model expects.\",\n );\n}\n\n/**\n * Start a password reset for the account whose `auth.passwordReset.identifierField`\n * (default `email`) equals `identifier`: invalidate the account's unused reset\n * tokens, issue a new one, and send it through the reset notification.\n *\n * **Anti-enumeration:** resolves `undefined` whether or not the account exists\n * — an unknown identifier simply sends nothing. Notification availability is\n * checked before the lookup, so a misconfigured app fails identically for both.\n * The notification is sent in the background: awaiting it (an SMTP round trip\n * for a known account, nothing for an unknown one) would let response timing\n * reveal which accounts exist. A send that fails is logged and emitted as\n * `password.resetDeliveryFailed`; set `auth.passwordReset.awaitDelivery: true`\n * to wait for it (and receive its error) instead.\n *\n * @throws NotificationsUnavailableError when `@warlock.js/notifications` is not installed or not configured.\n *\n * @example\n * await requestPasswordReset(User, request.input(\"email\"));\n * return response.success({ message: \"If the account exists, we sent a reset link.\" });\n */\nexport async function requestPasswordReset<T extends Auth>(\n Model: ChildModel<T>,\n identifier: string,\n): Promise<void> {\n const notification = await resolveTokenNotification(\"password-reset\");\n\n if (typeof identifier !== \"string\" || identifier.length === 0) return;\n\n const user = (await Model.first({\n [authConfig.passwordReset.identifierField()]: identifier,\n })) as T | null;\n\n if (!user) return;\n\n const { token, expiresAt } = await issueOneTimeToken(\n user,\n \"password-reset\",\n authConfig.passwordReset.expiresInMs(),\n true,\n );\n\n authEvents.emit(\"password.resetRequested\", user, token);\n\n const url = authConfig.passwordReset.url()?.(token, user);\n\n const delivery = Promise.resolve().then(() =>\n notification.send(user, { token, expiresAt, ...(url ? { url } : {}) }),\n );\n\n if (authConfig.passwordReset.awaitDelivery()) {\n await delivery;\n\n return;\n }\n\n delivery.catch((error: unknown) => {\n log.error(\"auth\", \"password-reset\", error);\n authEvents.emit(\"password.resetDeliveryFailed\", user, error);\n });\n}\n\n/**\n * Complete a password reset: consume the token, store the new password, then\n * revoke every access token, refresh token and cookie session the user holds\n * (`authService.revokeAllTokens`). Resolves to the user.\n *\n * Validate password strength BEFORE calling this — the token is consumed first.\n *\n * @throws InvalidOneTimeTokenError for an unknown, verification-purpose,\n * expired, superseded or already-used token.\n */\nexport async function resetPassword(token: string, newPassword: string): Promise<Auth> {\n const user = await consumeOneTimeToken(token, \"password-reset\");\n\n const setPassword = authConfig.passwordReset.setPassword();\n\n if (setPassword) {\n await setPassword(user, newPassword);\n } else {\n await writePassword(user, newPassword);\n }\n\n await authService.revokeAllTokens(user);\n\n authEvents.emit(\"password.reset\", user);\n\n return user;\n}\n"],"mappings":";;;;;;;;;;;;;;;;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,MAAM,oBAAoB,OAAO,gBAAgB;CAE9D,MAAM,cAAc,WAAW,cAAc,YAAY;CAEzD,IAAI,aACF,MAAM,YAAY,MAAM,WAAW;MAEnC,MAAM,cAAc,MAAM,WAAW;CAGvC,MAAM,YAAY,gBAAgB,IAAI;CAEtC,WAAW,KAAK,kBAAkB,IAAI;CAEtC,OAAO;AACT"}
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-request-user.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/services/resolve-request-user.ts"],"mappings":";;;YAgBY;;EAEV,YAAY;;EAEZ,oBAAoB;;EAEpB;;EAEA;;EAEA;;EAEA;;EAEA,eAAe;;;;;;YAOL;YAEA,mBAAmB;EACzB,MAAM;EAAO;;EACb;EAAY,SAAS;;;wBAoBX,eAAe,SAAS,SAAS,WAAW;;;;;;;;;;;;wBAqBtC,0BACpB,SAAS,SACT,UAAU,UACV,UAAS,4BACR,QAAQ;;;;;;;;wBAoHK,mBACd,SAAS,SACT,UAAU,UACV,UAAS,4BACR"}
1
+ {"version":3,"file":"resolve-request-user.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/services/resolve-request-user.ts"],"mappings":";;;YAiBY;;EAEV,YAAY;;EAEZ,oBAAoB;;EAEpB;;EAEA;;EAEA;;EAEA;;EAEA,eAAe;;;;;;YAOL;YAEA,mBAAmB;EACzB,MAAM;EAAO;;EACb;EAAY,SAAS;;;wBA+BX,eAAe,SAAS,SAAS,WAAW;;;;;;;;;;;;wBAmBtC,0BACpB,SAAS,SACT,UAAU,UACV,UAAS,4BACR,QAAQ;;;;;;;;wBA6HK,mBACd,SAAS,SACT,UAAU,UACV,UAAS,4BACR"}
@@ -1,5 +1,6 @@
1
1
  import { AccessToken } from "../models/access-token/access-token.model.mjs";
2
2
  import "../models/access-token/index.mjs";
3
+ import { readAuthCookie } from "./auth-cookie-names.mjs";
3
4
  import { isInvalidCredentialError, jwt } from "./jwt.mjs";
4
5
  import { authService } from "./auth.service.mjs";
5
6
  import { config } from "@warlock.js/core";
@@ -22,11 +23,19 @@ import { log } from "@warlock.js/logger";
22
23
  function accessTokenRowIsExpired(accessToken) {
23
24
  return typeof accessToken.isExpired === "boolean" ? accessToken.isExpired : true;
24
25
  }
26
+ /**
27
+ * Whether the token's claims name the user its row was issued to. The row is
28
+ * what proves the token was issued and not revoked; the user it resolves to
29
+ * must be that row's user too, never only what the claims say.
30
+ */
31
+ function claimsMatchRow(decoded, accessToken) {
32
+ if (String(decoded.id) !== String(accessToken.userId)) return false;
33
+ return decoded.userType === void 0 || decoded.userType === accessToken.userType;
34
+ }
25
35
  /** Read one credential (access or refresh) from the header or a cookie. */
26
36
  function readCredential(request, tokenFrom) {
27
37
  if (tokenFrom === "header") return request.authorizationValue;
28
- const value = request.cookie(tokenFrom.slice(7));
29
- return value ? String(value) : "";
38
+ return readAuthCookie(request, tokenFrom.slice(7));
30
39
  }
31
40
  /**
32
41
  * Resolve a request's credential to a user, reporting WHY it failed.
@@ -86,7 +95,7 @@ async function resolveRequestUserOutcome(request, response, options = {}) {
86
95
  decoded = await jwt.verify(authorizationValue);
87
96
  } catch (error) {
88
97
  if (!isInvalidCredentialError(error)) throw error;
89
- log.error("http", "auth", error);
98
+ log.debug("http", "auth", error);
90
99
  request.locals.user = void 0;
91
100
  if (await renew()) continue;
92
101
  return fail("invalid");
@@ -104,6 +113,11 @@ async function resolveRequestUserOutcome(request, response, options = {}) {
104
113
  if (await renew()) continue;
105
114
  return fail("invalid");
106
115
  }
116
+ if (!claimsMatchRow(decoded, accessToken)) {
117
+ request.locals.user = void 0;
118
+ if (await renew()) continue;
119
+ return fail("invalid");
120
+ }
107
121
  break;
108
122
  }
109
123
  const userType = decoded.userType ?? accessToken.userType;
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-request-user.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/resolve-request-user.ts"],"sourcesContent":["import { config, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport type { CookieDomainResolver, TokenFrom } from \"../contracts/types\";\nimport { AccessToken } from \"../models/access-token\";\nimport { authService } from \"./auth.service\";\nimport { isInvalidCredentialError, jwt } from \"./jwt\";\n\n/**\n * Decoded access-token claims the resolver reads. The full payload carries\n * more (`created_at`, `tokenType`, `iat`, `exp`) but only these drive routing.\n */\ntype DecodedAccessToken = {\n id: string | number;\n userType?: string;\n};\n\nexport type ResolveRequestUserOptions = {\n /** Where the access token is read from. Defaults to `\"header\"`. */\n tokenFrom?: TokenFrom;\n /** Refresh credential source; enables one automatic renewal per call. */\n refreshCredential?: TokenFrom;\n /** Refresh overlap window forwarded to `authService.renewAutomaticSession`. */\n overlapMs?: number;\n /** User types allowed to pass. Empty means any authenticated type. */\n allowedTypes?: string[];\n /** Absolute family lifetime in ms; rotation never extends a family past it. */\n maxAgeMs?: number;\n /** The single user type a renewal mints for. Required for renewal. */\n renewalUserType?: string;\n /** Select a request-scoped Domain for renewed cookies. */\n cookieDomain?: CookieDomainResolver;\n};\n\n/**\n * Why a request did not resolve to a user. The middleware maps each reason to\n * its own response; `resolveRequestUser` collapses them all to `null`.\n */\nexport type RequestUserFailure = \"missing\" | \"invalid\" | \"forbidden\" | \"unauthorized\";\n\nexport type RequestUserOutcome<TUser = any> =\n | { user: TUser; failure?: undefined }\n | { user: null; failure: RequestUserFailure };\n\n/**\n * Whether the persisted row says the token is dead.\n *\n * The answer belongs to the model (`AccessToken.isExpired`), so a registered\n * override that renames or reshapes its expiry column stays authoritative. A\n * row that cannot answer at all — an override that dropped the getter — is\n * treated as **expired**: a check must never quietly answer \"fine\" when it has\n * nothing to check.\n *\n * This is independent of the `exp` claim required by `jwt.verify`: that guard\n * catches a token whose *claims* carry no deadline; this one catches a token\n * whose *row* says the deadline has passed.\n */\nfunction accessTokenRowIsExpired(accessToken: AccessToken): boolean {\n return typeof accessToken.isExpired === \"boolean\" ? accessToken.isExpired : true;\n}\n\n/** Read one credential (access or refresh) from the header or a cookie. */\nexport function readCredential(request: Request, tokenFrom: TokenFrom): string {\n if (tokenFrom === \"header\") {\n return request.authorizationValue;\n }\n\n const value = request.cookie(tokenFrom.slice(\"cookie:\".length));\n\n return value ? String(value) : \"\";\n}\n\n/**\n * Resolve a request's credential to a user, reporting WHY it failed.\n *\n * Side effects match what `authMiddleware` always did: `request.locals.user` is\n * cleared on every failure, `request.decodedAccessToken` is set once a token\n * verifies, and stale rows are destroyed. It does NOT set `request.locals.user`\n * on success — the caller decides that.\n *\n * At most one renewal is attempted per call. The renewed access token is\n * checked through the same path; no handler or unsafe request replay happens.\n */\nexport async function resolveRequestUserOutcome(\n request: Request,\n response: Response,\n options: ResolveRequestUserOptions = {},\n): Promise<RequestUserOutcome> {\n const tokenFrom = options.tokenFrom ?? \"header\";\n const allowedTypes = options.allowedTypes ?? [];\n const { refreshCredential } = options;\n let authorizationValue = readCredential(request, tokenFrom);\n let renewalAttempted = false;\n\n const renew = async (): Promise<boolean> => {\n const { renewalUserType } = options;\n if (!refreshCredential || !renewalUserType || renewalAttempted) return false;\n\n renewalAttempted = true;\n const refreshToken = readCredential(request, refreshCredential);\n if (!refreshToken) return false;\n\n const pair = await authService.renewAutomaticSession(refreshToken, renewalUserType, {\n overlapMs: options.overlapMs,\n maxAgeMs: options.maxAgeMs,\n });\n if (!pair?.refreshToken) return false;\n\n authService.setAuthCookie(response, pair.accessToken, {\n name: tokenFrom.slice(\"cookie:\".length),\n domain: options.cookieDomain?.(request),\n });\n authService.setAuthCookie(response, pair.refreshToken, {\n name: refreshCredential.slice(\"cookie:\".length),\n domain: options.cookieDomain?.(request),\n });\n authorizationValue = pair.accessToken.token;\n\n return true;\n };\n\n const fail = (failure: RequestUserFailure): RequestUserOutcome => {\n request.locals.user = undefined;\n\n return { user: null, failure };\n };\n\n let decoded: DecodedAccessToken;\n let accessToken: AccessToken | null;\n\n while (true) {\n if (!authorizationValue) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"missing\");\n }\n\n try {\n decoded = await jwt.verify<DecodedAccessToken>(authorizationValue);\n } catch (error) {\n if (!isInvalidCredentialError(error)) throw error;\n log.error(\"http\", \"auth\", error);\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n request.decodedAccessToken = decoded;\n const AccessTokenModel = config.key(\"auth.accessToken.model\", AccessToken);\n accessToken = await AccessTokenModel.findByToken(authorizationValue);\n\n if (!accessToken) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n if (accessTokenRowIsExpired(accessToken)) {\n await accessToken.destroy();\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n break;\n }\n\n const userType = decoded.userType ?? accessToken.userType;\n\n if (allowedTypes.length && !allowedTypes.includes(userType)) {\n return { user: null, failure: \"forbidden\" };\n }\n\n const UserModel = config.key(`auth.userType.${userType}`);\n\n if (!UserModel) {\n // Configuration, not credentials. Throwing keeps a mis-registered app\n // loudly broken instead of quietly rejecting every request of this type.\n throw new Error(`User type ${userType} is unknown type.`);\n }\n\n const currentUser = await UserModel.find(decoded.id);\n\n if (!currentUser) {\n await accessToken.destroy();\n\n return fail(\"invalid\");\n }\n\n if (!(await authService.canAuthenticate(currentUser))) {\n return fail(\"unauthorized\");\n }\n\n return { user: currentUser };\n}\n\n/**\n * Resolve the request's credential to its user model, or `null` when there is\n * none (missing, invalid, expired, wrong type, or not allowed to authenticate).\n *\n * Includes the middleware's automatic renewal when `options.refreshCredential`\n * is set. Use `resolveRequestUserOutcome` when the failure reason matters.\n */\nexport function resolveRequestUser(\n request: Request,\n response: Response,\n options: ResolveRequestUserOptions = {},\n): Promise<any> {\n // Single-flight: the PROMISE is stored, so concurrent and repeat callers in\n // one request share one verify, one lookup and at most one renewal. The first\n // caller's options win for the rest of the request.\n if (!request.locals.session) {\n request.locals.session = resolveRequestUserOutcome(request, response, options).then(\n (outcome) => outcome.user,\n );\n }\n\n return request.locals.session;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAwDA,SAA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AId,IAAI,CAAC,QAAQ,OAAO,SAClB,QAAQ,OAAO,UAAU,0BAA0B,SAAS,UAAU,OAAO,CAAC,CAAC,MAC5E,YAAY,QAAQ,IACvB;CAGF,OAAO,QAAQ,OAAO;AACxB"}
1
+ {"version":3,"file":"resolve-request-user.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/resolve-request-user.ts"],"sourcesContent":["import { config, type Request, type Response } from \"@warlock.js/core\";\nimport { log } from \"@warlock.js/logger\";\nimport type { CookieDomainResolver, TokenFrom } from \"../contracts/types\";\nimport { AccessToken } from \"../models/access-token\";\nimport { readAuthCookie } from \"./auth-cookie-names\";\nimport { authService } from \"./auth.service\";\nimport { isInvalidCredentialError, jwt } from \"./jwt\";\n\n/**\n * Decoded access-token claims the resolver reads. The full payload carries\n * more (`created_at`, `tokenType`, `iat`, `exp`) but only these drive routing.\n */\ntype DecodedAccessToken = {\n id: string | number;\n userType?: string;\n};\n\nexport type ResolveRequestUserOptions = {\n /** Where the access token is read from. Defaults to `\"header\"`. */\n tokenFrom?: TokenFrom;\n /** Refresh credential source; enables one automatic renewal per call. */\n refreshCredential?: TokenFrom;\n /** Refresh overlap window forwarded to `authService.renewAutomaticSession`. */\n overlapMs?: number;\n /** User types allowed to pass. Empty means any authenticated type. */\n allowedTypes?: string[];\n /** Absolute family lifetime in ms; rotation never extends a family past it. */\n maxAgeMs?: number;\n /** The single user type a renewal mints for. Required for renewal. */\n renewalUserType?: string;\n /** Select a request-scoped Domain for renewed cookies. */\n cookieDomain?: CookieDomainResolver;\n};\n\n/**\n * Why a request did not resolve to a user. The middleware maps each reason to\n * its own response; `resolveRequestUser` collapses them all to `null`.\n */\nexport type RequestUserFailure = \"missing\" | \"invalid\" | \"forbidden\" | \"unauthorized\";\n\nexport type RequestUserOutcome<TUser = any> =\n | { user: TUser; failure?: undefined }\n | { user: null; failure: RequestUserFailure };\n\n/**\n * Whether the persisted row says the token is dead.\n *\n * The answer belongs to the model (`AccessToken.isExpired`), so a registered\n * override that renames or reshapes its expiry column stays authoritative. A\n * row that cannot answer at all — an override that dropped the getter — is\n * treated as **expired**: a check must never quietly answer \"fine\" when it has\n * nothing to check.\n *\n * This is independent of the `exp` claim required by `jwt.verify`: that guard\n * catches a token whose *claims* carry no deadline; this one catches a token\n * whose *row* says the deadline has passed.\n */\nfunction accessTokenRowIsExpired(accessToken: AccessToken): boolean {\n return typeof accessToken.isExpired === \"boolean\" ? accessToken.isExpired : true;\n}\n\n/**\n * Whether the token's claims name the user its row was issued to. The row is\n * what proves the token was issued and not revoked; the user it resolves to\n * must be that row's user too, never only what the claims say.\n */\nfunction claimsMatchRow(decoded: DecodedAccessToken, accessToken: AccessToken): boolean {\n if (String(decoded.id) !== String(accessToken.userId)) return false;\n\n return decoded.userType === undefined || decoded.userType === accessToken.userType;\n}\n\n/** Read one credential (access or refresh) from the header or a cookie. */\nexport function readCredential(request: Request, tokenFrom: TokenFrom): string {\n if (tokenFrom === \"header\") {\n return request.authorizationValue;\n }\n\n return readAuthCookie(request, tokenFrom.slice(\"cookie:\".length));\n}\n\n/**\n * Resolve a request's credential to a user, reporting WHY it failed.\n *\n * Side effects match what `authMiddleware` always did: `request.locals.user` is\n * cleared on every failure, `request.decodedAccessToken` is set once a token\n * verifies, and stale rows are destroyed. It does NOT set `request.locals.user`\n * on success — the caller decides that.\n *\n * At most one renewal is attempted per call. The renewed access token is\n * checked through the same path; no handler or unsafe request replay happens.\n */\nexport async function resolveRequestUserOutcome(\n request: Request,\n response: Response,\n options: ResolveRequestUserOptions = {},\n): Promise<RequestUserOutcome> {\n const tokenFrom = options.tokenFrom ?? \"header\";\n const allowedTypes = options.allowedTypes ?? [];\n const { refreshCredential } = options;\n let authorizationValue = readCredential(request, tokenFrom);\n let renewalAttempted = false;\n\n const renew = async (): Promise<boolean> => {\n const { renewalUserType } = options;\n if (!refreshCredential || !renewalUserType || renewalAttempted) return false;\n\n renewalAttempted = true;\n const refreshToken = readCredential(request, refreshCredential);\n if (!refreshToken) return false;\n\n const pair = await authService.renewAutomaticSession(refreshToken, renewalUserType, {\n overlapMs: options.overlapMs,\n maxAgeMs: options.maxAgeMs,\n });\n if (!pair?.refreshToken) return false;\n\n authService.setAuthCookie(response, pair.accessToken, {\n name: tokenFrom.slice(\"cookie:\".length),\n domain: options.cookieDomain?.(request),\n });\n authService.setAuthCookie(response, pair.refreshToken, {\n name: refreshCredential.slice(\"cookie:\".length),\n domain: options.cookieDomain?.(request),\n });\n authorizationValue = pair.accessToken.token;\n\n return true;\n };\n\n const fail = (failure: RequestUserFailure): RequestUserOutcome => {\n request.locals.user = undefined;\n\n return { user: null, failure };\n };\n\n let decoded: DecodedAccessToken;\n let accessToken: AccessToken | null;\n\n while (true) {\n if (!authorizationValue) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"missing\");\n }\n\n try {\n decoded = await jwt.verify<DecodedAccessToken>(authorizationValue);\n } catch (error) {\n if (!isInvalidCredentialError(error)) throw error;\n // An expired or garbage token is an ordinary client error that any\n // anonymous caller can produce at will: debug, so it cannot flood the\n // error log.\n log.debug(\"http\", \"auth\", error);\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n request.decodedAccessToken = decoded;\n const AccessTokenModel = config.key(\"auth.accessToken.model\", AccessToken);\n accessToken = await AccessTokenModel.findByToken(authorizationValue);\n\n if (!accessToken) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n if (accessTokenRowIsExpired(accessToken)) {\n await accessToken.destroy();\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n if (!claimsMatchRow(decoded, accessToken)) {\n request.locals.user = undefined;\n if (await renew()) continue;\n return fail(\"invalid\");\n }\n\n break;\n }\n\n const userType = decoded.userType ?? accessToken.userType;\n\n if (allowedTypes.length && !allowedTypes.includes(userType)) {\n return { user: null, failure: \"forbidden\" };\n }\n\n const UserModel = config.key(`auth.userType.${userType}`);\n\n if (!UserModel) {\n // Configuration, not credentials. Throwing keeps a mis-registered app\n // loudly broken instead of quietly rejecting every request of this type.\n throw new Error(`User type ${userType} is unknown type.`);\n }\n\n const currentUser = await UserModel.find(decoded.id);\n\n if (!currentUser) {\n await accessToken.destroy();\n\n return fail(\"invalid\");\n }\n\n if (!(await authService.canAuthenticate(currentUser))) {\n return fail(\"unauthorized\");\n }\n\n return { user: currentUser };\n}\n\n/**\n * Resolve the request's credential to its user model, or `null` when there is\n * none (missing, invalid, expired, wrong type, or not allowed to authenticate).\n *\n * Includes the middleware's automatic renewal when `options.refreshCredential`\n * is set. Use `resolveRequestUserOutcome` when the failure reason matters.\n */\nexport function resolveRequestUser(\n request: Request,\n response: Response,\n options: ResolveRequestUserOptions = {},\n): Promise<any> {\n // Single-flight: the PROMISE is stored, so concurrent and repeat callers in\n // one request share one verify, one lookup and at most one renewal. The first\n // caller's options win for the rest of the request.\n if (!request.locals.session) {\n request.locals.session = resolveRequestUserOutcome(request, response, options).then(\n (outcome) => outcome.user,\n );\n }\n\n return request.locals.session;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAyDA,SAAS,wBAAwB,aAAmC;CAClE,OAAO,OAAO,YAAY,cAAc,YAAY,YAAY,YAAY;AAC9E;;;;;;AAOA,SAAS,eAAe,SAA6B,aAAmC;CACtF,IAAI,OAAO,QAAQ,EAAE,MAAM,OAAO,YAAY,MAAM,GAAG,OAAO;CAE9D,OAAO,QAAQ,aAAa,UAAa,QAAQ,aAAa,YAAY;AAC5E;;AAGA,SAAgB,eAAe,SAAkB,WAA8B;CAC7E,IAAI,cAAc,UAChB,OAAO,QAAQ;CAGjB,OAAO,eAAe,SAAS,UAAU,MAAM,CAAgB,CAAC;AAClE;;;;;;;;;;;;AAaA,eAAsB,0BACpB,SACA,UACA,UAAqC,CAAC,GACT;CAC7B,MAAM,YAAY,QAAQ,aAAa;CACvC,MAAM,eAAe,QAAQ,gBAAgB,CAAC;CAC9C,MAAM,EAAE,sBAAsB;CAC9B,IAAI,qB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S,SAAS,UAAU,WAAW;IAAU,OAAO;IAAQ,MAAM;;;YAGpE;;EAEV;;EAEA;;EAEA,UAAU;;EAEV;;EAEA;;EAEA;;EAEA;;EAEA,eAAe;;YAGL,mBAAmB,QAAQ,SAAS;;EAE9C,UAAU,OAAO,WAAW,QAAQ,QAAQ;;YAGlC,2BAA2B;;EAErC;;;;;;;;;wBAgFc,YAAY,kBAAkB,iBAC5C,SAAS,mBAAmB,QAAQ,SACnC,oBAAoB,QAAQ;;;;;;;wBAmCf,kBAAkB,UAAS,2BAAgC"}
1
+ {"version":3,"file":"page-session.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/session/page-session.ts"],"mappings":";;;;YAsBY;;;;;;YAUA,oBAAoB,kBAAkB;EAChD,QAAQ,SAAS,SAAS,UAAU,WAAW;IAAU,OAAO;IAAQ,MAAM;;;YAGpE;;EAEV;;EAEA;;EAEA,UAAU;;EAEV;;EAEA;;EAEA;;EAEA;;EAEA,eAAe;;YAGL,mBAAmB,QAAQ,SAAS;;EAE9C,UAAU,OAAO,WAAW,QAAQ,QAAQ;;YAGlC,2BAA2B;;EAErC;;;;;;;;;wBAmFc,YAAY,kBAAkB,iBAC5C,SAAS,mBAAmB,QAAQ,SACnC,oBAAoB,QAAQ;;;;;;;wBAmCf,kBAAkB,UAAS,2BAAgC"}
@@ -1,6 +1,7 @@
1
1
  import { AuthErrorCodes } from "../utils/auth-error-codes.mjs";
2
2
  import { CsrfOriginMismatchError, assertCsrfOriginAllowed, requiresCsrfOriginCheck } from "../middleware/csrf-origin-check.mjs";
3
3
  import { authConfig } from "../services/auth-config.mjs";
4
+ import { readAuthCookie } from "../services/auth-cookie-names.mjs";
4
5
  import { resolveRequestUser } from "../services/resolve-request-user.mjs";
5
6
  import { config, markAuthGuard, t } from "@warlock.js/core";
6
7
  import { log } from "@warlock.js/logger";
@@ -35,7 +36,8 @@ function createModelResolver(options) {
35
36
  const refreshName = options.refreshCookie ?? authConfig.cookie.refreshName();
36
37
  const headerWins = useHeader && Boolean(request.authorizationValue);
37
38
  if (!headerWins && !useCookie) return null;
38
- if (!headerWins && !request.cookie(accessName) && !request.cookie(refreshName)) return null;
39
+ const hasCookie = Boolean(readAuthCookie(request, accessName)) || Boolean(readAuthCookie(request, refreshName));
40
+ if (!headerWins && !hasCookie) return null;
39
41
  const allowedTypes = resolveUserTypes(options.userTypes);
40
42
  const renewalUserType = allowedTypes.length === 1 ? allowedTypes[0] : void 0;
41
43
  const canRenew = !headerWins && renew && Boolean(renewalUserType);
@@ -96,11 +98,11 @@ function sessionMiddleware(options = {}) {
96
98
  if (!(sources.includes("header") && Boolean(request.authorizationValue)) && requiresCsrfOriginCheck("cookie:x", request.method)) {
97
99
  const accessName = options.cookie ?? authConfig.cookie.name();
98
100
  const refreshName = options.refreshCookie ?? authConfig.cookie.refreshName();
99
- if (request.cookie(accessName) || request.cookie(refreshName)) try {
101
+ if (readAuthCookie(request, accessName) || readAuthCookie(request, refreshName)) try {
100
102
  assertCsrfOriginAllowed(request);
101
103
  } catch (error) {
102
104
  if (!(error instanceof CsrfOriginMismatchError)) throw error;
103
- log.error("http", "auth", error);
105
+ log.debug("http", "auth", error);
104
106
  return response.forbidden({
105
107
  error: t("auth.errors.csrfOriginMismatch"),
106
108
  errorCode: "EC006"
@@ -1 +1 @@
1
- {"version":3,"file":"page-session.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/session/page-session.ts"],"sourcesContent":["import {\n config,\n markAuthGuard,\n t,\n type Middleware,\n type Request,\n type Response,\n} from \"@warlock.js/core\";\nimport type { CookieDomainResolver } from \"../contracts/types\";\nimport { log } from \"@warlock.js/logger\";\nimport ms from \"ms\";\nimport {\n assertCsrfOriginAllowed,\n CsrfOriginMismatchError,\n requiresCsrfOriginCheck,\n} from \"../middleware/csrf-origin-check\";\nimport { authConfig } from \"../services/auth-config\";\nimport { resolveRequestUser } from \"../services/resolve-request-user\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/** Credential sources a session can be read from. */\nexport type SessionSource = \"cookie\" | \"header\";\n\n/** Absolute family lifetime used when `session.maxAge` is not configured. */\nconst DEFAULT_SESSION_MAX_AGE = \"30d\";\n\n/**\n * The seam web consumes. Declared here, not imported: web and auth never\n * depend on each other, and `pageSession()` satisfies web's `SessionResolver`\n * structurally.\n */\nexport type PageSessionResolver<TModel = unknown, TUser = unknown> = {\n resolve(request: Request, response: Response): Promise<{ model: TModel; user: TUser } | null>;\n};\n\nexport type SessionResolverOptions = {\n /** Access cookie name. @default auth.cookie.name */\n cookie?: string;\n /** Refresh cookie name. @default auth.cookie.refreshName */\n refreshCookie?: string;\n /** Credential sources. A present Authorization header always wins. @default [\"cookie\", \"header\"] */\n sources?: SessionSource[];\n /** Renew an expired access cookie from the refresh cookie. Cookie source only. @default true */\n renew?: boolean;\n /** Allowed user types. @default auth.defaultUserType */\n userTypes?: string | string[];\n /** Absolute family lifetime, an `ms` string or milliseconds. @default auth.session.maxAge, else \"30d\" */\n maxAge?: string | number;\n /** Refresh overlap window forwarded to renewal. */\n overlapMs?: number;\n /** Select a request-scoped Domain for renewed cookies; `undefined` keeps them host-only. */\n cookieDomain?: CookieDomainResolver;\n};\n\nexport type PageSessionOptions<TModel, TUser> = SessionResolverOptions & {\n /** Model → wire projection. Required: a model never crosses the wire by default. */\n project: (model: TModel) => TUser | Promise<TUser>;\n};\n\nexport type SessionMiddlewareOptions = SessionResolverOptions & {\n /** Let guests through with no user instead of a 401. @default false */\n optional?: boolean;\n};\n\nfunction resolveMaxAgeMs(maxAge: string | number | undefined): number {\n const raw = maxAge ?? config.key(\"auth.session.maxAge\", DEFAULT_SESSION_MAX_AGE);\n const parsed = typeof raw === \"number\" ? raw : ms(raw as ms.StringValue);\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `session.maxAge: ${JSON.stringify(raw)} is not a valid ms duration — use a positive duration such as \"30d\".`,\n );\n }\n\n return parsed;\n}\n\nfunction resolveUserTypes(value: string | string[] | undefined): string[] {\n if (value !== undefined) return Array.isArray(value) ? value : [value];\n\n const configured = config.key(\"auth.defaultUserType\");\n\n return configured ? [configured as string] : [];\n}\n\n/**\n * The shared \"credential → model\" step behind `pageSession` and\n * `sessionMiddleware`. Resolved once per request through\n * `resolveRequestUser`'s single-flight memo.\n */\nfunction createModelResolver(options: SessionResolverOptions) {\n const sources = options.sources?.length ? options.sources : ([\"cookie\", \"header\"] as const);\n const useHeader = sources.includes(\"header\");\n const useCookie = sources.includes(\"cookie\");\n const renew = options.renew ?? true;\n\n const resolveModel = async (\n request: Request,\n response: Response,\n ): Promise<{ model: unknown; source: \"header\" | \"cookie\" } | null> => {\n const accessName = options.cookie ?? authConfig.cookie.name();\n const refreshName = options.refreshCookie ?? authConfig.cookie.refreshName();\n // A present Authorization header wins and never falls back to the cookie.\n const headerWins = useHeader && Boolean(request.authorizationValue);\n\n if (!headerWins && !useCookie) return null;\n\n // Cheap guest path: nothing to decode, so nothing is marked auth-derived.\n if (!headerWins && !request.cookie(accessName) && !request.cookie(refreshName)) return null;\n\n const allowedTypes = resolveUserTypes(options.userTypes);\n const renewalUserType = allowedTypes.length === 1 ? allowedTypes[0] : undefined;\n const canRenew = !headerWins && renew && Boolean(renewalUserType);\n\n const model = await resolveRequestUser(request, response, {\n tokenFrom: headerWins ? \"header\" : `cookie:${accessName}`,\n refreshCredential: canRenew ? `cookie:${refreshName}` : undefined,\n overlapMs: options.overlapMs,\n maxAgeMs: resolveMaxAgeMs(options.maxAge),\n allowedTypes,\n renewalUserType,\n cookieDomain: options.cookieDomain ?? authConfig.cookie.cookieDomain(),\n });\n\n if (!model) return null;\n\n request.locals.user = model;\n\n return { model, source: headerWins ? \"header\" : \"cookie\" };\n };\n\n return resolveModel;\n}\n\n/**\n * Session resolver for pages: cookie-or-header credential, reactive renewal,\n * one resolution per request. Plug it into `web.session`.\n *\n * @example\n * export default { session: pageSession({ project: (user: User) => userResource(user) }) };\n */\nexport function pageSession<TModel = unknown, TUser = unknown>(\n options: PageSessionOptions<TModel, TUser>,\n): PageSessionResolver<TModel, TUser> {\n if (typeof options?.project !== \"function\") {\n throw new Error(\n \"pageSession requires a `project(model)` function: a model never crosses the wire by default.\",\n );\n }\n\n const resolveModel = createModelResolver(options);\n const projections = new WeakMap<object, Promise<unknown>>();\n\n return {\n async resolve(request, response) {\n const resolved = await resolveModel(request, response);\n\n if (!resolved) return null;\n\n const model = resolved.model as TModel;\n let projected = projections.get(request as object);\n\n if (!projected) {\n projected = Promise.resolve(options.project(model));\n projections.set(request as object, projected);\n }\n\n return { model, user: (await projected) as TUser };\n },\n };\n}\n\n/**\n * Middleware for cookie API routes over the same resolver as `pageSession`.\n * A cookie-authenticated unsafe request must pass the Origin/Referer check\n * (renewal can mint cookies, so it runs even when the access cookie is gone).\n * Guests get a 401 unless `optional`. The user lands on `request.locals.user`.\n */\nexport function sessionMiddleware(options: SessionMiddlewareOptions = {}): Middleware {\n const resolveModel = createModelResolver(options);\n const sources = options.sources?.length ? options.sources : [\"cookie\", \"header\"];\n\n const middleware: Middleware = async ({ request, response }) => {\n const headerWins = sources.includes(\"header\") && Boolean(request.authorizationValue);\n\n if (!headerWins && requiresCsrfOriginCheck(\"cookie:x\", request.method)) {\n const accessName = options.cookie ?? authConfig.cookie.name();\n const refreshName = options.refreshCookie ?? authConfig.cookie.refreshName();\n\n if (request.cookie(accessName) || request.cookie(refreshName)) {\n try {\n assertCsrfOriginAllowed(request);\n } catch (error) {\n if (!(error instanceof CsrfOriginMismatchError)) throw error;\n\n log.error(\"http\", \"auth\", error);\n\n return response.forbidden({\n error: t(\"auth.errors.csrfOriginMismatch\"),\n errorCode: AuthErrorCodes.CsrfOriginMismatch,\n });\n }\n }\n }\n\n const resolved = await resolveModel(request, response);\n\n if (resolved || options.optional) return;\n\n return response.unauthorized({\n error: t(\"auth.errors.unauthorized\"),\n errorCode: AuthErrorCodes.Unauthorized,\n });\n };\n Object.defineProperty(middleware, Symbol.for(\"warlock.auth\"), {\n value: Object.freeze({\n sources: Object.freeze(\n sources.map((source) =>\n source === \"header\"\n ? \"header\"\n : Object.freeze({ cookie: options.cookie ?? authConfig.cookie.name() }),\n ),\n ),\n userTypes: Object.freeze([...resolveUserTypes(options.userTypes)]),\n required: options.optional !== true,\n }),\n enumerable: false,\n });\n return markAuthGuard(middleware, options.optional !== true);\n}\n"],"mappings":";;;;;;;;;;AAwBA,MAAM,0BAA0B;AAwChC,SAAS,gBAAgB,QAA6C;CACpE,MAAM,MAAM,UAAU,OAAO,IAAI,uBAAuB,uBAAuB;CAC/E,MAAM,SAAS,OAAO,QAAQ,WAAW,MAAM,GAAG,GAAqB;CAEvE,IAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,MAAM,KAAK,UAAU,GACtE,MAAM,IAAI,MACR,mBAAmB,KAAK,UAAU,GAAG,EAAE,qEACzC;CAGF,OAAO;AACT;AAEA,SAAS,iBAAiB,OAAgD;CACxE,IAAI,UAAU,QAAW,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;CAErE,MAAM,aAAa,OAAO,IAAI,sBAAsB;CAEpD,OAAO,aAAa,CAAC,UAAoB,IAAI,CAAC;AAChD;;;;;;AAOA,SAAS,oBAAoB,SAAiC;CAC5D,MAAM,UAAU,QAAQ,SAAS,SAAS,QAAQ,UAAW,CAAC,UAAU,QAAQ;CAChF,MAAM,YAAY,QAAQ,SAAS,QAAQ;CAC3C,MAAM,YAAY,QAAQ,SAAS,QAAQ;CAC3C,MAAM,QAAQ,QAAQ,SAAS;CAE/B,MAAM,eAAe,OACnB,SACA,aACoE;EACpE,MAAM,aAAa,QAAQ,UAAU,WAAW,OAAO,KAAK;EAC5D,MAAM,cAAc,QAAQ,iBAAiB,WAAW,OAAO,YAAY;EAE3E,MAAM,aAAa,aAAa,QAAQ,QAAQ,kBAAkB;EAElE,IAAI,CAAC,cAAc,CAAC,WAAW,OAAO;EAGtC,IAAI,CAAC,cAAc,CAAC,QAAQ,OAAO,UAAU,KA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O,EAAE,SAAS,eAAe;EAG9D,IAAI,EAFe,QAAQ,SAAS,QAAQ,KAAK,QAAQ,QAAQ,kBAAkB,MAEhE,wBAAwB,YAAY,QAAQ,MAAM,GAAG;GACtE,MAAM,aAAa,QAAQ,UAAU,WAAW,OAAO,KAAK;GAC5D,MAAM,cAAc,QAAQ,iBAAiB,WAAW,OAAO,YAAY;GAE3E,IAAI,QAAQ,OAAO,UAAU,KAAK,QAAQ,OAAO,WAAW,GAC1D,IAAI;IACF,wBAAwB,OAAO;GACjC,SAAS,OAAO;IACd,IAAI,EAAE,iBAAiB,0BAA0B,MAAM;IAEvD,IAAI,MAAM,QAAQ,QAAQ,KAAK;IAE/B,OAAO,SAAS,UAAU;KACxB,OAAO,EAAE,gCAAgC;KACzC;IACF,CAAC;GACH;EAEJ;EAIA,IAAI,MAFmB,aAAa,SAAS,QAAQ,KAErC,QAAQ,UAAU;EAElC,OAAO,SAAS,aAAa;GAC3B,OAAO,EAAE,0BAA0B;GACnC;EACF,CAAC;CACH;CACA,OAAO,eAAe,YAAY,OAAO,IAAI,cAAc,GAAG;EAC5D,OAAO,OAAO,OAAO;GACnB,SAAS,OAAO,OACd,QAAQ,KAAK,WACX,WAAW,WACP,WACA,OAAO,OAAO,EAAE,QAAQ,QAAQ,UAAU,WAAW,OAAO,KAAK,EAAE,CAAC,CAC1E,CACF;GACA,WAAW,OAAO,OAAO,CAAC,GAAG,iBAAiB,QAAQ,SAAS,CAAC,CAAC;GACjE,UAAU,QAAQ,aAAa;EACjC,CAAC;EACD,YAAY;CACd,CAAC;CACD,OAAO,cAAc,YAAY,QAAQ,aAAa,IAAI;AAC5D"}
1
+ {"version":3,"file":"page-session.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/session/page-session.ts"],"sourcesContent":["import {\n config,\n markAuthGuard,\n t,\n type Middleware,\n type Request,\n type Response,\n} from \"@warlock.js/core\";\nimport type { CookieDomainResolver } from \"../contracts/types\";\nimport { log } from \"@warlock.js/logger\";\nimport ms from \"ms\";\nimport {\n assertCsrfOriginAllowed,\n CsrfOriginMismatchError,\n requiresCsrfOriginCheck,\n} from \"../middleware/csrf-origin-check\";\nimport { authConfig } from \"../services/auth-config\";\nimport { readAuthCookie } from \"../services/auth-cookie-names\";\nimport { resolveRequestUser } from \"../services/resolve-request-user\";\nimport { AuthErrorCodes } from \"../utils/auth-error-codes\";\n\n/** Credential sources a session can be read from. */\nexport type SessionSource = \"cookie\" | \"header\";\n\n/** Absolute family lifetime used when `session.maxAge` is not configured. */\nconst DEFAULT_SESSION_MAX_AGE = \"30d\";\n\n/**\n * The seam web consumes. Declared here, not imported: web and auth never\n * depend on each other, and `pageSession()` satisfies web's `SessionResolver`\n * structurally.\n */\nexport type PageSessionResolver<TModel = unknown, TUser = unknown> = {\n resolve(request: Request, response: Response): Promise<{ model: TModel; user: TUser } | null>;\n};\n\nexport type SessionResolverOptions = {\n /** Access cookie name. @default auth.cookie.name */\n cookie?: string;\n /** Refresh cookie name. @default auth.cookie.refreshName */\n refreshCookie?: string;\n /** Credential sources. A present Authorization header always wins. @default [\"cookie\", \"header\"] */\n sources?: SessionSource[];\n /** Renew an expired access cookie from the refresh cookie. Cookie source only. @default true */\n renew?: boolean;\n /** Allowed user types. @default auth.defaultUserType */\n userTypes?: string | string[];\n /** Absolute family lifetime, an `ms` string or milliseconds. @default auth.session.maxAge, else \"30d\" */\n maxAge?: string | number;\n /** Refresh overlap window forwarded to renewal. */\n overlapMs?: number;\n /** Select a request-scoped Domain for renewed cookies; `undefined` keeps them host-only. */\n cookieDomain?: CookieDomainResolver;\n};\n\nexport type PageSessionOptions<TModel, TUser> = SessionResolverOptions & {\n /** Model → wire projection. Required: a model never crosses the wire by default. */\n project: (model: TModel) => TUser | Promise<TUser>;\n};\n\nexport type SessionMiddlewareOptions = SessionResolverOptions & {\n /** Let guests through with no user instead of a 401. @default false */\n optional?: boolean;\n};\n\nfunction resolveMaxAgeMs(maxAge: string | number | undefined): number {\n const raw = maxAge ?? config.key(\"auth.session.maxAge\", DEFAULT_SESSION_MAX_AGE);\n const parsed = typeof raw === \"number\" ? raw : ms(raw as ms.StringValue);\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `session.maxAge: ${JSON.stringify(raw)} is not a valid ms duration — use a positive duration such as \"30d\".`,\n );\n }\n\n return parsed;\n}\n\nfunction resolveUserTypes(value: string | string[] | undefined): string[] {\n if (value !== undefined) return Array.isArray(value) ? value : [value];\n\n const configured = config.key(\"auth.defaultUserType\");\n\n return configured ? [configured as string] : [];\n}\n\n/**\n * The shared \"credential → model\" step behind `pageSession` and\n * `sessionMiddleware`. Resolved once per request through\n * `resolveRequestUser`'s single-flight memo.\n */\nfunction createModelResolver(options: SessionResolverOptions) {\n const sources = options.sources?.length ? options.sources : ([\"cookie\", \"header\"] as const);\n const useHeader = sources.includes(\"header\");\n const useCookie = sources.includes(\"cookie\");\n const renew = options.renew ?? true;\n\n const resolveModel = async (\n request: Request,\n response: Response,\n ): Promise<{ model: unknown; source: \"header\" | \"cookie\" } | null> => {\n const accessName = options.cookie ?? authConfig.cookie.name();\n const refreshName = options.refreshCookie ?? authConfig.cookie.refreshName();\n // A present Authorization header wins and never falls back to the cookie.\n const headerWins = useHeader && Boolean(request.authorizationValue);\n\n if (!headerWins && !useCookie) return null;\n\n // Cheap guest path: nothing to decode, so nothing is marked auth-derived.\n const hasCookie =\n Boolean(readAuthCookie(request, accessName)) || Boolean(readAuthCookie(request, refreshName));\n\n if (!headerWins && !hasCookie) return null;\n\n const allowedTypes = resolveUserTypes(options.userTypes);\n const renewalUserType = allowedTypes.length === 1 ? allowedTypes[0] : undefined;\n const canRenew = !headerWins && renew && Boolean(renewalUserType);\n\n const model = await resolveRequestUser(request, response, {\n tokenFrom: headerWins ? \"header\" : `cookie:${accessName}`,\n refreshCredential: canRenew ? `cookie:${refreshName}` : undefined,\n overlapMs: options.overlapMs,\n maxAgeMs: resolveMaxAgeMs(options.maxAge),\n allowedTypes,\n renewalUserType,\n cookieDomain: options.cookieDomain ?? authConfig.cookie.cookieDomain(),\n });\n\n if (!model) return null;\n\n request.locals.user = model;\n\n return { model, source: headerWins ? \"header\" : \"cookie\" };\n };\n\n return resolveModel;\n}\n\n/**\n * Session resolver for pages: cookie-or-header credential, reactive renewal,\n * one resolution per request. Plug it into `web.session`.\n *\n * @example\n * export default { session: pageSession({ project: (user: User) => userResource(user) }) };\n */\nexport function pageSession<TModel = unknown, TUser = unknown>(\n options: PageSessionOptions<TModel, TUser>,\n): PageSessionResolver<TModel, TUser> {\n if (typeof options?.project !== \"function\") {\n throw new Error(\n \"pageSession requires a `project(model)` function: a model never crosses the wire by default.\",\n );\n }\n\n const resolveModel = createModelResolver(options);\n const projections = new WeakMap<object, Promise<unknown>>();\n\n return {\n async resolve(request, response) {\n const resolved = await resolveModel(request, response);\n\n if (!resolved) return null;\n\n const model = resolved.model as TModel;\n let projected = projections.get(request as object);\n\n if (!projected) {\n projected = Promise.resolve(options.project(model));\n projections.set(request as object, projected);\n }\n\n return { model, user: (await projected) as TUser };\n },\n };\n}\n\n/**\n * Middleware for cookie API routes over the same resolver as `pageSession`.\n * A cookie-authenticated unsafe request must pass the Origin/Referer check\n * (renewal can mint cookies, so it runs even when the access cookie is gone).\n * Guests get a 401 unless `optional`. The user lands on `request.locals.user`.\n */\nexport function sessionMiddleware(options: SessionMiddlewareOptions = {}): Middleware {\n const resolveModel = createModelResolver(options);\n const sources = options.sources?.length ? options.sources : [\"cookie\", \"header\"];\n\n const middleware: Middleware = async ({ request, response }) => {\n const headerWins = sources.includes(\"header\") && Boolean(request.authorizationValue);\n\n if (!headerWins && requiresCsrfOriginCheck(\"cookie:x\", request.method)) {\n const accessName = options.cookie ?? authConfig.cookie.name();\n const refreshName = options.refreshCookie ?? authConfig.cookie.refreshName();\n\n if (readAuthCookie(request, accessName) || readAuthCookie(request, refreshName)) {\n try {\n assertCsrfOriginAllowed(request);\n } catch (error) {\n if (!(error instanceof CsrfOriginMismatchError)) throw error;\n\n // A client error any cross-site page can trigger: debug, not error.\n log.debug(\"http\", \"auth\", error);\n\n return response.forbidden({\n error: t(\"auth.errors.csrfOriginMismatch\"),\n errorCode: AuthErrorCodes.CsrfOriginMismatch,\n });\n }\n }\n }\n\n const resolved = await resolveModel(request, response);\n\n if (resolved || options.optional) return;\n\n return response.unauthorized({\n error: t(\"auth.errors.unauthorized\"),\n errorCode: AuthErrorCodes.Unauthorized,\n });\n };\n Object.defineProperty(middleware, Symbol.for(\"warlock.auth\"), {\n value: Object.freeze({\n sources: Object.freeze(\n sources.map((source) =>\n source === \"header\"\n ? \"header\"\n : Object.freeze({ cookie: options.cookie ?? authConfig.cookie.name() }),\n ),\n ),\n userTypes: Object.freeze([...resolveUserTypes(options.userTypes)]),\n required: options.optional !== true,\n }),\n enumerable: false,\n });\n return markAuthGuard(middleware, options.optional !== true);\n}\n"],"mappings":";;;;;;;;;;;AAyBA,MAAM,0BAA0B;AAwChC,SAAS,gBAAgB,QAA6C;CACpE,MAAM,MAAM,UAAU,OAAO,IAAI,uBAAuB,uBAAuB;CAC/E,MAAM,SAAS,OAAO,QAAQ,WAAW,MAAM,GAAG,GAAqB;CAEvE,IAAI,OAAO,WAAW,YAAY,CAAC,OAAO,SAAS,MAAM,KAAK,UAAU,GACtE,MAAM,IAAI,MACR,mBAAmB,KAAK,UAAU,GAAG,EAAE,qEACzC;CAGF,OAAO;AACT;AAEA,SAAS,iBAAiB,OAAgD;CACxE,IAAI,UAAU,QAAW,OAAO,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK;CAErE,MAAM,aAAa,OAAO,IAAI,sBAAsB;CAEpD,OAAO,aAAa,CAAC,UAAoB,IAAI,CAAC;AAChD;;;;;;AAOA,SAAS,oBAAoB,SAAiC;CAC5D,MAAM,UAAU,QAAQ,SAAS,SAAS,QAAQ,UAAW,CAAC,UAAU,QAAQ;CAChF,MAAM,YAAY,QAAQ,SAAS,QAAQ;CAC3C,MAAM,YAAY,QAA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AAC,GAAG,iBAAiB,QAAQ,SAAS,CAAC,CAAC;GACjE,UAAU,QAAQ,aAAa;EACjC,CAAC;EACD,YAAY;CACd,CAAC;CACD,OAAO,cAAc,YAAY,QAAQ,aAAa,IAAI;AAC5D"}
@@ -70,7 +70,14 @@ export declare enum AuthErrorCodes {
70
70
  * challenge, unknown credential, failed verification, or a signature counter
71
71
  * that did not advance.
72
72
  */
73
- InvalidPasskey = "EC011"
73
+ InvalidPasskey = "EC011", // Error Code 011
74
+ /**
75
+ * Provider Account Link Blocked Error Code EC012
76
+ * EC012 = a provider login matched an existing account by email, but
77
+ * `auth.providers.linkExisting` refused to link it automatically (by
78
+ * default: the account never verified that email).
79
+ */
80
+ ProviderAccountLinkBlocked = "EC012"
74
81
  }
75
82
  //#endregion
76
83
  //# sourceMappingURL=auth-error-codes.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"auth-error-codes.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/utils/auth-error-codes.ts"],"mappings":";oBAAY;;;;;EAKV;;;;;EAKA;;;;;EAKA;;;;;;EAMA;;;;;;;;;EASA;;;;;;;;EAQA;;;;;;EAMA;;;;;;;EAOA;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA"}
1
+ {"version":3,"file":"auth-error-codes.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/utils/auth-error-codes.ts"],"mappings":";oBAAY;;;;;EAKV;;;;;EAKA;;;;;EAKA;;;;;;EAMA;;;;;;;;;EASA;;;;;;;;EAQA;;;;;;EAMA;;;;;;;EAOA;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;;;;EAOA"}
@@ -71,6 +71,13 @@ let AuthErrorCodes = /* @__PURE__ */ function(AuthErrorCodes) {
71
71
  * that did not advance.
72
72
  */
73
73
  AuthErrorCodes["InvalidPasskey"] = "EC011";
74
+ /**
75
+ * Provider Account Link Blocked Error Code EC012
76
+ * EC012 = a provider login matched an existing account by email, but
77
+ * `auth.providers.linkExisting` refused to link it automatically (by
78
+ * default: the account never verified that email).
79
+ */
80
+ AuthErrorCodes["ProviderAccountLinkBlocked"] = "EC012";
74
81
  return AuthErrorCodes;
75
82
  }({});
76
83
 
@@ -1 +1 @@
1
- {"version":3,"file":"auth-error-codes.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/auth-error-codes.ts"],"sourcesContent":["export enum AuthErrorCodes {\n /**\n * Missing Access Token Error Code EC001\n * EC001 = Missing Access Token\n */\n MissingAccessToken = \"EC001\", // Error Code 001\n /**\n * Invalid Access Token Error Code EC002\n * EC002 = Invalid Access Token\n */\n InvalidAccessToken = \"EC002\", // Error Code 002\n /**\n * Unauthorized Error Code EC003\n * EC003 = Unauthorized\n */\n Unauthorized = \"EC003\", // Error Code 003\n /**\n * Too Many Attempts Error Code EC004\n * EC004 = Too Many Attempts — issued by the login-throttle middleware once\n * a per-account or per-IP failure counter trips its threshold.\n */\n TooManyAttempts = \"EC004\", // Error Code 004\n /**\n * Invalid Token Type Error Code EC005\n * EC005 = Invalid Token Type — the token's `tokenType` claim does not match\n * what the caller expects (e.g. a refresh token presented where an access\n * token is required, or vice versa). Carried on the `code` property of the\n * `Error` thrown by `assertTokenType` (`services/jwt.ts`) so callers can\n * classify it as a credential failure without matching on the message.\n */\n InvalidTokenType = \"EC005\", // Error Code 005\n /**\n * CSRF Origin Mismatch Error Code EC006\n * EC006 = a cookie-authenticated, unsafe-method (POST/PUT/PATCH/DELETE)\n * request whose `Origin` (or, absent that, `Referer`) did not match the\n * request's own origin or an entry in `auth.csrf.allowedOrigins`, or whose\n * request carried neither header at all.\n */\n CsrfOriginMismatch = \"EC006\", // Error Code 006\n /**\n * Email Not Verified Error Code EC007\n * EC007 = the authenticated user has not verified their email address —\n * thrown by `requireVerifiedEmail()` as `EmailNotVerifiedError` (403).\n */\n EmailNotVerified = \"EC007\", // Error Code 007\n /**\n * Invalid One-Time Token Error Code EC008\n * EC008 = an email-verification or password-reset token that is unknown,\n * issued for the other purpose, expired, or already used. One code for all\n * four on purpose: the caller learns nothing about which it was.\n */\n InvalidOneTimeToken = \"EC008\", // Error Code 008\n /**\n * Invalid Provider Callback Error Code EC009\n * EC009 = a redirect-provider callback was rejected: missing, forged or\n * expired state cookie, `state` mismatch, failed code exchange, or an\n * id_token with a bad signature, issuer, audience, expiry or nonce.\n */\n InvalidProviderCallback = \"EC009\", // Error Code 009\n /**\n * Provider Email Not Verified Error Code EC010\n * EC010 = the provider did not verify the email, so auth refused to link or\n * create an account from it.\n */\n ProviderEmailNotVerified = \"EC010\", // Error Code 010\n /**\n * Invalid Passkey Error Code EC011\n * EC011 = a passkey ceremony was rejected: unknown, expired or used\n * challenge, unknown credential, failed verification, or a signature counter\n * that did not advance.\n */\n InvalidPasskey = \"EC011\", // Error Code 011\n}\n"],"mappings":";AAAA,IAAY,iBAAL;;;;;CAKL;;;;;CAKA;;;;;CAKA;;;;;;CAMA;;;;;;;;;CASA;;;;;;;;CAQA;;;;;;CAMA;;;;;;;CAOA;;;;;;;CAOA;;;;;;CAMA;;;;;;;CAOA;;AACF"}
1
+ {"version":3,"file":"auth-error-codes.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/utils/auth-error-codes.ts"],"sourcesContent":["export enum AuthErrorCodes {\n /**\n * Missing Access Token Error Code EC001\n * EC001 = Missing Access Token\n */\n MissingAccessToken = \"EC001\", // Error Code 001\n /**\n * Invalid Access Token Error Code EC002\n * EC002 = Invalid Access Token\n */\n InvalidAccessToken = \"EC002\", // Error Code 002\n /**\n * Unauthorized Error Code EC003\n * EC003 = Unauthorized\n */\n Unauthorized = \"EC003\", // Error Code 003\n /**\n * Too Many Attempts Error Code EC004\n * EC004 = Too Many Attempts — issued by the login-throttle middleware once\n * a per-account or per-IP failure counter trips its threshold.\n */\n TooManyAttempts = \"EC004\", // Error Code 004\n /**\n * Invalid Token Type Error Code EC005\n * EC005 = Invalid Token Type — the token's `tokenType` claim does not match\n * what the caller expects (e.g. a refresh token presented where an access\n * token is required, or vice versa). Carried on the `code` property of the\n * `Error` thrown by `assertTokenType` (`services/jwt.ts`) so callers can\n * classify it as a credential failure without matching on the message.\n */\n InvalidTokenType = \"EC005\", // Error Code 005\n /**\n * CSRF Origin Mismatch Error Code EC006\n * EC006 = a cookie-authenticated, unsafe-method (POST/PUT/PATCH/DELETE)\n * request whose `Origin` (or, absent that, `Referer`) did not match the\n * request's own origin or an entry in `auth.csrf.allowedOrigins`, or whose\n * request carried neither header at all.\n */\n CsrfOriginMismatch = \"EC006\", // Error Code 006\n /**\n * Email Not Verified Error Code EC007\n * EC007 = the authenticated user has not verified their email address —\n * thrown by `requireVerifiedEmail()` as `EmailNotVerifiedError` (403).\n */\n EmailNotVerified = \"EC007\", // Error Code 007\n /**\n * Invalid One-Time Token Error Code EC008\n * EC008 = an email-verification or password-reset token that is unknown,\n * issued for the other purpose, expired, or already used. One code for all\n * four on purpose: the caller learns nothing about which it was.\n */\n InvalidOneTimeToken = \"EC008\", // Error Code 008\n /**\n * Invalid Provider Callback Error Code EC009\n * EC009 = a redirect-provider callback was rejected: missing, forged or\n * expired state cookie, `state` mismatch, failed code exchange, or an\n * id_token with a bad signature, issuer, audience, expiry or nonce.\n */\n InvalidProviderCallback = \"EC009\", // Error Code 009\n /**\n * Provider Email Not Verified Error Code EC010\n * EC010 = the provider did not verify the email, so auth refused to link or\n * create an account from it.\n */\n ProviderEmailNotVerified = \"EC010\", // Error Code 010\n /**\n * Invalid Passkey Error Code EC011\n * EC011 = a passkey ceremony was rejected: unknown, expired or used\n * challenge, unknown credential, failed verification, or a signature counter\n * that did not advance.\n */\n InvalidPasskey = \"EC011\", // Error Code 011\n /**\n * Provider Account Link Blocked Error Code EC012\n * EC012 = a provider login matched an existing account by email, but\n * `auth.providers.linkExisting` refused to link it automatically (by\n * default: the account never verified that email).\n */\n ProviderAccountLinkBlocked = \"EC012\", // Error Code 012\n}\n"],"mappings":";AAAA,IAAY,iBAAL;;;;;CAKL;;;;;CAKA;;;;;CAKA;;;;;;CAMA;;;;;;;;;CASA;;;;;;;;CAQA;;;;;;CAMA;;;;;;;CAOA;;;;;;;CAOA;;;;;;CAMA;;;;;;;CAOA;;;;;;;CAOA;;AACF"}
@@ -0,0 +1,47 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ //#region ../../packages/auth/src/utils/token-digest.ts
4
+ /**
5
+ * SHA-256 hex digest of a raw access or refresh token — what a token row
6
+ * stores instead of the token when `auth.hashTokensAtRest` is on.
7
+ */
8
+ function tokenDigest(token) {
9
+ return createHash("sha256").update(token).digest("hex");
10
+ }
11
+ const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
12
+ /**
13
+ * Whether a stored token value is a digest rather than a raw JWT. A JWT always
14
+ * contains dots, so the two forms cannot be confused.
15
+ */
16
+ function isTokenDigest(stored) {
17
+ return typeof stored === "string" && DIGEST_PATTERN.test(stored);
18
+ }
19
+ /**
20
+ * Every stored form a presented token may have: its digest (rows issued with
21
+ * `auth.hashTokensAtRest` on) and the raw value (rows issued with it off, or
22
+ * before it was turned on). Lookups match either, so switching the option in
23
+ * either direction never signs anyone out.
24
+ */
25
+ function storedTokenForms(token) {
26
+ return [tokenDigest(token), token];
27
+ }
28
+ /** Raw tokens of rows issued in this process, for handing back to the caller. */
29
+ const plainTokens = /* @__PURE__ */ new WeakMap();
30
+ /** Remember the raw token of a freshly issued row whose column holds a digest. */
31
+ function rememberPlainToken(row, token) {
32
+ if (typeof row === "object" && row !== null) plainTokens.set(row, token);
33
+ }
34
+ /**
35
+ * The raw token of a row: the one remembered at issue, else the stored value
36
+ * when it is not a digest. `undefined` for a hashed row loaded from storage —
37
+ * its raw token exists only with the client.
38
+ */
39
+ function plainTokenOf(row, stored) {
40
+ const remembered = plainTokens.get(row);
41
+ if (remembered !== void 0) return remembered;
42
+ return typeof stored === "string" && !isTokenDigest(stored) ? stored : void 0;
43
+ }
44
+
45
+ //#endregion
46
+ export { isTokenDigest, plainTokenOf, rememberPlainToken, storedTokenForms, tokenDigest };
47
+ //# sourceMappingURL=token-digest.mjs.map