@warlock.js/auth 5.53.1 → 5.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/esm/contracts/providers.d.mts +1 -1
  3. package/esm/contracts/types.d.mts +22 -0
  4. package/esm/contracts/types.d.mts.map +1 -1
  5. package/esm/contracts/types.mjs.map +1 -1
  6. package/esm/middleware/login-throttle.middleware.d.mts +1 -1
  7. package/esm/middleware/login-throttle.middleware.d.mts.map +1 -1
  8. package/esm/middleware/login-throttle.middleware.mjs +18 -1
  9. package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
  10. package/esm/models/auth-token-family/auth-token-family.model.d.mts +14 -0
  11. package/esm/models/auth-token-family/auth-token-family.model.d.mts.map +1 -1
  12. package/esm/models/auth-token-family/auth-token-family.model.mjs +43 -0
  13. package/esm/models/auth-token-family/auth-token-family.model.mjs.map +1 -1
  14. package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
  15. package/esm/models/refresh-token/refresh-token.model.mjs +6 -1
  16. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  17. package/esm/otp/otp.d.mts +5 -4
  18. package/esm/otp/otp.d.mts.map +1 -1
  19. package/esm/otp/otp.mjs +25 -20
  20. package/esm/otp/otp.mjs.map +1 -1
  21. package/esm/services/auth-config.mjs +40 -3
  22. package/esm/services/auth-config.mjs.map +1 -1
  23. package/esm/services/auth.service.d.mts +11 -2
  24. package/esm/services/auth.service.d.mts.map +1 -1
  25. package/esm/services/auth.service.mjs +36 -9
  26. package/esm/services/auth.service.mjs.map +1 -1
  27. package/esm/services/background-work.mjs +16 -0
  28. package/esm/services/background-work.mjs.map +1 -0
  29. package/esm/services/jwt.d.mts +2 -2
  30. package/esm/services/jwt.d.mts.map +1 -1
  31. package/esm/services/jwt.mjs +51 -26
  32. package/esm/services/jwt.mjs.map +1 -1
  33. package/esm/services/password-reset.d.mts +7 -5
  34. package/esm/services/password-reset.d.mts.map +1 -1
  35. package/esm/services/password-reset.mjs +25 -19
  36. package/esm/services/password-reset.mjs.map +1 -1
  37. package/llms-full.txt +8 -6
  38. package/package.json +11 -11
  39. package/skills/auth-basics/SKILL.md +1 -1
  40. package/skills/login-with-providers/SKILL.md +2 -2
  41. package/skills/manage-tokens/SKILL.md +2 -0
  42. package/skills/throttle-login-attempts/SKILL.md +2 -2
  43. package/skills/verify-email-and-reset-password/SKILL.md +1 -1
package/esm/otp/otp.d.mts CHANGED
@@ -11,10 +11,11 @@ import { ChildModel } from "@warlock.js/cascade";
11
11
  * The code is stored only as a keyed hash in `one_time_tokens` (purpose
12
12
  * `otp`), expires after `auth.otp.expiresIn` (default 5m), and replaces any
13
13
  * earlier unused code. **Anti-enumeration:** an unknown phone resolves the same
14
- * way and sends nothing, and the code is delivered in the background so the
15
- * response time does not reveal a known phone. A failed delivery is logged and
16
- * emitted as `otp.deliveryFailed`; set `auth.otp.awaitDelivery: true` to wait
17
- * for it (and receive its error) instead. Throttle the route with
14
+ * way and sends nothing, and the lookup, the code writes and the delivery run
15
+ * in the background so the response time does not reveal a known phone. A
16
+ * failure is logged and emitted as `otp.deliveryFailed`; set
17
+ * `auth.otp.awaitDelivery: true` to wait for all of it (and receive its error)
18
+ * instead. Throttle the route with
18
19
  * `otpRequestThrottleMiddleware()`.
19
20
  *
20
21
  * @throws AuthProviderSdkMissingError when `@warlock.js/notifications` is not
@@ -1 +1 @@
1
- {"version":3,"file":"otp.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/otp/otp.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;wBA6FsB,WAAW,UAAU,MACzC,OAAO,WAAW,IAClB,eACA;EAAW;IACV;;;;;;;;;;;;;wBA6CmB,UAAU,UAAU,MACxC,OAAO,WAAW,IAClB,eACA,cACA,aAAa,aACZ,QAAQ,YAAY"}
1
+ {"version":3,"file":"otp.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/otp/otp.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;wBA+FsB,WAAW,UAAU,MACzC,OAAO,WAAW,IAClB,eACA;EAAW;IACV;;;;;;;;;;;;;wBAsDmB,UAAU,UAAU,MACxC,OAAO,WAAW,IAClB,eACA,cACA,aAAa,aACZ,QAAQ,YAAY"}
package/esm/otp/otp.mjs CHANGED
@@ -3,6 +3,7 @@ import { authEvents } from "../services/auth-events.mjs";
3
3
  import { authService } from "../services/auth.service.mjs";
4
4
  import { InvalidOneTimeTokenError } from "../errors/invalid-one-time-token.error.mjs";
5
5
  import { oneTimeTokenModel } from "../services/one-time-tokens.mjs";
6
+ import { runInBackground } from "../services/background-work.mjs";
6
7
  import { loadOptionalPeer } from "../services/optional-peer.mjs";
7
8
  import { safeEqual } from "../utils/safe-equal.mjs";
8
9
  import { createHmac, randomBytes, randomInt } from "node:crypto";
