@warlock.js/auth 5.11.0 → 5.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (185) hide show
  1. package/CHANGELOG.md +65 -0
  2. package/README.md +88 -86
  3. package/esm/commands/auth-cleanup-command.mjs +1 -1
  4. package/esm/commands/auth-cleanup-command.mjs.map +1 -1
  5. package/esm/contracts/index.d.mts +4 -2
  6. package/esm/contracts/providers.d.mts +101 -0
  7. package/esm/contracts/providers.d.mts.map +1 -0
  8. package/esm/contracts/request-locals.d.mts +43 -0
  9. package/esm/contracts/request-locals.d.mts.map +1 -0
  10. package/esm/contracts/types.d.mts +159 -1
  11. package/esm/contracts/types.d.mts.map +1 -1
  12. package/esm/contracts/types.mjs.map +1 -1
  13. package/esm/errors/auth-provider-sdk-missing.error.d.mts +17 -0
  14. package/esm/errors/auth-provider-sdk-missing.error.d.mts.map +1 -0
  15. package/esm/errors/auth-provider-sdk-missing.error.mjs +22 -0
  16. package/esm/errors/auth-provider-sdk-missing.error.mjs.map +1 -0
  17. package/esm/errors/email-not-verified.error.d.mts +16 -0
  18. package/esm/errors/email-not-verified.error.d.mts.map +1 -0
  19. package/esm/errors/email-not-verified.error.mjs +20 -0
  20. package/esm/errors/email-not-verified.error.mjs.map +1 -0
  21. package/esm/errors/index.d.mts +7 -0
  22. package/esm/errors/index.mjs +9 -0
  23. package/esm/errors/invalid-one-time-token.error.d.mts +17 -0
  24. package/esm/errors/invalid-one-time-token.error.d.mts.map +1 -0
  25. package/esm/errors/invalid-one-time-token.error.mjs +21 -0
  26. package/esm/errors/invalid-one-time-token.error.mjs.map +1 -0
  27. package/esm/errors/invalid-passkey.error.d.mts +18 -0
  28. package/esm/errors/invalid-passkey.error.d.mts.map +1 -0
  29. package/esm/errors/invalid-passkey.error.mjs +23 -0
  30. package/esm/errors/invalid-passkey.error.mjs.map +1 -0
  31. package/esm/errors/invalid-provider-callback.error.d.mts +18 -0
  32. package/esm/errors/invalid-provider-callback.error.d.mts.map +1 -0
  33. package/esm/errors/invalid-provider-callback.error.mjs +23 -0
  34. package/esm/errors/invalid-provider-callback.error.mjs.map +1 -0
  35. package/esm/errors/notifications-unavailable.error.d.mts +15 -0
  36. package/esm/errors/notifications-unavailable.error.d.mts.map +1 -0
  37. package/esm/errors/notifications-unavailable.error.mjs +20 -0
  38. package/esm/errors/notifications-unavailable.error.mjs.map +1 -0
  39. package/esm/errors/provider-email-not-verified.error.d.mts +16 -0
  40. package/esm/errors/provider-email-not-verified.error.d.mts.map +1 -0
  41. package/esm/errors/provider-email-not-verified.error.mjs +20 -0
  42. package/esm/errors/provider-email-not-verified.error.mjs.map +1 -0
  43. package/esm/index.d.mts +31 -3
  44. package/esm/index.mjs +29 -1
  45. package/esm/middleware/auth.middleware.d.mts.map +1 -1
  46. package/esm/middleware/auth.middleware.mjs +13 -2
  47. package/esm/middleware/auth.middleware.mjs.map +1 -1
  48. package/esm/middleware/csrf-origin-check.d.mts +40 -0
  49. package/esm/middleware/csrf-origin-check.d.mts.map +1 -0
  50. package/esm/middleware/csrf-origin-check.mjs +105 -0
  51. package/esm/middleware/csrf-origin-check.mjs.map +1 -0
  52. package/esm/middleware/index.d.mts +5 -1
  53. package/esm/middleware/index.mjs +4 -0
  54. package/esm/middleware/one-time-token-throttle.middleware.d.mts +36 -0
  55. package/esm/middleware/one-time-token-throttle.middleware.d.mts.map +1 -0
  56. package/esm/middleware/one-time-token-throttle.middleware.mjs +53 -0
  57. package/esm/middleware/one-time-token-throttle.middleware.mjs.map +1 -0
  58. package/esm/middleware/otp-throttle.middleware.d.mts +30 -0
  59. package/esm/middleware/otp-throttle.middleware.d.mts.map +1 -0
  60. package/esm/middleware/otp-throttle.middleware.mjs +45 -0
  61. package/esm/middleware/otp-throttle.middleware.mjs.map +1 -0
  62. package/esm/middleware/require-verified-email.middleware.d.mts +18 -0
  63. package/esm/middleware/require-verified-email.middleware.d.mts.map +1 -0
  64. package/esm/middleware/require-verified-email.middleware.mjs +24 -0
  65. package/esm/middleware/require-verified-email.middleware.mjs.map +1 -0
  66. package/esm/models/access-token/access-token.model.d.mts +8 -0
  67. package/esm/models/access-token/access-token.model.d.mts.map +1 -1
  68. package/esm/models/access-token/access-token.model.mjs +3 -0
  69. package/esm/models/access-token/access-token.model.mjs.map +1 -1
  70. package/esm/models/index.d.mts +3 -1
  71. package/esm/models/index.d.mts.map +1 -1
  72. package/esm/models/index.mjs +16 -1
  73. package/esm/models/index.mjs.map +1 -1
  74. package/esm/models/one-time-token/index.d.mts +1 -0
  75. package/esm/models/one-time-token/index.mjs +3 -0
  76. package/esm/models/one-time-token/migration.mjs +31 -0
  77. package/esm/models/one-time-token/migration.mjs.map +1 -0
  78. package/esm/models/one-time-token/one-time-token.model.d.mts +173 -0
  79. package/esm/models/one-time-token/one-time-token.model.d.mts.map +1 -0
  80. package/esm/models/one-time-token/one-time-token.model.mjs +151 -0
  81. package/esm/models/one-time-token/one-time-token.model.mjs.map +1 -0
  82. package/esm/models/passkey-credential/index.d.mts +1 -0
  83. package/esm/models/passkey-credential/index.mjs +3 -0
  84. package/esm/models/passkey-credential/migration.mjs +25 -0
  85. package/esm/models/passkey-credential/migration.mjs.map +1 -0
  86. package/esm/models/passkey-credential/passkey-credential.model.d.mts +108 -0
  87. package/esm/models/passkey-credential/passkey-credential.model.d.mts.map +1 -0
  88. package/esm/models/passkey-credential/passkey-credential.model.mjs +70 -0
  89. package/esm/models/passkey-credential/passkey-credential.model.mjs.map +1 -0
  90. package/esm/models/provider-account/index.d.mts +1 -0
  91. package/esm/models/provider-account/index.mjs +3 -0
  92. package/esm/models/provider-account/migration.mjs +25 -0
  93. package/esm/models/provider-account/migration.mjs.map +1 -0
  94. package/esm/models/provider-account/provider-account.model.d.mts +75 -0
  95. package/esm/models/provider-account/provider-account.model.d.mts.map +1 -0
  96. package/esm/models/provider-account/provider-account.model.mjs +55 -0
  97. package/esm/models/provider-account/provider-account.model.mjs.map +1 -0
  98. package/esm/models/refresh-token/refresh-token.model.d.mts +7 -0
  99. package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
  100. package/esm/models/refresh-token/refresh-token.model.mjs +3 -0
  101. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  102. package/esm/otp/index.d.mts +1 -0
  103. package/esm/otp/index.mjs +3 -0
  104. package/esm/otp/otp.d.mts +38 -0
  105. package/esm/otp/otp.d.mts.map +1 -0
  106. package/esm/otp/otp.mjs +105 -0
  107. package/esm/otp/otp.mjs.map +1 -0
  108. package/esm/passkeys/index.d.mts +3 -0
  109. package/esm/passkeys/index.mjs +4 -0
  110. package/esm/passkeys/passkey-authentication.d.mts +33 -0
  111. package/esm/passkeys/passkey-authentication.d.mts.map +1 -0
  112. package/esm/passkeys/passkey-authentication.mjs +93 -0
  113. package/esm/passkeys/passkey-authentication.mjs.map +1 -0
  114. package/esm/passkeys/passkey-challenges.mjs +53 -0
  115. package/esm/passkeys/passkey-challenges.mjs.map +1 -0
  116. package/esm/passkeys/passkey-registration.d.mts +29 -0
  117. package/esm/passkeys/passkey-registration.d.mts.map +1 -0
  118. package/esm/passkeys/passkey-registration.mjs +88 -0
  119. package/esm/passkeys/passkey-registration.mjs.map +1 -0
  120. package/esm/passkeys/simplewebauthn.d.mts +21 -0
  121. package/esm/passkeys/simplewebauthn.d.mts.map +1 -0
  122. package/esm/passkeys/simplewebauthn.mjs +13 -0
  123. package/esm/passkeys/simplewebauthn.mjs.map +1 -0
  124. package/esm/providers/google-provider.d.mts +40 -0
  125. package/esm/providers/google-provider.d.mts.map +1 -0
  126. package/esm/providers/google-provider.mjs +105 -0
  127. package/esm/providers/google-provider.mjs.map +1 -0
  128. package/esm/providers/index.d.mts +2 -0
  129. package/esm/providers/index.mjs +4 -0
  130. package/esm/providers/provider-login.d.mts +43 -0
  131. package/esm/providers/provider-login.d.mts.map +1 -0
  132. package/esm/providers/provider-login.mjs +86 -0
  133. package/esm/providers/provider-login.mjs.map +1 -0
  134. package/esm/providers/provider-state-cookie.mjs +63 -0
  135. package/esm/providers/provider-state-cookie.mjs.map +1 -0
  136. package/esm/providers/resolve-provider-user.mjs +45 -0
  137. package/esm/providers/resolve-provider-user.mjs.map +1 -0
  138. package/esm/services/auth-config.mjs +84 -0
  139. package/esm/services/auth-config.mjs.map +1 -1
  140. package/esm/services/auth.service.d.mts +59 -2
  141. package/esm/services/auth.service.d.mts.map +1 -1
  142. package/esm/services/auth.service.mjs +86 -1
  143. package/esm/services/auth.service.mjs.map +1 -1
  144. package/esm/services/current-user.d.mts +21 -0
  145. package/esm/services/current-user.d.mts.map +1 -0
  146. package/esm/services/current-user.mjs +24 -0
  147. package/esm/services/current-user.mjs.map +1 -0
  148. package/esm/services/email-verification.d.mts +35 -0
  149. package/esm/services/email-verification.d.mts.map +1 -0
  150. package/esm/services/email-verification.mjs +55 -0
  151. package/esm/services/email-verification.mjs.map +1 -0
  152. package/esm/services/index.d.mts +5 -1
  153. package/esm/services/index.mjs +4 -0
  154. package/esm/services/one-time-tokens.d.mts +32 -0
  155. package/esm/services/one-time-tokens.d.mts.map +1 -0
  156. package/esm/services/one-time-tokens.mjs +56 -0
  157. package/esm/services/one-time-tokens.mjs.map +1 -0
  158. package/esm/services/optional-peer.mjs +37 -0
  159. package/esm/services/optional-peer.mjs.map +1 -0
  160. package/esm/services/password-reset.d.mts +34 -0
  161. package/esm/services/password-reset.d.mts.map +1 -0
  162. package/esm/services/password-reset.mjs +81 -0
  163. package/esm/services/password-reset.mjs.map +1 -0
  164. package/esm/services/token-notifications.mjs +87 -0
  165. package/esm/services/token-notifications.mjs.map +1 -0
  166. package/esm/utils/auth-error-codes.d.mts +48 -1
  167. package/esm/utils/auth-error-codes.d.mts.map +1 -1
  168. package/esm/utils/auth-error-codes.mjs +41 -0
  169. package/esm/utils/auth-error-codes.mjs.map +1 -1
  170. package/esm/utils/index.mjs +1 -0
  171. package/esm/utils/safe-equal.d.mts +6 -0
  172. package/esm/utils/safe-equal.d.mts.map +1 -0
  173. package/esm/utils/safe-equal.mjs +13 -0
  174. package/esm/utils/safe-equal.mjs.map +1 -0
  175. package/llms-full.txt +402 -29
  176. package/llms.txt +2 -0
  177. package/package.json +21 -7
  178. package/skills/handle-login-and-logout/SKILL.md +1 -1
  179. package/skills/login-with-providers/SKILL.md +154 -0
  180. package/skills/manage-tokens/SKILL.md +7 -1
  181. package/skills/overview/SKILL.md +1 -1
  182. package/skills/protect-routes/SKILL.md +71 -13
  183. package/skills/register-user/SKILL.md +6 -8
  184. package/skills/run-auth-commands/SKILL.md +1 -1
  185. package/skills/verify-email-and-reset-password/SKILL.md +137 -0
