@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
@@ -1 +1 @@
1
- {"version":3,"file":"one-time-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/one-time-token/one-time-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport { isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/** What a one-time token may be used for. A token only ever satisfies its own purpose. */\nexport type OneTimeTokenPurpose =\n | \"email-verification\"\n | \"password-reset\"\n | \"otp\"\n | \"passkey-registration\"\n | \"passkey-authentication\";\n\n/**\n * Seal schema for the persisted one-time token. Exported so an override can\n * extend it (e.g. a tenant key).\n */\nexport const oneTimeTokenSchema = v.object({\n token_hash: v.string().required(),\n purpose: v.string().required(),\n // Absent only on a passkey authentication challenge (no user identified yet).\n user_id: v.scalar().optional(),\n user_type: v.string().optional(),\n expires_at: v.date().required(),\n consumed_at: v.date().optional(),\n attempts: v.int().optional(),\n});\n\n/**\n * Persisted one-time secret: email-verification / password-reset token, OTP\n * code, or passkey ceremony challenge.\n *\n * **Only a SHA-256 hash is stored** — the raw token exists in the notification\n * and nowhere else, so a leaked table cannot be replayed. Single use is\n * enforced by {@link consumeIfActive}, a conditional update in the same shape\n * as `RefreshToken.revokeIfActive`. Override via `config.auth.oneTimeToken.model`.\n */\nexport class OneTimeToken extends Model {\n public static table = \"one_time_tokens\";\n\n public static schema = oneTimeTokenSchema;\n\n /**\n * The SHA-256 of a one-time secret. For a short OTP code the hash is\n * brute-forceable offline, so it is as sensitive as the code itself — never\n * serialize it. Only `toJSON()` is affected; `findByHash` still queries it.\n */\n public static hidden = [\"token_hash\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy spent token hashes into\n * `one_time_tokensTrash` on every `destroy()`. A purged one-time token must\n * not survive anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** The user this token was issued for. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The user-type slug this token was issued for. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /** Whether the token has been used (or invalidated by a newer one). */\n public get isConsumed(): boolean {\n return !!this.get(\"consumed_at\");\n }\n\n /** Whether the expiry has passed. Fails closed: an unusable `expires_at` counts as expired. */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date(expiresAt).getTime() <= Date.now();\n }\n\n /**\n * Atomically mark this token consumed ONLY if nobody has yet. Resolves `true`\n * for the single caller that won; every concurrent or later caller gets\n * `false`.\n */\n public async consumeIfActive(): Promise<boolean> {\n const modelClass = this.constructor as typeof OneTimeToken;\n\n const consumed = await modelClass.atomic(\n { id: this.id, consumed_at: null },\n { $set: { consumed_at: new Date() } },\n );\n\n return consumed > 0;\n }\n\n /** Persist a new token row. `tokenHash` is the SHA-256 hex digest, never the raw token. */\n public static issue(\n user: Auth,\n purpose: OneTimeTokenPurpose,\n tokenHash: string,\n expiresAt: Date,\n ) {\n return this.create({\n token_hash: tokenHash,\n purpose,\n user_id: user.id,\n user_type: user.userType,\n expires_at: expiresAt,\n consumed_at: null,\n attempts: 0,\n });\n }\n\n /**\n * Persist a passkey ceremony challenge. `user` is omitted for an\n * authentication challenge, issued before anyone is identified.\n */\n public static issueChallenge(\n purpose: OneTimeTokenPurpose,\n tokenHash: string,\n expiresAt: Date,\n user?: Auth,\n ) {\n return this.create({\n token_hash: tokenHash,\n purpose,\n user_id: user?.id ?? null,\n user_type: user?.userType ?? null,\n expires_at: expiresAt,\n consumed_at: null,\n attempts: 0,\n });\n }\n\n /** The user's newest unconsumed token of `purpose` (at most one for OTP). */\n public static findActiveFor(\n user: Auth,\n purpose: OneTimeTokenPurpose,\n ): Promise<OneTimeToken | null> {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, purpose, consumed_at: null })\n .orderBy(\"created_at\", \"desc\")\n .first();\n }\n\n /**\n * Atomically count one verify attempt, ONLY while fewer than `max` have been\n * counted and the token is unconsumed. Resolves `false` once the cap is\n * reached — of N concurrent attempts, at most `max` ever resolve `true`.\n */\n public async recordAttempt(max: number): Promise<boolean> {\n const modelClass = this.constructor as typeof OneTimeToken;\n\n const counted = await modelClass.atomic(\n { id: this.id, consumed_at: null, attempts: { $lt: max } },\n { $inc: { attempts: 1 } },\n // Code-authored filter; nothing here comes from the request.\n { trustedFilter: true },\n );\n\n return counted > 0;\n }\n\n /**\n * Hard-delete every spent row — expired, or consumed (used, invalidated by a\n * newer token, or exhausted). Neither can ever be redeemed again, so nothing\n * reads them. Hard-deleted, never trashed. Returns the number removed. Runs from the `auth.cleanup` CLI\n * command (a cold batch path).\n */\n public static async purgeSpent(): Promise<number> {\n const expired = await this.query().where(\"expires_at\", \"<\", new Date()).get();\n const consumed = await this.query().whereNotNull(\"consumed_at\").get();\n const spent = new Map([...expired, ...consumed].map((token) => [String(token.id), token]));\n\n for (const token of spent.values()) {\n // `static deleteStrategy` above already forces \"permanent\" regardless\n // of the data source default (Mongo's is \"trash\").\n await token.destroy();\n }\n\n return spent.size;\n }\n\n /** Find a token by hash, scoped to a purpose — a token of the other purpose is not found. */\n public static findByHash(\n tokenHash: string,\n purpose: OneTimeTokenPurpose,\n ): Promise<OneTimeToken | null> {\n return this.first({ token_hash: tokenHash, purpose });\n }\n\n /**\n * Consume every still-unused token of `purpose` for the user, returning how\n * many were invalidated. Used before issuing a new password-reset token.\n */\n public static invalidateActiveFor(user: Auth, purpose: OneTimeTokenPurpose): Promise<number> {\n return this.atomic(\n { user_id: user.id, user_type: user.userType, purpose, consumed_at: null },\n { $set: { consumed_at: new Date() } },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAiBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAE7B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;CAC9B,aAAa,EAAE,KAAK,CAAC,CAAC,SAAS;CAC/B,UAAU,EAAE,IAAI,CAAC,CAAC,SAAS;AAC7B,CAAC;;;;;;;;;;AAWD,IAAa,eAAb,cAAkC,MAAM;;eAChB;;;gBAEC;;;gBAOA,CAAC,YAAY;;;wBAQL;;;CAG/B,IAAW,SAAS;EAClB,OAAO,KAAK,IAAI,SAAS;CAC3B;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;CAGA,IAAW,aAAsB;EAC/B,OAAO,CAAC,CAAC,KAAK,IAAI,aAAa;CACjC;;CAGA,IAAW,YAAqB;EAC9B,MAAM,YAAY,KAAK,IAAI,YAAY;EAEvC,IAAI,CAAC,eAAe,SAAS,GAAG,OAAO;EAEvC,OAAO,IAAI,KAAK,SAAS,CAAC,CAAC,QAAQ,KAAK,KAAK,IAAI;CACnD;;;;;;CAOA,MAAa,kBAAoC;EAQ/C,OAAO,MAPY,KAAK,YAEU,OAChC;GAAE,IAAI,KAAK;GAAI,aAAa;EAAK,GACjC,EAAE,MAAM,EAAE,6BAAa,IAAI,KAAK,EAAE,EAAE,CACtC,IAEkB;CACpB;;CAGA,OAAc,MACZ,MACA,SACA,WACA,WACA;EACA,OAAO,KAAK,OAAO;GACjB,YAAY;GACZ;GACA,SAAS,KAAK;GACd,WAAW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AO,KAAK,OACV;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU;GAAS,aAAa;EAAK,GACzE,EAAE,MAAM,EAAE,6BAAa,IAAI,KAAK,EAAE,EAAE,CACtC;CACF;AACF"}
1
+ {"version":3,"file":"one-time-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/one-time-token/one-time-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport { isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/** What a one-time token may be used for. A token only ever satisfies its own purpose. */\nexport type OneTimeTokenPurpose =\n | \"email-verification\"\n | \"password-reset\"\n | \"otp\"\n | \"passkey-registration\"\n | \"passkey-authentication\";\n\n/**\n * Seal schema for the persisted one-time token. Exported so an override can\n * extend it (e.g. a tenant key).\n */\nexport const oneTimeTokenSchema = v.object({\n token_hash: v.string().required(),\n purpose: v.string().required(),\n // Absent only on a passkey authentication challenge (no user identified yet).\n user_id: v.scalar().optional(),\n user_type: v.string().optional(),\n expires_at: v.date().required(),\n consumed_at: v.date().optional(),\n attempts: v.int().optional(),\n});\n\n/**\n * Persisted one-time secret: email-verification / password-reset token, OTP\n * code, or passkey ceremony challenge.\n *\n * **Only a SHA-256 hash is stored** — the raw token exists in the notification\n * and nowhere else, so a leaked table cannot be replayed. Single use is\n * enforced by {@link consumeIfActive}, a conditional update in the same shape\n * as `RefreshToken.revokeIfActive`. Override via `config.auth.oneTimeToken.model`.\n */\nexport class OneTimeToken extends Model {\n public static table = \"one_time_tokens\";\n\n public static schema = oneTimeTokenSchema;\n\n /**\n * The SHA-256 of a one-time secret. For a short OTP code the hash is\n * brute-forceable offline, so it is as sensitive as the code itself — never\n * serialize it. Only `toJSON()` is affected; `findByHash` still queries it.\n */\n public static hidden = [\"token_hash\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy spent token hashes into\n * `one_time_tokensTrash` on every `destroy()`. A purged one-time token must\n * not survive anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** The user this token was issued for. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The user-type slug this token was issued for. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /** Whether the token has been used (or invalidated by a newer one). */\n public get isConsumed(): boolean {\n return !!this.get(\"consumed_at\");\n }\n\n /** Whether the expiry has passed. Fails closed: an unusable `expires_at` counts as expired. */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date(expiresAt).getTime() <= Date.now();\n }\n\n /**\n * Atomically mark this token consumed ONLY if nobody has yet. Resolves `true`\n * for the single caller that won; every concurrent or later caller gets\n * `false`.\n */\n public async consumeIfActive(): Promise<boolean> {\n const modelClass = this.constructor as typeof OneTimeToken;\n\n const consumed = await modelClass.atomic(\n { id: this.id, consumed_at: null },\n { $set: { consumed_at: new Date() } },\n );\n\n return consumed > 0;\n }\n\n /** Persist a new token row. `tokenHash` is the SHA-256 hex digest, never the raw token. */\n public static issue(\n user: Auth,\n purpose: OneTimeTokenPurpose,\n tokenHash: string,\n expiresAt: Date,\n ) {\n return this.create({\n token_hash: tokenHash,\n purpose,\n user_id: user.id,\n user_type: user.userType,\n expires_at: expiresAt,\n consumed_at: null,\n attempts: 0,\n });\n }\n\n /**\n * Persist a passkey ceremony challenge. `user` is omitted for an\n * authentication challenge, issued before anyone is identified.\n */\n public static issueChallenge(\n purpose: OneTimeTokenPurpose,\n tokenHash: string,\n expiresAt: Date,\n user?: Auth,\n ) {\n return this.create({\n token_hash: tokenHash,\n purpose,\n user_id: user?.id ?? null,\n user_type: user?.userType ?? null,\n expires_at: expiresAt,\n consumed_at: null,\n attempts: 0,\n });\n }\n\n /** The user's newest unconsumed token of `purpose` (at most one for OTP). */\n public static findActiveFor(\n user: Auth,\n purpose: OneTimeTokenPurpose,\n ): Promise<OneTimeToken | null> {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, purpose, consumed_at: null })\n .orderBy(\"created_at\", \"desc\")\n .first();\n }\n\n /**\n * Atomically count one verify attempt, ONLY while fewer than `max` have been\n * counted and the token is unconsumed. Resolves `false` once the cap is\n * reached — of N concurrent attempts, at most `max` ever resolve `true`.\n */\n public async recordAttempt(max: number): Promise<boolean> {\n const modelClass = this.constructor as typeof OneTimeToken;\n\n const counted = await modelClass.atomic(\n { id: this.id, consumed_at: null, attempts: { $lt: max } },\n { $inc: { attempts: 1 } },\n // Code-authored filter; nothing here comes from the request.\n { trustedFilter: true },\n );\n\n return counted > 0;\n }\n\n /**\n * Hard-delete every spent row — expired, or consumed (used, invalidated by a\n * newer token, or exhausted). Neither can ever be redeemed again, so nothing\n * reads them. Returns the number removed. Runs from the `auth.cleanup` CLI\n * command.\n *\n * Two set-based deletes, never a read: the rows are not loaded into memory,\n * so a table grown by anonymous passkey-option calls cannot make the cleanup\n * run out of memory. A query-builder delete is a driver-level hard delete,\n * so no token hash is copied into a trash collection.\n */\n public static async purgeSpent(): Promise<number> {\n const expired = await this.query().where(\"expires_at\", \"<\", new Date()).delete();\n const consumed = await this.query().whereNotNull(\"consumed_at\").delete();\n\n return expired + consumed;\n }\n\n /** Find a token by hash, scoped to a purpose — a token of the other purpose is not found. */\n public static findByHash(\n tokenHash: string,\n purpose: OneTimeTokenPurpose,\n ): Promise<OneTimeToken | null> {\n return this.first({ token_hash: tokenHash, purpose });\n }\n\n /**\n * Consume every still-unused token of `purpose` for the user, returning how\n * many were invalidated. Used before issuing a new password-reset token.\n */\n public static invalidateActiveFor(user: Auth, purpose: OneTimeTokenPurpose): Promise<number> {\n return this.atomic(\n { user_id: user.id, user_type: user.userType, purpose, consumed_at: null },\n { $set: { consumed_at: new Date() } },\n );\n }\n}\n"],"mappings":";;;;;;;;;AAiBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,YAAY,EAAE,OAAO,CAAC,CAAC,SAAS;CAChC,SAAS,EAAE,O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AGA,OAAc,cACZ,MACA,SAC8B;EAC9B,OAAO,KAAK,MAAM,CAAC,CAChB,MAAM;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU;GAAS,aAAa;EAAK,CAAC,CAAC,CACjF,QAAQ,cAAc,MAAM,CAAC,CAC7B,MAAM;CACX;;;;;;CAOA,MAAa,cAAc,KAA+B;EAUxD,OAAO,MATY,KAAK,YAES,OAC/B;GAAE,IAAI,KAAK;GAAI,aAAa;GAAM,UAAU,EAAE,KAAK,IAAI;EAAE,GACzD,EAAE,MAAM,EAAE,UAAU,EAAE,EAAE,GAExB,EAAE,eAAe,KAAK,CACxB,IAEiB;CACnB;;;;;;;;;;;;CAaA,aAAoB,aAA8B;EAIhD,OAAO,MAHe,KAAK,MAAM,CAAC,CAAC,MAAM,cAAc,qBAAK,IAAI,KAAK,CAAC,CAAC,CAAC,OAAO,IAG9D,MAFM,KAAK,MAAM,CAAC,CAAC,aAAa,aAAa,CAAC,CAAC,OAAO;CAGzE;;CAGA,OAAc,WACZ,WACA,SAC8B;EAC9B,OAAO,KAAK,MAAM;GAAE,YAAY;GAAW;EAAQ,CAAC;CACtD;;;;;CAMA,OAAc,oBAAoB,MAAY,SAA+C;EAC3F,OAAO,KAAK,OACV;GAAE,SAAS,KAAK;GAAI,WAAW,KAAK;GAAU;GAAS,aAAa;EAAK,GACzE,EAAE,MAAM,EAAE,6BAAa,IAAI,KAAK,EAAE,EAAE,CACtC;CACF;AACF"}
@@ -89,6 +89,10 @@ export declare class RefreshToken extends Model {
89
89
  * `hidden` only strips it from `toJSON()` / `JSON.stringify(model)` (e.g. a
90
90
  * session list returned via `response.json`); `get("token")`,
91
91
  * `findByToken` / `findForUser` and every query still read the column.
92
+ *
93
+ * With `auth.hashTokensAtRest` on, the column holds the token's SHA-256
94
+ * digest instead; read the raw token of a freshly issued row through
95
+ * {@link plainToken}.
92
96
  */
93
97
  static hidden: string[];
94
98
  /**
@@ -100,6 +104,12 @@ export declare class RefreshToken extends Model {
100
104
  static deleteStrategy: "permanent";
101
105
  /** Token family this row belongs to (rotation / replay grouping). */
102
106
  get familyId(): string;
107
+ /**
108
+ * The raw refresh token, when it is known: always for a row stored
109
+ * unhashed, and for a hashed row only in the process that just issued it
110
+ * (e.g. the row `authService.createRefreshToken` returns).
111
+ */
112
+ get plainToken(): string | undefined;
103
113
  /**
104
114
  * Whether the token's `expires_at` is in the past.
105
115
  *
@@ -137,11 +147,13 @@ export declare class RefreshToken extends Model {
137
147
  */
138
148
  markAsUsed(): Promise<void>;
139
149
  /**
140
- * Persist a freshly-signed refresh token for the user.
150
+ * Persist a freshly-signed refresh token for the user. `token` is the value
151
+ * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.
141
152
  */
142
153
  static issue(user: Auth, token: string, options: RefreshTokenIssueOptions): Promise<RefreshToken>;
143
154
  /**
144
- * Find a refresh-token row by its raw token string.
155
+ * Find a refresh-token row by its raw token string, whether the row stores
156
+ * the token hashed or raw (one query).
145
157
  */
146
158
  static findByToken(token: string): Promise<RefreshToken | null>;
147
159
  /**
@@ -157,7 +169,7 @@ export declare class RefreshToken extends Model {
157
169
  */
158
170
  static familiesForUser(user: Auth): Promise<RefreshToken[]>;
159
171
  /**
160
- * Delete a specific refresh token belonging to the user.
172
+ * Delete a specific refresh token belonging to the user, stored hashed or raw.
161
173
  */
162
174
  static deleteForUser(user: Auth, token: string): Promise<number>;
163
175
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"refresh-token.model.d.mts","names":[],"sources":["../../../../../../../../../packages/auth/src/models/refresh-token/refresh-token.model.ts"],"mappings":";;;;;;;;;;;;;;;;qBAkBa,+CAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;YAiBnB;EACV;EACA;EACA,aAAa;;;;;;;;;;;;qBAaF,qBAAqB;SAClB;SAEA,mCAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAQN;;;;;;;SAQA;;MAGH;;;;;;;;;;;MAcA;;;;;MAYA;;MAKA;;MAK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AO,QAAQ;iBAI9B;;;;;;;;;SAcK,aAAa,MAAM,OAAO,QAAQ;;;;;SAgBlC,aAAa,mBAAmB,QAAQ;;;;;;SAexC,WAAW,MAAM,MAAM,cAAc;;;;;;SAiBrC,gBAAgB,QAAQ;;;;;;;SAgBxB,qBAAqB,QAAQ;;;;;;;;;;SAe7B,sBAAsB,QAAQ"}
@@ -1,3 +1,4 @@
1
+ import { plainTokenOf, storedTokenForms } from "../../utils/token-digest.mjs";
1
2
  import { isNeverExpiring, isUsableExpiry } from "../../utils/token-expiry.mjs";
