@warlock.js/auth 5.24.0 → 5.26.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 (52) hide show
  1. package/CHANGELOG.md +26 -9
  2. package/LICENSE +21 -21
  3. package/esm/contracts/index.d.mts +1 -1
  4. package/esm/contracts/request-locals.d.mts +1 -1
  5. package/esm/contracts/types.d.mts +8 -3
  6. package/esm/contracts/types.d.mts.map +1 -1
  7. package/esm/contracts/types.mjs.map +1 -1
  8. package/esm/index.d.mts +3 -3
  9. package/esm/index.mjs +2 -2
  10. package/esm/middleware/auth.middleware.mjs +1 -1
  11. package/esm/middleware/auth.middleware.mjs.map +1 -1
  12. package/esm/middleware/login-throttle.middleware.mjs.map +1 -1
  13. package/esm/models/access-token/access-token.model.mjs.map +1 -1
  14. package/esm/models/access-token/migration.mjs.map +1 -1
  15. package/esm/models/auth-token-family/auth-token-family.model.d.mts.map +1 -1
  16. package/esm/models/auth-token-family/auth-token-family.model.mjs +5 -0
  17. package/esm/models/auth-token-family/auth-token-family.model.mjs.map +1 -1
  18. package/esm/models/auth.model.mjs.map +1 -1
  19. package/esm/models/refresh-token/migration.mjs.map +1 -1
  20. package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
  21. package/esm/services/auth-config.mjs +3 -1
  22. package/esm/services/auth-config.mjs.map +1 -1
  23. package/esm/services/auth-events.mjs.map +1 -1
  24. package/esm/services/auth.service.d.mts +9 -4
  25. package/esm/services/auth.service.d.mts.map +1 -1
  26. package/esm/services/auth.service.mjs +45 -17
  27. package/esm/services/auth.service.mjs.map +1 -1
  28. package/esm/services/index.d.mts +1 -1
  29. package/esm/services/index.mjs +1 -1
  30. package/esm/services/resolve-request-user.d.mts +3 -2
  31. package/esm/services/resolve-request-user.d.mts.map +1 -1
  32. package/esm/services/resolve-request-user.mjs +8 -2
  33. package/esm/services/resolve-request-user.mjs.map +1 -1
  34. package/esm/session/page-session.d.mts +3 -1
  35. package/esm/session/page-session.d.mts.map +1 -1
  36. package/esm/session/page-session.mjs +2 -1
  37. package/esm/session/page-session.mjs.map +1 -1
  38. package/esm/utils/auth-error-codes.mjs.map +1 -1
  39. package/llms-full.txt +1946 -1927
  40. package/package.json +8 -8
  41. package/skills/auth-basics/SKILL.md +1 -1
  42. package/skills/customize-token-storage/SKILL.md +160 -160
  43. package/skills/customize-user-type/SKILL.md +168 -168
  44. package/skills/handle-login-and-logout/SKILL.md +195 -180
  45. package/skills/login-with-providers/SKILL.md +283 -283
  46. package/skills/manage-tokens/SKILL.md +196 -196
  47. package/skills/overview/SKILL.md +74 -74
  48. package/skills/protect-routes/SKILL.md +299 -299
  49. package/skills/register-user/SKILL.md +147 -147
  50. package/skills/run-auth-commands/SKILL.md +159 -159
  51. package/skills/throttle-login-attempts/SKILL.md +117 -117
  52. package/skills/verify-email-and-reset-password/SKILL.md +137 -137