@@ -0,0 +1,25 @@
1
+ import { ProviderAccount } from "./provider-account.model.mjs";
2
+ import { migrate } from "@warlock.js/cascade";
3
+
4
+ //#region ../auth/src/models/provider-account/migration.ts
5
+ const ProviderAccountMigration = migrate(ProviderAccount, {
6
+ name: "providerAccount",
7
+ up() {
8
+ this.createTableIfNotExists();
9
+ this.primaryUuid();
10
+ this.string("provider", 50);
11
+ this.string("provider_user_id", 255);
12
+ this.foreignId("user_id").index();
13
+ this.string("user_type", 50).nullable();
14
+ this.string("email", 255).nullable();
15
+ this.unique(["provider", "provider_user_id"]);
16
+ this.timestamps();
17
+ },
18
+ down() {
19
+ this.dropTableIfExists();
20
+ }
21
+ });
22
+
23
+ //#endregion
24
+ export { ProviderAccountMigration };
25
+ //# sourceMappingURL=migration.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration.mjs","names":[],"sources":["../../../../../../../../auth/src/models/provider-account/migration.ts"],"sourcesContent":["import { migrate } from \"@warlock.js/cascade\";\nimport { ProviderAccount } from \"./provider-account.model\";\n\nexport const ProviderAccountMigration = migrate(ProviderAccount, {\n name: \"providerAccount\",\n up() {\n this.createTableIfNotExists();\n\n this.primaryUuid();\n\n this.string(\"provider\", 50);\n this.string(\"provider_user_id\", 255);\n this.foreignId(\"user_id\").index();\n this.string(\"user_type\", 50).nullable();\n this.string(\"email\", 255).nullable();\n\n // One app user per provider identity.\n this.unique([\"provider\", \"provider_user_id\"]);\n\n this.timestamps();\n },\n down() {\n this.dropTableIfExists();\n },\n});\n"],"mappings":";;;;AAGA,MAAa,2BAA2B,QAAQ,iBAAiB;CAC/D,MAAM;CACN,KAAK;EACH,KAAK,uBAAuB;EAE5B,KAAK,YAAY;EAEjB,KAAK,OAAO,YAAY,EAAE;EAC1B,KAAK,OAAO,oBAAoB,GAAG;EACnC,KAAK,UAAU,SAAS,CAAC,CAAC,MAAM;EAChC,KAAK,OAAO,aAAa,EAAE,CAAC,CAAC,SAAS;EACtC,KAAK,OAAO,SAAS,GAAG,CAAC,CAAC,SAAS;EAGnC,KAAK,OAAO,CAAC,YAAY,kBAAkB,CAAC;EAE5C,KAAK,WAAW;CAClB;CACA,OAAO;EACL,KAAK,kBAAkB;CACzB;AACF,CAAC"}
@@ -0,0 +1,75 @@
1
+ import { Auth } from "../auth.model.mjs";
2
+ import { Model } from "@warlock.js/cascade";
3
+
4
+ //#region ../auth/src/models/provider-account/provider-account.model.d.ts
5
+ /** Seal schema for a provider link. Exported so an override can extend it. */
6
+ declare const providerAccountSchema: import("@warlock.js/seal").ObjectValidator<{
7
+ provider: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
8
+ provider_user_id: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
9
+ user_id: import("@warlock.js/seal").ScalarValidator & import("@warlock.js/seal").StandardSchemaV1<string | number | boolean, string | number | boolean>;
10
+ user_type: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
11
+ email: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string> & {
12
+ isOptional: true;
13
+ };
14
+ }> & import("@warlock.js/seal").StandardSchemaV1<import("@warlock.js/seal").InferInputObjectShape<{
15
+ provider: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
16
+ provider_user_id: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
17
+ user_id: import("@warlock.js/seal").ScalarValidator & import("@warlock.js/seal").StandardSchemaV1<string | number | boolean, string | number | boolean>;
18
+ user_type: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
19
+ email: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string> & {
20
+ isOptional: true;
21
+ };
22
+ }>, import("@warlock.js/seal").InferInputObjectShape<{
23
+ provider: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
24
+ provider_user_id: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
25
+ user_id: import("@warlock.js/seal").ScalarValidator & import("@warlock.js/seal").StandardSchemaV1<string | number | boolean, string | number | boolean>;
26
+ user_type: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
27
+ email: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string> & {
28
+ isOptional: true;
29
+ };
30
+ }>>;
31
+ /**
32
+ * Links a provider identity (`provider` + the provider's stable user id) to
33
+ * an app user. Created the first time a VERIFIED provider email is matched or
34
+ * a user is created for it; afterwards the link alone resolves the user, so a
35
+ * later email change at the provider cannot move the login to another account.
36
+ */
37
+ declare class ProviderAccount extends Model {
38
+ static table: string;
39
+ static schema: import("@warlock.js/seal").ObjectValidator<{
40
+ provider: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
41
+ provider_user_id: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
42
+ user_id: import("@warlock.js/seal").ScalarValidator & import("@warlock.js/seal").StandardSchemaV1<string | number | boolean, string | number | boolean>;
43
+ user_type: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
44
+ email: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string> & {
45
+ isOptional: true;
46
+ };
47
+ }> & import("@warlock.js/seal").StandardSchemaV1<import("@warlock.js/seal").InferInputObjectShape<{
48
+ provider: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
49
+ provider_user_id: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
50
+ user_id: import("@warlock.js/seal").ScalarValidator & import("@warlock.js/seal").StandardSchemaV1<string | number | boolean, string | number | boolean>;
51
+ user_type: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
52
+ email: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string> & {
53
+ isOptional: true;
54
+ };
55
+ }>, import("@warlock.js/seal").InferInputObjectShape<{
56
+ provider: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
57
+ provider_user_id: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
58
+ user_id: import("@warlock.js/seal").ScalarValidator & import("@warlock.js/seal").StandardSchemaV1<string | number | boolean, string | number | boolean>;
59
+ user_type: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string>;
60
+ email: import("@warlock.js/seal").StringValidator & import("@warlock.js/seal").StandardSchemaV1<string, string> & {
61
+ isOptional: true;
62
+ };
63
+ }>>;
64
+ /** The linked user's id. */
65
+ get userId(): any;
66
+ /** The linked user's type slug. */
67
+ get userType(): string;
68
+ /** Find the link for a provider identity. */
69
+ static findLink(provider: string, providerUserId: string): Promise<ProviderAccount | null>;
70
+ /** Link a provider identity to a user. */
71
+ static link(provider: string, providerUserId: string, user: Auth, email?: string): Promise<ProviderAccount>;
72
+ }
73
+ //#endregion
74
+ export { ProviderAccount, providerAccountSchema };
75
+ //# sourceMappingURL=provider-account.model.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-account.model.d.mts","names":[],"sources":["../../../../../../../../auth/src/models/provider-account/provider-account.model.ts"],"mappings":";;;;;cAKa,qBAAA,6BAAqB,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAcrB,eAAA,SAAwB,KAAA;EAAA,OACrB,KAAA;EAAA,OAEA,MAAA,6BAAM,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;MAGT,MAAA;EANgB;EAAA,IAWhB,QAAA;EAQA;EAAA,OAHG,QAAA,CACZ,QAAA,UACA,cAAA,WACC,OAAA,CAAQ,eAAA;EAKwD;EAAA,OAArD,IAAA,CAAK,QAAA,UAAkB,cAAA,UAAwB,IAAA,EAAM,IAAA,EAAM,KAAA,YAAc,OAAA,CAAA,eAAA;AAAA"}
@@ -0,0 +1,55 @@
1
+ import { Model } from "@warlock.js/cascade";
2
+ import { v } from "@warlock.js/seal";
3
+
4
+ //#region ../auth/src/models/provider-account/provider-account.model.ts
5
+ /** Seal schema for a provider link. Exported so an override can extend it. */
6
+ const providerAccountSchema = v.object({
7
+ provider: v.string().required(),
8
+ provider_user_id: v.string().required(),
9
+ user_id: v.scalar().required(),
10
+ user_type: v.string().required(),
11
+ email: v.string().optional()
12
+ });
13
+ /**
14
+ * Links a provider identity (`provider` + the provider's stable user id) to
15
+ * an app user. Created the first time a VERIFIED provider email is matched or
16
+ * a user is created for it; afterwards the link alone resolves the user, so a
17
+ * later email change at the provider cannot move the login to another account.
18
+ */
19
+ var ProviderAccount = class extends Model {
20
+ static {
21
+ this.table = "provider_accounts";
22
+ }
23
+ static {
24
+ this.schema = providerAccountSchema;
25
+ }
26
+ /** The linked user's id. */
27
+ get userId() {
28
+ return this.get("user_id");
29
+ }
30
+ /** The linked user's type slug. */
31
+ get userType() {
32
+ return this.get("user_type");
33
+ }
34
+ /** Find the link for a provider identity. */
35
+ static findLink(provider, providerUserId) {
36
+ return this.first({
37
+ provider,
38
+ provider_user_id: providerUserId
39
+ });
40
+ }
41
+ /** Link a provider identity to a user. */
42
+ static link(provider, providerUserId, user, email) {
43
+ return this.create({
44
+ provider,
45
+ provider_user_id: providerUserId,
46
+ user_id: user.id,
47
+ user_type: user.userType,
48
+ ...email ? { email } : {}
49
+ });
50
+ }
51
+ };
52
+
53
+ //#endregion
54
+ export { ProviderAccount, providerAccountSchema };
55
+ //# sourceMappingURL=provider-account.model.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider-account.model.mjs","names":[],"sources":["../../../../../../../../auth/src/models/provider-account/provider-account.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\nimport { v } from \"@warlock.js/seal\";\nimport type { Auth } from \"../auth.model\";\n\n/** Seal schema for a provider link. Exported so an override can extend it. */\nexport const providerAccountSchema = v.object({\n provider: v.string().required(),\n provider_user_id: v.string().required(),\n user_id: v.scalar().required(),\n user_type: v.string().required(),\n email: v.string().optional(),\n});\n\n/**\n * Links a provider identity (`provider` + the provider's stable user id) to\n * an app user. Created the first time a VERIFIED provider email is matched or\n * a user is created for it; afterwards the link alone resolves the user, so a\n * later email change at the provider cannot move the login to another account.\n */\nexport class ProviderAccount extends Model {\n public static table = \"provider_accounts\";\n\n public static schema = providerAccountSchema;\n\n /** The linked user's id. */\n public get userId() {\n return this.get(\"user_id\");\n }\n\n /** The linked user's type slug. */\n public get userType(): string {\n return this.get(\"user_type\");\n }\n\n /** Find the link for a provider identity. */\n public static findLink(\n provider: string,\n providerUserId: string,\n ): Promise<ProviderAccount | null> {\n return this.first({ provider, provider_user_id: providerUserId });\n }\n\n /** Link a provider identity to a user. */\n public static link(provider: string, providerUserId: string, user: Auth, email?: string) {\n return this.create({\n provider,\n provider_user_id: providerUserId,\n user_id: user.id,\n user_type: user.userType,\n ...(email ? { email } : {}),\n });\n }\n}\n"],"mappings":";;;;;AAKA,MAAa,wBAAwB,EAAE,OAAO;CAC5C,UAAU,EAAE,OAAO,CAAC,CAAC,SAAS;CAC9B,kBAAkB,EAAE,OAAO,CAAC,CAAC,SAAS;CACtC,SAAS,EAAE,OAAO,CAAC,CAAC,SAAS;CAC7B,WAAW,EAAE,OAAO,CAAC,CAAC,SAAS;CAC/B,OAAO,EAAE,OAAO,CAAC,CAAC,SAAS;AAC7B,CAAC;;;;;;;AAQD,IAAa,kBAAb,cAAqC,MAAM;;eACnB;;;gBAEC;;;CAGvB,IAAW,SAAS;EAClB,OAAO,KAAK,IAAI,SAAS;CAC3B;;CAGA,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;CAGA,OAAc,SACZ,UACA,gBACiC;EACjC,OAAO,KAAK,MAAM;GAAE;GAAU,kBAAkB;EAAe,CAAC;CAClE;;CAGA,OAAc,KAAK,UAAkB,gBAAwB,MAAY,OAAgB;EACvF,OAAO,KAAK,OAAO;GACjB;GACA,kBAAkB;GAClB,SAAS,KAAK;GACd,WAAW,KAAK;GAChB,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;EAC3B,CAAC;CACH;AACF"}
@@ -139,6 +139,13 @@ declare class RefreshToken extends Model {
139
139
  isOptional: true;
140
140
  };