2
3
  import { Model } from "@warlock.js/cascade";
3
4
  import { v } from "@warlock.js/seal";
@@ -56,6 +57,14 @@ var RefreshToken = class extends Model {
56
57
  return this.get("family_id");
57
58
  }
58
59
  /**
60
+ * The raw refresh token, when it is known: always for a row stored
61
+ * unhashed, and for a hashed row only in the process that just issued it
62
+ * (e.g. the row `authService.createRefreshToken` returns).
63
+ */
64
+ get plainToken() {
65
+ return plainTokenOf(this, this.get("token"));
66
+ }
67
+ /**
59
68
  * Whether the token's `expires_at` is in the past.
60
69
  *
61
70
  * **Fails closed as of 4.12.0**: a missing or unparseable `expires_at` now
@@ -111,7 +120,8 @@ var RefreshToken = class extends Model {
111
120
  await this.merge({ last_used_at: /* @__PURE__ */ new Date() }).save();
112
121
  }
113
122
  /**
114
- * Persist a freshly-signed refresh token for the user.
123
+ * Persist a freshly-signed refresh token for the user. `token` is the value
124
+ * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.
115
125
  */
116
126
  static issue(user, token, options) {
117
127
  return this.create({
@@ -128,20 +138,18 @@ var RefreshToken = class extends Model {
128
138
  });
129
139
  }
130
140
  /**
131
- * Find a refresh-token row by its raw token string.
141
+ * Find a refresh-token row by its raw token string, whether the row stores
142
+ * the token hashed or raw (one query).
132
143
  */
133
144
  static findByToken(token) {
134
- return this.first({ token });
145
+ return this.query().whereIn("token", storedTokenForms(token)).first();
135
146
  }
136
147
  /**
137
148
  * Find a refresh token scoped to a user — used by logout so a caller can only
138
149
  * revoke a token that actually belongs to them.
139
150
  */
140
151
  static findForUser(user, token) {
141
- return this.first({
142
- token,
143
- user_id: user.id
144
- });
152
+ return this.query().where({ user_id: user.id }).whereIn("token", storedTokenForms(token)).first();
145
153
  }
146
154
  /** Find any member of a family, including an already-revoked legacy member. */
147
155
  static findInFamily(familyId) {
@@ -158,13 +166,10 @@ var RefreshToken = class extends Model {
158
166
  }).get();
159
167
  }
160
168
  /**
161
- * Delete a specific refresh token belonging to the user.
169
+ * Delete a specific refresh token belonging to the user, stored hashed or raw.
162
170
  */
163
171
  static deleteForUser(user, token) {
164
- return this.delete({
165
- token,
166
- user_id: user.id
167
- });
172
+ return this.query().where({ user_id: user.id }).whereIn("token", storedTokenForms(token)).delete();
168
173
  }