@@ -53,10 +54,11 @@ async function resolveDelivery(channel) {
53
54
  * The code is stored only as a keyed hash in `one_time_tokens` (purpose
54
55
  * `otp`), expires after `auth.otp.expiresIn` (default 5m), and replaces any
55
56
  * earlier unused code. **Anti-enumeration:** an unknown phone resolves the same
56
- * way and sends nothing, and the code is delivered in the background so the
57
- * response time does not reveal a known phone. A failed delivery is logged and
58
- * emitted as `otp.deliveryFailed`; set `auth.otp.awaitDelivery: true` to wait
59
- * for it (and receive its error) instead. Throttle the route with
57
+ * way and sends nothing, and the lookup, the code writes and the delivery run
58
+ * in the background so the response time does not reveal a known phone. A
59
+ * failure is logged and emitted as `otp.deliveryFailed`; set
60
+ * `auth.otp.awaitDelivery: true` to wait for all of it (and receive its error)
61
+ * instead. Throttle the route with
60
62
  * `otpRequestThrottleMiddleware()`.
61
63
  *
62
64
  * @throws AuthProviderSdkMissingError when `@warlock.js/notifications` is not
@@ -66,27 +68,30 @@ async function requestOtp(Model, phone, options = {}) {
66
68
  const channel = options.channel ?? authConfig.otp.channel();
67
69
  const deliver = await resolveDelivery(channel);
68
70
  if (typeof phone !== "string" || phone.length === 0) return;
69
- const user = await Model.first({ [authConfig.otp.phoneField()]: phone });
70
- if (!user) return;
71
- const code = String(randomInt(0, 1e6)).padStart(6, "0");
72
- const expiresAt = new Date(Date.now() + authConfig.otp.expiresInMs());
73
- const TokenModel = oneTimeTokenModel();
74
- await TokenModel.invalidateActiveFor(user, "otp");
75
- await TokenModel.issue(user, "otp", storedCodeHash(user, code), expiresAt);
76
- const message = {
77
- body: authConfig.otp.message(code),
78
- code,
79
- expiresAt
71
+ let user = null;
72
+ const issueAndDeliver = async () => {
73
+ user = await Model.first({ [authConfig.otp.phoneField()]: phone });
74
+ if (!user) return;
75
+ const code = String(randomInt(0, 1e6)).padStart(6, "0");
76
+ const expiresAt = new Date(Date.now() + authConfig.otp.expiresInMs());
77
+ const TokenModel = oneTimeTokenModel();
78
+ await TokenModel.invalidateActiveFor(user, "otp");
79
+ await TokenModel.issue(user, "otp", storedCodeHash(user, code), expiresAt);
80
+ const message = {
81
+ body: authConfig.otp.message(code),
82
+ code,
83
+ expiresAt
84
+ };
85
+ await deliver(phone, message, channel);
80
86
  };
81
- const delivery = Promise.resolve().then(() => deliver(phone, message, channel));
82
87
  if (authConfig.otp.awaitDelivery()) {
83
- await delivery;
88
+ await issueAndDeliver();
84
89
  return;
85
90
  }
86
- delivery.catch((error) => {
91
+ runInBackground(() => issueAndDeliver().catch((error) => {
87
92
  log.error("auth", "otp", error);
88
- authEvents.emit("otp.deliveryFailed", user, error);
89
- });
93
+ if (user) authEvents.emit("otp.deliveryFailed", user, error);
94
+ }));
90
95
  }
91
96
  /**
92
97
  * Verify a phone login code and log the user in through
@@ -1 +1 @@
1
- {"version":3,"file":"otp.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/otp/otp.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport { log } from \"@warlock.js/logger\";\nimport { createHmac, randomBytes, randomInt } from \"node:crypto\";\nimport type { OtpMessage, OtpSender } from \"../contracts/providers\";\nimport type { DeviceInfo, LoginResult } from \"../contracts/types\";\nimport { InvalidOneTimeTokenError } from \"../errors/invalid-one-time-token.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { authConfig } from \"../services/auth-config\";\nimport { authEvents } from \"../services/auth-events\";\nimport { authService } from \"../services/auth.service\";\nimport { oneTimeTokenModel } from \"../services/one-time-tokens\";\nimport { loadOptionalPeer } from \"../services/optional-peer\";\nimport { safeEqual } from \"../utils/safe-equal\";\n\n/** The slice of `@warlock.js/notifications` OTP delivery uses (an optional peer). */\ntype NotifyModule = {\n notify: {\n channel: (name: string) => { send: (to: string, payload: unknown) => Promise<unknown> };\n };\n};\n\nconst CODE_PATTERN = /^\\d{6}$/;\n\n/** One error for every rejection: unknown phone, no code, wrong, expired, used, over the cap. */\nfunction invalidCode(): InvalidOneTimeTokenError {\n return new InvalidOneTimeTokenError(\"Invalid or expired code.\");\n}\n\n/**\n * Keyed hash of a code. A plain SHA-256 of a 6-digit code is reversed by\n * trying all million values, so the MAC key (derived from the access-token\n * secret) is what keeps a leaked table useless. `salt` makes each stored\n * value unique.\n */\nfunction macCode(user: Auth, salt: string, code: string): string {\n const key = createHmac(\"sha256\", authConfig.accessToken.secret())\n .update(\"@warlock.js/auth:otp\")\n .digest();\n\n return createHmac(\"sha256\", key)\n .update(`${salt}:${user.userType}:${user.id}:${code}`)\n .digest(\"base64url\");\n}\n\n/** Stored form: `<salt>.<mac>` — 16 + 1 + 43 chars, inside the 64-char `token_hash` column. */\nfunction storedCodeHash(user: Auth, code: string): string {\n const salt = randomBytes(12).toString(\"base64url\");\n\n return `${salt}.${macCode(user, salt, code)}`;\n}\n\nfunction codeMatches(user: Auth, stored: string, code: string): boolean {\n const [salt, mac] = stored.split(\".\");\n\n return !!salt && !!mac && safeEqual(mac, macCode(user, salt, code));\n}\n\n/**\n * Resolve how a code is sent: `auth.otp.send`, else the app's notifications\n * channel. Resolved BEFORE the user lookup, so a missing notifications package\n * fails identically for known and unknown phones.\n */\nasync function resolveDelivery(channel: string): Promise<OtpSender> {\n const custom = authConfig.otp.send();\n\n if (custom) return custom;\n\n const { notify } = await loadOptionalPeer<NotifyModule>(\n \"@warlock.js/notifications\",\n \"notifications\",\n );\n\n return (phone, message, channelName) => notify.channel(channelName).send(phone, message);\n}\n\n/**\n * Send a 6-digit login code to the account whose `auth.otp.phoneField`\n * (default `phone`) equals `phone`, through the notifications channel named by\n * `options.channel` / `auth.otp.channel` (default `\"sms\"`). Auth ships no\n * SMS/WhatsApp driver — the app registers that channel.\n *\n * The code is stored only as a keyed hash in `one_time_tokens` (purpose\n * `otp`), expires after `auth.otp.expiresIn` (default 5m), and replaces any\n * earlier unused code. **Anti-enumeration:** an unknown phone resolves the same\n * way and sends nothing, and the code is delivered in the background so the\n * response time does not reveal a known phone. A failed delivery is logged and\n * emitted as `otp.deliveryFailed`; set `auth.otp.awaitDelivery: true` to wait\n * for it (and receive its error) instead. Throttle the route with\n * `otpRequestThrottleMiddleware()`.\n *\n * @throws AuthProviderSdkMissingError when `@warlock.js/notifications` is not\n * installed and no `auth.otp.send` is configured.\n */\nexport async function requestOtp<T extends Auth>(\n Model: ChildModel<T>,\n phone: string,\n options: { channel?: string } = {},\n): Promise<void> {\n const channel = options.channel ?? authConfig.otp.channel();\n const deliver = await resolveDelivery(channel);\n\n if (typeof phone !== \"string\" || phone.length === 0) return;\n\n const user = (await Model.first({ [authConfig.otp.phoneField()]: phone })) as T | null;\n\n if (!user) return;\n\n const code = String(randomInt(0, 1_000_000)).padStart(6, \"0\");\n const expiresAt = new Date(Date.now() + authConfig.otp.expiresInMs());\n const TokenModel = oneTimeTokenModel();\n\n await TokenModel.invalidateActiveFor(user, \"otp\");\n await TokenModel.issue(user, \"otp\", storedCodeHash(user, code), expiresAt);\n\n const message: OtpMessage = { body: authConfig.otp.message(code), code, expiresAt };\n\n const delivery = Promise.resolve().then(() => deliver(phone, message, channel));\n\n if (authConfig.otp.awaitDelivery()) {\n await delivery;\n\n return;\n }\n\n delivery.catch((error: unknown) => {\n log.error(\"auth\", \"otp\", error);\n authEvents.emit(\"otp.deliveryFailed\", user, error);\n });\n}\n\n/**\n * Verify a phone login code and log the user in through\n * `authService.completeLogin` — the same outcome as password login.\n *\n * Each check first counts an attempt atomically; once `auth.otp.maxAttempts`\n * (default 5) have been counted the code is invalidated, so it is compared at\n * most that many times even under concurrent guesses. A correct code is\n * consumed single-use. Throttle the route with `otpVerifyThrottleMiddleware()`.\n *\n * @throws InvalidOneTimeTokenError (400, EC008) — the same for an unknown\n * phone, a wrong, expired, used or exhausted code.\n */\nexport async function verifyOtp<T extends Auth>(\n Model: ChildModel<T>,\n phone: string,\n code: string,\n deviceInfo?: DeviceInfo,\n): Promise<LoginResult<T>> {\n if (typeof phone !== \"string\" || phone.length === 0) throw invalidCode();\n if (typeof code !== \"string\" || !CODE_PATTERN.test(code)) throw invalidCode();\n\n const user = (await Model.first({ [authConfig.otp.phoneField()]: phone })) as T | null;\n\n if (!user) throw invalidCode();\n\n const row = await oneTimeTokenModel().findActiveFor(user, \"otp\");\n\n if (!row || row.isConsumed || row.isExpired) throw invalidCode();\n\n if (!(await row.recordAttempt(authConfig.otp.maxAttempts()))) {\n await row.consumeIfActive();\n\n throw invalidCode();\n }\n\n if (!codeMatches(user, String(row.get(\"token_hash\") ?? \"\"), code)) throw invalidCode();\n\n if (!(await row.consumeIfActive())) throw invalidCode();\n\n return authService.completeLogin(user, deviceInfo);\n}\n"],"mappings":";;;;;;;;;;;AAqBA,MAAM,eAAe;;AAGrB,SAAS,cAAwC;CAC/C,OAAO,IAAI,yBAAyB,0BAA0B;AAChE;;;;;;;AAQA,SAAS,QAAQ,MAAY,MAAc,MAAsB;CAC/D,MAAM,MAAM,WAAW,UAAU,WAAW,YAAY,OAAO,CAAC,CAAC,CAC9D,OAAO,sBAAsB,CAAC,CAC9B,OAAO;CAEV,OAAO,WAAW,UAAU,GAAG,CAAC,CAC7B,OAAO,GAAG,KAAK,GAAG,KAAK,SAAS,GAAG,KAAK,GAAG,GAAG,MAAM,CA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,IAAI,QAAQ,IAAI;EAAG;EAAM;CAAU;CAElF,MAAM,WAAW,QAAQ,QAAQ,CAAC,CAAC,WAAW,QAAQ,OAAO,SAAS,OAAO,CAAC;CAE9E,IAAI,WAAW,IAAI,cAAc,GAAG;EAClC,MAAM;EAEN;CACF;CAEA,SAAS,OAAO,UAAmB;EACjC,IAAI,MAAM,QAAQ,OAAO,KAAK;EAC9B,WAAW,KAAK,sBAAsB,MAAM,KAAK;CACnD,CAAC;AACH;;;;;;;;;;;;;AAcA,eAAsB,UACpB,OACA,OACA,MACA,YACyB;CACzB,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG,MAAM,YAAY;CACvE,IAAI,OAAO,SAAS,YAAY,CAAC,aAAa,KAAK,IAAI,GAAG,MAAM,YAAY;CAE5E,MAAM,OAAQ,MAAM,MAAM,MAAM,GAAG,WAAW,IAAI,WAAW,IAAI,MAAM,CAAC;CAExE,IAAI,CAAC,MAAM,MAAM,YAAY;CAE7B,MAAM,MAAM,MAAM,kBAAkB,CAAC,CAAC,cAAc,MAAM,KAAK;CAE/D,IAAI,CAAC,OAAO,IAAI,cAAc,IAAI,WAAW,MAAM,YAAY;CAE/D,IAAI,CAAE,MAAM,IAAI,cAAc,WAAW,IAAI,YAAY,CAAC,GAAI;EAC5D,MAAM,IAAI,gBAAgB;EAE1B,MAAM,YAAY;CACpB;CAEA,IAAI,CAAC,YAAY,MAAM,OAAO,IAAI,IAAI,YAAY,KAAK,EAAE,GAAG,IAAI,GAAG,MAAM,YAAY;CAErF,IAAI,CAAE,MAAM,IAAI,gBAAgB,GAAI,MAAM,YAAY;CAEtD,OAAO,YAAY,cAAc,MAAM,UAAU;AACnD"}
1
+ {"version":3,"file":"otp.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/otp/otp.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport { log } from \"@warlock.js/logger\";\nimport { createHmac, randomBytes, randomInt } from \"node:crypto\";\nimport type { OtpMessage, OtpSender } from \"../contracts/providers\";\nimport type { DeviceInfo, LoginResult } from \"../contracts/types\";\nimport { InvalidOneTimeTokenError } from \"../errors/invalid-one-time-token.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { authConfig } from \"../services/auth-config\";\nimport { authEvents } from \"../services/auth-events\";\nimport { authService } from \"../services/auth.service\";\nimport { runInBackground } from \"../services/background-work\";\nimport { oneTimeTokenModel } from \"../services/one-time-tokens\";\nimport { loadOptionalPeer } from \"../services/optional-peer\";\nimport { safeEqual } from \"../utils/safe-equal\";\n\n/** The slice of `@warlock.js/notifications` OTP delivery uses (an optional peer). */\ntype NotifyModule = {\n notify: {\n channel: (name: string) => { send: (to: string, payload: unknown) => Promise<unknown> };\n };\n};\n\nconst CODE_PATTERN = /^\\d{6}$/;\n\n/** One error for every rejection: unknown phone, no code, wrong, expired, used, over the cap. */\nfunction invalidCode(): InvalidOneTimeTokenError {\n return new InvalidOneTimeTokenError(\"Invalid or expired code.\");\n}\n\n/**\n * Keyed hash of a code. A plain SHA-256 of a 6-digit code is reversed by\n * trying all million values, so the MAC key (derived from the access-token\n * secret) is what keeps a leaked table useless. `salt` makes each stored\n * value unique.\n */\nfunction macCode(user: Auth, salt: string, code: string): string {\n const key = createHmac(\"sha256\", authConfig.accessToken.secret())\n .update(\"@warlock.js/auth:otp\")\n .digest();\n\n return createHmac(\"sha256\", key)\n .update(`${salt}:${user.userType}:${user.id}:${code}`)\n .digest(\"base64url\");\n}\n\n/** Stored form: `<salt>.<mac>` — 16 + 1 + 43 chars, inside the 64-char `token_hash` column. */\nfunction storedCodeHash(user: Auth, code: string): string {\n const salt = randomBytes(12).toString(\"base64url\");\n\n return `${salt}.${macCode(user, salt, code)}`;\n}\n\nfunction codeMatches(user: Auth, stored: string, code: string): boolean {\n const [salt, mac] = stored.split(\".\");\n\n return !!salt && !!mac && safeEqual(mac, macCode(user, salt, code));\n}\n\n/**\n * Resolve how a code is sent: `auth.otp.send`, else the app's notifications\n * channel. Resolved BEFORE the user lookup, so a missing notifications package\n * fails identically for known and unknown phones.\n */\nasync function resolveDelivery(channel: string): Promise<OtpSender> {\n const custom = authConfig.otp.send();\n\n if (custom) return custom;\n\n const { notify } = await loadOptionalPeer<NotifyModule>(\n \"@warlock.js/notifications\",\n \"notifications\",\n );\n\n return (phone, message, channelName) => notify.channel(channelName).send(phone, message);\n}\n\n/**\n * Send a 6-digit login code to the account whose `auth.otp.phoneField`\n * (default `phone`) equals `phone`, through the notifications channel named by\n * `options.channel` / `auth.otp.channel` (default `\"sms\"`). Auth ships no\n * SMS/WhatsApp driver — the app registers that channel.\n *\n * The code is stored only as a keyed hash in `one_time_tokens` (purpose\n * `otp`), expires after `auth.otp.expiresIn` (default 5m), and replaces any\n * earlier unused code. **Anti-enumeration:** an unknown phone resolves the same\n * way and sends nothing, and the lookup, the code writes and the delivery run\n * in the background so the response time does not reveal a known phone. A\n * failure is logged and emitted as `otp.deliveryFailed`; set\n * `auth.otp.awaitDelivery: true` to wait for all of it (and receive its error)\n * instead. Throttle the route with\n * `otpRequestThrottleMiddleware()`.\n *\n * @throws AuthProviderSdkMissingError when `@warlock.js/notifications` is not\n * installed and no `auth.otp.send` is configured.\n */\nexport async function requestOtp<T extends Auth>(\n Model: ChildModel<T>,\n phone: string,\n options: { channel?: string } = {},\n): Promise<void> {\n const channel = options.channel ?? authConfig.otp.channel();\n const deliver = await resolveDelivery(channel);\n\n if (typeof phone !== \"string\" || phone.length === 0) return;\n\n let user: T | null = null;\n\n const issueAndDeliver = async (): Promise<void> => {\n user = (await Model.first({ [authConfig.otp.phoneField()]: phone })) as T | null;\n\n if (!user) return;\n\n const code = String(randomInt(0, 1_000_000)).padStart(6, \"0\");\n const expiresAt = new Date(Date.now() + authConfig.otp.expiresInMs());\n const TokenModel = oneTimeTokenModel();\n\n await TokenModel.invalidateActiveFor(user, \"otp\");\n await TokenModel.issue(user, \"otp\", storedCodeHash(user, code), expiresAt);\n\n const message: OtpMessage = { body: authConfig.otp.message(code), code, expiresAt };\n\n await deliver(phone, message, channel);\n };\n\n if (authConfig.otp.awaitDelivery()) {\n await issueAndDeliver();\n\n return;\n }\n\n // The lookup, the code writes and the delivery all run after the response,\n // so a known and an unknown phone answer in the same time.\n runInBackground(() =>\n issueAndDeliver().catch((error: unknown) => {\n log.error(\"auth\", \"otp\", error);\n\n if (user) authEvents.emit(\"otp.deliveryFailed\", user, error);\n }),\n );\n}\n\n/**\n * Verify a phone login code and log the user in through\n * `authService.completeLogin` — the same outcome as password login.\n *\n * Each check first counts an attempt atomically; once `auth.otp.maxAttempts`\n * (default 5) have been counted the code is invalidated, so it is compared at\n * most that many times even under concurrent guesses. A correct code is\n * consumed single-use. Throttle the route with `otpVerifyThrottleMiddleware()`.\n *\n * @throws InvalidOneTimeTokenError (400, EC008) — the same for an unknown\n * phone, a wrong, expired, used or exhausted code.\n */\nexport async function verifyOtp<T extends Auth>(\n Model: ChildModel<T>,\n phone: string,\n code: string,\n deviceInfo?: DeviceInfo,\n): Promise<LoginResult<T>> {\n if (typeof phone !== \"string\" || phone.length === 0) throw invalidCode();\n if (typeof code !== \"string\" || !CODE_PATTERN.test(code)) throw invalidCode();\n\n const user = (await Model.first({ [authConfig.otp.phoneField()]: phone })) as T | null;\n\n if (!user) throw invalidCode();\n\n const row = await oneTimeTokenModel().findActiveFor(user, \"otp\");\n\n if (!row || row.isConsumed || row.isExpired) throw invalidCode();\n\n if (!(await row.recordAttempt(authConfig.otp.maxAttempts()))) {\n await row.consumeIfActive();\n\n throw invalidCode();\n }\n\n if (!codeMatches(user, String(row.get(\"token_hash\") ?? \"\"), code)) throw invalidCode();\n\n if (!(await row.consumeIfActive())) throw invalidCode();\n\n return authService.completeLogin(user, deviceInfo);\n}\n"],"mappings":";;;;;;;;;;;;AAsBA,MAAM,eAAe;;AAGrB,SAAS,cAAwC;CAC/C,OAAO,IAAI,yBAAyB,0BAA0B;AAChE;;;;;;;AAQA,SAAS,QAAQ,MAAY,MAAc,MAAsB;CAC/D,MAAM,MAA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GAAI,MAAM,YAAY;CAEtD,OAAO,YAAY,cAAc,MAAM,UAAU;AACnD"}
@@ -21,10 +21,27 @@ function warnOnceInProduction(key, message) {
21
21
  warnedProduction.add(key);
22
22
  log.warn("auth", "config", message);
23
23
  }
24
+ /** Log `message` once per process, in any environment. */
25
+ function warnOnce(key, message) {
26
+ if (warnedProduction.has(key)) return;
27
+ warnedProduction.add(key);
28
+ log.warn("auth", "config", message);
29
+ }
24
30
  /** Warn (production, once) when a signing secret is too short to resist offline guessing. */
25
31
  function checkSecretStrength(key, secret) {
26
32
  if (Buffer.byteLength(secret) >= MIN_SECRET_BYTES) return;
27
- warnOnceInProduction(`secret:${key}`, `auth.${key} is shorter than ${MIN_SECRET_BYTES} bytes, so a captured token lets an attacker guess it offline and forge tokens. Generate a strong secret with "warlock jwt.generate".`);
33
+ warnOnceInProduction(`secret:${key}`, `auth.${key} is shorter than ${MIN_SECRET_BYTES} bytes, so a captured token lets an attacker guess it offline and forge tokens. Generate a strong secret with "warlock jwt.generate". From 6.0 a secret this short stops the app from booting.`);
34
+ }
35
+ /**
36
+ * Read a list of retired secrets: non-empty strings only. Each one gets the
37
+ * same strength warning as an active secret.
38
+ */
39
+ function readPreviousSecrets(key) {
40
+ const raw = config.key(`auth.${key}`);
41
+ if (!Array.isArray(raw)) return [];
42
+ const secrets = raw.filter((value) => typeof value === "string" && value !== "");
43
+ for (const secret of secrets) checkSecretStrength(key, secret);
44
+ return secrets;
28
45
  }
29
46
  const permitAuthentication = () => true;
30
47
  /**
@@ -109,6 +126,12 @@ const authConfig = {
109
126
  * (`auth.hashTokensAtRest`). @default false
110
127
  */
111
128
  hashTokensAtRest: () => config.key("auth.hashTokensAtRest", false) === true,
129
+ /**
130
+ * Replace a password hash made with another algorithm or cost than
131
+ * `encryption.password` asks for, after a successful login
132
+ * (`auth.rehashPasswords`). @default true
133
+ */
134
+ rehashPasswords: () => config.key("auth.rehashPasswords", true) !== false,
112
135
  /** Login identifier normalizer, or `false` for exact matching. */
113
136
  normalizeCredentials: () => config.key("auth.normalizeCredentials", defaultNormalizeCredentials),
114
137
  accessToken: {
@@ -119,6 +142,11 @@ const authConfig = {
119
142
  checkSecretStrength("accessToken.secret", secret);
120
143
  return secret;
121
144
  },
145
+ /**
146
+ * Retired signing secrets, tried only when verifying an access token whose
147
+ * signature the current secret rejects. Never used to sign.
148
+ */
149
+ previousSecrets: () => readPreviousSecrets("accessToken.previousSecrets"),
122
150
  /** Signing algorithm (legacy: `auth.jwt.algorithm`). */
123
151
  algorithm: () => resolve("accessToken.algorithm", "jwt.algorithm", "HS256"),
124
152
  /** `iss` claim stamped on and required of every token; unset ⇒ not used. */
@@ -247,8 +275,12 @@ allowedOrigins: () => config.key("auth.csrf.allowedOrigins", []) },
247
275
  const { origin } = authConfig.passkeys.settings();
248
276
  return Array.isArray(origin) ? origin : [origin];
249
277
  },