141
141
  }>>;
142
+ /**
143
+ * Permanent regardless of the data source default — Mongo's driver default
144
+ * is `"trash"`, which would copy live credential material (the JWT itself)
145
+ * into `refresh_tokensTrash` on every `destroy()` (expiry purge,
146
+ * never-expiring purge). A purged refresh token must not survive anywhere.
147
+ */
148
+ static deleteStrategy: "permanent";
142
149
  /** Token family this row belongs to (rotation / replay grouping). */
143
150
  get familyId(): string;
144
151
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"refresh-token.model.d.mts","names":[],"sources":["../../../../../../../../auth/src/models/refresh-token/refresh-token.model.ts"],"mappings":";;;;;;;AAkBA;;;;;;;;;;cAAa,kBAAA,6BAAkB,eAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAcnB,wBAAA;EACV,QAAA;EACA,SAAA;EACA,UAAA,GAAa,UAAU;AAAA;;;;;;;;;;;cAaZ,YAAA,SAAqB,KAAA;EAAA,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Q,YAAA;;;;;;;SAgBxB,iBAAA,IAAqB,OAAA,CAAQ,YAAA;;;;;;;;;;SAe7B,kBAAA,IAAsB,OAAA,CAAQ,YAAA;AAAA"}
@@ -42,6 +42,9 @@ var RefreshToken = class extends Model {
42
42
  static {
43
43
  this.schema = refreshTokenSchema;
44
44
  }
45
+ static {
46
+ this.deleteStrategy = "permanent";
47
+ }
45
48
  /** Token family this row belongs to (rotation / replay grouping). */
46
49
  get familyId() {
47
50
  return this.get("family_id");
@@ -1 +1 @@
1
- {"version":3,"file":"refresh-token.model.mjs","names":[],"sources":["../../../../../../../../auth/src/models/refresh-token/refresh-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\r\nimport { v } from \"@warlock.js/seal\";\r\nimport type { DeviceInfo } from \"../../contracts/types\";\r\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\r\nimport type { Auth } from \"../auth.model\";\r\n\r\n/**\r\n * Seal schema for the persisted refresh-token record. Exported so an override\r\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\r\n * base shape:\r\n *\r\n * @example\r\n * export class AppRefreshToken extends RefreshToken {\r\n * public static schema = refreshTokenSchema.extend({\r\n * organization_id: v.string().required(),\r\n * });\r\n * }\r\n */\r\nexport const refreshTokenSchema = v.object({\r\n token: v.string().required(),\r\n user_id: v.scalar().required(),\r\n user_type: v.string().required(),\r\n family_id: v.string().required(),\r\n expires_at: v.date().required(),\r\n last_used_at: v.date().default(() => new Date()),\r\n revoked_at: v.date().optional(),\r\n device_info: v.record(v.any()).optional(),\r\n});\r\n\r\n/**\r\n * Extra attributes captured when a refresh token is issued.\r\n */\r\nexport type RefreshTokenIssueOptions = {\r\n familyId: string;\r\n expiresAt: string;\r\n deviceInfo?: DeviceInfo;\r\n};\r\n\r\n/**\r\n * Persisted refresh-token record + the data layer for refresh tokens.\r\n *\r\n * **Role.** Owns every refresh-token read, write, and lifecycle transition.\r\n * The auth service drives refresh-token state exclusively through this model's\r\n * named statics and instance methods, so it never hard-codes a column name —\r\n * which is what makes a snake/camel mismatch (the historical `userId` bug)\r\n * structurally impossible and lets an override rename or add columns by\r\n * extending this class and registering it under `config.auth.refreshToken.model`.\r\n */\r\nexport class RefreshToken extends Model {\r\n public static table = \"refresh_tokens\";\r\n\r\n public static schema = refreshTokenSchema;\r\n\r\n /** Token family this row belongs to (rotation / replay grouping). */\r\n public get familyId(): string {\r\n return this.get(\"family_id\");\r\n }\r\n\r\n /**\r\n * Whether the token's `expires_at` is in the past.\r\n *\r\n * **Fails closed as of 4.12.0**: a missing or unparseable `expires_at` now\r\n * counts as expired. It previously answered `false` for both — \"no expiry\r\n * recorded ⇒ never expires\" — which handed an unlimited life to precisely the\r\n * malformed rows, including the `Invalid Date` a pre-4.12.0 unparseable\r\n * `expiresIn` could write. `expires_at` is `required` in the schema, so a row\r\n * that cannot say when it dies is malformed, not immortal.\r\n */\r\n public get isExpired(): boolean {\r\n const expiresAt = this.get(\"expires_at\");\r\n\r\n if (!isUsableExpiry(expiresAt)) return true;\r\n\r\n return new Date().getTime() > new Date(expiresAt).getTime();\r\n }\r\n\r\n /**\r\n * Whether nothing can ever retire this row — an unusable `expires_at`, or a\r\n * token carrying no `exp` claim. See {@link isNeverExpiring}.\r\n */\r\n public get neverExpires(): boolean {\r\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\r\n }\r\n\r\n /** Whether the token has been revoked. */\r\n public get isRevoked(): boolean {\r\n return !!this.get(\"revoked_at\");\r\n }\r\n\r\n /** Whether the token is still usable (not expired and not revoked). */\r\n public get isValid(): boolean {\r\n return !this.isExpired && !this.isRevoked;\r\n }\r\n\r\n /**\r\n * Unconditionally stamp `revoked_at` on this token.\r\n */\r\n public async revoke(): Promise<this> {\r\n return this.merge({ revoked_at: new Date() }).save();\r\n }\r\n\r\n /**\r\n * Atomically revoke this token ONLY if it is still active. Resolves to `true`\r\n * when this call performed the revoke, `false` when a concurrent request had\r\n * already revoked it — the win/lose signal that powers rotation replay\r\n * detection. Uses a conditional UPDATE so two concurrent rotations of the\r\n * same token can never both succeed.\r\n */\r\n public async revokeIfActive(): Promise<boolean> {\r\n const modelClass = this.constructor as typeof RefreshToken;\r\n\r\n const revokedCount = await modelClass.atomic(\r\n { id: this.id, revoked_at: null },\r\n { $set: { revoked_at: new Date() } },\r\n );\r\n\r\n return revokedCount > 0;\r\n }\r\n\r\n /**\r\n * Touch `last_used_at` without revoking — the non-rotating refresh path.\r\n */\r\n public async markAsUsed(): Promise<void> {\r\n await this.merge({ last_used_at: new Date() }).save();\r\n }\r\n\r\n /**\r\n * Persist a freshly-signed refresh token for the user.\r\n */\r\n public static issue(user: Auth, token: string, options: RefreshTokenIssueOptions) {\r\n return this.create({\r\n token,\r\n user_id: user.id,\r\n user_type: user.userType,\r\n family_id: options.familyId,\r\n expires_at: options.expiresAt,\r\n device_info: options.deviceInfo\r\n ? {\r\n userAgent: options.deviceInfo.userAgent,\r\n ip: options.deviceInfo.ip,\r\n deviceId: options.deviceInfo.deviceId,\r\n }\r\n : undefined,\r\n });\r\n }\r\n\r\n /**\r\n * Find a refresh-token row by its raw token string.\r\n */\r\n public static findByToken(token: string): Promise<RefreshToken | null> {\r\n return this.first({ token });\r\n }\r\n\r\n /**\r\n * Find a refresh token scoped to a user — used by logout so a caller can only\r\n * revoke a token that actually belongs to them.\r\n */\r\n public static findForUser(user: Auth, token: string): Promise<RefreshToken | null> {\r\n return this.first({ token, user_id: user.id });\r\n }\r\n\r\n /**\r\n * Delete a specific refresh token belonging to the user.\r\n */\r\n public static deleteForUser(user: Auth, token: string) {\r\n return this.delete({ token, user_id: user.id });\r\n }\r\n\r\n /**\r\n * Active, unexpired sessions for the user, newest first.\r\n */\r\n public static activeFor(user: Auth): Promise<RefreshToken[]> {\r\n return this.query()\r\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\r\n .where(\"expires_at\", \">\", new Date())\r\n .orderBy(\"created_at\", \"desc\")\r\n .get();\r\n }\r\n\r\n /**\r\n * Revoke every still-active refresh token for the user, returning the rows\r\n * that were revoked so the caller can emit a per-token event for each.\r\n *\r\n * Rows are fetched BEFORE they are revoked: a bulk `findAndUpdate` keyed on\r\n * `revoked_at: null` would re-query the same predicate after the update and\r\n * match nothing, returning an empty set.\r\n */\r\n public static async revokeAllFor(user: Auth): Promise<RefreshToken[]> {\r\n const tokens = await this.query()\r\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\r\n .get();\r\n\r\n for (const token of tokens) {\r\n await token.revoke();\r\n }\r\n\r\n return tokens;\r\n }\r\n\r\n /**\r\n * Revoke every still-active token in a family (rotation breach containment),\r\n * returning the revoked rows (fetched before revocation — see `revokeAllFor`).\r\n */\r\n public static async revokeFamily(familyId: string): Promise<RefreshToken[]> {\r\n const tokens = await this.query().where({ family_id: familyId, revoked_at: null }).get();\r\n\r\n for (const token of tokens) {\r\n await token.revoke();\r\n }\r\n\r\n return tokens;\r\n }\r\n\r\n /**\r\n * Revoke the oldest active tokens so at most `max - 1` remain — making room\r\n * for the about-to-be-issued one. Bounded by `max`, so the per-row loop is\r\n * small.\r\n */\r\n public static async enforceMax(user: Auth, max: number): Promise<void> {\r\n const activeTokens = await this.query()\r\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\r\n .orderBy(\"created_at\", \"asc\")\r\n .get();\r\n\r\n if (activeTokens.length < max) return;\r\n\r\n const tokensToRevoke = activeTokens.slice(0, activeTokens.length - max + 1);\r\n\r\n for (const token of tokensToRevoke) {\r\n await token.revoke();\r\n }\r\n }\r\n\r\n /**\r\n * Hard-delete every expired refresh token, returning the deleted rows so the\r\n * caller can emit a per-token event. Runs from the `auth.cleanup` CLI command\r\n * (a cold batch path).\r\n */\r\n public static async purgeExpired(): Promise<RefreshToken[]> {\r\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\r\n\r\n for (const token of expiredTokens) {\r\n await token.destroy();\r\n }\r\n\r\n return expiredTokens;\r\n }\r\n\r\n /**\r\n * Every row that can never retire itself — see {@link neverExpires}. A full\r\n * scan filtered in memory, for the reason given on\r\n * {@link AccessToken.findNeverExpiring}: neither an `Invalid Date` nor a\r\n * missing `exp` claim is expressible as a `where`.\r\n */\r\n public static async findNeverExpiring(): Promise<RefreshToken[]> {\r\n const tokens = await this.query().get();\r\n\r\n return tokens.filter((token: RefreshToken) => token.neverExpires);\r\n }\r\n\r\n /**\r\n * Hard-delete every never-expiring row, returning the rows removed.\r\n *\r\n * Deleted rather than `revoked_at`-stamped: a revoked row is still a row this\r\n * table has to carry, and one of the two shapes being removed is a row whose\r\n * date column cannot be compared at all — leaving it in place keeps a\r\n * permanently unpurgeable record. Rotation replay-detection is unaffected;\r\n * these rows can no longer be presented successfully either way.\r\n */\r\n public static async purgeNeverExpiring(): Promise<RefreshToken[]> {\r\n const tokens = await this.findNeverExpiring();\r\n\r\n for (const token of tokens) {\r\n await token.destroy();\r\n }\r\n\r\n return tokens;\r\n }\r\n}\r\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;CAC9B,aAAa,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,CAAC,SAAS;AAC1C,CAAC;;;;;;;;;;;AAqBD,IAAa,eAAb,cAAkC,MAAM;;eAChB;;;gBAEC;;;CAGvB,IAAW,WAAmB;EAC5B,OAAO,KAAK,IAAI,WAAW;CAC7B;;;;;;;;;;;CAYA,IAAW,YAAqB;EAC9B,MAAM,YAAY,KAAK,IAAI,YAA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I,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":["../../../../../../../../auth/src/models/refresh-token/refresh-token.model.ts"],"sourcesContent":["import { Model } from \"@warlock.js/cascade\";\r\nimport { v } from \"@warlock.js/seal\";\r\nimport type { DeviceInfo } from \"../../contracts/types\";\r\nimport { isNeverExpiring, isUsableExpiry } from \"../../utils/token-expiry\";\r\nimport type { Auth } from \"../auth.model\";\r\n\r\n/**\r\n * Seal schema for the persisted refresh-token record. Exported so an override\r\n * can spread it and add columns (e.g. a tenant key) without re-declaring the\r\n * base shape:\r\n *\r\n * @example\r\n * export class AppRefreshToken extends RefreshToken {\r\n * public static schema = refreshTokenSchema.extend({\r\n * organization_id: v.string().required(),\r\n * });\r\n * }\r\n */\r\nexport const refreshTokenSchema = v.object({\r\n token: v.string().required(),\r\n user_id: v.scalar().required(),\r\n user_type: v.string().required(),\r\n family_id: v.string().required(),\r\n expires_at: v.date().required(),\r\n last_used_at: v.date().default(() => new Date()),\r\n revoked_at: v.date().optional(),\r\n device_info: v.record(v.any()).optional(),\r\n});\r\n\r\n/**\r\n * Extra attributes captured when a refresh token is issued.\r\n */\r\nexport type RefreshTokenIssueOptions = {\r\n familyId: string;\r\n expiresAt: string;\r\n deviceInfo?: DeviceInfo;\r\n};\r\n\r\n/**\r\n * Persisted refresh-token record + the data layer for refresh tokens.\r\n *\r\n * **Role.** Owns every refresh-token read, write, and lifecycle transition.\r\n * The auth service drives refresh-token state exclusively through this model's\r\n * named statics and instance methods, so it never hard-codes a column name —\r\n * which is what makes a snake/camel mismatch (the historical `userId` bug)\r\n * structurally impossible and lets an override rename or add columns by\r\n * extending this class and registering it under `config.auth.refreshToken.model`.\r\n */\r\nexport class RefreshToken extends Model {\r\n public static table = \"refresh_tokens\";\r\n\r\n public static schema = refreshTokenSchema;\r\n\r\n /**\r\n * Permanent regardless of the data source default — Mongo's driver default\r\n * is `\"trash\"`, which would copy live credential material (the JWT itself)\r\n * into `refresh_tokensTrash` on every `destroy()` (expiry purge,\r\n * never-expiring purge). A purged refresh token must not survive anywhere.\r\n */\r\n public static deleteStrategy = \"permanent\" as const;\r\n\r\n /** Token family this row belongs to (rotation / replay grouping). */\r\n public get familyId(): string {\r\n return this.get(\"family_id\");\r\n }\r\n\r\n /**\r\n * Whether the token's `expires_at` is in the past.\r\n *\r\n * **Fails closed as of 4.12.0**: a missing or unparseable `expires_at` now\r\n * counts as expired. It previously answered `false` for both — \"no expiry\r\n * recorded ⇒ never expires\" — which handed an unlimited life to precisely the\r\n * malformed rows, including the `Invalid Date` a pre-4.12.0 unparseable\r\n * `expiresIn` could write. `expires_at` is `required` in the schema, so a row\r\n * that cannot say when it dies is malformed, not immortal.\r\n */\r\n public get isExpired(): boolean {\r\n const expiresAt = this.get(\"expires_at\");\r\n\r\n if (!isUsableExpiry(expiresAt)) return true;\r\n\r\n return new Date().getTime() > new Date(expiresAt).getTime();\r\n }\r\n\r\n /**\r\n * Whether nothing can ever retire this row — an unusable `expires_at`, or a\r\n * token carrying no `exp` claim. See {@link isNeverExpiring}.\r\n */\r\n public get neverExpires(): boolean {\r\n return isNeverExpiring(this.get(\"token\"), this.get(\"expires_at\"));\r\n }\r\n\r\n /** Whether the token has been revoked. */\r\n public get isRevoked(): boolean {\r\n return !!this.get(\"revoked_at\");\r\n }\r\n\r\n /** Whether the token is still usable (not expired and not revoked). */\r\n public get isValid(): boolean {\r\n return !this.isExpired && !this.isRevoked;\r\n }\r\n\r\n /**\r\n * Unconditionally stamp `revoked_at` on this token.\r\n */\r\n public async revoke(): Promise<this> {\r\n return this.merge({ revoked_at: new Date() }).save();\r\n }\r\n\r\n /**\r\n * Atomically revoke this token ONLY if it is still active. Resolves to `true`\r\n * when this call performed the revoke, `false` when a concurrent request had\r\n * already revoked it — the win/lose signal that powers rotation replay\r\n * detection. Uses a conditional UPDATE so two concurrent rotations of the\r\n * same token can never both succeed.\r\n */\r\n public async revokeIfActive(): Promise<boolean> {\r\n const modelClass = this.constructor as typeof RefreshToken;\r\n\r\n const revokedCount = await modelClass.atomic(\r\n { id: this.id, revoked_at: null },\r\n { $set: { revoked_at: new Date() } },\r\n );\r\n\r\n return revokedCount > 0;\r\n }\r\n\r\n /**\r\n * Touch `last_used_at` without revoking — the non-rotating refresh path.\r\n */\r\n public async markAsUsed(): Promise<void> {\r\n await this.merge({ last_used_at: new Date() }).save();\r\n }\r\n\r\n /**\r\n * Persist a freshly-signed refresh token for the user.\r\n */\r\n public static issue(user: Auth, token: string, options: RefreshTokenIssueOptions) {\r\n return this.create({\r\n token,\r\n user_id: user.id,\r\n user_type: user.userType,\r\n family_id: options.familyId,\r\n expires_at: options.expiresAt,\r\n device_info: options.deviceInfo\r\n ? {\r\n userAgent: options.deviceInfo.userAgent,\r\n ip: options.deviceInfo.ip,\r\n deviceId: options.deviceInfo.deviceId,\r\n }\r\n : undefined,\r\n });\r\n }\r\n\r\n /**\r\n * Find a refresh-token row by its raw token string.\r\n */\r\n public static findByToken(token: string): Promise<RefreshToken | null> {\r\n return this.first({ token });\r\n }\r\n\r\n /**\r\n * Find a refresh token scoped to a user — used by logout so a caller can only\r\n * revoke a token that actually belongs to them.\r\n */\r\n public static findForUser(user: Auth, token: string): Promise<RefreshToken | null> {\r\n return this.first({ token, user_id: user.id });\r\n }\r\n\r\n /**\r\n * Delete a specific refresh token belonging to the user.\r\n */\r\n public static deleteForUser(user: Auth, token: string) {\r\n return this.delete({ token, user_id: user.id });\r\n }\r\n\r\n /**\r\n * Active, unexpired sessions for the user, newest first.\r\n */\r\n public static activeFor(user: Auth): Promise<RefreshToken[]> {\r\n return this.query()\r\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\r\n .where(\"expires_at\", \">\", new Date())\r\n .orderBy(\"created_at\", \"desc\")\r\n .get();\r\n }\r\n\r\n /**\r\n * Revoke every still-active refresh token for the user, returning the rows\r\n * that were revoked so the caller can emit a per-token event for each.\r\n *\r\n * Rows are fetched BEFORE they are revoked: a bulk `findAndUpdate` keyed on\r\n * `revoked_at: null` would re-query the same predicate after the update and\r\n * match nothing, returning an empty set.\r\n */\r\n public static async revokeAllFor(user: Auth): Promise<RefreshToken[]> {\r\n const tokens = await this.query()\r\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\r\n .get();\r\n\r\n for (const token of tokens) {\r\n await token.revoke();\r\n }\r\n\r\n return tokens;\r\n }\r\n\r\n /**\r\n * Revoke every still-active token in a family (rotation breach containment),\r\n * returning the revoked rows (fetched before revocation — see `revokeAllFor`).\r\n */\r\n public static async revokeFamily(familyId: string): Promise<RefreshToken[]> {\r\n const tokens = await this.query().where({ family_id: familyId, revoked_at: null }).get();\r\n\r\n for (const token of tokens) {\r\n await token.revoke();\r\n }\r\n\r\n return tokens;\r\n }\r\n\r\n /**\r\n * Revoke the oldest active tokens so at most `max - 1` remain — making room\r\n * for the about-to-be-issued one. Bounded by `max`, so the per-row loop is\r\n * small.\r\n */\r\n public static async enforceMax(user: Auth, max: number): Promise<void> {\r\n const activeTokens = await this.query()\r\n .where({ user_id: user.id, user_type: user.userType, revoked_at: null })\r\n .orderBy(\"created_at\", \"asc\")\r\n .get();\r\n\r\n if (activeTokens.length < max) return;\r\n\r\n const tokensToRevoke = activeTokens.slice(0, activeTokens.length - max + 1);\r\n\r\n for (const token of tokensToRevoke) {\r\n await token.revoke();\r\n }\r\n }\r\n\r\n /**\r\n * Hard-delete every expired refresh token, returning the deleted rows so the\r\n * caller can emit a per-token event. Runs from the `auth.cleanup` CLI command\r\n * (a cold batch path).\r\n */\r\n public static async purgeExpired(): Promise<RefreshToken[]> {\r\n const expiredTokens = await this.query().where(\"expires_at\", \"<\", new Date()).get();\r\n\r\n for (const token of expiredTokens) {\r\n await token.destroy();\r\n }\r\n\r\n return expiredTokens;\r\n }\r\n\r\n /**\r\n * Every row that can never retire itself — see {@link neverExpires}. A full\r\n * scan filtered in memory, for the reason given on\r\n * {@link AccessToken.findNeverExpiring}: neither an `Invalid Date` nor a\r\n * missing `exp` claim is expressible as a `where`.\r\n */\r\n public static async findNeverExpiring(): Promise<RefreshToken[]> {\r\n const tokens = await this.query().get();\r\n\r\n return tokens.filter((token: RefreshToken) => token.neverExpires);\r\n }\r\n\r\n /**\r\n * Hard-delete every never-expiring row, returning the rows removed.\r\n *\r\n * Deleted rather than `revoked_at`-stamped: a revoked row is still a row this\r\n * table has to carry, and one of the two shapes being removed is a row whose\r\n * date column cannot be compared at all — leaving it in place keeps a\r\n * permanently unpurgeable record. Rotation replay-detection is unaffected;\r\n * these rows can no longer be presented successfully either way.\r\n */\r\n public static async purgeNeverExpiring(): Promise<RefreshToken[]> {\r\n const tokens = await this.findNeverExpiring();\r\n\r\n for (const token of tokens) {\r\n await token.destroy();\r\n }\r\n\r\n return tokens;\r\n }\r\n}\r\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;CAC9B,aAAa,EAAE,OAA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AEP,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"}
@@ -0,0 +1 @@
1
+ import { requestOtp, verifyOtp } from "./otp.mjs";
@@ -0,0 +1,3 @@
1
+ import { requestOtp, verifyOtp } from "./otp.mjs";
2
+
3
+ export { };
@@ -0,0 +1,38 @@
1
+ import { Auth } from "../models/auth.model.mjs";
2
+ import { DeviceInfo, LoginResult } from "../contracts/types.mjs";
3
+ import { ChildModel } from "@warlock.js/cascade";
4
+
5
+ //#region ../auth/src/otp/otp.d.ts
6
+ /**
7
+ * Send a 6-digit login code to the account whose `auth.otp.phoneField`
8
+ * (default `phone`) equals `phone`, through the notifications channel named by
9
+ * `options.channel` / `auth.otp.channel` (default `"sms"`). Auth ships no
10
+ * SMS/WhatsApp driver — the app registers that channel.
11
+ *
12
+ * The code is stored only as a keyed hash in `one_time_tokens` (purpose
13
+ * `otp`), expires after `auth.otp.expiresIn` (default 5m), and replaces any
14
+ * earlier unused code. **Anti-enumeration:** an unknown phone resolves the same
15
+ * way and sends nothing. Throttle the route with `otpRequestThrottleMiddleware()`.
16
+ *
17
+ * @throws AuthProviderSdkMissingError when `@warlock.js/notifications` is not
18
+ * installed and no `auth.otp.send` is configured.
19
+ */
20
+ declare function requestOtp<T extends Auth>(Model: ChildModel<T>, phone: string, options?: {
21
+ channel?: string;
22
+ }): Promise<void>;
23
+ /**
24
+ * Verify a phone login code and log the user in through
25
+ * `authService.completeLogin` — the same outcome as password login.
26
+ *
27
+ * Each check first counts an attempt atomically; once `auth.otp.maxAttempts`
28
+ * (default 5) have been counted the code is invalidated, so it is compared at
29
+ * most that many times even under concurrent guesses. A correct code is
30
+ * consumed single-use. Throttle the route with `otpVerifyThrottleMiddleware()`.
31
+ *
32
+ * @throws InvalidOneTimeTokenError (400, EC008) — the same for an unknown
33
+ * phone, a wrong, expired, used or exhausted code.
34
+ */
35
+ declare function verifyOtp<T extends Auth>(Model: ChildModel<T>, phone: string, code: string, deviceInfo?: DeviceInfo): Promise<LoginResult<T>>;
36
+ //#endregion
37
+ export { requestOtp, verifyOtp };
38
+ //# sourceMappingURL=otp.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"otp.d.mts","names":[],"sources":["../../../../../../../auth/src/otp/otp.ts"],"mappings":";;;;;;;AAuFA;;;;;;;;;;;;iBAAsB,UAAA,WAAqB,IAAA,EACzC,KAAA,EAAO,UAAA,CAAW,CAAA,GAClB,KAAA,UACA,OAAA;EAAW,OAAA;AAAA,IACV,OAAA;;;;;AAAO;AAkCV;;;;;;;iBAAsB,SAAA,WAAoB,IAAA,EACxC,KAAA,EAAO,UAAA,CAAW,CAAA,GAClB,KAAA,UACA,IAAA,UACA,UAAA,GAAa,UAAA,GACZ,OAAA,CAAQ,WAAA,CAAY,CAAA"}
@@ -0,0 +1,105 @@
1
+ import { authConfig } from "../services/auth-config.mjs";
2
+ import { authService } from "../services/auth.service.mjs";
3
+ import { InvalidOneTimeTokenError } from "../errors/invalid-one-time-token.error.mjs";
4
+ import { oneTimeTokenModel } from "../services/one-time-tokens.mjs";
5
+ import { loadOptionalPeer } from "../services/optional-peer.mjs";
6
+ import { safeEqual } from "../utils/safe-equal.mjs";
7
+ import { createHmac, randomBytes, randomInt } from "node:crypto";
8
+
9
+ //#region ../auth/src/otp/otp.ts
10
+ const CODE_PATTERN = /^\d{6}$/;
11
+ /** One error for every rejection: unknown phone, no code, wrong, expired, used, over the cap. */
12
+ function invalidCode() {
13
+ return new InvalidOneTimeTokenError("Invalid or expired code.");
14
+ }
15
+ /**
16
+ * Keyed hash of a code. A plain SHA-256 of a 6-digit code is reversed by
17
+ * trying all million values, so the MAC key (derived from the access-token
18
+ * secret) is what keeps a leaked table useless. `salt` makes each stored
19
+ * value unique.
20
+ */
21
+ function macCode(user, salt, code) {
22
+ return createHmac("sha256", createHmac("sha256", authConfig.accessToken.secret()).update("@warlock.js/auth:otp").digest()).update(`${salt}:${user.userType}:${user.id}:${code}`).digest("base64url");
23
+ }
24
+ /** Stored form: `<salt>.<mac>` — 16 + 1 + 43 chars, inside the 64-char `token_hash` column. */
25
+ function storedCodeHash(user, code) {
26
+ const salt = randomBytes(12).toString("base64url");
27
+ return `${salt}.${macCode(user, salt, code)}`;
28
+ }
29
+ function codeMatches(user, stored, code) {
30
+ const [salt, mac] = stored.split(".");
31
+ return !!salt && !!mac && safeEqual(mac, macCode(user, salt, code));
32
+ }
33
+ /**
34
+ * Resolve how a code is sent: `auth.otp.send`, else the app's notifications
35
+ * channel. Resolved BEFORE the user lookup, so a missing notifications package
36
+ * fails identically for known and unknown phones.
37
+ */
38
+ async function resolveDelivery(channel) {
39
+ const custom = authConfig.otp.send();
40
+ if (custom) return custom;
41
+ const { notify } = await loadOptionalPeer("@warlock.js/notifications", "notifications");
42
+ return (phone, message, channelName) => notify.channel(channelName).send(phone, message);
43
+ }
44
+ /**
45
+ * Send a 6-digit login code to the account whose `auth.otp.phoneField`
46
+ * (default `phone`) equals `phone`, through the notifications channel named by
47
+ * `options.channel` / `auth.otp.channel` (default `"sms"`). Auth ships no
48
+ * SMS/WhatsApp driver — the app registers that channel.
49
+ *
50
+ * The code is stored only as a keyed hash in `one_time_tokens` (purpose
51
+ * `otp`), expires after `auth.otp.expiresIn` (default 5m), and replaces any
52
+ * earlier unused code. **Anti-enumeration:** an unknown phone resolves the same
53
+ * way and sends nothing. Throttle the route with `otpRequestThrottleMiddleware()`.
54
+ *
55
+ * @throws AuthProviderSdkMissingError when `@warlock.js/notifications` is not
56
+ * installed and no `auth.otp.send` is configured.
57
+ */
58
+ async function requestOtp(Model, phone, options = {}) {
59
+ const channel = options.channel ?? authConfig.otp.channel();
60
+ const deliver = await resolveDelivery(channel);
61
+ if (typeof phone !== "string" || phone.length === 0) return;
62
+ const user = await Model.first({ [authConfig.otp.phoneField()]: phone });
63
+ if (!user) return;
64
+ const code = String(randomInt(0, 1e6)).padStart(6, "0");
65
+ const expiresAt = new Date(Date.now() + authConfig.otp.expiresInMs());
66
+ const TokenModel = oneTimeTokenModel();
67
+ await TokenModel.invalidateActiveFor(user, "otp");
68
+ await TokenModel.issue(user, "otp", storedCodeHash(user, code), expiresAt);
69
+ await deliver(phone, {
70
+ body: authConfig.otp.message(code),
71
+ code,
72
+ expiresAt
73
+ }, channel);
74
+ }
75
+ /**
76
+ * Verify a phone login code and log the user in through
77
+ * `authService.completeLogin` — the same outcome as password login.
78
+ *
79
+ * Each check first counts an attempt atomically; once `auth.otp.maxAttempts`
80
+ * (default 5) have been counted the code is invalidated, so it is compared at
81
+ * most that many times even under concurrent guesses. A correct code is
82
+ * consumed single-use. Throttle the route with `otpVerifyThrottleMiddleware()`.
83
+ *
84
+ * @throws InvalidOneTimeTokenError (400, EC008) — the same for an unknown
85
+ * phone, a wrong, expired, used or exhausted code.
86
+ */
87
+ async function verifyOtp(Model, phone, code, deviceInfo) {
88
+ if (typeof phone !== "string" || phone.length === 0) throw invalidCode();
89
+ if (typeof code !== "string" || !CODE_PATTERN.test(code)) throw invalidCode();
90
+ const user = await Model.first({ [authConfig.otp.phoneField()]: phone });
91
+ if (!user) throw invalidCode();
92
+ const row = await oneTimeTokenModel().findActiveFor(user, "otp");
93
+ if (!row || row.isConsumed || row.isExpired) throw invalidCode();
94
+ if (!await row.recordAttempt(authConfig.otp.maxAttempts())) {
95
+ await row.consumeIfActive();
96
+ throw invalidCode();
97
+ }
98
+ if (!codeMatches(user, String(row.get("token_hash") ?? ""), code)) throw invalidCode();
99
+ if (!await row.consumeIfActive()) throw invalidCode();
100
+ return authService.completeLogin(user, deviceInfo);
101
+ }
102
+
103
+ //#endregion
104
+ export { requestOtp, verifyOtp };
105
+ //# sourceMappingURL=otp.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"otp.mjs","names":[],"sources":["../../../../../../../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,yBAA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S,GAAG,GAAG;CAC5D,MAAM,YAAY,IAAI,KAAK,KAAK,IAAI,IAAI,WAAW,IAAI,YAAY,CAAC;CACpE,MAAM,aAAa,kBAAkB;CAErC,MAAM,WAAW,oBAAoB,MAAM,KAAK;CAChD,MAAM,WAAW,MAAM,MAAM,OAAO,eAAe,MAAM,IAAI,GAAG,SAAS;CAIzE,MAAM,QAAQ,OAAO;EAFS,MAAM,WAAW,IAAI,QAAQ,IAAI;EAAG;EAAM;CAE7C,GAAG,OAAO;AACvC;;;;;;;;;;;;;AAcA,eAAsB,UACpB,OACA,OACA,MACA,YACyB;CACzB,IAAI,OAAO,UAAU,YAAY,MAAM,WAAW,GAAG,MAAM,YAAY;CACvE,IAAI,OAAO,SAAS,YAAY,CAAC,aAAa,KAAK,IAAI,GAAG,MAAM,YAAY;CAE5E,MAAM,OAAQ,MAAM,MAAM,MAAM,GAAG,WAAW,IAAI,WAAW,IAAI,MAAM,CAAC;CAExE,IAAI,CAAC,MAAM,MAAM,YAAY;CAE7B,MAAM,MAAM,MAAM,kBAAkB,CAAC,CAAC,cAAc,MAAM,KAAK;CAE/D,IAAI,CAAC,OAAO,IAAI,cAAc,IAAI,WAAW,MAAM,YAAY;CAE/D,IAAI,CAAE,MAAM,IAAI,cAAc,WAAW,IAAI,YAAY,CAAC,GAAI;EAC5D,MAAM,IAAI,gBAAgB;EAE1B,MAAM,YAAY;CACpB;CAEA,IAAI,CAAC,YAAY,MAAM,OAAO,IAAI,IAAI,YAAY,KAAK,EAAE,GAAG,IAAI,GAAG,MAAM,YAAY;CAErF,IAAI,CAAE,MAAM,IAAI,gBAAgB,GAAI,MAAM,YAAY;CAEtD,OAAO,YAAY,cAAc,MAAM,UAAU;AACnD"}
@@ -0,0 +1,3 @@
1
+ import { PasskeyOptionsJSON, PasskeyResponseJSON } from "./simplewebauthn.mjs";
2
+ import { generatePasskeyAuthenticationOptions, verifyPasskeyAuthentication } from "./passkey-authentication.mjs";
3
+ import { generatePasskeyRegistrationOptions, verifyPasskeyRegistration } from "./passkey-registration.mjs";
@@ -0,0 +1,4 @@
1
+ import { generatePasskeyAuthenticationOptions, verifyPasskeyAuthentication } from "./passkey-authentication.mjs";
2
+ import { generatePasskeyRegistrationOptions, verifyPasskeyRegistration } from "./passkey-registration.mjs";
3
+
4
+ export { };
@@ -0,0 +1,33 @@
1
+ import { Auth } from "../models/auth.model.mjs";
2
+ import { DeviceInfo, LoginResult } from "../contracts/types.mjs";
3
+ import { PasskeyOptionsJSON, PasskeyResponseJSON } from "./simplewebauthn.mjs";
4
+ import { Request } from "@warlock.js/core";
5
+
6
+ //#region ../auth/src/passkeys/passkey-authentication.d.ts
7
+ /**
8
+ * Authentication options for a passkey login. No user is identified yet
9
+ * (discoverable credentials), so the stored single-use challenge has no owner;
10
+ * the credential the browser returns decides the user.
11
+ *
12
+ * @example
13
+ * // POST /auth/passkeys/login/options
14
+ * response.success(await generatePasskeyAuthenticationOptions());
15
+ */
16
+ declare function generatePasskeyAuthenticationOptions(): Promise<PasskeyOptionsJSON>;
17
+ /**
18
+ * Verify a passkey assertion and log its owner in through
19
+ * `authService.completeLogin` — the same outcome as password login.
20
+ *
21
+ * Checks, in order: the request `Origin` (CSRF), the single-use challenge
22
+ * (consumed even if what follows fails), the credential is registered, the
23
+ * assertion via `@simplewebauthn/server`, then that the signature counter
24
+ * ADVANCED — a counter that did not move past the stored one (when either is
25
+ * non-zero) means a cloned authenticator and is rejected. The new counter is
26
+ * written with a compare-and-set.
27
+ *
28
+ * @throws InvalidPasskeyError (400, EC011) on any rejection.
29
+ */
30
+ declare function verifyPasskeyAuthentication(request: Request, credential: PasskeyResponseJSON, deviceInfo?: DeviceInfo): Promise<LoginResult<Auth>>;
31
+ //#endregion
32
+ export { generatePasskeyAuthenticationOptions, verifyPasskeyAuthentication };
33
+ //# sourceMappingURL=passkey-authentication.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passkey-authentication.d.mts","names":[],"sources":["../../../../../../../auth/src/passkeys/passkey-authentication.ts"],"mappings":";;;;;;;;AAiDA;;;;AAAwF;AA0BxF;;iBA1BsB,oCAAA,IAAwC,OAAO,CAAC,kBAAA;;;;;;;;;;;;;;iBA0BhD,2BAAA,CACpB,OAAA,EAAS,OAAA,EACT,UAAA,EAAY,mBAAA,EACZ,UAAA,GAAa,UAAA,GACZ,OAAA,CAAQ,WAAA,CAAY,IAAA"}
@@ -0,0 +1,93 @@
1
+ import { authConfig } from "../services/auth-config.mjs";
2
+ import { authService } from "../services/auth.service.mjs";
3
+ import { InvalidPasskeyError } from "../errors/invalid-passkey.error.mjs";
4
+ import { PasskeyCredential } from "../models/passkey-credential/passkey-credential.model.mjs";
5
+ import "../models/passkey-credential/index.mjs";
6
+ import { assertPasskeyOrigin, storePasskeyChallenge, takePasskeyChallenge } from "./passkey-challenges.mjs";
7
+ import { loadSimpleWebAuthn } from "./simplewebauthn.mjs";
8
+ import { config } from "@warlock.js/core";
9
+
10
+ //#region ../auth/src/passkeys/passkey-authentication.ts
11
+ /** A counter that did not advance past the stored one (when either is non-zero): a cloned authenticator. */
12
+ function counterRegressed(stored, presented) {
13
+ if (presented === void 0) return false;
14
+ return (stored > 0 || presented > 0) && !(presented > stored);
15
+ }
16
+ /**
17
+ * The signature counter an assertion CLAIMS (bytes 33–36 of authenticatorData).
18
+ * Unverified — only used to label a rejection the SDK already made.
19
+ */
20
+ function presentedCounter(credential) {
21
+ const encoded = credential.response.authenticatorData;
22
+ if (typeof encoded !== "string") return void 0;
23
+ const authData = Buffer.from(encoded, "base64url");
24
+ return authData.length >= 37 ? authData.readUInt32BE(33) : void 0;
25
+ }
26
+ /**
27
+ * Authentication options for a passkey login. No user is identified yet
28
+ * (discoverable credentials), so the stored single-use challenge has no owner;
29
+ * the credential the browser returns decides the user.
30
+ *
31
+ * @example
32
+ * // POST /auth/passkeys/login/options
33
+ * response.success(await generatePasskeyAuthenticationOptions());
34
+ */
35
+ async function generatePasskeyAuthenticationOptions() {
36
+ const options = await (await loadSimpleWebAuthn()).generateAuthenticationOptions({
37
+ rpID: authConfig.passkeys.settings().rpID,
38
+ userVerification: "preferred"
39
+ });
40
+ await storePasskeyChallenge("passkey-authentication", options.challenge);
41
+ return options;
42
+ }
43
+ /**
44
+ * Verify a passkey assertion and log its owner in through
45
+ * `authService.completeLogin` — the same outcome as password login.
46
+ *
47
+ * Checks, in order: the request `Origin` (CSRF), the single-use challenge
48
+ * (consumed even if what follows fails), the credential is registered, the
49
+ * assertion via `@simplewebauthn/server`, then that the signature counter
50
+ * ADVANCED — a counter that did not move past the stored one (when either is
51
+ * non-zero) means a cloned authenticator and is rejected. The new counter is
52
+ * written with a compare-and-set.
53
+ *
54
+ * @throws InvalidPasskeyError (400, EC011) on any rejection.
55
+ */
56
+ async function verifyPasskeyAuthentication(request, credential, deviceInfo) {
57
+ const webauthn = await loadSimpleWebAuthn();
58
+ const origins = assertPasskeyOrigin(request);
59
+ const { challenge } = await takePasskeyChallenge("passkey-authentication", credential);
60
+ const stored = typeof credential.id === "string" ? await PasskeyCredential.findByCredentialId(credential.id) : null;
61
+ if (!stored) throw new InvalidPasskeyError("unknown-credential");
62
+ let verification;
63
+ try {
64
+ verification = await webauthn.verifyAuthenticationResponse({
65
+ response: credential,
66
+ expectedChallenge: challenge,
67
+ expectedOrigin: origins,
68
+ expectedRPID: authConfig.passkeys.settings().rpID,
69
+ credential: {
70
+ id: stored.credentialId,
71
+ publicKey: new Uint8Array(Buffer.from(String(stored.get("public_key")), "base64url")),
72
+ counter: stored.counter,
73
+ transports: stored.get("transports") ?? void 0
74
+ },
75
+ requireUserVerification: false
76
+ });
77
+ } catch (error) {
78
+ throw new InvalidPasskeyError(counterRegressed(stored.counter, presentedCounter(credential)) ? "counter-regression" : "authentication-verification-failed", error);
79
+ }
80
+ if (!verification.verified) throw new InvalidPasskeyError("authentication-not-verified");
81
+ const previous = stored.counter;
82
+ const next = Number(verification.authenticationInfo.newCounter);
83
+ if (counterRegressed(previous, next)) throw new InvalidPasskeyError("counter-regression");
84
+ if (!await stored.advanceCounter(previous, next)) throw new InvalidPasskeyError("counter-changed-concurrently");
85
+ const UserModel = config.key(`auth.userType.${stored.userType}`);
86
+ const user = UserModel ? await UserModel.find(stored.userId) : null;
87
+ if (!user) throw new InvalidPasskeyError("credential-owner-missing");
88
+ return authService.completeLogin(user, deviceInfo);
89
+ }
90
+
91
+ //#endregion
92
+ export { generatePasskeyAuthenticationOptions, verifyPasskeyAuthentication };
93
+ //# sourceMappingURL=passkey-authentication.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"passkey-authentication.mjs","names":[],"sources":["../../../../../../../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,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;CACpB,CAAC;CAED,MAAM,sBAAsB,0BAA0B,QAAQ,SAAS;CAEvE,OAAO;AACT;;;;;;;;;;;;;;AAeA,eAAsB,4BACpB,SACA,YACA,YAC4B;CAC5B,MAAM,WAAW,MAAM,mBAAmB;CAC1C,MAAM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