169
174
  /**
170
175
  * Active, unexpired sessions for the user, newest first.
@@ -1 +1 @@
1
- {"version":3,"file":"refresh-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/refresh-token/refresh-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { DeviceInfo } from \"../../contracts/types\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted refresh-token record. Exported so an override\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\n * base shape:\n *\n * @example\n * export class AppRefreshToken extends RefreshToken {\n * public static schema = refreshTokenSchema.extend({\n * organization_id: v.string().required(),\n * });\n * }\n */\nexport const refreshTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n family_id: v.string().required(),\n expires_at: v.date().required(),\n last_used_at: v.date().default(() => new Date()),\n revoked_at: v.date().optional(),\n /** The successor pair a bounded concurrent renewal may reuse. */\n successor_access_token_id: v.string().optional(),\n successor_refresh_token_id: v.string().optional(),\n device_info: v.record(v.any()).optional(),\n});\n\n/**\n * Extra attributes captured when a refresh token is issued.\n */\nexport type RefreshTokenIssueOptions = {\n familyId: string;\n expiresAt: string;\n deviceInfo?: DeviceInfo;\n};\n\n/**\n * Persisted refresh-token record + the data layer for refresh tokens.\n *\n * **Role.** Owns every refresh-token read, write, and lifecycle transition.\n * The auth service drives refresh-token state exclusively through this model's\n * named statics and instance methods, so it never hard-codes a column name —\n * which is what makes a snake/camel mismatch (the historical `userId` bug)\n * structurally impossible and lets an override rename or add columns by\n * extending this class and registering it under `config.auth.refreshToken.model`.\n */\nexport class RefreshToken extends Model {\n public static table = \"refresh_tokens\";\n\n public static schema = refreshTokenSchema;\n\n /**\n * The raw signed refresh JWT is a bearer credential — never serialize it.\n * `hidden` only strips it from `toJSON()` / `JSON.stringify(model)` (e.g. a\n * session list returned via `response.json`); `get(\"token\")`,\n * `findByToken` / `findForUser` and every query still read the column.\n */\n public static hidden = [\"token\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\n * into `refresh_tokensTrash` on every `destroy()` (expiry purge,\n * never-expiring purge). A purged refresh token must not survive anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** Token family this row belongs to (rotation / replay grouping). */\n public get familyId(): string {\n return this.get(\"family_id\");\n }\n\n /**\n * Whether the token's `expires_at` is in the past.\n *\n * **Fails closed as of 4.12.0**: a missing or unparseable `expires_at` now\n * counts as expired. It previously answered `false` for both — \"no expiry\n * recorded ⇒ never expires\" — which handed an unlimited life to precisely the\n * malformed rows, including the `Invalid Date` a pre-4.12.0 unparseable\n * `expiresIn` could write. `expires_at` is `required` in the schema, so a row\n * that cannot say when it dies is malformed, not immortal.\n */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date().getTime() > new Date(expiresAt).getTime();\n }\n\n /**\n * Whether nothing can ever retire this row — an unusable `expires_at`, or a\n * token carrying no `exp` claim. See {@link isNeverExpiring}.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /** Whether the token has been revoked. */\n public get isRevoked(): boolean {\n return !!this.get(\"revoked_at\");\n }\n\n /** Whether the token is still usable (not expired and not revoked). */\n public get isValid(): boolean {\n return !this.isExpired && !this.isRevoked;\n }\n\n /**\n * Unconditionally stamp `revoked_at` on this token.\n */\n public async revoke(): Promise<this> {\n return this.merge({ revoked_at: new Date() }).save();\n }\n\n /**\n * Atomically revoke this token ONLY if it is still active. Resolves to `true`\n * when this call performed the revoke, `false` when a concurrent request had\n * already revoked it — the win/lose signal that powers rotation replay\n * detection. Uses a conditional UPDATE so two concurrent rotations of the\n * same token can never both succeed.\n */\n public async revokeIfActive(): Promise<boolean> {\n const modelClass = this.constructor as typeof RefreshToken;\n\n const revokedCount = await modelClass.atomic(\n { id: this.id, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n\n return revokedCount > 0;\n }\n\n /**\n * Touch `last_used_at` without revoking — the non-rotating refresh path.\n */\n public async markAsUsed(): Promise<void> {\n await this.merge({ last_used_at: new Date() }).save();\n }\n\n /**\n * Persist a freshly-signed refresh token for the user.\n */\n public static issue(user: Auth, token: string, options: RefreshTokenIssueOptions) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: options.familyId,\n expires_at: options.expiresAt,\n device_info: options.deviceInfo\n ? {\n userAgent: options.deviceInfo.userAgent,\n ip: options.deviceInfo.ip,\n deviceId: options.deviceInfo.deviceId,\n }\n : undefined,\n });\n }\n\n /**\n * Find a refresh-token row by its raw token string.\n */\n public static findByToken(token: string): Promise<RefreshToken | null> {\n return this.first({ token });\n }\n\n /**\n * Find a refresh token scoped to a user — used by logout so a caller can only\n * revoke a token that actually belongs to them.\n */\n public static findForUser(user: Auth, token: string): Promise<RefreshToken | null> {\n return this.first({ token, user_id: user.id });\n }\n\n /** Find any member of a family, including an already-revoked legacy member. */\n public static findInFamily(familyId: string): Promise<RefreshToken | null> {\n return this.first({ family_id: familyId });\n }\n\n /**\n * Every refresh lineage for a user, including rotated rows. Logout uses this\n * to bootstrap durable family records before it starts family revocations.\n */\n public static familiesForUser(user: Auth): Promise<RefreshToken[]> {\n return this.query().where({ user_id: user.id, user_type: user.userType }).get();\n }\n\n /**\n * Delete a specific refresh token belonging to the user.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.delete({ token, user_id: user.id });\n }\n\n /**\n * Active, unexpired sessions for the user, newest first.\n */\n public static activeFor(user: Auth): Promise<RefreshToken[]> {\n return this.activeQuery(user).orderBy(\"created_at\", \"desc\").get();\n }\n\n private static activeQuery(user: Auth) {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .where(\"expires_at\", \">\", new Date());\n }\n\n /**\n * Revoke every still-active refresh token for the user, returning the rows\n * that were revoked so the caller can emit a per-token event for each.\n *\n * Rows are fetched BEFORE they are revoked: a bulk `findAndUpdate` keyed on\n * `revoked_at: null` would re-query the same predicate after the update and\n * match nothing, returning an empty set.\n */\n public static async revokeAllFor(user: Auth): Promise<RefreshToken[]> {\n const tokens = await this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .get();\n\n for (const token of tokens) {\n await token.revoke();\n }\n\n return tokens;\n }\n\n /**\n * Revoke every still-active token in a family (rotation breach containment),\n * returning the revoked rows (fetched before revocation — see `revokeAllFor`).\n */\n public static async revokeFamily(familyId: string): Promise<RefreshToken[]> {\n const tokens = await this.query().where({ family_id: familyId, revoked_at: null }).get();\n\n for (const token of tokens) {\n await token.revoke();\n }\n\n return tokens;\n }\n\n /**\n * Revoke the oldest active tokens so at most `max - 1` remain — making room\n * for the about-to-be-issued one. Bounded by `max`, so the per-row loop is\n * small.\n */\n public static async enforceMax(user: Auth, max: number): Promise<void> {\n const activeTokens = await this.activeQuery(user).orderBy(\"created_at\", \"asc\").get();\n\n if (activeTokens.length < max) return;\n\n const tokensToRevoke = activeTokens.slice(0, activeTokens.length - max + 1);\n\n for (const token of tokensToRevoke) {\n await token.revoke();\n }\n }\n\n /**\n * Hard-delete every expired refresh token, returning the deleted rows so the\n * caller can emit a per-token event. Runs from the `auth.cleanup` CLI command\n * (a cold batch path).\n */\n public static async purgeExpired(): Promise<RefreshToken[]> {\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\n\n for (const token of expiredTokens) {\n await token.destroy();\n }\n\n return expiredTokens;\n }\n\n /**\n * Every row that can never retire itself — see {@link neverExpires}. A full\n * scan filtered in memory, for the reason given on\n * {@link AccessToken.findNeverExpiring}: neither an `Invalid Date` nor a\n * missing `exp` claim is expressible as a `where`.\n */\n public static async findNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: RefreshToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed.\n *\n * Deleted rather than `revoked_at`-stamped: a revoked row is still a row this\n * table has to carry, and one of the two shapes being removed is a row whose\n * date column cannot be compared at all — leaving it in place keeps a\n * permanently unpurgeable record. Rotation replay-detection is unaffected;\n * these rows can no longer be presented successfully either way.\n */\n public static async purgeNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.findNeverExpiring();\n\n for (const token of tokens) {\n await token.destroy();\n }\n\n return tokens;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAkBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;CAC9B,cAAc,EAAE,KAAK,CAAC,CAAC,8BAAc,IAAI,KAAK,CAAC;CAC/C,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;;CAE9B,2BAA2B,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/C,4BAA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S,MAAM,KAAK,MAAM,CAAC,CAAC,MAAM;GAAE,WAAW;GAAU,YAAY;EAAK,CAAC,CAAC,CAAC,IAAI;EAEvF,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,OAAO;EAGrB,OAAO;CACT;;;;;;CAOA,aAAoB,WAAW,MAAY,KAA4B;EACrE,MAAM,eAAe,MAAM,KAAK,YAAY,IAAI,CAAC,CAAC,QAAQ,cAAc,KAAK,CAAC,CAAC,IAAI;EAEnF,IAAI,aAAa,SAAS,KAAK;EAE/B,MAAM,iBAAiB,aAAa,MAAM,GAAG,aAAa,SAAS,MAAM,CAAC;EAE1E,KAAK,MAAM,SAAS,gBAClB,MAAM,MAAM,OAAO;CAEvB;;;;;;CAOA,aAAoB,eAAwC;EAC1D,MAAM,gBAAgB,MAAM,KAAK,MAAM,CAAC,CAAC,MAAM,cAAc,qBAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI;EAElF,KAAK,MAAM,SAAS,eAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;;;;;;;CAQA,aAAoB,oBAA6C;EAG/D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAwB,MAAM,YAAY;CAClE;;;;;;;;;;CAWA,aAAoB,qBAA8C;EAChE,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"refresh-token.model.mjs","names":[],"sources":["../../../../../../../../../packages/auth/src/models/refresh-token/refresh-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { DeviceInfo } from \"../../contracts/types\";\nimport { plainTokenOf, storedTokenForms } from \"../../utils/token-digest\";\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\nimport type { Auth } from \"../auth.model\";\n\n/**\n * Seal schema for the persisted refresh-token record. Exported so an override\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\n * base shape:\n *\n * @example\n * export class AppRefreshToken extends RefreshToken {\n * public static schema = refreshTokenSchema.extend({\n * organization_id: v.string().required(),\n * });\n * }\n */\nexport const refreshTokenSchema = v.object({\n token: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n family_id: v.string().required(),\n expires_at: v.date().required(),\n last_used_at: v.date().default(() => new Date()),\n revoked_at: v.date().optional(),\n /** The successor pair a bounded concurrent renewal may reuse. */\n successor_access_token_id: v.string().optional(),\n successor_refresh_token_id: v.string().optional(),\n device_info: v.record(v.any()).optional(),\n});\n\n/**\n * Extra attributes captured when a refresh token is issued.\n */\nexport type RefreshTokenIssueOptions = {\n familyId: string;\n expiresAt: string;\n deviceInfo?: DeviceInfo;\n};\n\n/**\n * Persisted refresh-token record + the data layer for refresh tokens.\n *\n * **Role.** Owns every refresh-token read, write, and lifecycle transition.\n * The auth service drives refresh-token state exclusively through this model's\n * named statics and instance methods, so it never hard-codes a column name —\n * which is what makes a snake/camel mismatch (the historical `userId` bug)\n * structurally impossible and lets an override rename or add columns by\n * extending this class and registering it under `config.auth.refreshToken.model`.\n */\nexport class RefreshToken extends Model {\n public static table = \"refresh_tokens\";\n\n public static schema = refreshTokenSchema;\n\n /**\n * The raw signed refresh JWT is a bearer credential — never serialize it.\n * `hidden` only strips it from `toJSON()` / `JSON.stringify(model)` (e.g. a\n * session list returned via `response.json`); `get(\"token\")`,\n * `findByToken` / `findForUser` and every query still read the column.\n *\n * With `auth.hashTokensAtRest` on, the column holds the token's SHA-256\n * digest instead; read the raw token of a freshly issued row through\n * {@link plainToken}.\n */\n public static hidden = [\"token\"];\n\n /**\n * Permanent regardless of the data source default — Mongo's driver default\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\n * into `refresh_tokensTrash` on every `destroy()` (expiry purge,\n * never-expiring purge). A purged refresh token must not survive anywhere.\n */\n public static deleteStrategy = \"permanent\" as const;\n\n /** Token family this row belongs to (rotation / replay grouping). */\n public get familyId(): string {\n return this.get(\"family_id\");\n }\n\n /**\n * The raw refresh token, when it is known: always for a row stored\n * unhashed, and for a hashed row only in the process that just issued it\n * (e.g. the row `authService.createRefreshToken` returns).\n */\n public get plainToken(): string | undefined {\n return plainTokenOf(this, this.get(\"token\"));\n }\n\n /**\n * Whether the token's `expires_at` is in the past.\n *\n * **Fails closed as of 4.12.0**: a missing or unparseable `expires_at` now\n * counts as expired. It previously answered `false` for both — \"no expiry\n * recorded ⇒ never expires\" — which handed an unlimited life to precisely the\n * malformed rows, including the `Invalid Date` a pre-4.12.0 unparseable\n * `expiresIn` could write. `expires_at` is `required` in the schema, so a row\n * that cannot say when it dies is malformed, not immortal.\n */\n public get isExpired(): boolean {\n const expiresAt = this.get(\"expires_at\");\n\n if (!isUsableExpiry(expiresAt)) return true;\n\n return new Date().getTime() > new Date(expiresAt).getTime();\n }\n\n /**\n * Whether nothing can ever retire this row — an unusable `expires_at`, or a\n * token carrying no `exp` claim. See {@link isNeverExpiring}.\n */\n public get neverExpires(): boolean {\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\n }\n\n /** Whether the token has been revoked. */\n public get isRevoked(): boolean {\n return !!this.get(\"revoked_at\");\n }\n\n /** Whether the token is still usable (not expired and not revoked). */\n public get isValid(): boolean {\n return !this.isExpired && !this.isRevoked;\n }\n\n /**\n * Unconditionally stamp `revoked_at` on this token.\n */\n public async revoke(): Promise<this> {\n return this.merge({ revoked_at: new Date() }).save();\n }\n\n /**\n * Atomically revoke this token ONLY if it is still active. Resolves to `true`\n * when this call performed the revoke, `false` when a concurrent request had\n * already revoked it — the win/lose signal that powers rotation replay\n * detection. Uses a conditional UPDATE so two concurrent rotations of the\n * same token can never both succeed.\n */\n public async revokeIfActive(): Promise<boolean> {\n const modelClass = this.constructor as typeof RefreshToken;\n\n const revokedCount = await modelClass.atomic(\n { id: this.id, revoked_at: null },\n { $set: { revoked_at: new Date() } },\n );\n\n return revokedCount > 0;\n }\n\n /**\n * Touch `last_used_at` without revoking — the non-rotating refresh path.\n */\n public async markAsUsed(): Promise<void> {\n await this.merge({ last_used_at: new Date() }).save();\n }\n\n /**\n * Persist a freshly-signed refresh token for the user. `token` is the value\n * to store: the raw JWT, or its digest under `auth.hashTokensAtRest`.\n */\n public static issue(user: Auth, token: string, options: RefreshTokenIssueOptions) {\n return this.create({\n token,\n user_id: user.id,\n user_type: user.userType,\n family_id: options.familyId,\n expires_at: options.expiresAt,\n device_info: options.deviceInfo\n ? {\n userAgent: options.deviceInfo.userAgent,\n ip: options.deviceInfo.ip,\n deviceId: options.deviceInfo.deviceId,\n }\n : undefined,\n });\n }\n\n /**\n * Find a refresh-token row by its raw token string, whether the row stores\n * the token hashed or raw (one query).\n */\n public static findByToken(token: string): Promise<RefreshToken | null> {\n return this.query().whereIn(\"token\", storedTokenForms(token)).first();\n }\n\n /**\n * Find a refresh token scoped to a user — used by logout so a caller can only\n * revoke a token that actually belongs to them.\n */\n public static findForUser(user: Auth, token: string): Promise<RefreshToken | null> {\n return this.query()\n .where({ user_id: user.id })\n .whereIn(\"token\", storedTokenForms(token))\n .first();\n }\n\n /** Find any member of a family, including an already-revoked legacy member. */\n public static findInFamily(familyId: string): Promise<RefreshToken | null> {\n return this.first({ family_id: familyId });\n }\n\n /**\n * Every refresh lineage for a user, including rotated rows. Logout uses this\n * to bootstrap durable family records before it starts family revocations.\n */\n public static familiesForUser(user: Auth): Promise<RefreshToken[]> {\n return this.query().where({ user_id: user.id, user_type: user.userType }).get();\n }\n\n /**\n * Delete a specific refresh token belonging to the user, stored hashed or raw.\n */\n public static deleteForUser(user: Auth, token: string) {\n return this.query()\n .where({ user_id: user.id })\n .whereIn(\"token\", storedTokenForms(token))\n .delete();\n }\n\n /**\n * Active, unexpired sessions for the user, newest first.\n */\n public static activeFor(user: Auth): Promise<RefreshToken[]> {\n return this.activeQuery(user).orderBy(\"created_at\", \"desc\").get();\n }\n\n private static activeQuery(user: Auth) {\n return this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .where(\"expires_at\", \">\", new Date());\n }\n\n /**\n * Revoke every still-active refresh token for the user, returning the rows\n * that were revoked so the caller can emit a per-token event for each.\n *\n * Rows are fetched BEFORE they are revoked: a bulk `findAndUpdate` keyed on\n * `revoked_at: null` would re-query the same predicate after the update and\n * match nothing, returning an empty set.\n */\n public static async revokeAllFor(user: Auth): Promise<RefreshToken[]> {\n const tokens = await this.query()\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\n .get();\n\n for (const token of tokens) {\n await token.revoke();\n }\n\n return tokens;\n }\n\n /**\n * Revoke every still-active token in a family (rotation breach containment),\n * returning the revoked rows (fetched before revocation — see `revokeAllFor`).\n */\n public static async revokeFamily(familyId: string): Promise<RefreshToken[]> {\n const tokens = await this.query().where({ family_id: familyId, revoked_at: null }).get();\n\n for (const token of tokens) {\n await token.revoke();\n }\n\n return tokens;\n }\n\n /**\n * Revoke the oldest active tokens so at most `max - 1` remain — making room\n * for the about-to-be-issued one. Bounded by `max`, so the per-row loop is\n * small.\n */\n public static async enforceMax(user: Auth, max: number): Promise<void> {\n const activeTokens = await this.activeQuery(user).orderBy(\"created_at\", \"asc\").get();\n\n if (activeTokens.length < max) return;\n\n const tokensToRevoke = activeTokens.slice(0, activeTokens.length - max + 1);\n\n for (const token of tokensToRevoke) {\n await token.revoke();\n }\n }\n\n /**\n * Hard-delete every expired refresh token, returning the deleted rows so the\n * caller can emit a per-token event. Runs from the `auth.cleanup` CLI command\n * (a cold batch path).\n */\n public static async purgeExpired(): Promise<RefreshToken[]> {\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\n\n for (const token of expiredTokens) {\n await token.destroy();\n }\n\n return expiredTokens;\n }\n\n /**\n * Every row that can never retire itself — see {@link neverExpires}. A full\n * scan filtered in memory, for the reason given on\n * {@link AccessToken.findNeverExpiring}: neither an `Invalid Date` nor a\n * missing `exp` claim is expressible as a `where`.\n */\n public static async findNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.query().get();\n\n return tokens.filter((token: RefreshToken) => token.neverExpires);\n }\n\n /**\n * Hard-delete every never-expiring row, returning the rows removed.\n *\n * Deleted rather than `revoked_at`-stamped: a revoked row is still a row this\n * table has to carry, and one of the two shapes being removed is a row whose\n * date column cannot be compared at all — leaving it in place keeps a\n * permanently unpurgeable record. Rotation replay-detection is unaffected;\n * these rows can no longer be presented successfully either way.\n */\n public static async purgeNeverExpiring(): Promise<RefreshToken[]> {\n const tokens = await this.findNeverExpiring();\n\n for (const token of tokens) {\n await token.destroy();\n }\n\n return tokens;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAa,qBAAqB,EAAE,OAAO;CACzC,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;CAC3B,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;CAC9B,cAAc,EAAE,KAAK,CAAC,CAAC,8BAAc,IAAI,KAAK,CAAC;CAC/C,YAAY,EAAE,KAAK,CAAC,CAAC,SAAS;;CAE9B,2BAA2B,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/C,4BAA4B,EAAE,OAAO,CAAC,CAAC,SAAS;CAChD,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,SAAS;AAC1C,CAAC;;;;;;;;;;;AAqBD,IAAa,eAAb,cAAkC,MAAM;;eAChB;;;gBAEC;;;gBAYA,CAAC,OAAO;;;wBAQA;;;CAG/B,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;;;;;CAOA,IAAW,aAAiC;EAC1C,OAAO,aAAa,MAAM,KAAK,IAAI,OAAO,CAAC;CAC7C;;;;;;;;;;;CAYA,IAAW,YAAqB;EAC9B,MAAM,YAAY,KAAK,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AClB,MAAM,MAAM,OAAO;EAGrB,OAAO;CACT;;;;;;CAOA,aAAoB,WAAW,MAAY,KAA4B;EACrE,MAAM,eAAe,MAAM,KAAK,YAAY,IAAI,CAAC,CAAC,QAAQ,cAAc,KAAK,CAAC,CAAC,IAAI;EAEnF,IAAI,aAAa,SAAS,KAAK;EAE/B,MAAM,iBAAiB,aAAa,MAAM,GAAG,aAAa,SAAS,MAAM,CAAC;EAE1E,KAAK,MAAM,SAAS,gBAClB,MAAM,MAAM,OAAO;CAEvB;;;;;;CAOA,aAAoB,eAAwC;EAC1D,MAAM,gBAAgB,MAAM,KAAK,MAAM,CAAC,CAAC,MAAM,cAAc,qBAAK,IAAI,KAAK,CAAC,CAAC,CAAC,IAAI;EAElF,KAAK,MAAM,SAAS,eAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;;;;;;;CAQA,aAAoB,oBAA6C;EAG/D,QAAO,MAFc,KAAK,MAAM,CAAC,CAAC,IAAI,EAEzB,CAAC,QAAQ,UAAwB,MAAM,YAAY;CAClE;;;;;;;;;;CAWA,aAAoB,qBAA8C;EAChE,MAAM,SAAS,MAAM,KAAK,kBAAkB;EAE5C,KAAK,MAAM,SAAS,QAClB,MAAM,MAAM,QAAQ;EAGtB,OAAO;CACT;AACF"}
package/esm/otp/otp.d.mts CHANGED
@@ -11,7 +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. Throttle the route with `otpRequestThrottleMiddleware()`.
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
18
+ * `otpRequestThrottleMiddleware()`.
15
19
  *