250
- /** User-verification requirement for both ceremonies. @default "preferred" */
251
- userVerification: () => config.key("auth.passkeys")?.userVerification === "required" ? "required" : "preferred",
278
+ /** User-verification requirement for both ceremonies. @default "preferred" (becomes "required" in 6.0) */
279
+ userVerification: () => {
280
+ const configured = config.key("auth.passkeys")?.userVerification;
281
+ if (configured === void 0) warnOnce("passkeys.userVerification", "auth.passkeys.userVerification is not set, so \"preferred\" applies: a passkey proving only possession of the device is accepted. The default changes to \"required\" in 6.0: set it explicitly to choose now.");
282
+ return configured === "required" ? "required" : "preferred";
283
+ },
252
284
  /** Challenge lifetime in ms; throws naming the key when unusable. @default "5m" */
253
285
  challengeExpiresInMs: () => parseDuration("passkeys.challengeExpiresIn", config.key("auth.passkeys.challengeExpiresIn", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN))
254
286
  },
@@ -278,6 +310,11 @@ allowedOrigins: () => config.key("auth.csrf.allowedOrigins", []) },
278
310
  if (secret) checkSecretStrength("refreshToken.secret", secret);
279
311
  return secret;
280
312
  },
313
+ /**
314
+ * Retired refresh secrets, tried only when verifying a refresh token whose
315
+ * signature the current secret rejects. Never used to sign.
316
+ */
317
+ previousSecrets: () => readPreviousSecrets("refreshToken.previousSecrets"),
281
318
  /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */
