@warlock.js/auth 4.2.11 → 4.3.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.
@@ -1,142 +1,142 @@
1
- ---
2
- name: customize-user-type
3
- description: 'Support multiple user types (user / admin / client / staff) in one auth system — each Auth subclass overrides userType, config.auth.userType.<slug> maps slug to model class, authMiddleware(''admin'') gates per type. Triggers: `Auth`, `userType`, `config.auth.userType`, `Authenticable`, `@RegisterModel`, `confirmPassword`; "add admins and users", "multiple user types", "separate client and vendor personas", "per-type login"; typical import `import { Auth } from "@warlock.js/auth"`. Skip: `authMiddleware` semantics — `@warlock.js/auth/protect-routes/SKILL.md`; login flow — `@warlock.js/auth/handle-login-and-logout/SKILL.md`; RBAC libs `casl`, `accesscontrol`, `rbac`.'
4
- ---
5
-
6
- # Customize user type (multi-user-type auth)
7
-
8
- The `Auth` base class has a `userType` slot. Subclass it once per type, register each class under `config.auth.userType.<slug>`, and the auth flow handles the rest.
9
-
10
- ## Define a model per user type
11
-
12
- ```ts title="src/app/users/models/user/user.model.ts"
13
- import { Auth } from "@warlock.js/auth";
14
- import { RegisterModel } from "@warlock.js/cascade";
15
-
16
- @RegisterModel()
17
- export class User extends Auth<UserSchema> {
18
- public static table = "users";
19
- public static schema = userSchema;
20
-
21
- public get userType(): string {
22
- return "user";
23
- }
24
- }
25
- ```
26
-
27
- ```ts title="src/app/admins/models/admin/admin.model.ts"
28
- @RegisterModel()
29
- export class Admin extends Auth<AdminSchema> {
30
- public static table = "admins";
31
- public static schema = adminSchema;
32
-
33
- public get userType(): string {
34
- return "admin";
35
- }
36
- }
37
- ```
38
-
39
- Each gets its own table, its own schema, its own `userType` slug. They DON'T share table — they're separate models.
40
-
41
- ## Register them in `config.auth`
42
-
43
- ```ts title="src/config/auth.ts"
44
- import { User } from "@/app/users/models/user.model";
45
- import { Admin } from "@/app/admins/models/admin.model";
46
-
47
- export default {
48
- userType: {
49
- user: User,
50
- admin: Admin,
51
- // staff: Staff,
52
- // client: Client,
53
- },
54
- accessToken: {
55
- secret: env("JWT_SECRET"),
56
- expiresIn: "1h",
57
- },
58
- refreshToken: {
59
- secret: env("JWT_REFRESH_SECRET"),
60
- enabled: true,
61
- expiresIn: "30d",
62
- rotation: true,
63
- },
64
- };
65
- ```
66
-
67
- The keys (`"user"`, `"admin"`) are the **userType slugs** that flow through every token, middleware call, and event payload.
68
-
69
- ## Gate routes per user type
70
-
71
- ```ts
72
- import { authMiddleware } from "@warlock.js/auth";
73
-
74
- router.get("/account", userAccountController, { middleware: [authMiddleware("user")] });
75
- router.get("/admin/users", listUsersController, { middleware: [authMiddleware("admin")] });
76
- router.get("/back-office", backOfficeController, { middleware: [authMiddleware(["admin", "staff"])] });
77
- router.get("/dashboard", dashboardController, { middleware: [authMiddleware([])] }); // any logged-in
78
- ```
79
-
80
- See [`@warlock.js/auth/protect-routes/SKILL.md`](@warlock.js/auth/protect-routes/SKILL.md).
81
-
82
- ## Login per user type — pass the right Model
83
-
84
- `authService.login(Model, credentials, deviceInfo?)` is keyed off the model you pass:
85
-
86
- ```ts
87
- // User login endpoint
88
- const result = await authService.login(User, credentials);
89
- // Issues tokens with userType "user"; middleware will route them to User model.
90
-
91
- // Admin login endpoint
92
- const result = await authService.login(Admin, credentials);
93
- // Issues tokens with userType "admin"; middleware will route them to Admin model.
94
- ```
95
-
96
- The middleware then uses `config.auth.userType[token.userType]` to know which model to hydrate.
97
-
98
- ## Cross-type behavior
99
-
100
- - **Tokens are scoped to their issuing user-type.** A user-type token doesn't unlock admin-type routes.
101
- - **AccessToken / RefreshToken rows carry the `user_type` column.** Same model classes, different rows per type.
102
- - **`authMiddleware(["admin", "user"])`** allows either — useful for endpoints shared between roles.
103
-
104
- ## When NOT to use multi-user-type
105
-
106
- If the distinction is **permissions/roles within one user shape**, use a `role` column on a single User model instead. Multi-user-type is right when:
107
-
108
- - Different tables / schemas (admins have an `admin_level`; users have a `subscription_tier`).
109
- - Separate registration flows (admins are created via an admin panel; users self-register).
110
- - Truly separate concepts at the data layer (clients vs vendors in a marketplace).
111
-
112
- If users and admins differ only in a `role` field, stick with one `User` model + a role check at the controller layer.
113
-
114
- ## `Auth` base — what your subclass inherits
115
-
116
- ```ts
117
- abstract class Auth<TSchema> extends Model<TSchema> implements Authenticable {
118
- // ...all the Model<> methods
119
- public abstract get userType(): string;
120
- public generateAccessToken(payload?: Record<string, unknown>): Promise<AccessTokenOutput>;
121
- public generateRefreshToken(deviceInfo?: DeviceInfo): Promise<RefreshToken | undefined>;
122
- public createTokenPair(deviceInfo?: DeviceInfo): Promise<TokenPair>;
123
- public confirmPassword(password: string): Promise<boolean>;
124
- }
125
- ```
126
-
127
- `userType` is the only required override (an abstract getter — return the type slug). Override `generateAccessToken` if you need a non-default payload.
128
-
129
- `Auth` implements the `Authenticable` contract — that interface mirrors exactly these methods (`userType`, `generateAccessToken`, `generateRefreshToken`, `createTokenPair`, `confirmPassword`), so the class fails to compile if it drifts from the contract. Use `confirmPassword(plaintext)` to check a password against the stored hash (e.g. a "confirm current password" step).
130
-
131
- ## Things NOT to do
132
-
133
- - Don't use multi-user-type for what's really role-based access control. Use a `role` column on a single User model when the data shape is shared.
134
- - Don't forget the `public get userType(): string` override. It's an abstract getter on `Auth` — a subclass without it won't compile, and middleware lookups key off its return value.
135
- - Don't reuse the same `userType` slug across two models — the `config.auth.userType` map can only point one slug at one model.
136
- - Don't put admins and users in the same table differentiated by a flag. Separate tables means migrations don't coupling, queries don't accidentally cross, and audit logs are cleaner.
137
-
138
- ## See also
139
-
140
- - [`@warlock.js/auth/protect-routes/SKILL.md`](@warlock.js/auth/protect-routes/SKILL.md) — `authMiddleware` semantics
141
- - [`@warlock.js/auth/handle-login-and-logout/SKILL.md`](@warlock.js/auth/handle-login-and-logout/SKILL.md) — passing the right Model to `login`
142
- - [`@warlock.js/cascade/define-model/SKILL.md`](@warlock.js/cascade/define-model/SKILL.md) — `@RegisterModel`, models in general
1
+ ---
2
+ name: customize-user-type
3
+ description: 'Support multiple user types (user / admin / client / staff) in one auth system — each Auth subclass overrides userType, config.auth.userType.<slug> maps slug to model class, authMiddleware(''admin'') gates per type. Triggers: `Auth`, `userType`, `config.auth.userType`, `Authenticable`, `@RegisterModel`, `confirmPassword`; "add admins and users", "multiple user types", "separate client and vendor personas", "per-type login"; typical import `import { Auth } from "@warlock.js/auth"`. Skip: `authMiddleware` semantics — `@warlock.js/auth/protect-routes/SKILL.md`; login flow — `@warlock.js/auth/handle-login-and-logout/SKILL.md`; RBAC libs `casl`, `accesscontrol`, `rbac`.'
4
+ ---
5
+
6
+ # Customize user type (multi-user-type auth)
7
+
8
+ The `Auth` base class has a `userType` slot. Subclass it once per type, register each class under `config.auth.userType.<slug>`, and the auth flow handles the rest.
9
+
10
+ ## Define a model per user type
11
+
12
+ ```ts title="src/app/users/models/user/user.model.ts"
13
+ import { Auth } from "@warlock.js/auth";
14
+ import { RegisterModel } from "@warlock.js/cascade";
15
+
16
+ @RegisterModel()
17
+ export class User extends Auth<UserSchema> {
18
+ public static table = "users";
19
+ public static schema = userSchema;
20
+
21
+ public get userType(): string {
22
+ return "user";
23
+ }
24
+ }
25
+ ```
26
+
27
+ ```ts title="src/app/admins/models/admin/admin.model.ts"
28
+ @RegisterModel()
29
+ export class Admin extends Auth<AdminSchema> {
30
+ public static table = "admins";
31
+ public static schema = adminSchema;
32
+
33
+ public get userType(): string {
34
+ return "admin";
35
+ }
36
+ }
37
+ ```
38
+
39
+ Each gets its own table, its own schema, its own `userType` slug. They DON'T share table — they're separate models.
40
+
41
+ ## Register them in `config.auth`
42
+
43
+ ```ts title="src/config/auth.ts"
44
+ import { User } from "@/app/users/models/user.model";
45
+ import { Admin } from "@/app/admins/models/admin.model";
46
+
47
+ export default {
48
+ userType: {
49
+ user: User,
50
+ admin: Admin,
51
+ // staff: Staff,
52
+ // client: Client,
53
+ },
54
+ accessToken: {
55
+ secret: env("JWT_SECRET"),
56
+ expiresIn: "1h",
57
+ },
58
+ refreshToken: {
59
+ secret: env("JWT_REFRESH_SECRET"),
60
+ enabled: true,
61
+ expiresIn: "30d",
62
+ rotation: true,
63
+ },
64
+ };
65
+ ```
66
+
67
+ The keys (`"user"`, `"admin"`) are the **userType slugs** that flow through every token, middleware call, and event payload.
68
+
69
+ ## Gate routes per user type
70
+
71
+ ```ts
72
+ import { authMiddleware } from "@warlock.js/auth";
73
+
74
+ router.get("/account", userAccountController, { middleware: [authMiddleware("user")] });
75
+ router.get("/admin/users", listUsersController, { middleware: [authMiddleware("admin")] });
76
+ router.get("/back-office", backOfficeController, { middleware: [authMiddleware(["admin", "staff"])] });
77
+ router.get("/dashboard", dashboardController, { middleware: [authMiddleware([])] }); // any logged-in
78
+ ```
79
+
80
+ See [`@warlock.js/auth/protect-routes/SKILL.md`](@warlock.js/auth/protect-routes/SKILL.md).
81
+
82
+ ## Login per user type — pass the right Model
83
+
84
+ `authService.login(Model, credentials, deviceInfo?)` is keyed off the model you pass:
85
+
86
+ ```ts
87
+ // User login endpoint
88
+ const result = await authService.login(User, credentials);
89
+ // Issues tokens with userType "user"; middleware will route them to User model.
90
+
91
+ // Admin login endpoint
92
+ const result = await authService.login(Admin, credentials);
93
+ // Issues tokens with userType "admin"; middleware will route them to Admin model.
94
+ ```
95
+
96
+ The middleware then uses `config.auth.userType[token.userType]` to know which model to hydrate.
97
+
98
+ ## Cross-type behavior
99
+
100
+ - **Tokens are scoped to their issuing user-type.** A user-type token doesn't unlock admin-type routes.
101
+ - **AccessToken / RefreshToken rows carry the `user_type` column.** Same model classes, different rows per type.
102
+ - **`authMiddleware(["admin", "user"])`** allows either — useful for endpoints shared between roles.
103
+
104
+ ## When NOT to use multi-user-type
105
+
106
+ If the distinction is **permissions/roles within one user shape**, use a `role` column on a single User model instead. Multi-user-type is right when:
107
+
108
+ - Different tables / schemas (admins have an `admin_level`; users have a `subscription_tier`).
109
+ - Separate registration flows (admins are created via an admin panel; users self-register).
110
+ - Truly separate concepts at the data layer (clients vs vendors in a marketplace).
111
+
112
+ If users and admins differ only in a `role` field, stick with one `User` model + a role check at the controller layer.
113
+
114
+ ## `Auth` base — what your subclass inherits
115
+
116
+ ```ts
117
+ abstract class Auth<TSchema> extends Model<TSchema> implements Authenticable {
118
+ // ...all the Model<> methods
119
+ public abstract get userType(): string;
120
+ public generateAccessToken(payload?: Record<string, unknown>): Promise<AccessTokenOutput>;
121
+ public generateRefreshToken(deviceInfo?: DeviceInfo): Promise<RefreshToken | undefined>;
122
+ public createTokenPair(deviceInfo?: DeviceInfo): Promise<TokenPair>;
123
+ public confirmPassword(password: string): Promise<boolean>;
124
+ }
125
+ ```
126
+
127
+ `userType` is the only required override (an abstract getter — return the type slug). Override `generateAccessToken` if you need a non-default payload.
128
+
129
+ `Auth` implements the `Authenticable` contract — that interface mirrors exactly these methods (`userType`, `generateAccessToken`, `generateRefreshToken`, `createTokenPair`, `confirmPassword`), so the class fails to compile if it drifts from the contract. Use `confirmPassword(plaintext)` to check a password against the stored hash (e.g. a "confirm current password" step).
130
+
131
+ ## Things NOT to do
132
+
133
+ - Don't use multi-user-type for what's really role-based access control. Use a `role` column on a single User model when the data shape is shared.
134
+ - Don't forget the `public get userType(): string` override. It's an abstract getter on `Auth` — a subclass without it won't compile, and middleware lookups key off its return value.
135
+ - Don't reuse the same `userType` slug across two models — the `config.auth.userType` map can only point one slug at one model.
136
+ - Don't put admins and users in the same table differentiated by a flag. Separate tables means migrations don't coupling, queries don't accidentally cross, and audit logs are cleaner.
137
+
138
+ ## See also
139
+
140
+ - [`@warlock.js/auth/protect-routes/SKILL.md`](@warlock.js/auth/protect-routes/SKILL.md) — `authMiddleware` semantics
141
+ - [`@warlock.js/auth/handle-login-and-logout/SKILL.md`](@warlock.js/auth/handle-login-and-logout/SKILL.md) — passing the right Model to `login`
142
+ - [`@warlock.js/cascade/define-model/SKILL.md`](@warlock.js/cascade/define-model/SKILL.md) — `@RegisterModel`, models in general
@@ -1,160 +1,160 @@
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
- ## Login — `authService.login(Model, credentials, deviceInfo?)`
11
-
12
- ```ts
13
- import { authService } from "@warlock.js/auth";
14
- import { User } from "@/app/users/models/user.model";
15
-
16
- async function loginController(request: Request, response: Response) {
17
- const result = await authService.login(User, {
18
- email: request.input("email"),
19
- password: request.input("password"),
20
- }, {
21
- userAgent: request.header("user-agent"),
22
- ip: request.ip,
23
- });
24
-
25
- if (!result) {
26
- return response.unauthorized({ error: "Invalid credentials" });
27
- }
28
-
29
- return response.success({
30
- user: result.user,
31
- tokens: result.tokens,
32
- });
33
- }
34
- ```
35
-
36
- The returned shape:
37
-
38
- ```ts
39
- {
40
- user: T, // your User subclass, hydrated
41
- tokens: {
42
- accessToken: { token: string, expiresAt: string },
43
- refreshToken?: { token: string, expiresAt: string }, // omitted if refresh tokens disabled
44
- },
45
- }
46
- ```
47
-
48
- 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.
49
-
50
- ## What `credentials` looks like
51
-
52
- The shape is **arbitrary** — every key except `password` is used as a `where(...)` filter against the model. The password is verified separately via bcrypt.
53
-
54
- ```ts
55
- // Email + password
56
- authService.login(User, { email: "ada@example.com", password: "..." });
57
-
58
- // Username + password
59
- authService.login(User, { username: "ada", password: "..." });
60
-
61
- // Phone-based OTP (where password is the OTP hash)
62
- authService.login(User, { phone: "+1...", password: hashedOTP });
63
- ```
64
-
65
- For lower-level credential verification (just check, don't issue tokens), use `authService.attemptLogin(Model, credentials)` — returns the user or null without creating tokens.
66
-
67
- ## Device info
68
-
69
- The optional `deviceInfo` carries metadata into the refresh token row:
70
-
71
- ```ts
72
- authService.login(User, credentials, {
73
- userAgent: request.header("user-agent"),
74
- ip: request.ip,
75
- deviceId: "...", // your client-side device fingerprint
76
- familyId: "...", // pre-existing family for token rotation, usually omitted
77
- });
78
- ```
79
-
80
- Useful for "show active sessions" UIs — see `authService.getActiveSessions(user)`.
81
-
82
- ## Logout — `authService.logout(user, accessToken?, refreshToken?)`
83
-
84
- ```ts
85
- async function logoutController(request: Request, response: Response) {
86
- await authService.logout(
87
- request.user!,
88
- request.authorizationValue, // access token from the Authorization header
89
- request.input("refreshToken"), // refresh token from the request body
90
- );
91
-
92
- return response.success({ message: "Logged out" });
93
- }
94
- ```
95
-
96
- The contract:
97
- - **Pass the access token** → that specific access-token row is deleted.
98
- - **Pass the refresh token** → that specific refresh-token row is revoked.
99
- - **Omit refresh token** → behavior depends on `config.auth.refreshToken.logoutWithoutToken`:
100
- - `"revoke-all"` (default) — every refresh token for this user is revoked. Fail-safe.
101
- - `"error"` — throws. Force the client to send the refresh token.
102
-
103
- 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.
104
-
105
- ## Logout-everywhere
106
-
107
- ```ts
108
- await authService.revokeAllTokens(user);
109
- // Revokes every refresh token + deletes every access token for this user.
110
- ```
111
-
112
- Useful for "logout from all devices" buttons. Fires `token.revoked` per token + `logout.all` once.
113
-
114
- ## Refresh tokens — `authService.refreshTokens(refreshTokenString, deviceInfo?)`
115
-
116
- ```ts
117
- async function refreshController(request: Request, response: Response) {
118
- const tokens = await authService.refreshTokens(
119
- request.input("refreshToken"),
120
- { userAgent: request.header("user-agent"), ip: request.ip },
121
- );
122
-
123
- if (!tokens) {
124
- return response.unauthorized({ error: "Invalid refresh token" });
125
- }
126
-
127
- return response.success({ tokens });
128
- }
129
- ```
130
-
131
- 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).
132
-
133
- ## Auth events
134
-
135
- `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`:
136
-
137
- ```ts
138
- import { authEvents } from "@warlock.js/auth";
139
-
140
- authEvents.on("login.success", (user, tokens, deviceInfo) => { /* audit */ });
141
- authEvents.on("login.failed", (credentials, reason) => { /* alert on brute force */ });
142
- authEvents.on("logout", (user) => { /* clear server-side session, if any */ });
143
- authEvents.on("token.refreshed", (user, newPair, oldToken) => { /* track rotation */ });
144
- authEvents.on("cleanup.completed", (count) => { /* metrics */ });
145
- ```
146
-
147
- 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`.
148
-
149
- ## Things NOT to do
150
-
151
- - 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.
152
- - Don't return the password hash in the response. `static toJsonColumns` on the User model should explicitly exclude it.
153
- - Don't store the refresh token in localStorage. Use an httpOnly secure cookie for refresh tokens; the access token can sit in memory.
154
- - 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.
155
-
156
- ## See also
157
-
158
- - [`@warlock.js/auth/manage-tokens/SKILL.md`](@warlock.js/auth/manage-tokens/SKILL.md) — token lifecycle, rotation, family revocation
159
- - [`@warlock.js/auth/register-user/SKILL.md`](@warlock.js/auth/register-user/SKILL.md) — sign-up that issues tokens after creation
160
- - [`@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
+ ## Login — `authService.login(Model, credentials, deviceInfo?)`
11
+
12
+ ```ts
13
+ import { authService } from "@warlock.js/auth";
14
+ import { User } from "@/app/users/models/user.model";
15
+
16
+ async function loginController(request: Request, response: Response) {
17
+ const result = await authService.login(User, {
18
+ email: request.input("email"),
19
+ password: request.input("password"),
20
+ }, {
21
+ userAgent: request.header("user-agent"),
22
+ ip: request.ip,
23
+ });
24
+
25
+ if (!result) {
26
+ return response.unauthorized({ error: "Invalid credentials" });
27
+ }
28
+
29
+ return response.success({
30
+ user: result.user,
31
+ tokens: result.tokens,
32
+ });
33
+ }
34
+ ```
35
+
36
+ The returned shape:
37
+
38
+ ```ts
39
+ {
40
+ user: T, // your User subclass, hydrated
41
+ tokens: {
42
+ accessToken: { token: string, expiresAt: string },
43
+ refreshToken?: { token: string, expiresAt: string }, // omitted if refresh tokens disabled
44
+ },
45
+ }
46
+ ```
47
+
48
+ 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.
49
+
50
+ ## What `credentials` looks like
51
+
52
+ The shape is **arbitrary** — every key except `password` is used as a `where(...)` filter against the model. The password is verified separately via bcrypt.
53
+
54
+ ```ts
55
+ // Email + password
56
+ authService.login(User, { email: "ada@example.com", password: "..." });
57
+
58
+ // Username + password
59
+ authService.login(User, { username: "ada", password: "..." });
60
+
61
+ // Phone-based OTP (where password is the OTP hash)
62
+ authService.login(User, { phone: "+1...", password: hashedOTP });
63
+ ```
64
+
65
+ For lower-level credential verification (just check, don't issue tokens), use `authService.attemptLogin(Model, credentials)` — returns the user or null without creating tokens.
66
+
67
+ ## Device info
68
+
69
+ The optional `deviceInfo` carries metadata into the refresh token row:
70
+
71
+ ```ts
72
+ authService.login(User, credentials, {
73
+ userAgent: request.header("user-agent"),
74
+ ip: request.ip,
75
+ deviceId: "...", // your client-side device fingerprint
76
+ familyId: "...", // pre-existing family for token rotation, usually omitted
77
+ });
78
+ ```
79
+
80
+ Useful for "show active sessions" UIs — see `authService.getActiveSessions(user)`.
81
+
82
+ ## Logout — `authService.logout(user, accessToken?, refreshToken?)`
83
+
84
+ ```ts
85
+ async function logoutController(request: Request, response: Response) {
86
+ await authService.logout(
87
+ request.user!,
88
+ request.authorizationValue, // access token from the Authorization header
89
+ request.input("refreshToken"), // refresh token from the request body
90
+ );
91
+
92
+ return response.success({ message: "Logged out" });
93
+ }
94
+ ```
95
+
96
+ The contract:
97
+ - **Pass the access token** → that specific access-token row is deleted.
98
+ - **Pass the refresh token** → that specific refresh-token row is revoked.
99
+ - **Omit refresh token** → behavior depends on `config.auth.refreshToken.logoutWithoutToken`:
100
+ - `"revoke-all"` (default) — every refresh token for this user is revoked. Fail-safe.
101
+ - `"error"` — throws. Force the client to send the refresh token.
102
+
103
+ 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.
104
+
105
+ ## Logout-everywhere
106
+
107
+ ```ts
108
+ await authService.revokeAllTokens(user);
109
+ // Revokes every refresh token + deletes every access token for this user.
110
+ ```
111
+
112
+ Useful for "logout from all devices" buttons. Fires `token.revoked` per token + `logout.all` once.
113
+
114
+ ## Refresh tokens — `authService.refreshTokens(refreshTokenString, deviceInfo?)`
115
+
116
+ ```ts
117
+ async function refreshController(request: Request, response: Response) {
118
+ const tokens = await authService.refreshTokens(
119
+ request.input("refreshToken"),
120
+ { userAgent: request.header("user-agent"), ip: request.ip },
121
+ );
122
+
123
+ if (!tokens) {
124
+ return response.unauthorized({ error: "Invalid refresh token" });
125
+ }
126
+
127
+ return response.success({ tokens });
128
+ }
129
+ ```
130
+
131
+ 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).
132
+
133
+ ## Auth events
134
+
135
+ `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`:
136
+
137
+ ```ts
138
+ import { authEvents } from "@warlock.js/auth";
139
+
140
+ authEvents.on("login.success", (user, tokens, deviceInfo) => { /* audit */ });
141
+ authEvents.on("login.failed", (credentials, reason) => { /* alert on brute force */ });
142
+ authEvents.on("logout", (user) => { /* clear server-side session, if any */ });
143
+ authEvents.on("token.refreshed", (user, newPair, oldToken) => { /* track rotation */ });
144
+ authEvents.on("cleanup.completed", (count) => { /* metrics */ });
145
+ ```
146
+
147
+ 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`.
148
+
149
+ ## Things NOT to do
150
+
151
+ - 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.
152
+ - Don't return the password hash in the response. `static toJsonColumns` on the User model should explicitly exclude it.
153
+ - Don't store the refresh token in localStorage. Use an httpOnly secure cookie for refresh tokens; the access token can sit in memory.
154
+ - 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.
155
+
156
+ ## See also
157
+
158
+ - [`@warlock.js/auth/manage-tokens/SKILL.md`](@warlock.js/auth/manage-tokens/SKILL.md) — token lifecycle, rotation, family revocation
159
+ - [`@warlock.js/auth/register-user/SKILL.md`](@warlock.js/auth/register-user/SKILL.md) — sign-up that issues tokens after creation
160
+ - [`@warlock.js/auth/protect-routes/SKILL.md`](@warlock.js/auth/protect-routes/SKILL.md) — where the access token gets consumed