16
20
  * @throws AuthProviderSdkMissingError when `@warlock.js/notifications` is not
17
21
  * installed and no `auth.otp.send` is configured.
@@ -1 +1 @@
1
- {"version":3,"file":"otp.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/otp/otp.ts"],"mappings":";;;;;;;;;;;;;;;;;;wBAuFsB,WAAW,UAAU,MACzC,OAAO,WAAW,IAClB,eACA;EAAW;IACV;;;;;;;;;;;;;wBAkCmB,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":";;;;;;;;;;;;;;;;;;;;;;wBA6FsB,WAAW,UAAU,MACzC,OAAO,WAAW,IAClB,eACA;EAAW;IACV;;;;;;;;;;;;;wBA6CmB,UAAU,UAAU,MACxC,OAAO,WAAW,IAClB,eACA,cACA,aAAa,aACZ,QAAQ,YAAY"}
package/esm/otp/otp.mjs CHANGED
@@ -1,10 +1,12 @@
1
1
  import { authConfig } from "../services/auth-config.mjs";
2
+ import { authEvents } from "../services/auth-events.mjs";
2
3
  import { authService } from "../services/auth.service.mjs";
3
4
  import { InvalidOneTimeTokenError } from "../errors/invalid-one-time-token.error.mjs";
4
5
  import { oneTimeTokenModel } from "../services/one-time-tokens.mjs";
5
6
  import { loadOptionalPeer } from "../services/optional-peer.mjs";
6
7
  import { safeEqual } from "../utils/safe-equal.mjs";
7
8
  import { createHmac, randomBytes, randomInt } from "node:crypto";
9
+ import { log } from "@warlock.js/logger";
8
10
 
9
11
  //#region ../../packages/auth/src/otp/otp.ts
10
12
  const CODE_PATTERN = /^\d{6}$/;