282
319
  enabled: () => resolve("refreshToken.enabled", "jwt.refresh.enabled", true),
283
320
  /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */
@@ -1 +1 @@
1
- {"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\nimport type { CookieDomainResolver } from \"../contracts/types\";\nimport { log } from \"@warlock.js/logger\";\nimport { type Algorithm } from \"fast-jwt\";\nimport ms from \"ms\";\nimport type {\n AuthNotification,\n CanAuthenticate,\n NormalizeCredentials,\n LogoutWithoutTokenBehavior,\n OneTimeTokenUrlBuilder,\n PasswordSetter,\n} from \"../contracts/types\";\nimport type {\n AppleProviderConfig,\n AuthProvider,\n DiscordProviderConfig,\n FacebookProviderConfig,\n GitHubProviderConfig,\n GoogleProviderConfig,\n LinkedInProviderConfig,\n OtpSender,\n PasskeysConfig,\n ProviderLinkExisting,\n ProviderUserCreator,\n XProviderConfig,\n} from \"../contracts/providers\";\nimport type { Auth } from \"../models/auth.model\";\nimport { defaultNormalizeCredentials } from \"../utils/normalize-credentials\";\n\nconst warnedLegacyKeys = new Set<string>();\n\n/** One-time production warnings already logged, by key. */\nconst warnedProduction = new Set<string>();\n\n/** Signing secrets shorter than this are brute-forceable from one captured token. */\nconst MIN_SECRET_BYTES = 32;\n\n/** Access-token lifetimes past this get a production warning. */\nconst LONG_ACCESS_TOKEN_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Same answer as core's `environment()`, read directly so config stays dependency-light. */\nfunction isProduction(): boolean {\n return process.env.NODE_ENV === \"production\";\n}\n\n/** Log `message` once per process, in production only. */\nfunction warnOnceInProduction(key: string, message: string): void {\n if (!isProduction() || warnedProduction.has(key)) return;\n\n warnedProduction.add(key);\n log.warn(\"auth\", \"config\", message);\n}\n\n/** Warn (production, once) when a signing secret is too short to resist offline guessing. */\nfunction checkSecretStrength(key: string, secret: string): void {\n if (Buffer.byteLength(secret) >= MIN_SECRET_BYTES) return;\n\n warnOnceInProduction(\n `secret:${key}`,\n `auth.${key} is shorter than ${MIN_SECRET_BYTES} bytes, so a captured token lets an attacker ` +\n `guess it offline and forge tokens. Generate a strong secret with \"warlock jwt.generate\".`,\n );\n}\n\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\n\n/**\n * `ms` accepts anything at runtime and answers `undefined` for a string it\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\n * `(value: ms.StringValue) => number`, which is exactly what let an\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\n * here, so every caller is forced to deal with the `undefined`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * Turn a configured lifetime into a positive number of milliseconds, or throw\n * naming the key.\n *\n * A token lifetime is a security boundary, so an unusable value is a hard error\n * rather than a silent fallback: substituting a default would trade one\n * unintended lifetime for another, just as quietly — and quiet is the whole\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\n *\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\n * claim** and an `Invalid Date` written to the token row.\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\n * emits with **no `exp` claim** — it survives any guard that only rejects\n * `undefined`. `\"-1h\"` signs an already-expired token.\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\n */\nfunction parseDuration(key: string, raw: unknown): number {\n let parsed: number | string | undefined;\n\n try {\n parsed = parseMs(raw);\n } catch {\n // ms throws (rather than returning undefined) for \"\" and non-strings\n parsed = undefined;\n }\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\n );\n }\n\n return parsed;\n}\n\n/** Email-verification token lifetime used when nothing is configured. */\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\n\n/** Password-reset token lifetime used when nothing is configured. */\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\n\n/** Passkey challenge lifetime used when nothing is configured. */\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\n\n/** OTP lifetime used when nothing is configured. */\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\n\n/** Access-token lifetime used when nothing is configured. */\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\n\n/**\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\n *\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\n * keep working after the config split.\n */\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\n const fromNew = config.key(`auth.${newKey}`);\n\n if (fromNew !== undefined && fromNew !== null) {\n return fromNew as T;\n }\n\n const fromLegacy = config.key(`auth.${legacyKey}`);\n\n if (fromLegacy !== undefined && fromLegacy !== null) {\n if (!warnedLegacyKeys.has(legacyKey)) {\n warnedLegacyKeys.add(legacyKey);\n log.warn(\n \"auth\",\n \"config-deprecation\",\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\n );\n }\n\n return fromLegacy as T;\n }\n\n return fallback as T;\n}\n\n/**\n * Typed, backward-compatible access to auth configuration. The service and the\n * jwt signer read configuration exclusively through here, so the new split\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\n */\nexport const authConfig = {\n canAuthenticate: async (user: Auth): Promise<boolean> => {\n const canAuthenticate = config.key<CanAuthenticate>(\n \"auth.canAuthenticate\",\n permitAuthentication,\n );\n\n return canAuthenticate(user);\n },\n /**\n * Store only a SHA-256 digest of each access and refresh token\n * (`auth.hashTokensAtRest`). @default false\n */\n hashTokensAtRest: (): boolean => config.key<boolean>(\"auth.hashTokensAtRest\", false) === true,\n /** Login identifier normalizer, or `false` for exact matching. */\n normalizeCredentials: (): false | NormalizeCredentials =>\n config.key<false | NormalizeCredentials>(\n \"auth.normalizeCredentials\",\n defaultNormalizeCredentials,\n ),\n accessToken: {\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\n secret: (): string => {\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\n\n if (!secret) {\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\n }\n\n checkSecretStrength(\"accessToken.secret\", secret);\n\n return secret;\n },\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\n /** `iss` claim stamped on and required of every token; unset ⇒ not used. */\n issuer: (): string | undefined => {\n const issuer = config.key<unknown>(\"auth.accessToken.issuer\");\n\n return typeof issuer === \"string\" && issuer.length > 0 ? issuer : undefined;\n },\n /** `aud` claim stamped on and required of every token; unset ⇒ not used. */\n audience: (): string | string[] | undefined => {\n const audience = config.key<unknown>(\"auth.accessToken.audience\");\n\n if (typeof audience === \"string\" && audience.length > 0) return audience;\n\n if (\n Array.isArray(audience) &&\n audience.length > 0 &&\n audience.every((entry) => typeof entry === \"string\" && entry.length > 0)\n ) {\n return audience as string[];\n }\n\n return undefined;\n },\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\n * to 1 hour when unset; throws naming the key when the configured value is\n * not a positive `ms` duration. See {@link parseDuration}.\n */\n expiresInMs: (): number => {\n const lifetime = parseDuration(\n \"accessToken.expiresIn\",\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\n );\n\n if (lifetime > LONG_ACCESS_TOKEN_MS) {\n warnOnceInProduction(\n \"accessToken.expiresIn\",\n \"auth.accessToken.expiresIn is longer than 30 days: a stolen access token stays usable \" +\n 'that long. Use a short lifetime (e.g. \"1h\") with refresh tokens ' +\n \"(auth.refreshToken.enabled) instead.\",\n );\n }\n\n return lifetime;\n },\n },\n pageAuth: {\n /**\n * Login path a guarded PAGE route redirects a logged-out browser to.\n *\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\n * to opt a browser-facing app into login-redirect UX: a logged-out human\n * navigating to a guarded page lands on the login screen instead of reading\n * a raw JSON error blob. Finding b9ab9804.\n */\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed. Defaults to\n * `\"returnUrl\"`.\n */\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\n },\n cookie: {\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\n /** Refresh-token cookie name the session cookie helpers use. @default \"refresh_token\" */\n refreshName: (): string => config.key(\"auth.cookie.refreshName\", \"refresh_token\"),\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\n /** Select the request-scoped cookie Domain; undefined keeps it host-only. */\n cookieDomain: (): CookieDomainResolver | undefined => config.key(\"auth.cookie.cookieDomain\"),\n /** Write the auth cookies as `__Host-<name>` (Secure, `Path=/`, no Domain). @default false */\n hostPrefix: (): boolean => config.key<boolean>(\"auth.cookie.hostPrefix\", false) === true,\n },\n csrf: {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * beyond the request's own origin. @default []\n */\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\n },\n verification: {\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\n expiresInMs: (): number =>\n parseDuration(\n \"verification.expiresIn\",\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\n ),\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\n /** App notification replacing the default verification email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\n },\n passwordReset: {\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\n expiresInMs: (): number =>\n parseDuration(\n \"passwordReset.expiresIn\",\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\n ),\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\n /** App notification replacing the default reset email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\n /** App-owned password writer replacing the default. */\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\n /** Wait for the reset notification before `requestPasswordReset` resolves. @default false */\n awaitDelivery: (): boolean =>\n config.key<boolean>(\"auth.passwordReset.awaitDelivery\", false) === true,\n },\n providers: {\n /** `auth.providers.google`, when configured. */\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\n /** `auth.providers.github`, when configured. */\n github: (): GitHubProviderConfig | undefined => config.key(\"auth.providers.github\"),\n /** `auth.providers.discord`, when configured. */\n discord: (): DiscordProviderConfig | undefined => config.key(\"auth.providers.discord\"),\n /** `auth.providers.linkedin`, when configured. */\n linkedin: (): LinkedInProviderConfig | undefined => config.key(\"auth.providers.linkedin\"),\n /** `auth.providers.apple`, when configured. */\n apple: (): AppleProviderConfig | undefined => config.key(\"auth.providers.apple\"),\n /** `auth.providers.facebook`, when configured. */\n facebook: (): FacebookProviderConfig | undefined => config.key(\"auth.providers.facebook\"),\n /** `auth.providers.x`, when configured. */\n x: (): XProviderConfig | undefined => config.key(\"auth.providers.x\"),\n /** An app-registered provider under `auth.providers.custom.<name>`. */\n custom: (name: string): AuthProvider | undefined => {\n const providers = config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {});\n\n // Own keys only: `name` arrives from a URL, and \"constructor\" must not resolve to Object.\n return Object.hasOwn(providers, name) ? providers[name] : undefined;\n },\n /** User attribute a verified provider email is matched against. @default \"email\" */\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\n /** App-owned user creation for a first provider login. */\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\n /** Linking a first provider login to an existing account by email. @default \"verified\" */\n linkExisting: (): ProviderLinkExisting => {\n const value = config.key<unknown>(\"auth.providers.linkExisting\", \"verified\");\n\n return value === \"always\" || value === \"never\" ? value : \"verified\";\n },\n },\n passkeys: {\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\n settings: (): PasskeysConfig => {\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\n\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\n throw new Error(\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\n );\n }\n\n return settings;\n },\n /** Allowed ceremony origins, as a list. */\n origins: (): string[] => {\n const { origin } = authConfig.passkeys.settings();\n\n return Array.isArray(origin) ? origin : [origin];\n },\n /** User-verification requirement for both ceremonies. @default \"preferred\" */\n userVerification: (): \"required\" | \"preferred\" =>\n config.key<PasskeysConfig | undefined>(\"auth.passkeys\")?.userVerification === \"required\"\n ? \"required\"\n : \"preferred\",\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n challengeExpiresInMs: (): number =>\n parseDuration(\n \"passkeys.challengeExpiresIn\",\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\n ),\n },\n otp: {\n /** Notifications channel the code is sent through. @default \"sms\" */\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\n /** User attribute holding the phone number. @default \"phone\" */\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n expiresInMs: (): number =>\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\n /** Verify attempts before the code is invalidated. @default 5 */\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\n /** The message text for a code. */\n message: (code: string): string => {\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\n\n return build ? build(code) : `Your verification code is ${code}`;\n },\n /** App-owned delivery replacing the notifications channel send. */\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\n /** Wait for the code delivery before `requestOtp` resolves. @default false */\n awaitDelivery: (): boolean => config.key<boolean>(\"auth.otp.awaitDelivery\", false) === true,\n },\n refreshToken: {\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\n secret: (): string | undefined => {\n const secret = resolve<string | undefined>(\"refreshToken.secret\", \"jwt.refresh.secret\");\n\n if (secret) checkSecretStrength(\"refreshToken.secret\", secret);\n\n return secret;\n },\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\n * naming the key when the configured value is not a positive `ms` duration.\n */\n expiresInMs: (): number =>\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\n logoutWithoutToken: (): LogoutWithoutTokenBehavior =>\n resolve(\"refreshToken.logoutWithoutToken\", \"jwt.refresh.logoutWithoutToken\", \"revoke-all\"),\n },\n};\n"],"mappings":";;;;;;AA8BA,MAAM,mCAAmB,IAAI,IAAY;;AAGzC,MAAM,mCAAmB,IAAI,IAAY;;AAGzC,MAAM,mBAAmB;;AAGzB,MAAM,uBAAuB;;AAG7B,SAAS,eAAwB;CAC/B,OAAO,QAAQ,IAAI,aAAa;AAClC;;AAGA,SAAS,qBAAqB,KAAa,SAAuB;CAChE,IAAI,CAAC,aAAa,KAAK,iBAAiB,IAAI,GAAG,GAAG;CAElD,iBAAiB,IAAI,GAAG;CACxB,IAAI,KAAK,QAAQ,UAAU,OAAO;AACpC;;AAGA,SAAS,oBAAoB,KAAa,QAAsB;CAC9D,IAAI,OAAO,WAAW,MAAM,KAAK,kBAAkB;CAEnD,qBACE,UAAU,OACV,QAAQ,IAAI,mBAAmB,iBAAiB,sIAElD;AACF;AAEA,MAAM,6BAAuD;;;;;;;;;;AAW7D,MAAM,UAAU;;;;;;;;;;;;;;;;;;AAmBhB,SAAS,cAAc,KAAa,KAAsB;CACxD,IAAI;CAEJ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AAO,IAAI,sBAAsB,sBAAsB,CAAC;;EAEzF,mBAA2B,OAAO,IAAI,wBAAwB,CAAC;;EAE/D,UAAU,SAAyB;GACjC,MAAM,QAAQ,OAAO,IAA4C,kBAAkB;GAEnF,OAAO,QAAQ,MAAM,IAAI,IAAI,6BAA6B;EAC5D;;EAEA,YAAmC,OAAO,IAAI,eAAe;;EAE7D,qBAA8B,OAAO,IAAa,0BAA0B,KAAK,MAAM;CACzF;CACA,cAAc;;EAEZ,cAAkC;GAChC,MAAM,SAAS,QAA4B,uBAAuB,oBAAoB;GAEtF,IAAI,QAAQ,oBAAoB,uBAAuB,MAAM;GAE7D,OAAO;EACT;;EAEA,eAAwB,QAAQ,wBAAwB,uBAAuB,IAAI;;EAEnF,iBAAyB,QAAQ,0BAA0B,yBAAyB,IAAI;;;;;EAKxF,mBACE,cAAc,0BAA0B,WAAW,aAAa,UAAU,CAAC;;EAE7E,gBAAyB,QAAQ,yBAAyB,wBAAwB,IAAI;;EAEtF,kBAA0B,QAAQ,2BAA2B,0BAA0B,CAAC;;EAExF,0BACE,QAAQ,mCAAmC,kCAAkC,YAAY;CAC7F;AACF"}
1
+ {"version":3,"file":"auth-config.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth-config.ts"],"sourcesContent":["import { config } from \"@warlock.js/core\";\nimport type { CookieDomainResolver } from \"../contracts/types\";\nimport { log } from \"@warlock.js/logger\";\nimport { type Algorithm } from \"fast-jwt\";\nimport ms from \"ms\";\nimport type {\n AuthNotification,\n CanAuthenticate,\n NormalizeCredentials,\n LogoutWithoutTokenBehavior,\n OneTimeTokenUrlBuilder,\n PasswordSetter,\n} from \"../contracts/types\";\nimport type {\n AppleProviderConfig,\n AuthProvider,\n DiscordProviderConfig,\n FacebookProviderConfig,\n GitHubProviderConfig,\n GoogleProviderConfig,\n LinkedInProviderConfig,\n OtpSender,\n PasskeysConfig,\n ProviderLinkExisting,\n ProviderUserCreator,\n XProviderConfig,\n} from \"../contracts/providers\";\nimport type { Auth } from \"../models/auth.model\";\nimport { defaultNormalizeCredentials } from \"../utils/normalize-credentials\";\n\nconst warnedLegacyKeys = new Set<string>();\n\n/** One-time production warnings already logged, by key. */\nconst warnedProduction = new Set<string>();\n\n/** Signing secrets shorter than this are brute-forceable from one captured token. */\nconst MIN_SECRET_BYTES = 32;\n\n/** Access-token lifetimes past this get a production warning. */\nconst LONG_ACCESS_TOKEN_MS = 30 * 24 * 60 * 60 * 1000;\n\n/** Same answer as core's `environment()`, read directly so config stays dependency-light. */\nfunction isProduction(): boolean {\n return process.env.NODE_ENV === \"production\";\n}\n\n/** Log `message` once per process, in production only. */\nfunction warnOnceInProduction(key: string, message: string): void {\n if (!isProduction() || warnedProduction.has(key)) return;\n\n warnedProduction.add(key);\n log.warn(\"auth\", \"config\", message);\n}\n\n/** Log `message` once per process, in any environment. */\nfunction warnOnce(key: string, message: string): void {\n if (warnedProduction.has(key)) return;\n\n warnedProduction.add(key);\n log.warn(\"auth\", \"config\", message);\n}\n\n/** Warn (production, once) when a signing secret is too short to resist offline guessing. */\nfunction checkSecretStrength(key: string, secret: string): void {\n if (Buffer.byteLength(secret) >= MIN_SECRET_BYTES) return;\n\n warnOnceInProduction(\n `secret:${key}`,\n `auth.${key} is shorter than ${MIN_SECRET_BYTES} bytes, so a captured token lets an attacker ` +\n `guess it offline and forge tokens. Generate a strong secret with \"warlock jwt.generate\". ` +\n `From 6.0 a secret this short stops the app from booting.`,\n );\n}\n\n/**\n * Read a list of retired secrets: non-empty strings only. Each one gets the\n * same strength warning as an active secret.\n */\nfunction readPreviousSecrets(key: string): string[] {\n const raw = config.key<unknown>(`auth.${key}`);\n\n if (!Array.isArray(raw)) return [];\n\n const secrets = raw.filter((value): value is string => typeof value === \"string\" && value !== \"\");\n\n for (const secret of secrets) checkSecretStrength(key, secret);\n\n return secrets;\n}\n\nconst permitAuthentication: CanAuthenticate = (): boolean => true;\n\n/**\n * `ms` accepts anything at runtime and answers `undefined` for a string it\n * cannot parse (`\"30dayz\"`), a *formatted string* for a number (`2592000` ⇒\n * `\"43m\"`), and throws for `\"\"`. Its published types claim the far narrower\n * `(value: ms.StringValue) => number`, which is exactly what let an\n * `as ms.StringValue` cast smuggle arbitrary config text past the compiler and\n * hand `undefined` to the JWT signer. Declare the honest runtime signature once,\n * here, so every caller is forced to deal with the `undefined`.\n */\nconst parseMs = ms as unknown as (value: unknown) => number | string | undefined;\n\n/**\n * Turn a configured lifetime into a positive number of milliseconds, or throw\n * naming the key.\n *\n * A token lifetime is a security boundary, so an unusable value is a hard error\n * rather than a silent fallback: substituting a default would trade one\n * unintended lifetime for another, just as quietly — and quiet is the whole\n * problem. Every non-positive, non-finite or non-numeric parse is rejected:\n *\n * - `\"30dayz\"` / `\"thirty days\"` ⇒ `undefined` ⇒ a JWT signed with **no `exp`\n * claim** and an `Invalid Date` written to the token row.\n * - `\"0d\"` ⇒ parses cleanly to `0`, which `fast-jwt` treats as falsy and also\n * emits with **no `exp` claim** — it survives any guard that only rejects\n * `undefined`. `\"-1h\"` signs an already-expired token.\n * - `2592000` (a bare number) ⇒ `ms` *formats* it as `\"43m\"`, a string, which\n * then turns `Date.now() + expiresIn` into an `Invalid Date`.\n */\nfunction parseDuration(key: string, raw: unknown): number {\n let parsed: number | string | undefined;\n\n try {\n parsed = parseMs(raw);\n } catch {\n // ms throws (rather than returning undefined) for \"\" and non-strings\n parsed = undefined;\n }\n\n if (typeof parsed !== \"number\" || !Number.isFinite(parsed) || parsed <= 0) {\n throw new Error(\n `auth.${key}: ${JSON.stringify(raw)} is not a valid ms duration — ` +\n `use a positive duration string such as \"1h\", \"7d\", or NO_EXPIRATION.`,\n );\n }\n\n return parsed;\n}\n\n/** Email-verification token lifetime used when nothing is configured. */\nconst DEFAULT_VERIFICATION_EXPIRES_IN = \"24h\";\n\n/** Password-reset token lifetime used when nothing is configured. */\nconst DEFAULT_PASSWORD_RESET_EXPIRES_IN = \"60m\";\n\n/** Passkey challenge lifetime used when nothing is configured. */\nconst DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN = \"5m\";\n\n/** OTP lifetime used when nothing is configured. */\nconst DEFAULT_OTP_EXPIRES_IN = \"5m\";\n\n/** Access-token lifetime used when nothing is configured. */\nconst DEFAULT_ACCESS_TOKEN_EXPIRES_IN = \"1h\";\n\n/**\n * Resolve an auth setting, preferring the new `auth.accessToken.*` /\n * `auth.refreshToken.*` key and falling back to the deprecated `auth.jwt.*`\n * shape — warning once per legacy key. Returns `fallback` when neither is set.\n *\n * This is the backward-compatible shim that lets existing `auth.jwt.*` configs\n * keep working after the config split.\n */\nfunction resolve<T>(newKey: string, legacyKey: string, fallback?: T): T {\n const fromNew = config.key(`auth.${newKey}`);\n\n if (fromNew !== undefined && fromNew !== null) {\n return fromNew as T;\n }\n\n const fromLegacy = config.key(`auth.${legacyKey}`);\n\n if (fromLegacy !== undefined && fromLegacy !== null) {\n if (!warnedLegacyKeys.has(legacyKey)) {\n warnedLegacyKeys.add(legacyKey);\n log.warn(\n \"auth\",\n \"config-deprecation\",\n `auth.${legacyKey} is deprecated — use auth.${newKey}`,\n );\n }\n\n return fromLegacy as T;\n }\n\n return fallback as T;\n}\n\n/**\n * Typed, backward-compatible access to auth configuration. The service and the\n * jwt signer read configuration exclusively through here, so the new split\n * config and the legacy `auth.jwt.*` shape both resolve the same way.\n */\nexport const authConfig = {\n canAuthenticate: async (user: Auth): Promise<boolean> => {\n const canAuthenticate = config.key<CanAuthenticate>(\n \"auth.canAuthenticate\",\n permitAuthentication,\n );\n\n return canAuthenticate(user);\n },\n /**\n * Store only a SHA-256 digest of each access and refresh token\n * (`auth.hashTokensAtRest`). @default false\n */\n hashTokensAtRest: (): boolean => config.key<boolean>(\"auth.hashTokensAtRest\", false) === true,\n /**\n * Replace a password hash made with another algorithm or cost than\n * `encryption.password` asks for, after a successful login\n * (`auth.rehashPasswords`). @default true\n */\n rehashPasswords: (): boolean => config.key<boolean>(\"auth.rehashPasswords\", true) !== false,\n /** Login identifier normalizer, or `false` for exact matching. */\n normalizeCredentials: (): false | NormalizeCredentials =>\n config.key<false | NormalizeCredentials>(\n \"auth.normalizeCredentials\",\n defaultNormalizeCredentials,\n ),\n accessToken: {\n /** Signing secret (legacy: `auth.jwt.secret`). Throws if neither is set. */\n secret: (): string => {\n const secret = resolve<string | undefined>(\"accessToken.secret\", \"jwt.secret\");\n\n if (!secret) {\n throw new Error(\"auth: no JWT secret configured — set `auth.accessToken.secret`.\");\n }\n\n checkSecretStrength(\"accessToken.secret\", secret);\n\n return secret;\n },\n /**\n * Retired signing secrets, tried only when verifying an access token whose\n * signature the current secret rejects. Never used to sign.\n */\n previousSecrets: (): string[] => readPreviousSecrets(\"accessToken.previousSecrets\"),\n /** Signing algorithm (legacy: `auth.jwt.algorithm`). */\n algorithm: (): Algorithm => resolve(\"accessToken.algorithm\", \"jwt.algorithm\", \"HS256\"),\n /** `iss` claim stamped on and required of every token; unset ⇒ not used. */\n issuer: (): string | undefined => {\n const issuer = config.key<unknown>(\"auth.accessToken.issuer\");\n\n return typeof issuer === \"string\" && issuer.length > 0 ? issuer : undefined;\n },\n /** `aud` claim stamped on and required of every token; unset ⇒ not used. */\n audience: (): string | string[] | undefined => {\n const audience = config.key<unknown>(\"auth.accessToken.audience\");\n\n if (typeof audience === \"string\" && audience.length > 0) return audience;\n\n if (\n Array.isArray(audience) &&\n audience.length > 0 &&\n audience.every((entry) => typeof entry === \"string\" && entry.length > 0)\n ) {\n return audience as string[];\n }\n\n return undefined;\n },\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.expiresIn`). */\n expiresIn: (): string | undefined => resolve(\"accessToken.expiresIn\", \"jwt.expiresIn\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Defaults\n * to 1 hour when unset; throws naming the key when the configured value is\n * not a positive `ms` duration. See {@link parseDuration}.\n */\n expiresInMs: (): number => {\n const lifetime = parseDuration(\n \"accessToken.expiresIn\",\n authConfig.accessToken.expiresIn() ?? DEFAULT_ACCESS_TOKEN_EXPIRES_IN,\n );\n\n if (lifetime > LONG_ACCESS_TOKEN_MS) {\n warnOnceInProduction(\n \"accessToken.expiresIn\",\n \"auth.accessToken.expiresIn is longer than 30 days: a stolen access token stays usable \" +\n 'that long. Use a short lifetime (e.g. \"1h\") with refresh tokens ' +\n \"(auth.refreshToken.enabled) instead.\",\n );\n }\n\n return lifetime;\n },\n },\n pageAuth: {\n /**\n * Login path a guarded PAGE route redirects a logged-out browser to.\n *\n * Unset (the default) ⇒ page-route auth failures keep the JSON 401 API\n * contract, so existing apps see NO behavior change. Set it (e.g. \"/login\")\n * to opt a browser-facing app into login-redirect UX: a logged-out human\n * navigating to a guarded page lands on the login screen instead of reading\n * a raw JSON error blob. Finding b9ab9804.\n */\n loginPath: (): string | undefined => config.key(\"auth.pageAuth.loginPath\"),\n /**\n * Query parameter the redirect carries the originally-requested path in, so\n * the login flow can send the user back where they were headed. Defaults to\n * `\"returnUrl\"`.\n */\n returnUrlParam: (): string => config.key(\"auth.pageAuth.returnUrlParam\", \"returnUrl\"),\n },\n cookie: {\n /** Cookie name `setAuthCookie`/`clearAuthCookie` use. @default \"access_token\" */\n name: (): string => config.key(\"auth.cookie.name\", \"access_token\"),\n /** Refresh-token cookie name the session cookie helpers use. @default \"refresh_token\" */\n refreshName: (): string => config.key(\"auth.cookie.refreshName\", \"refresh_token\"),\n /** Cookie `Path` attribute `setAuthCookie`/`clearAuthCookie` use. @default \"/\" */\n path: (): string => config.key(\"auth.cookie.path\", \"/\"),\n /** Select the request-scoped cookie Domain; undefined keeps it host-only. */\n cookieDomain: (): CookieDomainResolver | undefined => config.key(\"auth.cookie.cookieDomain\"),\n /** Write the auth cookies as `__Host-<name>` (Secure, `Path=/`, no Domain). @default false */\n hostPrefix: (): boolean => config.key<boolean>(\"auth.cookie.hostPrefix\", false) === true,\n },\n csrf: {\n /**\n * Extra origins allowed on a cookie-authenticated unsafe-method request,\n * beyond the request's own origin. @default []\n */\n allowedOrigins: (): string[] => config.key(\"auth.csrf.allowedOrigins\", []),\n },\n verification: {\n /** Lifetime in ms of an email-verification token; throws naming the key when unusable. @default \"24h\" */\n expiresInMs: (): number =>\n parseDuration(\n \"verification.expiresIn\",\n config.key(\"auth.verification.expiresIn\", DEFAULT_VERIFICATION_EXPIRES_IN),\n ),\n /** User attribute stamped with the verification date. @default \"emailVerifiedAt\" */\n field: (): string => config.key(\"auth.verification.field\", \"emailVerifiedAt\"),\n /** App notification replacing the default verification email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.verification.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.verification.url\"),\n },\n passwordReset: {\n /** Lifetime in ms of a password-reset token; throws naming the key when unusable. @default \"60m\" */\n expiresInMs: (): number =>\n parseDuration(\n \"passwordReset.expiresIn\",\n config.key(\"auth.passwordReset.expiresIn\", DEFAULT_PASSWORD_RESET_EXPIRES_IN),\n ),\n /** User attribute `requestPasswordReset` looks the account up by. @default \"email\" */\n identifierField: (): string => config.key(\"auth.passwordReset.identifierField\", \"email\"),\n /** App notification replacing the default reset email. */\n notification: (): AuthNotification | undefined => config.key(\"auth.passwordReset.notification\"),\n /** Link builder whose result is handed to the notification as `url`. */\n url: (): OneTimeTokenUrlBuilder | undefined => config.key(\"auth.passwordReset.url\"),\n /** App-owned password writer replacing the default. */\n setPassword: (): PasswordSetter | undefined => config.key(\"auth.passwordReset.setPassword\"),\n /** Wait for the reset notification before `requestPasswordReset` resolves. @default false */\n awaitDelivery: (): boolean =>\n config.key<boolean>(\"auth.passwordReset.awaitDelivery\", false) === true,\n },\n providers: {\n /** `auth.providers.google`, when configured. */\n google: (): GoogleProviderConfig | undefined => config.key(\"auth.providers.google\"),\n /** `auth.providers.github`, when configured. */\n github: (): GitHubProviderConfig | undefined => config.key(\"auth.providers.github\"),\n /** `auth.providers.discord`, when configured. */\n discord: (): DiscordProviderConfig | undefined => config.key(\"auth.providers.discord\"),\n /** `auth.providers.linkedin`, when configured. */\n linkedin: (): LinkedInProviderConfig | undefined => config.key(\"auth.providers.linkedin\"),\n /** `auth.providers.apple`, when configured. */\n apple: (): AppleProviderConfig | undefined => config.key(\"auth.providers.apple\"),\n /** `auth.providers.facebook`, when configured. */\n facebook: (): FacebookProviderConfig | undefined => config.key(\"auth.providers.facebook\"),\n /** `auth.providers.x`, when configured. */\n x: (): XProviderConfig | undefined => config.key(\"auth.providers.x\"),\n /** An app-registered provider under `auth.providers.custom.<name>`. */\n custom: (name: string): AuthProvider | undefined => {\n const providers = config.key<Record<string, AuthProvider>>(\"auth.providers.custom\", {});\n\n // Own keys only: `name` arrives from a URL, and \"constructor\" must not resolve to Object.\n return Object.hasOwn(providers, name) ? providers[name] : undefined;\n },\n /** User attribute a verified provider email is matched against. @default \"email\" */\n emailField: (): string => config.key(\"auth.providers.emailField\", \"email\"),\n /** App-owned user creation for a first provider login. */\n createUser: (): ProviderUserCreator | undefined => config.key(\"auth.providers.createUser\"),\n /** Linking a first provider login to an existing account by email. @default \"verified\" */\n linkExisting: (): ProviderLinkExisting => {\n const value = config.key<unknown>(\"auth.providers.linkExisting\", \"verified\");\n\n return value === \"always\" || value === \"never\" ? value : \"verified\";\n },\n },\n passkeys: {\n /** `auth.passkeys`; throws naming the keys when `rpID`, `rpName` or `origin` is missing. */\n settings: (): PasskeysConfig => {\n const settings = config.key<PasskeysConfig | undefined>(\"auth.passkeys\");\n\n if (!settings?.rpID || !settings.rpName || !settings.origin) {\n throw new Error(\n \"@warlock.js/auth: passkeys need `auth.passkeys.rpID`, `auth.passkeys.rpName` and `auth.passkeys.origin`.\",\n );\n }\n\n return settings;\n },\n /** Allowed ceremony origins, as a list. */\n origins: (): string[] => {\n const { origin } = authConfig.passkeys.settings();\n\n return Array.isArray(origin) ? origin : [origin];\n },\n /** User-verification requirement for both ceremonies. @default \"preferred\" (becomes \"required\" in 6.0) */\n userVerification: (): \"required\" | \"preferred\" => {\n const configured = config.key<PasskeysConfig | undefined>(\"auth.passkeys\")?.userVerification;\n\n if (configured === undefined) {\n warnOnce(\n \"passkeys.userVerification\",\n 'auth.passkeys.userVerification is not set, so \"preferred\" applies: a passkey proving only possession of the device is accepted. The default changes to \"required\" in 6.0: set it explicitly to choose now.',\n );\n }\n\n return configured === \"required\" ? \"required\" : \"preferred\";\n },\n /** Challenge lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n challengeExpiresInMs: (): number =>\n parseDuration(\n \"passkeys.challengeExpiresIn\",\n config.key(\"auth.passkeys.challengeExpiresIn\", DEFAULT_PASSKEY_CHALLENGE_EXPIRES_IN),\n ),\n },\n otp: {\n /** Notifications channel the code is sent through. @default \"sms\" */\n channel: (): string => config.key(\"auth.otp.channel\", \"sms\"),\n /** User attribute holding the phone number. @default \"phone\" */\n phoneField: (): string => config.key(\"auth.otp.phoneField\", \"phone\"),\n /** Code lifetime in ms; throws naming the key when unusable. @default \"5m\" */\n expiresInMs: (): number =>\n parseDuration(\"otp.expiresIn\", config.key(\"auth.otp.expiresIn\", DEFAULT_OTP_EXPIRES_IN)),\n /** Verify attempts before the code is invalidated. @default 5 */\n maxAttempts: (): number => config.key(\"auth.otp.maxAttempts\", 5),\n /** The message text for a code. */\n message: (code: string): string => {\n const build = config.key<((code: string) => string) | undefined>(\"auth.otp.message\");\n\n return build ? build(code) : `Your verification code is ${code}`;\n },\n /** App-owned delivery replacing the notifications channel send. */\n send: (): OtpSender | undefined => config.key(\"auth.otp.send\"),\n /** Wait for the code delivery before `requestOtp` resolves. @default false */\n awaitDelivery: (): boolean => config.key<boolean>(\"auth.otp.awaitDelivery\", false) === true,\n },\n refreshToken: {\n /** Separate refresh secret (legacy: `auth.jwt.refresh.secret`); empty ⇒ fall back to the access secret. */\n secret: (): string | undefined => {\n const secret = resolve<string | undefined>(\"refreshToken.secret\", \"jwt.refresh.secret\");\n\n if (secret) checkSecretStrength(\"refreshToken.secret\", secret);\n\n return secret;\n },\n /**\n * Retired refresh secrets, tried only when verifying a refresh token whose\n * signature the current secret rejects. Never used to sign.\n */\n previousSecrets: (): string[] => readPreviousSecrets(\"refreshToken.previousSecrets\"),\n /** Whether refresh tokens are enabled (legacy: `auth.jwt.refresh.enabled`). */\n enabled: (): boolean => resolve(\"refreshToken.enabled\", \"jwt.refresh.enabled\", true),\n /** Lifetime as an `ms`-string (legacy: `auth.jwt.refresh.expiresIn`). */\n expiresIn: (): string => resolve(\"refreshToken.expiresIn\", \"jwt.refresh.expiresIn\", \"7d\"),\n /**\n * Lifetime in milliseconds — the only form a token issuer may use. Throws\n * naming the key when the configured value is not a positive `ms` duration.\n */\n expiresInMs: (): number =>\n parseDuration(\"refreshToken.expiresIn\", authConfig.refreshToken.expiresIn()),\n /** Rotate-on-use (legacy: `auth.jwt.refresh.rotation`). */\n rotation: (): boolean => resolve(\"refreshToken.rotation\", \"jwt.refresh.rotation\", true),\n /** Max active tokens per user (legacy: `auth.jwt.refresh.maxPerUser`). */\n maxPerUser: (): number => resolve(\"refreshToken.maxPerUser\", \"jwt.refresh.maxPerUser\", 5),\n /** Logout-without-token behavior (legacy: `auth.jwt.refresh.logoutWithoutToken`). */\n logoutWithoutToken: (): LogoutWithoutTokenBehavior =>\n resolve(\"refreshToken.logoutWithoutToken\", \"jwt.refresh.logoutWithoutToken\", \"revoke-all\"),\n },\n};\n"],"mappings":";;;;;;AA8BA,MAAM,mCAAmB,IAAI,IAAY;;AAGzC,MAAM,mCAAmB,IAAI,IAAY;;AAGzC,MAAM,mBAAmB;;AAGzB,MAAM,uBAAuB;;AAG7B,SAAS,eAAwB;CAC/B,OAAO,QAAQ,IAAI,aAAa;AAClC;;AAGA,SAAS,qBAAqB,KAAa,SAAuB;CAChE,IAAI,CAAC,aAAa,KAAK,iBAAiB,IAAI,GAAG,GAAG;CAElD,iBAAiB,IAAI,GAAG;CACxB,IAAI,KAAK,QAAQ,UAAU,OAAO;AACpC;;AAGA,SAAS,SAAS,KAAa,SAAuB;CACpD,IAAI,iBAAiB,IAAI,GAAG,GAAG;CAE/B,iBAAiB,IAAI,GAAG;CAC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AAuB,IAAI;;EAEnF,iBAAyB,QAAQ,0BAA0B,yBAAyB,IAAI;;;;;EAKxF,mBACE,cAAc,0BAA0B,WAAW,aAAa,UAAU,CAAC;;EAE7E,gBAAyB,QAAQ,yBAAyB,wBAAwB,IAAI;;EAEtF,kBAA0B,QAAQ,2BAA2B,0BAA0B,CAAC;;EAExF,0BACE,QAAQ,mCAAmC,kCAAkC,YAAY;CAC7F;AACF"}
@@ -113,6 +113,13 @@ declare class AuthService {
113
113
  * missing user or a wrong password, emitting `login.failed` either way.
114
114
  */
115
115
  attemptLogin<T extends Auth>(Model: ChildModel<T>, data: AuthCredentials): Promise<T | null>;
116
+ /**
117
+ * After a successful password check, replace a hash that no longer matches
118
+ * the configured algorithm or cost (`auth.rehashPasswords`, default on) with
119
+ * a fresh one made from the password just verified. Never fails the login:
120
+ * a problem is logged and the old hash keeps working.
121
+ */
122
+ private rehashPassword;
116
123
  /**
117
124
  * Full login flow: validate credentials, issue tokens, emit events. Returns
118
125
  * the user + token pair on success, `null` on failure.
@@ -163,8 +170,10 @@ declare class AuthService {
163
170
  removeRefreshToken(user: Auth, token: string): Promise<void>;
164
171
  /**
165
172
  * Revoke every active refresh token for the user and delete their access
166
- * tokens — "log out of all devices". Each durable family is first marked through its revision coordinator; an
167
- * event fires per revoked token.
173
+ * tokens — "log out of all devices". Durable families are ensured together
174
+ * and revoked with one update, refresh tokens with another; a
175
+ * `token.familyRevoked` event fires per family (and `token.revoked` for a
176
+ * token outside any durable family).
168
177
  */
169
178
  revokeAllTokens(user: Auth): Promise<void>;
170
179
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"auth.service.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/services/auth.service.ts"],"mappings":";;;;;;;;;;qBAmDa,yCAAyC;EACpD,YAAmB;;cAyEf;;;;;;;cAOQ;;;;cAOA;;;;cAOA;;;;EAOL,wBAAwB,MAAM,OAAO;;EAS/B,gBAAgB,MAAM,OAAO;UAI5B;UAMA;;;;;;EAi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AAY;;;;;;;;EAaV,wBAAwB,UAAU,MAC7C,SAAS,SACT,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E,OAAO,WAAW,IAClB,aAAa,iBACb,aAAa,aACZ,QAAQ,YAAY;;UA0BT;;;;;;;;;;;EA2BD,OAAO,MAAM,MAAM,sBAAsB,wBAAwB;;;;EA6BjE,kBAAkB,MAAM,MAAM,gBAAgB;;;;EAO9C,sBAAsB,MAAM,OAAO;;;;EAOnC,mBAAmB,MAAM,MAAM,gBAAgB;;;;;;;;EAW/C,gBAAgB,MAAM,OAAO;;;;EAqD7B,kBAAkB,mBAAmB;;;;;;;EAyErC,wBAAwB;;;;;;;;;;;EAyBxB,2BAA2B;IACtC,cAAc;IACd,eAAe;;;;;;;;;;EAgBJ,4BAA4B;IACvC;IACA;;;;;EAkBW,kBAAkB,MAAM,OAAO,QAAQ;;;;;;UAS5C;UAUA;;;;;;;;;;;;;;;;;;;;;;EAmCD,cACL,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E,gBAAgB,mBAChB,UAAS;;;;;;;;;;;EA6BJ,gBACL,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E,UAAS,wBACT,UAAU;;;;;;;;;;;;EA8BL,kBACL,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E;IAAU,aAAa;IAAmB,cAAc;KACxD,UAAU;;;;;EA8BL,oBACL,aAAa,oCAAoC,MAAM,WAAW,SAAS,oBAC3E,UAAU;;qBAuBD,aAAW"}
@@ -15,7 +15,7 @@ import { authEvents } from "./auth-events.mjs";
15
15
  import { isInvalidCredentialError, jwt } from "./jwt.mjs";