@@ -1,183 +1,198 @@
1
- ---
2
- name: handle-login-and-logout
3
- description: 'Run the full login flow via authService.login(Model, credentials, deviceInfo?) — verify password, create access + refresh token pair, fire events. Logout via authService.logout(user, accessToken?, refreshToken?) revokes tokens. Triggers: `authService.login`, `authService.logout`, `authService.attemptLogin`, `authService.refreshTokens`, `authService.revokeAllTokens`, `authEvents`; "build a login endpoint", "POST /login controller", "logout from all devices", "verify credentials and issue tokens"; typical import `import { authService, authEvents } from "@warlock.js/auth"`. Skip: token internals — `@warlock.js/auth/manage-tokens/SKILL.md`; sign-up — `@warlock.js/auth/register-user/SKILL.md`; competing libs `passport-local`, `next-auth` credentials.'
4
- ---
5
-
6
- # Login + logout
7
-
8
- `authService` exposes the full flow. Pass the model class so the service knows which user-type to look up.
9
-
10
- ```ts title="src/app/users/models/user/user.model.ts"
11
- import { Auth } from "@warlock.js/auth";
12
- import { RegisterModel } from "@warlock.js/cascade";
13
-
14
- @RegisterModel()
15
- export class User extends Auth {
16
- public static table = "users";
17
-
18
- public get userType(): string {
19
- return "user";
20
- }
21
- }
22
- ```
23
-
24
- ## Login — `authService.login(Model, credentials, deviceInfo?)`
25
-
26
- ```ts
27
- import { authService } from "@warlock.js/auth";
28
- import { type RequestHandler } from "@warlock.js/core";
29
- import { User } from "app/users/models/user/user.model";
30
-
31
- export const loginController: RequestHandler = async ({ request, response }) => {
32
- const result = await authService.login(User, {
33
- email: request.input("email"),
34
- password: request.input("password"),
35
- }, {
36
- userAgent: request.header("user-agent"),
37
- ip: request.ip,
38
- });
39
-
40
- if (!result) {
41
- return response.unauthorized({ error: "Invalid credentials" });
42
- }
43
-
44
- return response.success({
45
- user: result.user,
46
- tokens: result.tokens,
47
- });
48
- };
49
- ```
50
-
51
- The returned shape:
52
-
53
- ```ts
54
- {
55
- user: T, // your User subclass, hydrated
56
- tokens: {
57
- accessToken: { token: string, expiresAt: string },
58
- refreshToken?: { token: string, expiresAt: string }, // omitted if refresh tokens disabled
59
- },
60
- }
61
- ```
62
-
63
- Returns `null` on failure (wrong password, user not found). The service emits `login.attempt` → `login.success` or `login.failed` events as it goes — subscribe via the auth event bus if you need an audit trail.
64
-
65
- ## What `credentials` looks like
66
-
67
- The shape is **arbitrary** — every key except `password` is used as a `where(...)` filter against the model. The password is verified separately via bcrypt.
68
-
69
- ```ts
70
- // Email + password
71
- authService.login(User, { email: "ada@example.com", password: "..." });
72
-
73
- // Username + password
74
- authService.login(User, { username: "ada", password: "..." });
75
-
76
- // Phone-based OTP (where password is the OTP hash)
77
- authService.login(User, { phone: "+1...", password: hashedOTP });
78
- ```
79
-
80
- For lower-level credential verification (just check, don't issue tokens), use `authService.attemptLogin(Model, credentials)` — returns the user or null without creating tokens.
81
-
82
- ## Device info
83
-
84
- The optional `deviceInfo` carries metadata into the refresh token row:
85
-
86
- ```ts
87
- authService.login(User, credentials, {
88
- userAgent: request.header("user-agent"),
89
- ip: request.ip,
90
- deviceId: "...", // your client-side device fingerprint
91
- familyId: "...", // pre-existing family for token rotation, usually omitted
92
- });
93
- ```
94
-
95
- Useful for "show active sessions" UIs — see `authService.getActiveSessions(user)`.
96
-
97
- ## Logout — `authService.logout(user, accessToken?, refreshToken?)`
98
-
99
- ```ts
100
- import { type RequestHandler } from "@warlock.js/core";
101
-
102
- export const logoutController: RequestHandler = async ({ request, response }) => {
103
- await authService.logout(
104
- request.locals.user!,
105
- request.authorizationValue, // access token from the Authorization header
106
- request.input("refreshToken"), // refresh token from the request body
107
- );
108
-
109
- return response.success({ message: "Logged out" });
110
- };
111
- ```
112
-
113
- The contract:
114
- - **Pass the access token** → that specific access-token row is deleted.
115
- - **Pass the refresh token** → that specific refresh-token row is revoked.
116
- - **Omit refresh token** → behavior depends on `config.auth.refreshToken.logoutWithoutToken`:
117
- - `"revoke-all"` (default) — every refresh token for this user is revoked. Fail-safe.
118
- - `"error"` — throws. Force the client to send the refresh token.
119
-
120
- The `revoke-all` default is the right call for most apps. If a client loses track of the refresh token, logout still works and the user has to log in fresh on every device.
121
-
122
- ## Logout-everywhere
123
-
124
- ```ts
125
- await authService.revokeAllTokens(user);
126
- // Revokes every refresh token + deletes every access token for this user.
127
- ```
128
-
129
- Useful for "logout from all devices" buttons. Fires `token.revoked` per token + `logout.all` once.
130
-
131
- ## Refresh tokens — `authService.refreshTokens(refreshTokenString, deviceInfo?)`
132
-
133
- ```ts
134
- import { type RequestHandler } from "@warlock.js/core";
135
-
136
- export const refreshController: RequestHandler = async ({ request, response }) => {
137
- const tokens = await authService.refreshTokens(
138
- request.input("refreshToken"),
139
- { userAgent: request.header("user-agent"), ip: request.ip },
140
- );
141
-
142
- if (!tokens) {
143
- return response.unauthorized({ error: "Invalid refresh token" });
144
- }
145
-
146
- return response.success({ tokens });
147
- };
148
- ```
149
-
150
- Returns a new token pair or `null` (token expired, revoked, or replay-detected). With rotation enabled (default), the old refresh token is consumed; the new pair stays in the same "family." Replay → revoke the whole family. See [`@warlock.js/auth/manage-tokens/SKILL.md`](@warlock.js/auth/manage-tokens/SKILL.md).
151
-
152
- ## Auth events
153
-
154
- `authEvents` is a type-safe event bus (over `@mongez/events`) that fires on every meaningful auth moment. Subscribe with `on` / `subscribe`, unsubscribe with `off` / `unsubscribeAll`:
155
-
156
- ```ts
157
- import { authEvents } from "@warlock.js/auth";
158
-
159
- authEvents.on("login.success", (user, tokens, deviceInfo) => { /* audit */ });
160
- authEvents.on("login.failed", (credentials, reason) => { /* alert on brute force */ });
161
- authEvents.on("logout", (user) => { /* clear server-side session, if any */ });
162
- authEvents.on("token.refreshed", (user, newPair, oldToken) => { /* track rotation */ });
163
- authEvents.on("cleanup.completed", (count) => { /* metrics */ });
164
- ```
165
-
166
- Full event list: `login.attempt`, `login.success`, `login.failed`, `logout`, `logout.all`, `logout.failsafe`, `token.created`, `token.refreshed`, `token.revoked`, `token.expired`, `token.familyRevoked`, `session.created`, `session.destroyed`, `cleanup.completed`.
167
-
168
- ## Things NOT to do
169
-
170
- - Don't `authService.login(User, { password })` without other credentials — the password is the secret; the other fields are the lookup. A login with only a password is a logic bug.
171
- - Don't return the password hash in the response. `static toJsonColumns` on the User model should explicitly exclude it.
172
- - Don't store the refresh token in localStorage. Use an httpOnly secure cookie for refresh tokens; the access token can sit in memory.
173
- - Don't issue a new token pair without revoking the old one when rotation is enabled. `refreshTokens` does this for you — don't bypass it.
174
-
175
- ## See also
176
-
177
- - [`@warlock.js/auth/manage-tokens/SKILL.md`](@warlock.js/auth/manage-tokens/SKILL.md) — token lifecycle, rotation, family revocation
178
- - [`@warlock.js/auth/register-user/SKILL.md`](@warlock.js/auth/register-user/SKILL.md) — sign-up that issues tokens after creation
179
- - [`@warlock.js/auth/protect-routes/SKILL.md`](@warlock.js/auth/protect-routes/SKILL.md) — where the access token gets consumed
1
+ ---
2
+ name: handle-login-and-logout
3
+ description: 'Run the full login flow via authService.login(Model, credentials, deviceInfo?) — verify password, create access + refresh token pair, fire events. Logout via authService.logout(user, accessToken?, refreshToken?) revokes tokens. Triggers: `authService.login`, `authService.logout`, `authService.attemptLogin`, `authService.refreshTokens`, `authService.revokeAllTokens`, `authEvents`; "build a login endpoint", "POST /login controller", "logout from all devices", "verify credentials and issue tokens"; typical import `import { authService, authEvents } from "@warlock.js/auth"`. Skip: token internals — `@warlock.js/auth/manage-tokens/SKILL.md`; sign-up — `@warlock.js/auth/register-user/SKILL.md`; competing libs `passport-local`, `next-auth` credentials.'
4
+ ---
5
+
6
+ # Login + logout
7
+
8
+ `authService` exposes the full flow. Pass the model class so the service knows which user-type to look up.
9
+
10
+ ```ts title="src/app/users/models/user/user.model.ts"
11
+ import { Auth } from "@warlock.js/auth";
12
+ import { RegisterModel } from "@warlock.js/cascade";
13
+
14
+ @RegisterModel()
15
+ export class User extends Auth {
16
+ public static table = "users";
17
+
18
+ public get userType(): string {
19
+ return "user";
20
+ }
21
+ }
22
+ ```
23
+
24
+ ## Login — `authService.login(Model, credentials, deviceInfo?)`
25
+
26
+ ```ts
27
+ import { authService } from "@warlock.js/auth";
28
+ import { type RequestHandler } from "@warlock.js/core";
29
+ import { User } from "app/users/models/user/user.model";
30
+
31
+ export const loginController: RequestHandler = async ({ request, response }) => {
32
+ const result = await authService.login(
33
+ User,
34
+ {
35
+ email: request.input("email"),
36
+ password: request.input("password"),
37
+ },
38
+ {
39
+ userAgent: request.header("user-agent"),
40
+ ip: request.ip,
41
+ },
42
+ );
43
+
44
+ if (!result) {
45
+ return response.unauthorized({ error: "Invalid credentials" });
46
+ }
47
+
48
+ return response.success({
49
+ user: result.user,
50
+ tokens: result.tokens,
51
+ });
52
+ };
53
+ ```
54
+
55
+ The returned shape:
56
+
57
+ ```ts
58
+ {
59
+ user: T, // your User subclass, hydrated
60
+ tokens: {
61
+ accessToken: { token: string, expiresAt: string },
62
+ refreshToken?: { token: string, expiresAt: string }, // omitted if refresh tokens disabled
63
+ },
64
+ }
65
+ ```
66
+
67
+ Returns `null` on failure (wrong password, user not found). The service emits `login.attempt` → `login.success` or `login.failed` events as it goes — subscribe via the auth event bus if you need an audit trail.
68
+
69
+ ## What `credentials` looks like
70
+
71
+ The shape is **arbitrary** — every key except `password` is used as a `where(...)` filter against the model. The password is verified separately via bcrypt.
72
+
73
+ ```ts
74
+ // Email + password
75
+ authService.login(User, { email: "ada@example.com", password: "..." });
76
+
77
+ // Username + password
78
+ authService.login(User, { username: "ada", password: "..." });
79
+
80
+ // Phone-based OTP (where password is the OTP hash)
81
+ authService.login(User, { phone: "+1...", password: hashedOTP });
82
+ ```
83
+
84
+ For lower-level credential verification (just check, don't issue tokens), use `authService.attemptLogin(Model, credentials)` — returns the user or null without creating tokens.
85
+
86
+ ## Device info
87
+
88
+ The optional `deviceInfo` carries metadata into the refresh token row:
89
+
90
+ ```ts
91
+ authService.login(User, credentials, {
92
+ userAgent: request.header("user-agent"),
93
+ ip: request.ip,
94
+ deviceId: "...", // your client-side device fingerprint
95
+ familyId: "...", // pre-existing family for token rotation, usually omitted
96
+ });
97
+ ```
98
+
99
+ Useful for "show active sessions" UIs — see `authService.getActiveSessions(user)`.
100
+
101
+ ## Logout — `authService.logout(user, accessToken?, refreshToken?)`
102
+
103
+ ```ts
104
+ import { type RequestHandler } from "@warlock.js/core";
105
+
106
+ export const logoutController: RequestHandler = async ({ request, response }) => {
107
+ await authService.logout(
108
+ request.locals.user!,
109
+ request.authorizationValue, // access token from the Authorization header
110
+ request.input("refreshToken"), // refresh token from the request body
111
+ );
112
+
113
+ return response.success({ message: "Logged out" });
114
+ };
115
+ ```
116
+
117
+ The contract:
118
+
119
+ - **Pass the access token** → that specific access-token row is deleted.
120
+ - **Pass the refresh token** → that specific refresh-token row is revoked.
121
+ - **Omit refresh token** → behavior depends on `config.auth.refreshToken.logoutWithoutToken`:
122
+ - `"revoke-all"` (default) — every refresh token for this user is revoked. Fail-safe.
123
+ - `"error"` — throws. Force the client to send the refresh token.
124
+
125
+ The `revoke-all` default is the right call for most apps. If a client loses track of the refresh token, logout still works and the user has to log in fresh on every device.
126
+
127
+ ## Logout-everywhere
128
+
129
+ ```ts
130
+ await authService.revokeAllTokens(user);
131
+ // Revokes every refresh token + deletes every access token for this user.
132
+ ```
133
+
134
+ Useful for "logout from all devices" buttons. Fires `token.revoked` per token + `logout.all` once.
135
+
136
+ ## Refresh tokens — `authService.refreshTokens(refreshTokenString, deviceInfo?)`
137
+
138
+ ```ts
139
+ import { type RequestHandler } from "@warlock.js/core";
140
+
141
+ export const refreshController: RequestHandler = async ({ request, response }) => {
142
+ const tokens = await authService.refreshTokens(request.input("refreshToken"), {
143
+ userAgent: request.header("user-agent"),
144
+ ip: request.ip,
145
+ });
146
+
147
+ if (!tokens) {
148
+ return response.unauthorized({ error: "Invalid refresh token" });
149
+ }
150
+
151
+ return response.success({ tokens });
152
+ };
153
+ ```
154
+
155
+ Returns a new token pair or `null` (token expired, revoked, or replay-detected). With rotation enabled (default), the old refresh token is consumed; the new pair stays in the same "family." Replay → revoke the whole family. See [`@warlock.js/auth/manage-tokens/SKILL.md`](@warlock.js/auth/manage-tokens/SKILL.md).
156
+
157
+ ## Auth events
158
+
159
+ `authEvents` is a type-safe event bus (over `@mongez/events`) that fires on every meaningful auth moment. Subscribe with `on` / `subscribe`, unsubscribe with `off` / `unsubscribeAll`:
160
+
161
+ ```ts
162
+ import { authEvents } from "@warlock.js/auth";
163
+
164
+ authEvents.on("login.success", (user, tokens, deviceInfo) => {
165
+ /* audit */
166
+ });
167
+ authEvents.on("login.failed", (credentials, reason) => {
168
+ /* alert on brute force */
169
+ });
170
+ authEvents.on("logout", (user) => {
171
+ /* clear server-side session, if any */
172
+ });
173
+ authEvents.on("token.refreshed", (user, newPair, oldToken) => {
174
+ /* track rotation */
175
+ });
176
+ authEvents.on("cleanup.completed", (count) => {
177
+ /* metrics */
178
+ });
179
+ ```
180
+
181
+ Full event list: `login.attempt`, `login.success`, `login.failed`, `logout`, `logout.all`, `logout.failsafe`, `token.created`, `token.refreshed`, `token.revoked`, `token.expired`, `token.familyRevoked`, `session.created`, `session.destroyed`, `cleanup.completed`.
182
+
183
+ ## Things NOT to do
184
+
185
+ - Don't `authService.login(User, { password })` without other credentials — the password is the secret; the other fields are the lookup. A login with only a password is a logic bug.
186
+ - Don't return the password hash in the response. `static toJsonColumns` on the User model should explicitly exclude it.
187
+ - Don't store the refresh token in localStorage. Use an httpOnly secure cookie for refresh tokens; the access token can sit in memory.
188
+ - Don't issue a new token pair without revoking the old one when rotation is enabled. `refreshTokens` does this for you — don't bypass it.
189
+
190
+ ## See also
191
+
192
+ - [`@warlock.js/auth/manage-tokens/SKILL.md`](@warlock.js/auth/manage-tokens/SKILL.md) — token lifecycle, rotation, family revocation
193
+ - [`@warlock.js/auth/register-user/SKILL.md`](@warlock.js/auth/register-user/SKILL.md) — sign-up that issues tokens after creation
194
+ - [`@warlock.js/auth/protect-routes/SKILL.md`](@warlock.js/auth/protect-routes/SKILL.md) — where the access token gets consumed
180
195
 
181
196
  ## Browser sessions for Web pages
182
197
 
183
- For cookie sessions read by `@warlock.js/web` pages, log in with `authService.loginWithSessionCookies(request, response, Model, credentials)`. It requires a same-origin `Origin`/`Referer` even without cookies (login CSRF) and sets the access and refresh cookies (`auth.cookie.name`, `auth.cookie.refreshName`, `Path=/`). Log out with `authService.logout(user, access, refresh)` then `authService.clearSessionCookies(response)`. Resolve pages with `pageSession({ project })` (`web.session`); header beats cookie; `auth.session.maxAge` defaults to `"30d"`. Multi-instance: share the JWT secret and the cache store, keep clocks in sync.
198
+ For cookie sessions read by `@warlock.js/web` pages, log in with `authService.loginWithSessionCookies(request, response, Model, credentials)`. It requires a same-origin `Origin`/`Referer` even without cookies (login CSRF) and sets the access and refresh cookies (`auth.cookie.name`, `auth.cookie.refreshName`, `Path=/`). To share a session across subdomains, configure `auth.cookie.cookieDomain(request)` to return (for example) `".example.com"`; return `undefined` for host-only cookies. With `cookieDomain` configured, always pass the request to cookie helpers so they select the same Domain: `authService.setSessionCookies(response, tokens, request)`, `authService.clearSessionCookies(response, request)`, and `authService.clearAuthCookie(response, options, request)`. Omitting it throws `CookieDomainRequestRequiredError`. Domain clears also remove the legacy host-only names. Resolve pages with `pageSession({ project })` (`web.session`); header beats cookie; `auth.session.maxAge` defaults to `"30d"`. A page session with multiple `userTypes` cannot renew its cookie: the resolver only supplies a renewal user type when exactly one type is allowed, so it reads the session but skips automatic renewal. Multi-instance: share the JWT secret and the cache store, keep clocks in sync.