@@ -51,7 +53,11 @@ async function resolveDelivery(channel) {
51
53
  * The code is stored only as a keyed hash in `one_time_tokens` (purpose
52
54
  * `otp`), expires after `auth.otp.expiresIn` (default 5m), and replaces any
53
55
  * earlier unused code. **Anti-enumeration:** an unknown phone resolves the same
54
- * way and sends nothing. Throttle the route with `otpRequestThrottleMiddleware()`.
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
60
+ * `otpRequestThrottleMiddleware()`.
55
61
  *
56
62
  * @throws AuthProviderSdkMissingError when `@warlock.js/notifications` is not
57
63
  * installed and no `auth.otp.send` is configured.
@@ -67,11 +73,20 @@ async function requestOtp(Model, phone, options = {}) {
67
73
  const TokenModel = oneTimeTokenModel();
68
74
  await TokenModel.invalidateActiveFor(user, "otp");
69
75
  await TokenModel.issue(user, "otp", storedCodeHash(user, code), expiresAt);
70
- await deliver(phone, {
76
+ const message = {
71
77
  body: authConfig.otp.message(code),
72
78
  code,
73
79
  expiresAt
74
- }, channel);
80
+ };
81
+ const delivery = Promise.resolve().then(() => deliver(phone, message, channel));
82
+ if (authConfig.otp.awaitDelivery()) {
83
+ await delivery;
84
+ return;
85
+ }
86
+ delivery.catch((error) => {
87
+ log.error("auth", "otp", error);
88
+ authEvents.emit("otp.deliveryFailed", user, error);
89
+ });
75
90
  }
76
91
  /**
77
92
  * 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 { 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 { 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. Throttle the route with `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 await deliver(phone, message, channel);\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":";;;;;;;;;AAmBA,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,CAAC,CACrD,OAAO,WAAW;AACvB;;AAGA,SAAS,eAAe,MAAY,MAAsB;CACxD,MAAM,OAAO,YAAY,EAAE,CAAC,CAAC,SAAS,WAAW;CAEjD,OAAO,GAAG,KAAK,GAAG,QAAQ,MAAM,MAAM,IAAI;AAC5C;AAEA,SAAS,YAAY,MAAY,QAAgB,MAAuB;CACtE,MAAM,CAAC,MAAM,OAAO,OAAO,MAAM,GAAG;CAEpC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,OAAO,UAAU,KAAK,QAAQ,MAAM,MAAM,IAAI,CAAC;AACpE;;;;;;AAOA,eAAe,gBAAgB,SAAqC;CAClE,MAAM,SAAS,WAAW,IAAI,KAAK;CAEnC,IAAI,QAAQ,OAAO;CAEnB,MAAM,EAAE,WAAW,MAAM,iBACvB,6BACA,eACF;CAEA,QAAQ,OAAO,SAAS,gBAAgB,OAAO,QAAQ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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 { 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,CAAC,CACrD,OAAO,WAAW;AACvB;;AAGA,SAAS,eAAe,MAAY,MAAsB;CACxD,MAAM,OAAO,YAAY,EAAE,CAAC,CAAC,SAAS,WAAW;CAEjD,OAAO,GAAG,KAAK,GAAG,QAAQ,MAAM,MAAM,IAAI;AAC5C;AAEA,SAAS,YAAY,MAAY,QAAgB,MAAuB;CACtE,MAAM,CAAC,MAAM,OAAO,OAAO,MAAM,GAAG;CAEpC,OAAO,CAAC,CAAC,QAAQ,CAAC,CAAC,OAAO,UAAU,KAAK,QAAQ,MAAM,MAAM,IAAI,CAAC;AACpE;;;;;;AAOA,eAAe,gBAAgB,SAAqC;CAClE,MAAM,SAAS,WAAW,IAAI,KAAK;CAEnC,IAAI,QAAQ,OAAO;CAEnB,MAAM,EAAE,WAAW,MAAM,iBACvB,6BACA,eACF;CAEA,QAAQ,OAAO,SAAS,gBAAgB,OAAO,QAAQ,WAAW,CAAC,CAAC,KAAK,OAAO,OAAO;AACzF;;;;;;;;;;;;;;;;;;;AAoBA,eAAsB,WACpB,OACA,OACA,UAAgC,CAAC,GAClB;CACf,MAAM,UAAU,QAAQ,WAAW,WAAW,IAAI,QAAQ;CAC1D,MAAM,UAAU,MAAM,gBAAgB,O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AAI,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"}
@@ -35,7 +35,7 @@ function presentedCounter(credential) {
35
35
  async function generatePasskeyAuthenticationOptions() {
36
36
  const options = await (await loadSimpleWebAuthn()).generateAuthenticationOptions({
37
37
  rpID: authConfig.passkeys.settings().rpID,
38
- userVerification: "preferred"
38
+ userVerification: authConfig.passkeys.userVerification()
39
39
  });
40
40
  await storePasskeyChallenge("passkey-authentication", options.challenge);
41
41
  return options;
@@ -72,7 +72,7 @@ async function verifyPasskeyAuthentication(request, credential, deviceInfo) {
72
72
  counter: stored.counter,
73
73
  transports: stored.get("transports") ?? void 0
74
74
  },
75
- requireUserVerification: false
75
+ requireUserVerification: authConfig.passkeys.userVerification() === "required"
76
76
  });
77
77
  } catch (error) {
78
78
  const reason = counterRegressed(stored.counter, presentedCounter(credential)) ? "counter-regression" : "authentication-verification-failed";
@@ -1 +1 @@
1
- {"version":3,"file":"passkey-authentication.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/passkeys/passkey-authentication.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport { config, type Request } from \"@warlock.js/core\";\nimport type { DeviceInfo, LoginResult } from \"../contracts/types\";\nimport { InvalidPasskeyError } from \"../errors/invalid-passkey.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { PasskeyCredential } from \"../models/passkey-credential\";\nimport { authConfig } from \"../services/auth-config\";\nimport { authService } from \"../services/auth.service\";\nimport {\n assertPasskeyOrigin,\n storePasskeyChallenge,\n takePasskeyChallenge,\n} from \"./passkey-challenges\";\nimport {\n loadSimpleWebAuthn,\n type PasskeyOptionsJSON,\n type PasskeyResponseJSON,\n} from \"./simplewebauthn\";\n\n/** A counter that did not advance past the stored one (when either is non-zero): a cloned authenticator. */\nfunction counterRegressed(stored: number, presented: number | undefined): boolean {\n if (presented === undefined) return false;\n\n return (stored > 0 || presented > 0) && !(presented > stored);\n}\n\n/**\n * The signature counter an assertion CLAIMS (bytes 33–36 of authenticatorData).\n * Unverified — only used to label a rejection the SDK already made.\n */\nfunction presentedCounter(credential: PasskeyResponseJSON): number | undefined {\n const encoded = credential.response.authenticatorData;\n\n if (typeof encoded !== \"string\") return undefined;\n\n const authData = Buffer.from(encoded, \"base64url\");\n\n return authData.length >= 37 ? authData.readUInt32BE(33) : undefined;\n}\n\n/**\n * Authentication options for a passkey login. No user is identified yet\n * (discoverable credentials), so the stored single-use challenge has no owner;\n * the credential the browser returns decides the user.\n *\n * @example\n * // POST /auth/passkeys/login/options\n * response.success(await generatePasskeyAuthenticationOptions());\n */\nexport async function generatePasskeyAuthenticationOptions(): Promise<PasskeyOptionsJSON> {\n const webauthn = await loadSimpleWebAuthn();\n\n const options = await webauthn.generateAuthenticationOptions({\n rpID: authConfig.passkeys.settings().rpID,\n userVerification: \"preferred\",\n });\n\n await storePasskeyChallenge(\"passkey-authentication\", options.challenge);\n\n return options;\n}\n\n/**\n * Verify a passkey assertion and log its owner in through\n * `authService.completeLogin` — the same outcome as password login.\n *\n * Checks, in order: the request `Origin` (CSRF), the single-use challenge\n * (consumed even if what follows fails), the credential is registered, the\n * assertion via `@simplewebauthn/server`, then that the signature counter\n * ADVANCED — a counter that did not move past the stored one (when either is\n * non-zero) means a cloned authenticator and is rejected. The new counter is\n * written with a compare-and-set.\n *\n * @throws InvalidPasskeyError (400, EC011) on any rejection.\n */\nexport async function verifyPasskeyAuthentication(\n request: Request,\n credential: PasskeyResponseJSON,\n deviceInfo?: DeviceInfo,\n): Promise<LoginResult<Auth>> {\n const webauthn = await loadSimpleWebAuthn();\n const origins = assertPasskeyOrigin(request);\n const { challenge } = await takePasskeyChallenge(\"passkey-authentication\", credential);\n\n const stored =\n typeof credential.id === \"string\"\n ? await PasskeyCredential.findByCredentialId(credential.id)\n : null;\n\n if (!stored) {\n throw new InvalidPasskeyError(\"unknown-credential\");\n }\n\n let verification: Awaited<ReturnType<typeof webauthn.verifyAuthenticationResponse>>;\n\n try {\n verification = await webauthn.verifyAuthenticationResponse({\n response: credential,\n expectedChallenge: challenge,\n expectedOrigin: origins,\n expectedRPID: authConfig.passkeys.settings().rpID,\n credential: {\n id: stored.credentialId,\n publicKey: new Uint8Array(Buffer.from(String(stored.get(\"public_key\")), \"base64url\")),\n counter: stored.counter,\n transports: stored.get(\"transports\") ?? undefined,\n },\n requireUserVerification: false,\n });\n } catch (error) {\n // The SDK enforces the counter rule itself and throws a generic Error for\n // it; keep clone detection visible as its own reason in the logs.\n const reason = counterRegressed(stored.counter, presentedCounter(credential))\n ? \"counter-regression\"\n : \"authentication-verification-failed\";\n\n throw new InvalidPasskeyError(reason, error);\n }\n\n if (!verification.verified) {\n throw new InvalidPasskeyError(\"authentication-not-verified\");\n }\n\n const previous = stored.counter;\n const next = Number(verification.authenticationInfo.newCounter);\n\n if (counterRegressed(previous, next)) {\n throw new InvalidPasskeyError(\"counter-regression\");\n }\n\n if (!(await stored.advanceCounter(previous, next))) {\n throw new InvalidPasskeyError(\"counter-changed-concurrently\");\n }\n\n const UserModel = config.key<ChildModel<Auth> | undefined>(`auth.userType.${stored.userType}`);\n const user = UserModel ? ((await UserModel.find(stored.userId)) as Auth | null) : null;\n\n if (!user) {\n throw new InvalidPasskeyError(\"credential-owner-missing\");\n }\n\n return authService.completeLogin(user, deviceInfo);\n}\n"],"mappings":";;;;;;;;;;;AAoBA,SAAS,iBAAiB,QAAgB,WAAwC;CAChF,IAAI,cAAc,QAAW,OAAO;CAEpC,QAAQ,SAAS,KAAK,YAAY,MAAM,EAAE,YAAY;AACxD;;;;;AAMA,SAAS,iBAAiB,YAAqD;CAC7E,MA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AG7D,MAAM,WAAW,OAAO;CACxB,MAAM,OAAO,OAAO,aAAa,mBAAmB,UAAU;CAE9D,IAAI,iBAAiB,UAAU,IAAI,GACjC,MAAM,IAAI,oBAAoB,oBAAoB;CAGpD,IAAI,CAAE,MAAM,OAAO,eAAe,UAAU,IAAI,GAC9C,MAAM,IAAI,oBAAoB,8BAA8B;CAG9D,MAAM,YAAY,OAAO,IAAkC,iBAAiB,OAAO,UAAU;CAC7F,MAAM,OAAO,YAAc,MAAM,UAAU,KAAK,OAAO,MAAM,IAAqB;CAElF,IAAI,CAAC,MACH,MAAM,IAAI,oBAAoB,0BAA0B;CAG1D,OAAO,YAAY,cAAc,MAAM,UAAU;AACnD"}
1
+ {"version":3,"file":"passkey-authentication.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/passkeys/passkey-authentication.ts"],"sourcesContent":["import type { ChildModel } from \"@warlock.js/cascade\";\nimport { config, type Request } from \"@warlock.js/core\";\nimport type { DeviceInfo, LoginResult } from \"../contracts/types\";\nimport { InvalidPasskeyError } from \"../errors/invalid-passkey.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { PasskeyCredential } from \"../models/passkey-credential\";\nimport { authConfig } from \"../services/auth-config\";\nimport { authService } from \"../services/auth.service\";\nimport {\n assertPasskeyOrigin,\n storePasskeyChallenge,\n takePasskeyChallenge,\n} from \"./passkey-challenges\";\nimport {\n loadSimpleWebAuthn,\n type PasskeyOptionsJSON,\n type PasskeyResponseJSON,\n} from \"./simplewebauthn\";\n\n/** A counter that did not advance past the stored one (when either is non-zero): a cloned authenticator. */\nfunction counterRegressed(stored: number, presented: number | undefined): boolean {\n if (presented === undefined) return false;\n\n return (stored > 0 || presented > 0) && !(presented > stored);\n}\n\n/**\n * The signature counter an assertion CLAIMS (bytes 33–36 of authenticatorData).\n * Unverified — only used to label a rejection the SDK already made.\n */\nfunction presentedCounter(credential: PasskeyResponseJSON): number | undefined {\n const encoded = credential.response.authenticatorData;\n\n if (typeof encoded !== \"string\") return undefined;\n\n const authData = Buffer.from(encoded, \"base64url\");\n\n return authData.length >= 37 ? authData.readUInt32BE(33) : undefined;\n}\n\n/**\n * Authentication options for a passkey login. No user is identified yet\n * (discoverable credentials), so the stored single-use challenge has no owner;\n * the credential the browser returns decides the user.\n *\n * @example\n * // POST /auth/passkeys/login/options\n * response.success(await generatePasskeyAuthenticationOptions());\n */\nexport async function generatePasskeyAuthenticationOptions(): Promise<PasskeyOptionsJSON> {\n const webauthn = await loadSimpleWebAuthn();\n\n const options = await webauthn.generateAuthenticationOptions({\n rpID: authConfig.passkeys.settings().rpID,\n userVerification: authConfig.passkeys.userVerification(),\n });\n\n await storePasskeyChallenge(\"passkey-authentication\", options.challenge);\n\n return options;\n}\n\n/**\n * Verify a passkey assertion and log its owner in through\n * `authService.completeLogin` — the same outcome as password login.\n *\n * Checks, in order: the request `Origin` (CSRF), the single-use challenge\n * (consumed even if what follows fails), the credential is registered, the\n * assertion via `@simplewebauthn/server`, then that the signature counter\n * ADVANCED — a counter that did not move past the stored one (when either is\n * non-zero) means a cloned authenticator and is rejected. The new counter is\n * written with a compare-and-set.\n *\n * @throws InvalidPasskeyError (400, EC011) on any rejection.\n */\nexport async function verifyPasskeyAuthentication(\n request: Request,\n credential: PasskeyResponseJSON,\n deviceInfo?: DeviceInfo,\n): Promise<LoginResult<Auth>> {\n const webauthn = await loadSimpleWebAuthn();\n const origins = assertPasskeyOrigin(request);\n const { challenge } = await takePasskeyChallenge(\"passkey-authentication\", credential);\n\n const stored =\n typeof credential.id === \"string\"\n ? await PasskeyCredential.findByCredentialId(credential.id)\n : null;\n\n if (!stored) {\n throw new InvalidPasskeyError(\"unknown-credential\");\n }\n\n let verification: Awaited<ReturnType<typeof webauthn.verifyAuthenticationResponse>>;\n\n try {\n verification = await webauthn.verifyAuthenticationResponse({\n response: credential,\n expectedChallenge: challenge,\n expectedOrigin: origins,\n expectedRPID: authConfig.passkeys.settings().rpID,\n credential: {\n id: stored.credentialId,\n publicKey: new Uint8Array(Buffer.from(String(stored.get(\"public_key\")), \"base64url\")),\n counter: stored.counter,\n transports: stored.get(\"transports\") ?? undefined,\n },\n requireUserVerification: authConfig.passkeys.userVerification() === \"required\",\n });\n } catch (error) {\n // The SDK enforces the counter rule itself and throws a generic Error for\n // it; keep clone detection visible as its own reason in the logs.\n const reason = counterRegressed(stored.counter, presentedCounter(credential))\n ? \"counter-regression\"\n : \"authentication-verification-failed\";\n\n throw new InvalidPasskeyError(reason, error);\n }\n\n if (!verification.verified) {\n throw new InvalidPasskeyError(\"authentication-not-verified\");\n }\n\n const previous = stored.counter;\n const next = Number(verification.authenticationInfo.newCounter);\n\n if (counterRegressed(previous, next)) {\n throw new InvalidPasskeyError(\"counter-regression\");\n }\n\n if (!(await stored.advanceCounter(previous, next))) {\n throw new InvalidPasskeyError(\"counter-changed-concurrently\");\n }\n\n const UserModel = config.key<ChildModel<Auth> | undefined>(`auth.userType.${stored.userType}`);\n const user = UserModel ? ((await UserModel.find(stored.userId)) as Auth | null) : null;\n\n if (!user) {\n throw new InvalidPasskeyError(\"credential-owner-missing\");\n }\n\n return authService.completeLogin(user, deviceInfo);\n}\n"],"mappings":";;;;;;;;;;;AAoBA,SAAS,iBAAiB,QAAgB,WAAwC;CAChF,IAAI,cAAc,QAAW,OAAO;CAEpC,QAAQ,SAAS,KAAK,YAAY,MAAM,EAAE,YAAY;AACxD;;;;;AAMA,SAAS,iBAAiB,YAAqD;CAC7E,MAAM,UAAU,WAAW,SAAS;CAEpC,IAAI,OAAO,YAAY,UAAU,OAAO;CAExC,MAAM,WAAW,OAAO,KAAK,SAAS,WAAW;CAEjD,OAAO,SAAS,UAAU,KAAK,SAAS,aAAa,EAAE,IAAI;AAC7D;;;;;;;;;;AAWA,eAAsB,uCAAoE;CAGxF,MAAM,UAAU,OAAM,MAFC,mBAAmB,EAEZ,CAAC,8BAA8B;EAC3D,MAAM,WAAW,SAAS,SAAS,CAAC,CAAC;EACrC,kBAAkB,WAAW,SAAS,iBAAiB;CACz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,YAAc,MAAM,UAAU,KAAK,OAAO,MAAM,IAAqB;CAElF,IAAI,CAAC,MACH,MAAM,IAAI,oBAAoB,0BAA0B;CAG1D,OAAO,YAAY,cAAc,MAAM,UAAU;AACnD"}
@@ -1 +1 @@
1
- {"version":3,"file":"passkey-registration.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/passkeys/passkey-registration.ts"],"mappings":";;;;;;;;;;;;;;;wBAoCsB,mCAAmC,MAAM,OAAO,QAAQ;;;;;;;;;;wBAgCxD,0BACpB,SAAS,SACT,MAAM,MACN,YAAY,sBACX,QAAQ"}
1
+ {"version":3,"file":"passkey-registration.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/passkeys/passkey-registration.ts"],"mappings":";;;;;;;;;;;;;;;wBAoCsB,mCAAmC,MAAM,OAAO,QAAQ;;;;;;;;;;wBAmCxD,0BACpB,SAAS,SACT,MAAM,MACN,YAAY,sBACX,QAAQ"}
@@ -38,7 +38,7 @@ async function generatePasskeyRegistrationOptions(user) {
38
38
  })),
39
39
  authenticatorSelection: {
40
40
  residentKey: "preferred",
41
- userVerification: "preferred"
41
+ userVerification: authConfig.passkeys.userVerification()
42
42
  }
43
43
  });
44
44
  await storePasskeyChallenge("passkey-registration", options.challenge, user);
@@ -65,7 +65,7 @@ async function verifyPasskeyRegistration(request, user, credential) {
65
65
  expectedChallenge: challenge,
66
66
  expectedOrigin: origins,
67
67
  expectedRPID: authConfig.passkeys.settings().rpID,
68
- requireUserVerification: false
68
+ requireUserVerification: authConfig.passkeys.userVerification() === "required"
69
69
  });