16
16
  import { TokenFamilyUnavailableError, afterTokenFamilyOperation, runTokenFamilyOperation } from "./token-family-operation.mjs";
17
17
  import { Random } from "@mongez/reinforcements";
18
- import { ForbiddenError, config, hashPassword, verifyPassword } from "@warlock.js/core";
18
+ import { ForbiddenError, config, hashPassword, needsRehash, verifyPassword } from "@warlock.js/core";
19
19
  import { createCipheriv, createDecipheriv, createHmac, randomBytes, randomUUID } from "node:crypto";
20
20
  import { cache } from "@warlock.js/cache";
21
21
  import { log } from "@warlock.js/logger";
@@ -469,9 +469,26 @@ var AuthService = class {
469
469
  authEvents.emit("login.failed", otherData, "Authentication not allowed");
470
470
  return null;
471
471
  }
472
+ await this.rehashPassword(user, String(password), storedHash);
472
473
  return user;
473
474
  }
474
475
  /**
476
+ * After a successful password check, replace a hash that no longer matches
477
+ * the configured algorithm or cost (`auth.rehashPasswords`, default on) with
478
+ * a fresh one made from the password just verified. Never fails the login:
479
+ * a problem is logged and the old hash keeps working.
480
+ */
481
+ async rehashPassword(user, plainPassword, storedHash) {
482
+ try {
483
+ if (!authConfig.rehashPasswords() || !needsRehash(storedHash)) return;
484
+ await user.merge({ password: await this.hashPassword(plainPassword) }).save();
485
+ if (await this.verifyPassword(plainPassword, user.string("password") ?? "")) return;
486
+ await user.merge({ password: plainPassword }).save();
487
+ } catch (error) {
488
+ log.error("auth", "rehash-password", error);
489
+ }
490
+ }
491
+ /**
475
492
  * Full login flow: validate credentials, issue tokens, emit events. Returns
476
493
  * the user + token pair on success, `null` on failure.
477
494
  */
@@ -569,17 +586,27 @@ var AuthService = class {
569
586
  }
570
587
  /**
571
588
  * Revoke every active refresh token for the user and delete their access
572
- * tokens — "log out of all devices". Each durable family is first marked through its revision coordinator; an
573
- * event fires per revoked token.
589
+ * tokens — "log out of all devices". Durable families are ensured together
590
+ * and revoked with one update, refresh tokens with another; a
591
+ * `token.familyRevoked` event fires per family (and `token.revoked` for a
592
+ * token outside any durable family).
574
593
  */
575
594
  async revokeAllTokens(user) {
576
595
  const existingRows = await this.refreshTokenModel.familiesForUser(user);
577
- const familyIds = new Set(existingRows.map((token) => token.familyId));
578
- for (const familyId of familyIds) await AuthTokenFamily.ensure(user, familyId);
579
- const families = await AuthTokenFamily.activeFor(user);
580
- for (const family of families) await this.revokeTokenFamily(family.get("family_id"));
581
- const legacyTokens = await this.refreshTokenModel.revokeAllFor(user);
582
- for (const token of legacyTokens) authEvents.emit("token.revoked", user, token);
596
+ const familyIds = new Set(existingRows.map((token) => token.familyId).filter(Boolean));
597
+ await AuthTokenFamily.ensureMany(user, [...familyIds]);
598
+ const revokedFamilyIds = (await AuthTokenFamily.activeFor(user)).map((family) => family.get("family_id"));
599
+ if (revokedFamilyIds.length > 0) await AuthTokenFamily.revokeAllFor(user);
600
+ const revokedTokens = await this.refreshTokenModel.revokeAllFor(user);
601
+ const tokensByFamily = /* @__PURE__ */ new Map();
602
+ const unfamilied = [];
603
+ for (const token of revokedTokens) {
604
+ const familyId = token.familyId;
605
+ if (familyId && revokedFamilyIds.includes(familyId)) tokensByFamily.set(familyId, [...tokensByFamily.get(familyId) ?? [], token]);
606
+ else unfamilied.push(token);
607
+ }
608
+ for (const familyId of revokedFamilyIds) authEvents.emit("token.familyRevoked", familyId, tokensByFamily.get(familyId) ?? []);
609
+ for (const token of unfamilied) authEvents.emit("token.revoked", user, token);
583
610
  await this.removeAllAccessTokens(user);
584
611
  authEvents.emit("logout.all", user);
585
612
  }