70
70
  } catch (error) {
71
71
  throw new InvalidPasskeyError("registration-verification-failed", error);
@@ -1 +1 @@
1
- {"version":3,"file":"passkey-registration.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/passkeys/passkey-registration.ts"],"sourcesContent":["import type { Request } from \"@warlock.js/core\";\nimport { InvalidPasskeyError } from \"../errors/invalid-passkey.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { PasskeyCredential } from \"../models/passkey-credential\";\nimport { authConfig } from \"../services/auth-config\";\nimport {\n assertPasskeyOrigin,\n storePasskeyChallenge,\n takePasskeyChallenge,\n} from \"./passkey-challenges\";\nimport {\n loadSimpleWebAuthn,\n type PasskeyOptionsJSON,\n type PasskeyResponseJSON,\n} from \"./simplewebauthn\";\n\n/** Account name the authenticator shows: `auth.passkeys.userName`, else email, else id. */\nfunction passkeyUserName(user: Auth): string {\n const configured = authConfig.passkeys.settings().userName;\n\n if (configured) return configured(user);\n\n const email = user.get(\"email\");\n\n return typeof email === \"string\" && email ? email : String(user.id);\n}\n\n/**\n * Registration options for a LOGGED-IN user adding a passkey. The challenge is\n * stored single-use and bound to this user; the user's existing credentials\n * are excluded so the same authenticator is not registered twice.\n *\n * @example\n * // POST /auth/passkeys/register/options (authMiddleware)\n * response.success(await generatePasskeyRegistrationOptions(request.locals.user));\n */\nexport async function generatePasskeyRegistrationOptions(user: Auth): Promise<PasskeyOptionsJSON> {\n const webauthn = await loadSimpleWebAuthn();\n const settings = authConfig.passkeys.settings();\n const existing = await PasskeyCredential.listFor(user);\n\n const options = await webauthn.generateRegistrationOptions({\n rpName: settings.rpName,\n rpID: settings.rpID,\n userName: passkeyUserName(user),\n userID: new TextEncoder().encode(`${user.userType}:${user.id}`),\n attestationType: \"none\",\n excludeCredentials: existing.map((credential) => ({\n id: credential.credentialId,\n transports: credential.get(\"transports\") ?? undefined,\n })),\n authenticatorSelection: { residentKey: \"preferred\", userVerification: \"preferred\" },\n });\n\n await storePasskeyChallenge(\"passkey-registration\", options.challenge, user);\n\n return options;\n}\n\n/**\n * Verify the browser's registration response and store the credential.\n * Checks, in order: the request `Origin` (CSRF), the single-use challenge\n * (consumed even if what follows fails) belongs to THIS user, then the\n * attestation via `@simplewebauthn/server` against the configured origins and\n * rpID.\n *\n * @throws InvalidPasskeyError (400, EC011) on any rejection.\n */\nexport async function verifyPasskeyRegistration(\n request: Request,\n user: Auth,\n credential: PasskeyResponseJSON,\n): Promise<PasskeyCredential> {\n const webauthn = await loadSimpleWebAuthn();\n const origins = assertPasskeyOrigin(request);\n const { challenge, row } = await takePasskeyChallenge(\"passkey-registration\", credential);\n\n if (String(row.userId) !== String(user.id) || row.userType !== user.userType) {\n throw new InvalidPasskeyError(\"challenge-issued-to-another-user\");\n }\n\n let verification: Awaited<ReturnType<typeof webauthn.verifyRegistrationResponse>>;\n\n try {\n verification = await webauthn.verifyRegistrationResponse({\n response: credential,\n expectedChallenge: challenge,\n expectedOrigin: origins,\n expectedRPID: authConfig.passkeys.settings().rpID,\n requireUserVerification: false,\n });\n } catch (error) {\n throw new InvalidPasskeyError(\"registration-verification-failed\", error);\n }\n\n if (!verification.verified || !verification.registrationInfo) {\n throw new InvalidPasskeyError(\"registration-not-verified\");\n }\n\n const { id, publicKey, counter, transports } = verification.registrationInfo.credential;\n\n if (await PasskeyCredential.findByCredentialId(id)) {\n throw new InvalidPasskeyError(\"credential-already-registered\");\n }\n\n return PasskeyCredential.create({\n credential_id: id,\n public_key: Buffer.from(publicKey).toString(\"base64url\"),\n counter,\n transports: transports ?? credential.response.transports ?? [],\n user_id: user.id,\n user_type: user.userType,\n });\n}\n"],"mappings":";;;;;;;;;AAiBA,SAAS,gBAAgB,MAAoB;CAC3C,MAAM,aAAa,WAAW,SAAS,SAAS,CAAC,CAAC;CAElD,IAAI,YAAY,OAAO,WAAW,IAAI;CAEtC,MAAM,QAAQ,KAAK,IAAI,OAAO;CAE9B,OAAO,OAAO,UAAU,YAAY,QAAQ,QAAQ,OAAO,KAAK,EAAE;AACpE;;;;;;;;;;AAWA,eAAsB,mCAAmC,MAAyC;CAChG,MAAM,WAAW,MAAM,mBAAmB;CAC1C,MAAM,WAAW,WAAW,SAAS,SAAS;CAC9C,MAAM,WAAW,MAAM,kBAAkB,QAAQ,IAAI;CAErD,MAAM,UAAU,MAAM,SAAS,4BAA4B;EACzD,QAAQ,SAAS;EACjB,MAAM,SAAS;EACf,UAAU,gBAAgB,IAAI;EAC9B,QAAQ,I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H"}
1
+ {"version":3,"file":"passkey-registration.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/passkeys/passkey-registration.ts"],"sourcesContent":["import type { Request } from \"@warlock.js/core\";\nimport { InvalidPasskeyError } from \"../errors/invalid-passkey.error\";\nimport type { Auth } from \"../models/auth.model\";\nimport { PasskeyCredential } from \"../models/passkey-credential\";\nimport { authConfig } from \"../services/auth-config\";\nimport {\n assertPasskeyOrigin,\n storePasskeyChallenge,\n takePasskeyChallenge,\n} from \"./passkey-challenges\";\nimport {\n loadSimpleWebAuthn,\n type PasskeyOptionsJSON,\n type PasskeyResponseJSON,\n} from \"./simplewebauthn\";\n\n/** Account name the authenticator shows: `auth.passkeys.userName`, else email, else id. */\nfunction passkeyUserName(user: Auth): string {\n const configured = authConfig.passkeys.settings().userName;\n\n if (configured) return configured(user);\n\n const email = user.get(\"email\");\n\n return typeof email === \"string\" && email ? email : String(user.id);\n}\n\n/**\n * Registration options for a LOGGED-IN user adding a passkey. The challenge is\n * stored single-use and bound to this user; the user's existing credentials\n * are excluded so the same authenticator is not registered twice.\n *\n * @example\n * // POST /auth/passkeys/register/options (authMiddleware)\n * response.success(await generatePasskeyRegistrationOptions(request.locals.user));\n */\nexport async function generatePasskeyRegistrationOptions(user: Auth): Promise<PasskeyOptionsJSON> {\n const webauthn = await loadSimpleWebAuthn();\n const settings = authConfig.passkeys.settings();\n const existing = await PasskeyCredential.listFor(user);\n\n const options = await webauthn.generateRegistrationOptions({\n rpName: settings.rpName,\n rpID: settings.rpID,\n userName: passkeyUserName(user),\n userID: new TextEncoder().encode(`${user.userType}:${user.id}`),\n attestationType: \"none\",\n excludeCredentials: existing.map((credential) => ({\n id: credential.credentialId,\n transports: credential.get(\"transports\") ?? undefined,\n })),\n authenticatorSelection: {\n residentKey: \"preferred\",\n userVerification: authConfig.passkeys.userVerification(),\n },\n });\n\n await storePasskeyChallenge(\"passkey-registration\", options.challenge, user);\n\n return options;\n}\n\n/**\n * Verify the browser's registration response and store the credential.\n * Checks, in order: the request `Origin` (CSRF), the single-use challenge\n * (consumed even if what follows fails) belongs to THIS user, then the\n * attestation via `@simplewebauthn/server` against the configured origins and\n * rpID.\n *\n * @throws InvalidPasskeyError (400, EC011) on any rejection.\n */\nexport async function verifyPasskeyRegistration(\n request: Request,\n user: Auth,\n credential: PasskeyResponseJSON,\n): Promise<PasskeyCredential> {\n const webauthn = await loadSimpleWebAuthn();\n const origins = assertPasskeyOrigin(request);\n const { challenge, row } = await takePasskeyChallenge(\"passkey-registration\", credential);\n\n if (String(row.userId) !== String(user.id) || row.userType !== user.userType) {\n throw new InvalidPasskeyError(\"challenge-issued-to-another-user\");\n }\n\n let verification: Awaited<ReturnType<typeof webauthn.verifyRegistrationResponse>>;\n\n try {\n verification = await webauthn.verifyRegistrationResponse({\n response: credential,\n expectedChallenge: challenge,\n expectedOrigin: origins,\n expectedRPID: authConfig.passkeys.settings().rpID,\n requireUserVerification: authConfig.passkeys.userVerification() === \"required\",\n });\n } catch (error) {\n throw new InvalidPasskeyError(\"registration-verification-failed\", error);\n }\n\n if (!verification.verified || !verification.registrationInfo) {\n throw new InvalidPasskeyError(\"registration-not-verified\");\n }\n\n const { id, publicKey, counter, transports } = verification.registrationInfo.credential;\n\n if (await PasskeyCredential.findByCredentialId(id)) {\n throw new InvalidPasskeyError(\"credential-already-registered\");\n }\n\n return PasskeyCredential.create({\n credential_id: id,\n public_key: Buffer.from(publicKey).toString(\"base64url\"),\n counter,\n transports: transports ?? credential.response.transports ?? [],\n user_id: user.id,\n user_type: user.userType,\n });\n}\n"],"mappings":";;;;;;;;;AAiBA,SAAS,gBAAgB,MAAoB;CAC3C,MAAM,aAAa,WAAW,SAAS,SAAS,CAAC,CAAC;CAElD,IAAI,YAAY,OAAO,WAAW,IAAI;CAEtC,MAAM,QAAQ,KAAK,IAAI,OAAO;CAE9B,OAAO,OAAO,UAAU,YAAY,QAAQ,QAAQ,OAAO,KAAK,EAAE;AACpE;;;;;;;;;;AAWA,eAAsB,mCAA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Ae,aAAa,iBAAiB;CAE7E,IAAI,MAAM,kBAAkB,mBAAmB,EAAE,GAC/C,MAAM,IAAI,oBAAoB,+BAA+B;CAG/D,OAAO,kBAAkB,OAAO;EAC9B,eAAe;EACf,YAAY,OAAO,KAAK,SAAS,CAAC,CAAC,SAAS,WAAW;EACvD;EACA,YAAY,cAAc,WAAW,SAAS,cAAc,CAAC;EAC7D,SAAS,KAAK;EACd,WAAW,KAAK;CAClB,CAAC;AACH"}
@@ -55,6 +55,8 @@ export declare class AppleProvider implements AuthProvider {
55
55
  readonly name = "apple";
56
56
  /** Apple's default scopes (`name`, `email`) force `response_mode=form_post`. */
57
57
  readonly callbackMode = "form_post";
58
+ /** Deadline for each request to Apple, in milliseconds. */
59
+ private readonly timeoutMs;
58
60
  constructor(settings: AppleProviderConfig);
59
61
  authorizationUrl(state: ProviderAuthorizationState): string;
60
62
  handleCallback({ query, expected }: ProviderCallbackParams): Promise<ProviderProfile>;
@@ -1 +1 @@
1
- {"version":3,"file":"apple-provider.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/providers/apple-provider.ts"],"mappings":";;;;qBAqBa;KAER;EACH,YAAY,mBAAmB;EAC/B,mBAAmB;EACnB,oBAAoB,iBAAiB;EACrC,cAAc,qBAAqB;EACnC,aAAa,oBAAoB;EACjC,OAAO,iBAAiB;;;;;;;YAQd,kBAAkB;EAC5B,cAAc,eAAe,gBAAgB;EAC7C,cAAc,SAAS;IACrB,qBAAqB,QAAQ,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAmChD,yBAAyB;mBAKA;WAJpB;;WAEA;EAEhB,YAAoC,UAAU;EAEvC,iBAAiB,OAAO;EAqBlB,iBACX,OACA,YACC,yBAAyB,QAAQ;;UAgCtB;;UAmBA;;UAuCA"}
1
+ {"version":3,"file":"apple-provider.d.mts","names":[],"sources":["../../../../../../../../packages/auth/src/providers/apple-provider.ts"],"mappings":";;;;qBAsBa;KAER;EACH,YAAY,mBAAmB;EAC/B,mBAAmB;EACnB,oBAAoB,iBAAiB;EACrC,cAAc,qBAAqB;EACnC,aAAa,oBAAoB;EACjC,OAAO,iBAAiB;;;;;;;YAQd,kBAAkB;EAC5B,cAAc,eAAe,gBAAgB;EAC7C,cAAc,SAAS;IACrB,qBAAqB,QAAQ,4BAA4B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAmChD,yBAAyB;mBAQA;WAPpB;;WAEA;;mBAGC;EAEjB,YAAoC,UAAU;EAIvC,iBAAiB,OAAO;EAqBlB,iBACX,OACA,YACC,yBAAyB,QAAQ;;UAgCtB;;UAmBA;;UAwCA"}
@@ -1,5 +1,6 @@
1
1
  import { InvalidProviderCallbackError } from "../errors/invalid-provider-callback.error.mjs";
2
2
  import { loadOptionalPeer } from "../services/optional-peer.mjs";
3
+ import { providerTimeoutMs } from "./provider-timeout.mjs";
3
4
  import { pkceChallenge } from "./google-provider.mjs";
4
5
 
5
6
  //#region ../../packages/auth/src/providers/apple-provider.ts
@@ -47,6 +48,7 @@ var AppleProvider = class {
47
48
  this.settings = settings;
48
49
  this.name = "apple";
49
50
  this.callbackMode = "form_post";
51
+ this.timeoutMs = providerTimeoutMs("Apple", settings.timeoutMs);
50
52
  }
51
53
  authorizationUrl(state) {
52
54
  const scopes = this.settings.scopes ?? DEFAULT_SCOPES;
@@ -98,6 +100,7 @@ var AppleProvider = class {
98
100
  let body;
99
101
  try {
100
102
  const response = await fetch(TOKEN_ENDPOINT, {
103
+ signal: AbortSignal.timeout(this.timeoutMs),
101
104
  method: "POST",
102
105
  headers: { "content-type": "application/x-www-form-urlencoded" },
103
106
  body: new URLSearchParams({
@@ -119,7 +122,7 @@ var AppleProvider = class {
119
122
  }
120
123
  /** Verify signature, issuer, audience and expiry; resolve the claims. */
121
124
  async verifyIdToken(jose, idToken) {
122
- appleKeySet ??= jose.createRemoteJWKSet(new URL(JWKS_URI));
125
+ appleKeySet ??= jose.createRemoteJWKSet(new URL(JWKS_URI), { timeoutDuration: this.timeoutMs });
123
126
  try {
124
127
  const { payload } = await jose.jwtVerify(idToken, appleKeySet, {
125
128
  issuer: [ISSUER],
@@ -1 +1 @@
1
- {"version":3,"file":"apple-provider.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/providers/apple-provider.ts"],"sourcesContent":["import type {\n AppleProviderConfig,\n AuthProvider,\n ProviderAuthorizationState,\n ProviderCallbackParams,\n ProviderProfile,\n} from \"../contracts/providers\";\nimport { InvalidProviderCallbackError } from \"../errors/invalid-provider-callback.error\";\nimport { loadOptionalPeer } from \"../services/optional-peer\";\nimport type { JoseModule } from \"./google-provider\";\nimport { pkceChallenge } from \"./google-provider\";\n\nconst AUTHORIZATION_ENDPOINT = \"https://appleid.apple.com/auth/authorize\";\nconst TOKEN_ENDPOINT = \"https://appleid.apple.com/auth/token\";\nconst JWKS_URI = \"https://appleid.apple.com/auth/keys\";\nconst ISSUER = \"https://appleid.apple.com\";\nconst DEFAULT_SCOPES = [\"name\", \"email\"];\n/** Apple's own recommendation for a per-request client secret: minutes, not the 6-month maximum it allows. */\nconst CLIENT_SECRET_TTL_SECONDS = 5 * 60;\n\n/** The `warlock add` feature that installs `jose`. */\nexport const APPLE_AUTH_FEATURE = \"auth-apple\";\n\ntype AppleSignJwtBuilder = {\n setIssuer: (issuer: string) => AppleSignJwtBuilder;\n setIssuedAt: () => AppleSignJwtBuilder;\n setExpirationTime: (time: number) => AppleSignJwtBuilder;\n setAudience: (audience: string) => AppleSignJwtBuilder;\n setSubject: (subject: string) => AppleSignJwtBuilder;\n sign: (key: unknown) => Promise<string>;\n};\n\n/**\n * The slice of `jose` the Apple provider uses on top of {@link JoseModule} —\n * `importPKCS8` and `SignJWT` sign the ES256 client-secret JWT Apple requires\n * instead of a static client secret.\n */\nexport type AppleJoseModule = JoseModule & {\n importPKCS8: (pkcs8: string, alg: string) => Promise<unknown>;\n SignJWT: new (payload: Record<string, unknown>) => {\n setProtectedHeader: (header: Record<string, unknown>) => AppleSignJwtBuilder;\n };\n};\n\n/** Apple's key set, created once per process; `jose` caches the fetched JWKS inside it. */\nlet appleKeySet: unknown;\n\n/**\n * Apple (\"Sign in with Apple\") is OpenID Connect over the authorization code\n * flow with PKCE (S256), `state` and `nonce`, the same shape as\n * {@link GoogleProvider} — with two differences that come straight from\n * Apple's own docs (this package has no Apple developer account, so nothing\n * here is proven against a live exchange):\n *\n * 1. Apple has no static client secret. The \"secret\" the token endpoint wants\n * is a fresh ES256 JWT (`iss` = team id, `sub` = client id, `aud` =\n * `https://appleid.apple.com`, signed with the app's private key and the\n * key id as `kid`) — signed once per callback here rather than cached, to\n * avoid ever presenting a stale one.\n * 2. Requesting `name`/`email` (the default scopes) forces\n * `response_mode=form_post`: Apple POSTs `code`, `state` and, on the\n * user's FIRST authorization only, a `user` field — a JSON string with\n * `{ name: { firstName, lastName }, email } ` that never comes back again\n * on a later login. The callback route must therefore accept a POST body,\n * not just a query string, and `request.input` must read that body the\n * same way it already reads a GET query for the other providers.\n *\n * The id_token is verified with `jose` against Apple's JWKS (signature,\n * `iss`, `aud` = the client id, `exp`), then its `nonce` is compared. Apple is\n * also documented to send `email_verified` (and `is_private_email`) as the\n * STRING `\"true\"`/`\"false\"` rather than a JSON boolean on some responses, so\n * both forms are accepted here — treating only the unambiguous `\"false\"` (or\n * `false`) as unverified. A private-relay address (`@privaterelay.appleid.com`)\n * is still a real, working forwarding address and is accepted as any other.\n */\nexport class AppleProvider implements AuthProvider {\n public readonly name = \"apple\";\n /** Apple's default scopes (`name`, `email`) force `response_mode=form_post`. */\n public readonly callbackMode = \"form_post\";\n\n public constructor(private readonly settings: AppleProviderConfig) {}\n\n public authorizationUrl(state: ProviderAuthorizationState): string {\n const scopes = this.settings.scopes ?? DEFAULT_SCOPES;\n const url = new URL(AUTHORIZATION_ENDPOINT);\n\n url.searchParams.set(\"client_id\", this.settings.clientId);\n url.searchParams.set(\"redirect_uri\", this.settings.redirectUri);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"scope\", scopes.join(\" \"));\n url.searchParams.set(\"state\", state.state);\n url.searchParams.set(\"nonce\", state.nonce);\n url.searchParams.set(\"code_challenge\", pkceChallenge(state.codeVerifier));\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n\n // Apple requires form_post whenever name/email scopes are requested.\n if (scopes.includes(\"name\") || scopes.includes(\"email\")) {\n url.searchParams.set(\"response_mode\", \"form_post\");\n }\n\n return url.toString();\n }\n\n public async handleCallback({\n query,\n expected,\n }: ProviderCallbackParams): Promise<ProviderProfile> {\n // Load the peer first: a missing SDK fails loudly before any network call.\n const jose = await loadOptionalPeer<AppleJoseModule>(\"jose\", APPLE_AUTH_FEATURE);\n\n const code = query.code;\n\n if (typeof code !== \"string\" || code.length === 0) {\n throw new InvalidProviderCallbackError(\"missing-code\");\n }\n\n const idToken = await this.exchangeCode(jose, code, expected.codeVerifier);\n const claims = await this.verifyIdToken(jose, idToken);\n\n if (typeof claims.nonce !== \"string\" || claims.nonce !== expected.nonce) {\n throw new InvalidProviderCallbackError(\"nonce-mismatch\");\n }\n\n if (typeof claims.sub !== \"string\" || claims.sub.length === 0) {\n throw new InvalidProviderCallbackError(\"missing-subject\");\n }\n\n return {\n provider: this.name,\n providerUserId: claims.sub,\n email: typeof claims.email === \"string\" ? claims.email : undefined,\n emailVerified: isVerifiedFlag(claims.email_verified),\n name: nameFromUserField(query.user),\n raw: claims,\n };\n }\n\n /** Sign a fresh ES256 client-secret JWT — Apple has no static one. */\n private async clientSecret(jose: AppleJoseModule): Promise<string> {\n const key = await jose.importPKCS8(this.settings.privateKey, \"ES256\");\n const now = Math.floor(Date.now() / 1000);\n\n try {\n return await new jose.SignJWT({})\n .setProtectedHeader({ alg: \"ES256\", kid: this.settings.keyId })\n .setIssuer(this.settings.teamId)\n .setIssuedAt()\n .setExpirationTime(now + CLIENT_SECRET_TTL_SECONDS)\n .setAudience(ISSUER)\n .setSubject(this.settings.clientId)\n .sign(key);\n } catch (error) {\n throw new InvalidProviderCallbackError(\"client-secret-signing-failed\", error);\n }\n }\n\n /** Redeem the authorization code (with the PKCE verifier) for an id_token. */\n private async exchangeCode(\n jose: AppleJoseModule,\n code: string,\n codeVerifier: string,\n ): Promise<string> {\n const clientSecret = await this.clientSecret(jose);\n let body: { id_token?: unknown };\n\n try {\n const response = await fetch(TOKEN_ENDPOINT, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n code,\n client_id: this.settings.clientId,\n client_secret: clientSecret,\n redirect_uri: this.settings.redirectUri,\n grant_type: \"authorization_code\",\n code_verifier: codeVerifier,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Apple token endpoint answered ${response.status}`);\n }\n\n body = (await response.json()) as { id_token?: unknown };\n } catch (error) {\n throw new InvalidProviderCallbackError(\"code-exchange-failed\", error);\n }\n\n if (typeof body.id_token !== \"string\") {\n throw new InvalidProviderCallbackError(\"missing-id-token\");\n }\n\n return body.id_token;\n }\n\n /** Verify signature, issuer, audience and expiry; resolve the claims. */\n private async verifyIdToken(\n jose: AppleJoseModule,\n idToken: string,\n ): Promise<Record<string, unknown>> {\n appleKeySet ??= jose.createRemoteJWKSet(new URL(JWKS_URI));\n\n try {\n const { payload } = await jose.jwtVerify(idToken, appleKeySet, {\n issuer: [ISSUER],\n audience: this.settings.clientId,\n });\n\n return payload;\n } catch (error) {\n throw new InvalidProviderCallbackError(\"invalid-id-token\", error);\n }\n }\n}\n\n/** Apple's `email_verified` arrives as a JSON boolean on some responses, a `\"true\"`/`\"false\"` string on others. */\nfunction isVerifiedFlag(value: unknown): boolean {\n return value === true || value === \"true\";\n}\n\n/**\n * Apple sends the account name only once, on the FIRST authorization, as a\n * `user` form field holding a JSON string: `{\"name\":{\"firstName\",\"lastName\"}}`.\n * Every later login omits it entirely — callers that need the name must save\n * it themselves the first time.\n */\nfunction nameFromUserField(user: unknown): string | undefined {\n if (typeof user !== \"string\" || user.length === 0) return undefined;\n\n try {\n const parsed = JSON.parse(user) as { name?: { firstName?: string; lastName?: string } };\n const first = parsed.name?.firstName;\n const last = parsed.name?.lastName;\n const name = [first, last].filter((part): part is string => Boolean(part)).join(\" \");\n\n return name.length > 0 ? name : undefined;\n } catch {\n return undefined;\n }\n}\n"],"mappings":";;;;;AAYA,MAAM,yBAAyB;AAC/B,MAAM,iBAAiB;AACvB,MAAM,WAAW;AACjB,MAAM,SAAS;AACf,MAAM,iBAAiB,CAAC,QAAQ,OAAO;;AAEvC,MAAM,4BAA4B;;AAGlC,MAAa,qBAAqB;;AAwBlC,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BJ,IAAa,gBAAb,MAAmD;CAKjD,AAAO,YAAY,AAAiB,UAA+B;EAA/B;cAJb;sBAEQ;CAEqC;CAEpE,AAAO,iBAAiB,OAA2C;EACjE,MAAM,SAAS,KAAK,SAAS,UAAU;EACvC,MAAM,MAAM,IAAI,IAAI,sBAAsB;EAE1C,IAAI,aAAa,IAAI,aAAa,KAAK,SAAS,QAAQ;EACxD,IAAI,aAAa,IAAI,gBAAgB,KAAK,SAAS,WAAW;EAC9D,IAAI,aAAa,IAAI,iBAAiB,MAAM;EAC5C,IAAI,aAAa,IAAI,SAAS,OAAO,KAAK,GAAG,CAAC;EAC9C,IAAI,aAAa,IAAI,SAAS,MAAM,KAAK;EACzC,IAAI,aAAa,IAAI,SAAS,MAAM,KAAK;EACzC,IAAI,aAAa,IAAI,kBAAkB,cAAc,MAAM,YAAY,CAAC;EACxE,IAAI,aAAa,IAAI,yBAAyB,MAAM;EAGpD,IAAI,OAAO,SAAS,MAAM,KAAK,OAAO,SAAS,OAAO,GACpD,IAAI,aAAa,IAAI,iBAAiB,WAAW;EAGnD,OAAO,IAAI,SAAS;CACtB;CAEA,MAAa,eAAe,EAC1B,OACA,YACmD;EAEnD,MAAM,OAAO,MAAM,iBAAkC,QAAQ,kBAAkB;EAE/E,MAAM,OAAO,MAAM;EAEnB,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,GAC9C,MAAM,IAAI,6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W,KAAK,SAAS;KACzB,eAAe;KACf,cAAc,KAAK,SAAS;KAC5B,YAAY;KACZ,eAAe;IACjB,CAAC;GACH,CAAC;GAED,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,iCAAiC,SAAS,QAAQ;GAGpE,OAAQ,MAAM,SAAS,KAAK;EAC9B,SAAS,OAAO;GACd,MAAM,IAAI,6BAA6B,wBAAwB,KAAK;EACtE;EAEA,IAAI,OAAO,KAAK,aAAa,UAC3B,MAAM,IAAI,6BAA6B,kBAAkB;EAG3D,OAAO,KAAK;CACd;;CAGA,MAAc,cACZ,MACA,SACkC;EAClC,gBAAgB,KAAK,mBAAmB,IAAI,IAAI,QAAQ,CAAC;EAEzD,IAAI;GACF,MAAM,EAAE,YAAY,MAAM,KAAK,UAAU,SAAS,aAAa;IAC7D,QAAQ,CAAC,MAAM;IACf,UAAU,KAAK,SAAS;GAC1B,CAAC;GAED,OAAO;EACT,SAAS,OAAO;GACd,MAAM,IAAI,6BAA6B,oBAAoB,KAAK;EAClE;CACF;AACF;;AAGA,SAAS,eAAe,OAAyB;CAC/C,OAAO,UAAU,QAAQ,UAAU;AACrC;;;;;;;AAQA,SAAS,kBAAkB,MAAmC;CAC5D,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,GAAG,OAAO;CAE1D,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;EAG9B,MAAM,OAAO,CAFC,OAAO,MAAM,WACd,OAAO,MAAM,QACD,CAAC,CAAC,QAAQ,SAAyB,QAAQ,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG;EAEnF,OAAO,KAAK,SAAS,IAAI,OAAO;CAClC,QAAQ;EACN;CACF;AACF"}
1
+ {"version":3,"file":"apple-provider.mjs","names":[],"sources":["../../../../../../../../packages/auth/src/providers/apple-provider.ts"],"sourcesContent":["import type {\n AppleProviderConfig,\n AuthProvider,\n ProviderAuthorizationState,\n ProviderCallbackParams,\n ProviderProfile,\n} from \"../contracts/providers\";\nimport { InvalidProviderCallbackError } from \"../errors/invalid-provider-callback.error\";\nimport { providerTimeoutMs } from \"./provider-timeout\";\nimport { loadOptionalPeer } from \"../services/optional-peer\";\nimport type { JoseModule } from \"./google-provider\";\nimport { pkceChallenge } from \"./google-provider\";\n\nconst AUTHORIZATION_ENDPOINT = \"https://appleid.apple.com/auth/authorize\";\nconst TOKEN_ENDPOINT = \"https://appleid.apple.com/auth/token\";\nconst JWKS_URI = \"https://appleid.apple.com/auth/keys\";\nconst ISSUER = \"https://appleid.apple.com\";\nconst DEFAULT_SCOPES = [\"name\", \"email\"];\n/** Apple's own recommendation for a per-request client secret: minutes, not the 6-month maximum it allows. */\nconst CLIENT_SECRET_TTL_SECONDS = 5 * 60;\n\n/** The `warlock add` feature that installs `jose`. */\nexport const APPLE_AUTH_FEATURE = \"auth-apple\";\n\ntype AppleSignJwtBuilder = {\n setIssuer: (issuer: string) => AppleSignJwtBuilder;\n setIssuedAt: () => AppleSignJwtBuilder;\n setExpirationTime: (time: number) => AppleSignJwtBuilder;\n setAudience: (audience: string) => AppleSignJwtBuilder;\n setSubject: (subject: string) => AppleSignJwtBuilder;\n sign: (key: unknown) => Promise<string>;\n};\n\n/**\n * The slice of `jose` the Apple provider uses on top of {@link JoseModule} —\n * `importPKCS8` and `SignJWT` sign the ES256 client-secret JWT Apple requires\n * instead of a static client secret.\n */\nexport type AppleJoseModule = JoseModule & {\n importPKCS8: (pkcs8: string, alg: string) => Promise<unknown>;\n SignJWT: new (payload: Record<string, unknown>) => {\n setProtectedHeader: (header: Record<string, unknown>) => AppleSignJwtBuilder;\n };\n};\n\n/** Apple's key set, created once per process; `jose` caches the fetched JWKS inside it. */\nlet appleKeySet: unknown;\n\n/**\n * Apple (\"Sign in with Apple\") is OpenID Connect over the authorization code\n * flow with PKCE (S256), `state` and `nonce`, the same shape as\n * {@link GoogleProvider} — with two differences that come straight from\n * Apple's own docs (this package has no Apple developer account, so nothing\n * here is proven against a live exchange):\n *\n * 1. Apple has no static client secret. The \"secret\" the token endpoint wants\n * is a fresh ES256 JWT (`iss` = team id, `sub` = client id, `aud` =\n * `https://appleid.apple.com`, signed with the app's private key and the\n * key id as `kid`) — signed once per callback here rather than cached, to\n * avoid ever presenting a stale one.\n * 2. Requesting `name`/`email` (the default scopes) forces\n * `response_mode=form_post`: Apple POSTs `code`, `state` and, on the\n * user's FIRST authorization only, a `user` field — a JSON string with\n * `{ name: { firstName, lastName }, email } ` that never comes back again\n * on a later login. The callback route must therefore accept a POST body,\n * not just a query string, and `request.input` must read that body the\n * same way it already reads a GET query for the other providers.\n *\n * The id_token is verified with `jose` against Apple's JWKS (signature,\n * `iss`, `aud` = the client id, `exp`), then its `nonce` is compared. Apple is\n * also documented to send `email_verified` (and `is_private_email`) as the\n * STRING `\"true\"`/`\"false\"` rather than a JSON boolean on some responses, so\n * both forms are accepted here — treating only the unambiguous `\"false\"` (or\n * `false`) as unverified. A private-relay address (`@privaterelay.appleid.com`)\n * is still a real, working forwarding address and is accepted as any other.\n */\nexport class AppleProvider implements AuthProvider {\n public readonly name = \"apple\";\n /** Apple's default scopes (`name`, `email`) force `response_mode=form_post`. */\n public readonly callbackMode = \"form_post\";\n\n /** Deadline for each request to Apple, in milliseconds. */\n private readonly timeoutMs: number;\n\n public constructor(private readonly settings: AppleProviderConfig) {\n this.timeoutMs = providerTimeoutMs(\"Apple\", settings.timeoutMs);\n }\n\n public authorizationUrl(state: ProviderAuthorizationState): string {\n const scopes = this.settings.scopes ?? DEFAULT_SCOPES;\n const url = new URL(AUTHORIZATION_ENDPOINT);\n\n url.searchParams.set(\"client_id\", this.settings.clientId);\n url.searchParams.set(\"redirect_uri\", this.settings.redirectUri);\n url.searchParams.set(\"response_type\", \"code\");\n url.searchParams.set(\"scope\", scopes.join(\" \"));\n url.searchParams.set(\"state\", state.state);\n url.searchParams.set(\"nonce\", state.nonce);\n url.searchParams.set(\"code_challenge\", pkceChallenge(state.codeVerifier));\n url.searchParams.set(\"code_challenge_method\", \"S256\");\n\n // Apple requires form_post whenever name/email scopes are requested.\n if (scopes.includes(\"name\") || scopes.includes(\"email\")) {\n url.searchParams.set(\"response_mode\", \"form_post\");\n }\n\n return url.toString();\n }\n\n public async handleCallback({\n query,\n expected,\n }: ProviderCallbackParams): Promise<ProviderProfile> {\n // Load the peer first: a missing SDK fails loudly before any network call.\n const jose = await loadOptionalPeer<AppleJoseModule>(\"jose\", APPLE_AUTH_FEATURE);\n\n const code = query.code;\n\n if (typeof code !== \"string\" || code.length === 0) {\n throw new InvalidProviderCallbackError(\"missing-code\");\n }\n\n const idToken = await this.exchangeCode(jose, code, expected.codeVerifier);\n const claims = await this.verifyIdToken(jose, idToken);\n\n if (typeof claims.nonce !== \"string\" || claims.nonce !== expected.nonce) {\n throw new InvalidProviderCallbackError(\"nonce-mismatch\");\n }\n\n if (typeof claims.sub !== \"string\" || claims.sub.length === 0) {\n throw new InvalidProviderCallbackError(\"missing-subject\");\n }\n\n return {\n provider: this.name,\n providerUserId: claims.sub,\n email: typeof claims.email === \"string\" ? claims.email : undefined,\n emailVerified: isVerifiedFlag(claims.email_verified),\n name: nameFromUserField(query.user),\n raw: claims,\n };\n }\n\n /** Sign a fresh ES256 client-secret JWT — Apple has no static one. */\n private async clientSecret(jose: AppleJoseModule): Promise<string> {\n const key = await jose.importPKCS8(this.settings.privateKey, \"ES256\");\n const now = Math.floor(Date.now() / 1000);\n\n try {\n return await new jose.SignJWT({})\n .setProtectedHeader({ alg: \"ES256\", kid: this.settings.keyId })\n .setIssuer(this.settings.teamId)\n .setIssuedAt()\n .setExpirationTime(now + CLIENT_SECRET_TTL_SECONDS)\n .setAudience(ISSUER)\n .setSubject(this.settings.clientId)\n .sign(key);\n } catch (error) {\n throw new InvalidProviderCallbackError(\"client-secret-signing-failed\", error);\n }\n }\n\n /** Redeem the authorization code (with the PKCE verifier) for an id_token. */\n private async exchangeCode(\n jose: AppleJoseModule,\n code: string,\n codeVerifier: string,\n ): Promise<string> {\n const clientSecret = await this.clientSecret(jose);\n let body: { id_token?: unknown };\n\n try {\n const response = await fetch(TOKEN_ENDPOINT, {\n signal: AbortSignal.timeout(this.timeoutMs),\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\" },\n body: new URLSearchParams({\n code,\n client_id: this.settings.clientId,\n client_secret: clientSecret,\n redirect_uri: this.settings.redirectUri,\n grant_type: \"authorization_code\",\n code_verifier: codeVerifier,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`Apple token endpoint answered ${response.status}`);\n }\n\n body = (await response.json()) as { id_token?: unknown };\n } catch (error) {\n throw new InvalidProviderCallbackError(\"code-exchange-failed\", error);\n }\n\n if (typeof body.id_token !== \"string\") {\n throw new InvalidProviderCallbackError(\"missing-id-token\");\n }\n\n return body.id_token;\n }\n\n /** Verify signature, issuer, audience and expiry; resolve the claims. */\n private async verifyIdToken(\n jose: AppleJoseModule,\n idToken: string,\n ): Promise<Record<string, unknown>> {\n appleKeySet ??= jose.createRemoteJWKSet(new URL(JWKS_URI), {\n timeoutDuration: this.timeoutMs,\n });\n\n try {\n const { payload } = await jose.jwtVerify(idToken, appleKeySet, {\n issuer: [ISSUER],\n audience: this.settings.clientId,\n });\n\n return payload;\n } catch (error) {\n throw new InvalidProviderCallbackError(\"invalid-id-token\", error);\n }\n }\n}\n\n/** Apple's `email_verified` arrives as a JSON boolean on some responses, a `\"true\"`/`\"false\"` string on others. */\nfunction isVerifiedFlag(value: unknown): boolean {\n return value === true || value === \"true\";\n}\n\n/**\n * Apple sends the account name only once, on the FIRST authorization, as a\n * `user` form field holding a JSON string: `{\"name\":{\"firstName\",\"lastName\"}}`.\n * Every later login omits it entirely — callers that need the name must save\n * it themselves the first time.\n */\nfunction nameFromUserField(user: unknown): string | undefined {\n if (typeof user !== \"string\" || user.length === 0) return undefined;\n\n try {\n const parsed = JSON.parse(user) as { name?: { firstName?: string; lastName?: string } };\n const first = parsed.name?.firstName;\n const last = parsed.name?.lastName;\n const name = [first, last].filter((part): part is string => Boolean(part)).join(\" \");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,KAAK,SAAS;KACzB,eAAe;KACf,cAAc,KAAK,SAAS;KAC5B,YAAY;KACZ,eAAe;IACjB,CAAC;GACH,CAAC;GAED,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,iCAAiC,SAAS,QAAQ;GAGpE,OAAQ,MAAM,SAAS,KAAK;EAC9B,SAAS,OAAO;GACd,MAAM,IAAI,6BAA6B,wBAAwB,KAAK;EACtE;EAEA,IAAI,OAAO,KAAK,aAAa,UAC3B,MAAM,IAAI,6BAA6B,kBAAkB;EAG3D,OAAO,KAAK;CACd;;CAGA,MAAc,cACZ,MACA,SACkC;EAClC,gBAAgB,KAAK,mBAAmB,IAAI,IAAI,QAAQ,GAAG,EACzD,iBAAiB,KAAK,UACxB,CAAC;EAED,IAAI;GACF,MAAM,EAAE,YAAY,MAAM,KAAK,UAAU,SAAS,aAAa;IAC7D,QAAQ,CAAC,MAAM;IACf,UAAU,KAAK,SAAS;GAC1B,CAAC;GAED,OAAO;EACT,SAAS,OAAO;GACd,MAAM,IAAI,6BAA6B,oBAAoB,KAAK;EAClE;CACF;AACF;;AAGA,SAAS,eAAe,OAAyB;CAC/C,OAAO,UAAU,QAAQ,UAAU;AACrC;;;;;;;AAQA,SAAS,kBAAkB,MAAmC;CAC5D,IAAI,OAAO,SAAS,YAAY,KAAK,WAAW,GAAG,OAAO;CAE1D,IAAI;EACF,MAAM,SAAS,KAAK,MAAM,IAAI;EAG9B,MAAM,OAAO,CAFC,OAAO,MAAM,WACd,OAAO,MAAM,QACD,CAAC,CAAC,QAAQ,SAAyB,QAAQ,IAAI,CAAC,CAAC,CAAC,KAAK,GAAG;EAEnF,OAAO,KAAK,SAAS,IAAI,OAAO;CAClC,QAAQ;EACN;CACF;AACF"}
@@ -9,6 +9,8 @@ import { AuthProvider, DiscordProviderConfig, ProviderAuthorizationState, Provid
9
9
  export declare class DiscordProvider implements AuthProvider {
10
10
  private readonly settings;
11
11
  readonly name = "discord";
12
+ /** Deadline for each request to Discord, in milliseconds. */
13
+ private readonly timeoutMs;
12
14
  constructor(settings: DiscordProviderConfig);
13
15
  authorizationUrl(state: ProviderAuthorizationState): string;
14
16
  handleCallback({ query, expected }: ProviderCallbackParams): Promise<ProviderProfile>;