@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.
- package/CHANGELOG.md +65 -0
- package/README.md +88 -86
- package/esm/commands/auth-cleanup-command.mjs +1 -1
- package/esm/commands/auth-cleanup-command.mjs.map +1 -1
- package/esm/contracts/index.d.mts +4 -2
- package/esm/contracts/providers.d.mts +101 -0
- package/esm/contracts/providers.d.mts.map +1 -0
- package/esm/contracts/request-locals.d.mts +43 -0
- package/esm/contracts/request-locals.d.mts.map +1 -0
- package/esm/contracts/types.d.mts +159 -1
- package/esm/contracts/types.d.mts.map +1 -1
- package/esm/contracts/types.mjs.map +1 -1
- package/esm/errors/auth-provider-sdk-missing.error.d.mts +17 -0
- package/esm/errors/auth-provider-sdk-missing.error.d.mts.map +1 -0
- package/esm/errors/auth-provider-sdk-missing.error.mjs +22 -0
- package/esm/errors/auth-provider-sdk-missing.error.mjs.map +1 -0
- package/esm/errors/email-not-verified.error.d.mts +16 -0
- package/esm/errors/email-not-verified.error.d.mts.map +1 -0
- package/esm/errors/email-not-verified.error.mjs +20 -0
- package/esm/errors/email-not-verified.error.mjs.map +1 -0
- package/esm/errors/index.d.mts +7 -0
- package/esm/errors/index.mjs +9 -0
- package/esm/errors/invalid-one-time-token.error.d.mts +17 -0
- package/esm/errors/invalid-one-time-token.error.d.mts.map +1 -0
- package/esm/errors/invalid-one-time-token.error.mjs +21 -0
- package/esm/errors/invalid-one-time-token.error.mjs.map +1 -0
- package/esm/errors/invalid-passkey.error.d.mts +18 -0
- package/esm/errors/invalid-passkey.error.d.mts.map +1 -0
- package/esm/errors/invalid-passkey.error.mjs +23 -0
- package/esm/errors/invalid-passkey.error.mjs.map +1 -0
- package/esm/errors/invalid-provider-callback.error.d.mts +18 -0
- package/esm/errors/invalid-provider-callback.error.d.mts.map +1 -0
- package/esm/errors/invalid-provider-callback.error.mjs +23 -0
- package/esm/errors/invalid-provider-callback.error.mjs.map +1 -0
- package/esm/errors/notifications-unavailable.error.d.mts +15 -0
- package/esm/errors/notifications-unavailable.error.d.mts.map +1 -0
- package/esm/errors/notifications-unavailable.error.mjs +20 -0
- package/esm/errors/notifications-unavailable.error.mjs.map +1 -0
- package/esm/errors/provider-email-not-verified.error.d.mts +16 -0
- package/esm/errors/provider-email-not-verified.error.d.mts.map +1 -0
- package/esm/errors/provider-email-not-verified.error.mjs +20 -0
- package/esm/errors/provider-email-not-verified.error.mjs.map +1 -0
- package/esm/index.d.mts +31 -3
- package/esm/index.mjs +29 -1
- package/esm/middleware/auth.middleware.d.mts.map +1 -1
- package/esm/middleware/auth.middleware.mjs +13 -2
- package/esm/middleware/auth.middleware.mjs.map +1 -1
- package/esm/middleware/csrf-origin-check.d.mts +40 -0
- package/esm/middleware/csrf-origin-check.d.mts.map +1 -0
- package/esm/middleware/csrf-origin-check.mjs +105 -0
- package/esm/middleware/csrf-origin-check.mjs.map +1 -0
- package/esm/middleware/index.d.mts +5 -1
- package/esm/middleware/index.mjs +4 -0
- package/esm/middleware/one-time-token-throttle.middleware.d.mts +36 -0
- package/esm/middleware/one-time-token-throttle.middleware.d.mts.map +1 -0
- package/esm/middleware/one-time-token-throttle.middleware.mjs +53 -0
- package/esm/middleware/one-time-token-throttle.middleware.mjs.map +1 -0
- package/esm/middleware/otp-throttle.middleware.d.mts +30 -0
- package/esm/middleware/otp-throttle.middleware.d.mts.map +1 -0
- package/esm/middleware/otp-throttle.middleware.mjs +45 -0
- package/esm/middleware/otp-throttle.middleware.mjs.map +1 -0
- package/esm/middleware/require-verified-email.middleware.d.mts +18 -0
- package/esm/middleware/require-verified-email.middleware.d.mts.map +1 -0
- package/esm/middleware/require-verified-email.middleware.mjs +24 -0
- package/esm/middleware/require-verified-email.middleware.mjs.map +1 -0
- package/esm/models/access-token/access-token.model.d.mts +8 -0
- package/esm/models/access-token/access-token.model.d.mts.map +1 -1
- package/esm/models/access-token/access-token.model.mjs +3 -0
- package/esm/models/access-token/access-token.model.mjs.map +1 -1
- package/esm/models/index.d.mts +3 -1
- package/esm/models/index.d.mts.map +1 -1
- package/esm/models/index.mjs +16 -1
- package/esm/models/index.mjs.map +1 -1
- package/esm/models/one-time-token/index.d.mts +1 -0
- package/esm/models/one-time-token/index.mjs +3 -0
- package/esm/models/one-time-token/migration.mjs +31 -0
- package/esm/models/one-time-token/migration.mjs.map +1 -0
- package/esm/models/one-time-token/one-time-token.model.d.mts +173 -0
- package/esm/models/one-time-token/one-time-token.model.d.mts.map +1 -0
- package/esm/models/one-time-token/one-time-token.model.mjs +151 -0
- package/esm/models/one-time-token/one-time-token.model.mjs.map +1 -0
- package/esm/models/passkey-credential/index.d.mts +1 -0
- package/esm/models/passkey-credential/index.mjs +3 -0
- package/esm/models/passkey-credential/migration.mjs +25 -0
- package/esm/models/passkey-credential/migration.mjs.map +1 -0
- package/esm/models/passkey-credential/passkey-credential.model.d.mts +108 -0
- package/esm/models/passkey-credential/passkey-credential.model.d.mts.map +1 -0
- package/esm/models/passkey-credential/passkey-credential.model.mjs +70 -0
- package/esm/models/passkey-credential/passkey-credential.model.mjs.map +1 -0
- package/esm/models/provider-account/index.d.mts +1 -0
- package/esm/models/provider-account/index.mjs +3 -0
- package/esm/models/provider-account/migration.mjs +25 -0
- package/esm/models/provider-account/migration.mjs.map +1 -0
- package/esm/models/provider-account/provider-account.model.d.mts +75 -0
- package/esm/models/provider-account/provider-account.model.d.mts.map +1 -0
- package/esm/models/provider-account/provider-account.model.mjs +55 -0
- package/esm/models/provider-account/provider-account.model.mjs.map +1 -0
- package/esm/models/refresh-token/refresh-token.model.d.mts +7 -0
- package/esm/models/refresh-token/refresh-token.model.d.mts.map +1 -1
- package/esm/models/refresh-token/refresh-token.model.mjs +3 -0
- package/esm/models/refresh-token/refresh-token.model.mjs.map +1 -1
- package/esm/otp/index.d.mts +1 -0
- package/esm/otp/index.mjs +3 -0
- package/esm/otp/otp.d.mts +38 -0
- package/esm/otp/otp.d.mts.map +1 -0
- package/esm/otp/otp.mjs +105 -0
- package/esm/otp/otp.mjs.map +1 -0
- package/esm/passkeys/index.d.mts +3 -0
- package/esm/passkeys/index.mjs +4 -0
- package/esm/passkeys/passkey-authentication.d.mts +33 -0
- package/esm/passkeys/passkey-authentication.d.mts.map +1 -0
- package/esm/passkeys/passkey-authentication.mjs +93 -0
- package/esm/passkeys/passkey-authentication.mjs.map +1 -0
- package/esm/passkeys/passkey-challenges.mjs +53 -0
- package/esm/passkeys/passkey-challenges.mjs.map +1 -0
- package/esm/passkeys/passkey-registration.d.mts +29 -0
- package/esm/passkeys/passkey-registration.d.mts.map +1 -0
- package/esm/passkeys/passkey-registration.mjs +88 -0
- package/esm/passkeys/passkey-registration.mjs.map +1 -0
- package/esm/passkeys/simplewebauthn.d.mts +21 -0
- package/esm/passkeys/simplewebauthn.d.mts.map +1 -0
- package/esm/passkeys/simplewebauthn.mjs +13 -0
- package/esm/passkeys/simplewebauthn.mjs.map +1 -0
- package/esm/providers/google-provider.d.mts +40 -0
- package/esm/providers/google-provider.d.mts.map +1 -0
- package/esm/providers/google-provider.mjs +105 -0
- package/esm/providers/google-provider.mjs.map +1 -0
- package/esm/providers/index.d.mts +2 -0
- package/esm/providers/index.mjs +4 -0
- package/esm/providers/provider-login.d.mts +43 -0
- package/esm/providers/provider-login.d.mts.map +1 -0
- package/esm/providers/provider-login.mjs +86 -0
- package/esm/providers/provider-login.mjs.map +1 -0
- package/esm/providers/provider-state-cookie.mjs +63 -0
- package/esm/providers/provider-state-cookie.mjs.map +1 -0
- package/esm/providers/resolve-provider-user.mjs +45 -0
- package/esm/providers/resolve-provider-user.mjs.map +1 -0
- package/esm/services/auth-config.mjs +84 -0
- package/esm/services/auth-config.mjs.map +1 -1
- package/esm/services/auth.service.d.mts +59 -2
- package/esm/services/auth.service.d.mts.map +1 -1
- package/esm/services/auth.service.mjs +86 -1
- package/esm/services/auth.service.mjs.map +1 -1
- package/esm/services/current-user.d.mts +21 -0
- package/esm/services/current-user.d.mts.map +1 -0
- package/esm/services/current-user.mjs +24 -0
- package/esm/services/current-user.mjs.map +1 -0
- package/esm/services/email-verification.d.mts +35 -0
- package/esm/services/email-verification.d.mts.map +1 -0
- package/esm/services/email-verification.mjs +55 -0
- package/esm/services/email-verification.mjs.map +1 -0
- package/esm/services/index.d.mts +5 -1
- package/esm/services/index.mjs +4 -0
- package/esm/services/one-time-tokens.d.mts +32 -0
- package/esm/services/one-time-tokens.d.mts.map +1 -0
- package/esm/services/one-time-tokens.mjs +56 -0
- package/esm/services/one-time-tokens.mjs.map +1 -0
- package/esm/services/optional-peer.mjs +37 -0
- package/esm/services/optional-peer.mjs.map +1 -0
- package/esm/services/password-reset.d.mts +34 -0
- package/esm/services/password-reset.d.mts.map +1 -0
- package/esm/services/password-reset.mjs +81 -0
- package/esm/services/password-reset.mjs.map +1 -0
- package/esm/services/token-notifications.mjs +87 -0
- package/esm/services/token-notifications.mjs.map +1 -0
- package/esm/utils/auth-error-codes.d.mts +48 -1
- package/esm/utils/auth-error-codes.d.mts.map +1 -1
- package/esm/utils/auth-error-codes.mjs +41 -0
- package/esm/utils/auth-error-codes.mjs.map +1 -1
- package/esm/utils/index.mjs +1 -0
- package/esm/utils/safe-equal.d.mts +6 -0
- package/esm/utils/safe-equal.d.mts.map +1 -0
- package/esm/utils/safe-equal.mjs +13 -0
- package/esm/utils/safe-equal.mjs.map +1 -0
- package/llms-full.txt +402 -29
- package/llms.txt +2 -0
- package/package.json +21 -7
- package/skills/handle-login-and-logout/SKILL.md +1 -1
- package/skills/login-with-providers/SKILL.md +154 -0
- package/skills/manage-tokens/SKILL.md +7 -1
- package/skills/overview/SKILL.md +1 -1
- package/skills/protect-routes/SKILL.md +71 -13
- package/skills/register-user/SKILL.md +6 -8
- package/skills/run-auth-commands/SKILL.md +1 -1
- package/skills/verify-email-and-reset-password/SKILL.md +137 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: login-with-providers
|
|
3
|
+
description: 'Log in without a password — Google (OIDC code + PKCE + state + nonce, id_token verified with `jose`), passkeys (WebAuthn via `@simplewebauthn/server`) and phone one-time codes (delivered through a `@warlock.js/notifications` channel). Every method ends in `authService.completeLogin(user)`, the same tokens, rows and events as password login. `startProviderLogin`, `completeProviderLogin`, `generatePasskeyRegistrationOptions`, `verifyPasskeyRegistration`, `generatePasskeyAuthenticationOptions`, `verifyPasskeyAuthentication`, `requestOtp`, `verifyOtp`, `otpRequestThrottleMiddleware`, `otpVerifyThrottleMiddleware`, `AuthProvider`. Triggers: "login with Google", "sign in with Google", "OAuth", "OIDC", "passkeys", "WebAuthn", "passwordless", "SMS code login", "WhatsApp OTP", "phone login", `warlock add auth-google`, `warlock add auth-passkeys`, `AuthProviderSdkMissingError`, `InvalidProviderCallbackError`, `ProviderEmailNotVerifiedError`, `InvalidPasskeyError`, `EC009`, `EC010`, `EC011`, `auth.providers`, `auth.passkeys`, `auth.otp`; typical import `import { completeProviderLogin, verifyOtp } from "@warlock.js/auth"`. Skip: password login — `@warlock.js/auth/handle-login-and-logout/SKILL.md`; email tokens — `@warlock.js/auth/verify-email-and-reset-password/SKILL.md`; defining an SMS channel — `@warlock.js/notifications/define-channel/SKILL.md`.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Login with Google, passkeys, or a phone code
|
|
7
|
+
|
|
8
|
+
Services only, as with password login: you write the routes. Each `verify`/`complete` call returns the same `LoginResult` as `authService.login`, so the next step is the same too:
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
const { user, tokens } = await completeProviderLogin(User, "google", request, response);
|
|
12
|
+
authService.setAuthCookie(response, tokens.accessToken); // cookie session, or return tokens as JSON
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
`authService.completeLogin(user, deviceInfo?)` is that shared ending. It applies `auth.canAuthenticate` (403) and issues tokens. Call it only for a user you have already authenticated.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
| Method | Command | Installs |
|
|
20
|
+
| --- | --- | --- |
|
|
21
|
+
| Google | `warlock add auth-google` | `jose` |
|
|
22
|
+
| Passkeys | `warlock add auth-passkeys` | `@simplewebauthn/server` (add `@simplewebauthn/browser` to your client bundle) |
|
|
23
|
+
| Phone code | `warlock add notifications` + your own `sms`/`whatsapp` channel | nothing else. Auth ships no SMS/WhatsApp driver |
|
|
24
|
+
|
|
25
|
+
The SDKs are optional peers, loaded with `import()` only when a method runs. If one is missing, the call throws `AuthProviderSdkMissingError` (500), and the message names the `warlock add` command. Run the migrations: `authMigrations` now includes `provider_accounts` and `passkey_credentials`, and `one_time_tokens` gained an `attempts` column.
|
|
26
|
+
|
|
27
|
+
## Google
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
// src/config/auth.ts
|
|
31
|
+
providers: {
|
|
32
|
+
google: {
|
|
33
|
+
clientId: env("GOOGLE_CLIENT_ID"),
|
|
34
|
+
clientSecret: env("GOOGLE_CLIENT_SECRET"),
|
|
35
|
+
redirectUri: `${env("APP_URL")}/auth/google/callback`, // exactly as registered at Google
|
|
36
|
+
// scopes: ["openid", "email", "profile"],
|
|
37
|
+
},
|
|
38
|
+
// emailField: "email",
|
|
39
|
+
// createUser: async (profile, Model) => Model.create({ ... }),
|
|
40
|
+
},
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
```ts
|
|
44
|
+
router.get("/auth/google", async ({ response }) =>
|
|
45
|
+
response.redirect(await startProviderLogin(response, "google")),
|
|
46
|
+
);
|
|
47
|
+
|
|
48
|
+
router.get("/auth/google/callback", async ({ request, response }) => {
|
|
49
|
+
const { tokens } = await completeProviderLogin(User, "google", request, response);
|
|
50
|
+
authService.setAuthCookie(response, tokens.accessToken);
|
|
51
|
+
return response.redirect("/");
|
|
52
|
+
});
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Client side, the button is just a link. It must be a top-level navigation, not a `fetch`, so the state cookie goes out and comes back:
|
|
56
|
+
|
|
57
|
+
```tsx
|
|
58
|
+
<a href="/auth/google">Continue with Google</a>
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
- `state`, `nonce` and the PKCE verifier go into a signed, 10-minute, HttpOnly `auth_provider_state` cookie (SameSite=Lax, so it survives Google's redirect back). The callback clears the cookie, so a started login can complete only once.
|
|
62
|
+
- The callback rejects, with `InvalidProviderCallbackError` (400, `EC009`): a missing, forged or expired cookie, a `state` mismatch, a `?error=` from Google, a failed code exchange, and an id_token with a bad signature, `iss`, `aud`, `exp` or `nonce`. `error.reason` says which. The response message is generic.
|
|
63
|
+
- **Linking.** An existing `provider_accounts` row (provider plus Google `sub`) always decides the user. Without one, the Google email must be verified (`email_verified: true`), or the call throws `ProviderEmailNotVerifiedError` (403, `EC010`) and nothing is linked or created. A verified email links the matching user, or creates one with `{ email, name, emailVerifiedAt: now }`.
|
|
64
|
+
- Other OIDC providers: implement `AuthProvider` (`authorizationUrl(state)`, `handleCallback({ query, expected })`) and register it under `auth.providers.custom.<name>`.
|
|
65
|
+
|
|
66
|
+
## Passkeys
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
passkeys: { rpID: "example.com", rpName: "Example", origin: "https://example.com" },
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
```ts
|
|
73
|
+
// Register (logged in)
|
|
74
|
+
router.post("/auth/passkeys/register/options", async ({ request, response }) =>
|
|
75
|
+
response.success(await generatePasskeyRegistrationOptions(request.locals.user)),
|
|
76
|
+
{ middleware: [authMiddleware("user")] });
|
|
77
|
+
router.post("/auth/passkeys/register", async ({ request, response }) => {
|
|
78
|
+
await verifyPasskeyRegistration(request, request.locals.user, request.input("credential"));
|
|
79
|
+
return response.success({ registered: true });
|
|
80
|
+
}, { middleware: [authMiddleware("user")] });
|
|
81
|
+
|
|
82
|
+
// Log in
|
|
83
|
+
router.post("/auth/passkeys/login/options", async ({ response }) =>
|
|
84
|
+
response.success(await generatePasskeyAuthenticationOptions()));
|
|
85
|
+
router.post("/auth/passkeys/login", async ({ request, response }) => {
|
|
86
|
+
const { tokens } = await verifyPasskeyAuthentication(request, request.input("credential"));
|
|
87
|
+
authService.setAuthCookie(response, tokens.accessToken);
|
|
88
|
+
return response.success({ ok: true });
|
|
89
|
+
});
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Browser:
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
import { startAuthentication, startRegistration } from "@simplewebauthn/browser";
|
|
96
|
+
|
|
97
|
+
const post = (url: string, body?: unknown) =>
|
|
98
|
+
fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })
|
|
99
|
+
.then((r) => r.json());
|
|
100
|
+
|
|
101
|
+
// register
|
|
102
|
+
const regOptions = await post("/auth/passkeys/register/options");
|
|
103
|
+
await post("/auth/passkeys/register", { credential: await startRegistration({ optionsJSON: regOptions }) });
|
|
104
|
+
|
|
105
|
+
// log in
|
|
106
|
+
const authOptions = await post("/auth/passkeys/login/options");
|
|
107
|
+
await post("/auth/passkeys/login", { credential: await startAuthentication({ optionsJSON: authOptions }) });
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
(Unwrap `response.success`'s envelope if your app wraps payloads.)
|
|
111
|
+
|
|
112
|
+
- Challenges live in `one_time_tokens` as SHA-256 hashes, expire after 5m (`auth.passkeys.challengeExpiresIn`), and are **consumed before verification**. A replayed challenge fails, and so does one whose first verification failed.
|
|
113
|
+
- The request `Origin` must be one of `auth.passkeys.origin`. The same list is checked against the signed `clientDataJSON`.
|
|
114
|
+
- The signature counter must advance. A counter that did not move past the stored value (when either is non-zero) is rejected as a cloned authenticator. The new counter is saved with a compare-and-set.
|
|
115
|
+
- Every rejection throws `InvalidPasskeyError` (400, `EC011`) with a `reason`.
|
|
116
|
+
|
|
117
|
+
## Phone code (OTP)
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
otp: { channel: "sms" /* or "whatsapp" */, phoneField: "phone", expiresIn: "5m", maxAttempts: 5 },
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
router.post("/auth/otp/request", async ({ request, response }) => {
|
|
125
|
+
await requestOtp(User, request.input("phone"), { channel: request.input("via") === "whatsapp" ? "whatsapp" : "sms" });
|
|
126
|
+
return response.success({ message: "If that number is registered, a code is on its way." });
|
|
127
|
+
}, { middleware: [otpRequestThrottleMiddleware()] }); // 3 / 1h per phone + IP
|
|
128
|
+
|
|
129
|
+
router.post("/auth/otp/verify", async ({ request, response }) => {
|
|
130
|
+
const { tokens } = await verifyOtp(User, request.input("phone"), request.input("code"));
|
|
131
|
+
authService.setAuthCookie(response, tokens.accessToken);
|
|
132
|
+
return response.success({ ok: true });
|
|
133
|
+
}, { middleware: [otpVerifyThrottleMiddleware()] }); // 5 failures / 15m per phone + IP
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
- Codes have 6 digits and are stored in `one_time_tokens` (purpose `otp`) as a salted HMAC keyed from your access-token secret, never as plain SHA-256, which is trivially reversible for 6 digits. A new request invalidates the previous code.
|
|
137
|
+
- Every verify counts an attempt atomically first. After `maxAttempts` the code is invalidated, even if the right code comes next, and even under concurrent guesses.
|
|
138
|
+
- Delivery: `notify.channel(channel).send(phone, { body, code, expiresAt })`. Register that channel in `config/notifications.ts`, or set `auth.otp.send(phone, message, channel)`. `auth.otp.message(code)` changes the text.
|
|
139
|
+
- **Anti-enumeration:** an unknown phone gets the same `requestOtp` result (nothing sent) and the same `InvalidOneTimeTokenError` (400, `EC008`) from `verifyOtp`.
|
|
140
|
+
- CSRF: `verifyOtp` is a POST. If the route uses cookie auth, the 5.12 Origin check applies. Otherwise there is no ambient credential to ride.
|
|
141
|
+
|
|
142
|
+
## Gotchas
|
|
143
|
+
|
|
144
|
+
- `completeProviderLogin` needs the **same** response object to clear the state cookie. Do not pass a different one.
|
|
145
|
+
- One provider identity links to one account, of one user type.
|
|
146
|
+
- `auth.cleanup` hard-deletes expired and consumed `one_time_tokens` rows (challenges and codes included).
|
|
147
|
+
- The passkey specs run the real `@simplewebauthn/server` against a software ES256 authenticator, and the consume-once, OTP attempt cap, counter compare-and-set and provider-link uniqueness are proven on real MongoDB and Postgres. Google's token endpoint is still mocked, so test a real Google client before you ship.
|
|
148
|
+
- A counter the SDK rejects is reported with `reason: "counter-regression"`, the same as auth's own check.
|
|
149
|
+
|
|
150
|
+
## See also
|
|
151
|
+
|
|
152
|
+
- [`@warlock.js/auth/handle-login-and-logout/SKILL.md`](@warlock.js/auth/handle-login-and-logout/SKILL.md): password login and `setAuthCookie`
|
|
153
|
+
- [`@warlock.js/auth/throttle-login-attempts/SKILL.md`](@warlock.js/auth/throttle-login-attempts/SKILL.md): the throttle the OTP presets wrap
|
|
154
|
+
- [`@warlock.js/notifications/define-channel/SKILL.md`](@warlock.js/notifications/define-channel/SKILL.md): an SMS/WhatsApp channel
|
|
@@ -120,10 +120,16 @@ When issuing a new refresh token, the service counts active tokens for the user
|
|
|
120
120
|
|
|
121
121
|
```ts
|
|
122
122
|
const cleaned = await authService.cleanupExpiredTokens();
|
|
123
|
-
// Returns: number of expired refresh tokens removed (also purges expired access-token rows
|
|
123
|
+
// Returns: number of expired refresh tokens removed (also purges expired access-token rows
|
|
124
|
+
// and hard-deletes expired or consumed one_time_tokens rows).
|
|
124
125
|
// Fires "token.expired" event per token + "cleanup.completed" with the count.
|
|
125
126
|
```
|
|
126
127
|
|
|
128
|
+
Every purge is a hard delete on every driver, including MongoDB. `AccessToken`, `RefreshToken`,
|
|
129
|
+
`OneTimeToken` and `PasskeyCredential` all declare `static deleteStrategy = "permanent"`, so a
|
|
130
|
+
purge never copies credential material into a `*Trash` collection despite MongoDB's driver
|
|
131
|
+
default being `"trash"`.
|
|
132
|
+
|
|
127
133
|
Run this periodically via the scheduler:
|
|
128
134
|
|
|
129
135
|
```ts
|
package/skills/overview/SKILL.md
CHANGED
|
@@ -41,7 +41,7 @@ Start here. The `Auth` base model, `authMiddleware` gate, `authService` (login/l
|
|
|
41
41
|
Sign up a new user and issue the first token pair — `User.create({ ...password: await hashPassword(plain) })` then `authService.createTokenPair(user)`. For `POST /register`.
|
|
42
42
|
|
|
43
43
|
#### [`protect-routes`](@warlock.js/auth/protect-routes/SKILL.md)
|
|
44
|
-
`authMiddleware(allowedUserType)` — the argument is required and always requires a valid token: `[]` allows any authenticated user, a user-type argument restricts to those types. Sets `request.user` + `request.decodedAccessToken`, responds 401 on failure.
|
|
44
|
+
`authMiddleware(allowedUserType)` — the argument is required and always requires a valid token: `[]` allows any authenticated user, a user-type argument restricts to those types. Sets `request.locals.user` + `request.decodedAccessToken`, responds 401 on failure.
|
|
45
45
|
|
|
46
46
|
### Going deeper
|
|
47
47
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: protect-routes
|
|
3
|
-
description: 'Gate HTTP routes via authMiddleware(allowedUserType) — the argument is required and a valid token is always required: [] allows any authenticated user, a user-type restricts to those types. Sets request.user + request.decodedAccessToken on success, 401 on failure. Triggers: `authMiddleware`, `request.user`, `request.decodedAccessToken`, `AuthErrorCodes`, `MissingAccessToken`, `InvalidAccessToken`; "how do I protect a route", "restrict route by user type", "require any logged-in user"; typical import `import { authMiddleware } from "@warlock.js/auth"`. Skip: multi-user-type config — `@warlock.js/auth/customize-user-type/SKILL.md`; issuing the token — `@warlock.js/auth/handle-login-and-logout/SKILL.md`; competing libs `passport`, `express-jwt`, `next-auth` middleware.'
|
|
3
|
+
description: 'Gate HTTP routes via authMiddleware(allowedUserType) — the argument is required and a valid token is always required: [] allows any authenticated user, a user-type restricts to those types. Sets request.locals.user + request.decodedAccessToken on success, 401 on failure. Triggers: `authMiddleware`, `request.locals.user`, `request.decodedAccessToken`, `AuthErrorCodes`, `MissingAccessToken`, `InvalidAccessToken`; "how do I protect a route", "restrict route by user type", "require any logged-in user"; typical import `import { authMiddleware } from "@warlock.js/auth"`. Skip: multi-user-type config — `@warlock.js/auth/customize-user-type/SKILL.md`; issuing the token — `@warlock.js/auth/handle-login-and-logout/SKILL.md`; competing libs `passport`, `express-jwt`, `next-auth` middleware.'
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Gate routes with `authMiddleware`
|
|
@@ -38,7 +38,7 @@ The `userType` slug must match a key in `config.auth.userType.<name>` — see [`
|
|
|
38
38
|
On success, before your controller runs:
|
|
39
39
|
|
|
40
40
|
```ts
|
|
41
|
-
request.user = <hydrated user model instance>;
|
|
41
|
+
request.locals.user = <hydrated user model instance>;
|
|
42
42
|
request.decodedAccessToken = <decoded JWT payload>;
|
|
43
43
|
```
|
|
44
44
|
|
|
@@ -90,7 +90,7 @@ The page-vs-API signal is `request.route.isPage`. Config is typed as `PageAuthCo
|
|
|
90
90
|
import { type RequestHandler } from "@warlock.js/core";
|
|
91
91
|
|
|
92
92
|
export const accountController: RequestHandler = async ({ request, response }) => {
|
|
93
|
-
const user = request.user!; // typed via your Auth subclass
|
|
93
|
+
const user = request.locals.user!; // typed via your Auth subclass
|
|
94
94
|
return response.success({
|
|
95
95
|
id: user.id,
|
|
96
96
|
email: user.get("email"),
|
|
@@ -98,7 +98,7 @@ export const accountController: RequestHandler = async ({ request, response }) =
|
|
|
98
98
|
};
|
|
99
99
|
```
|
|
100
100
|
|
|
101
|
-
Because the middleware always requires a valid token, `request.user` is guaranteed present inside any gated controller (the middleware would have responded 401 otherwise). The `!` is safe here.
|
|
101
|
+
Because the middleware always requires a valid token, `request.locals.user` is guaranteed present inside any gated controller (the middleware would have responded 401 otherwise). The `!` is safe here.
|
|
102
102
|
|
|
103
103
|
## Route-group protection
|
|
104
104
|
|
|
@@ -113,7 +113,7 @@ Every route inside the group is gated — the group's `middleware` array applies
|
|
|
113
113
|
|
|
114
114
|
## Optional auth is an app-owned middleware (the sanctioned pattern)
|
|
115
115
|
|
|
116
|
-
`authMiddleware` is a **hard gate** — it always requires a valid token and rejects when one is absent. There is deliberately no built-in "hydrate `request.user` if a token is present, otherwise continue" mode, because the *sanctioned generic pattern* for soft/optional auth is a small **app-owned optional-auth middleware**: resolve the user when a valid token is present, and otherwise leave the route to decide. The app owns it because the "what to do when absent" policy is the app's, not the framework's.
|
|
116
|
+
`authMiddleware` is a **hard gate** — it always requires a valid token and rejects when one is absent. There is deliberately no built-in "hydrate `request.locals.user` if a token is present, otherwise continue" mode, because the *sanctioned generic pattern* for soft/optional auth is a small **app-owned optional-auth middleware**: resolve the user when a valid token is present, and otherwise leave the route to decide. The app owns it because the "what to do when absent" policy is the app's, not the framework's.
|
|
117
117
|
|
|
118
118
|
```ts title="src/app/middleware/optional-auth.middleware.ts"
|
|
119
119
|
import { type Middleware } from "@warlock.js/core";
|
|
@@ -126,7 +126,7 @@ export const optionalAuth: Middleware = async ({ request }) => {
|
|
|
126
126
|
if (!token) return; // absent → continue anonymously; the route decides
|
|
127
127
|
try {
|
|
128
128
|
const decoded = await jwt.verify(token);
|
|
129
|
-
// hydrate request.user from your token/user model when valid
|
|
129
|
+
// hydrate request.locals.user from your token/user model when valid
|
|
130
130
|
} catch {
|
|
131
131
|
// invalid token on an optional route → treat as anonymous, don't reject
|
|
132
132
|
}
|
|
@@ -134,7 +134,7 @@ export const optionalAuth: Middleware = async ({ request }) => {
|
|
|
134
134
|
};
|
|
135
135
|
```
|
|
136
136
|
|
|
137
|
-
Wire it like any middleware (`{ middleware: [optionalAuth] }`), then branch on `request.user` in the controller. Use `authMiddleware` when the route must be gated; use this when the route is public but personalizes for a signed-in user. `auth.pageAuth` (above) is the built-in **adapter** over this same "unauthenticated" outcome for the common page-redirect case — it is not a competing mechanism.
|
|
137
|
+
Wire it like any middleware (`{ middleware: [optionalAuth] }`), then branch on `request.locals.user` in the controller. Use `authMiddleware` when the route must be gated; use this when the route is public but personalizes for a signed-in user. `auth.pageAuth` (above) is the built-in **adapter** over this same "unauthenticated" outcome for the common page-redirect case — it is not a competing mechanism.
|
|
138
138
|
|
|
139
139
|
## Custom error responses
|
|
140
140
|
|
|
@@ -163,24 +163,82 @@ definePolicy("users.create", (actor, target, ctx) =>
|
|
|
163
163
|
ctx.hasRole("superAdmin") || (target as User).userType === "teacher",
|
|
164
164
|
);
|
|
165
165
|
|
|
166
|
-
if (await can(request.user, "users.create", { resource: payload })) { /* ... */ }
|
|
166
|
+
if (await can(request.locals.user, "users.create", { resource: payload })) { /* ... */ }
|
|
167
167
|
```
|
|
168
168
|
|
|
169
169
|
Use `authMiddleware` to establish *who the caller is*, and `access` to decide *what they may do*. They compose — `access` reads the user `authMiddleware` put on the request.
|
|
170
170
|
|
|
171
|
-
##
|
|
171
|
+
## Cookie sessions: `authMiddleware([], "cookie:<name>")`
|
|
172
172
|
|
|
173
|
-
|
|
173
|
+
`authMiddleware`'s second argument, `tokenFrom`, selects the credential source and defaults to `"header"`. Pass `` `cookie:<name>` `` to read the credential from a named cookie instead of the `Authorization` header — the same gate, the same three checks, the same `request.locals.user` / `request.decodedAccessToken` outcome, just a different place to find the token:
|
|
174
174
|
|
|
175
|
-
|
|
175
|
+
```ts
|
|
176
|
+
router.get("/browser-account", accountController, {
|
|
177
|
+
middleware: [authMiddleware([], "cookie:token")],
|
|
178
|
+
});
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
A route is header-only or cookie-only, never both — `tokenFrom` accepts exactly one source, so there is no header/cookie precedence to define. A route that legitimately needs to accept either composes two `authMiddleware` instances against the app's own optional-auth pattern (above).
|
|
182
|
+
|
|
183
|
+
### Writing and clearing the cookie: `authService.setAuthCookie` / `clearAuthCookie`
|
|
184
|
+
|
|
185
|
+
Reading a cookie is opt-in per route (above); *writing* one is a separate, explicit step your login/logout controller calls — `authService.login`/`logout` never set cookies implicitly, so upgrading never starts emitting `Set-Cookie` for an existing bearer-only app.
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import { authService } from "@warlock.js/auth";
|
|
189
|
+
|
|
190
|
+
// after issuing tokens
|
|
191
|
+
const { user, tokens } = await authService.login(User, credentials);
|
|
192
|
+
authService.setAuthCookie(response, tokens.accessToken); // Max-Age derived from tokens.accessToken.expiresAt
|
|
193
|
+
|
|
194
|
+
// after revoking tokens
|
|
195
|
+
await authService.logout(user, accessToken, refreshToken);
|
|
196
|
+
authService.clearAuthCookie(response);
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
`setAuthCookie(response, token, options?)` accepts either the raw token string or an `AccessTokenOutput` (`{ token, expiresAt }`, e.g. `tokens.accessToken` from `login`) — passing the latter derives `Max-Age` from `expiresAt` automatically; pass `options.maxAge` (seconds) to override it, or a bare string with no `maxAge` for a session cookie. `clearAuthCookie(response, options?)` clears it.
|
|
200
|
+
|
|
201
|
+
Cookie **attribute flags are not configurable** — `HttpOnly`, `SameSite=Lax`, and `Secure` outside development come from core's `secureCookieDefaults()`, the same floor every `response.cookie()` call gets. Only the cookie's `name` (default `"access_token"`) and `path` (default `"/"`) can be set, via `options` or the `auth.cookie` config block:
|
|
202
|
+
|
|
203
|
+
```ts title="src/config/auth.ts"
|
|
204
|
+
export default {
|
|
205
|
+
userType: { user: User },
|
|
206
|
+
cookie: {
|
|
207
|
+
name: "access_token", // must match the `cookie:<name>` a route reads
|
|
208
|
+
path: "/",
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
The cookie name `setAuthCookie`/`clearAuthCookie` write **must match** the name a `cookie:<name>` token source reads — they are not linked automatically.
|
|
214
|
+
|
|
215
|
+
### CSRF: an automatic Origin check on cookie-authenticated writes
|
|
216
|
+
|
|
217
|
+
Cookie auth changes the CSRF picture that bearer-token auth doesn't have: a browser attaches cookies to same-site requests it didn't originate. `SameSite=Lax` already blocks the classic cross-site `<form method="post">` case, but not a same-site GET redirect chain or a client that ignores `SameSite`.
|
|
218
|
+
|
|
219
|
+
To close that gap, `authMiddleware` automatically runs a CSRF Origin check on every request whose credential came from a `cookie:` source **and** whose method is unsafe (`POST`/`PUT`/`PATCH`/`DELETE`) — there is nothing to opt into, and nothing to configure to turn it on:
|
|
220
|
+
|
|
221
|
+
- **Allowed** when `Origin` equals the request's own origin, or is listed in `auth.csrf.allowedOrigins` (config, default `[]`).
|
|
222
|
+
- If `Origin` is absent, `Referer`'s origin is checked the same way.
|
|
223
|
+
- If **both** are absent, or the check fails, the request is rejected with `403` and `errorCode: AuthErrorCodes.CsrfOriginMismatch` ("EC006") — never silently passed through.
|
|
224
|
+
- **Header-token auth is completely unaffected**, as are safe methods (`GET`/`HEAD`/`OPTIONS`) under cookie auth.
|
|
225
|
+
|
|
226
|
+
```ts title="src/config/auth.ts"
|
|
227
|
+
export default {
|
|
228
|
+
userType: { user: User },
|
|
229
|
+
csrf: {
|
|
230
|
+
allowedOrigins: ["https://admin.example.com"], // extra trusted origins, beyond same-origin
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
```
|
|
176
234
|
|
|
177
|
-
|
|
235
|
+
This is an Origin check, not a double-submit CSRF token — cheaper, and closes the gap `SameSite=Lax` leaves open, but it doesn't help a client whose privacy proxy strips both `Origin` and `Referer` (that request is rejected outright, fail-closed, rather than silently allowed). A double-submit token mechanism is deferred to a later release; track it if your threat model includes Origin-stripping clients.
|
|
178
236
|
|
|
179
237
|
## Things NOT to do
|
|
180
238
|
|
|
181
239
|
- Don't call `authMiddleware` outside route definition. It returns a function — the function is what runs per-request. Calling it once per request creates a fresh middleware on every hit (wasteful) and a fresh allowed-types Set (correctness if the input changes per call).
|
|
182
240
|
- Don't manually decode JWTs in the controller. The middleware already does it and exposes the decoded payload via `request.decodedAccessToken`.
|
|
183
|
-
- Don't trust `request.user` set by client-supplied headers. The middleware is the only place that sets it on the server — client headers can't reach this slot.
|
|
241
|
+
- Don't trust `request.locals.user` set by client-supplied headers. The middleware is the only place that sets it on the server — client headers can't reach this slot.
|
|
184
242
|
- Don't pass an unknown user-type to `authMiddleware("typo")`. The middleware will reject every request because the lookup fails. Test the wire-up with a real token of each user type.
|
|
185
243
|
|
|
186
244
|
## See also
|
|
@@ -87,22 +87,20 @@ Without this, `JSON.stringify(user)` in your response leaks the hash.
|
|
|
87
87
|
|
|
88
88
|
## Email verification flow (extending registration)
|
|
89
89
|
|
|
90
|
-
|
|
90
|
+
Since 5.13 auth ships this. Declare `emailVerifiedAt: v.date().optional()` on the schema, then send the verification after creating the user:
|
|
91
91
|
|
|
92
92
|
```ts
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
verification_token: Random.string(64),
|
|
97
|
-
});
|
|
93
|
+
import { authService, sendEmailVerification } from "@warlock.js/auth";
|
|
94
|
+
|
|
95
|
+
const user = await User.create({ ...data, password: await hashPassword(data.password) });
|
|
98
96
|
|
|
99
|
-
await
|
|
97
|
+
await sendEmailVerification(user); // hashed, single-use, 24h token via @warlock.js/notifications
|
|
100
98
|
|
|
101
99
|
const tokens = await authService.createTokenPair(user);
|
|
102
100
|
return response.successCreate({ user, tokens });
|
|
103
101
|
```
|
|
104
102
|
|
|
105
|
-
|
|
103
|
+
Gate routes that need a confirmed address with `requireVerifiedEmail()` after `authMiddleware`. See [`@warlock.js/auth/verify-email-and-reset-password/SKILL.md`](@warlock.js/auth/verify-email-and-reset-password/SKILL.md).
|
|
106
104
|
|
|
107
105
|
## Side effects via auth events
|
|
108
106
|
|
|
@@ -46,7 +46,7 @@ Run it once when setting up a new project. Each developer typically runs it loca
|
|
|
46
46
|
npx warlock auth.cleanup
|
|
47
47
|
```
|
|
48
48
|
|
|
49
|
-
Runs `authService.cleanupExpiredTokens()` — deletes every refresh token whose `expires_at` has passed, then sweeps expired access-token rows
|
|
49
|
+
Runs `authService.cleanupExpiredTokens()` — deletes every refresh token whose `expires_at` has passed, then sweeps expired access-token rows and hard-deletes expired or consumed `one_time_tokens` rows (verification/reset tokens, OTP codes, passkey challenges). Fires `token.expired` per refresh token and `cleanup.completed` once.
|
|
50
50
|
|
|
51
51
|
Schedule it periodically. Two common shapes:
|
|
52
52
|
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: verify-email-and-reset-password
|
|
3
|
+
description: 'Email verification and password reset with hashed, single-use, expiring, purpose-bound tokens delivered through `@warlock.js/notifications` — `sendEmailVerification(user)`, `verifyEmail(token)`, `requestPasswordReset(Model, email)`, `resetPassword(token, newPassword)`, the `requireVerifiedEmail()` guard, and the `tokenIssueThrottleMiddleware` / `tokenConsumeThrottleMiddleware` presets. Reset revokes every access token, refresh token and cookie session; a reset request answers the same for unknown emails. Triggers: `sendEmailVerification`, `verifyEmail`, `requestPasswordReset`, `resetPassword`, `requireVerifiedEmail`, `isEmailVerified`, `OneTimeToken`, `InvalidOneTimeTokenError`, `EmailNotVerifiedError`, `NotificationsUnavailableError`, `EC007`, `EC008`, `auth.verification`, `auth.passwordReset`; "verify email", "confirm email address", "forgot password", "reset password link", "block unverified users", "resend verification email"; typical import `import { requestPasswordReset, resetPassword } from "@warlock.js/auth"`. Skip: sign-up itself — `@warlock.js/auth/register-user/SKILL.md`; login throttling — `@warlock.js/auth/throttle-login-attempts/SKILL.md`; defining notifications — `@warlock.js/notifications/define-notification/SKILL.md`.'
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Verify email + reset password
|
|
7
|
+
|
|
8
|
+
Four service functions, one guard, two throttle presets. Auth ships no controllers — wire the routes yourself (examples below).
|
|
9
|
+
|
|
10
|
+
## Prerequisites
|
|
11
|
+
|
|
12
|
+
1. **`@warlock.js/notifications` installed and configured with a `mail` channel.** It is an optional peer; without it (or without `src/config/notifications.ts`) every send/request call throws `NotificationsUnavailableError` **before** a token is issued — never a silent skip.
|
|
13
|
+
2. **The `one_time_tokens` table.** It ships in `authMigrations` next to the access/refresh tables; run your migrations.
|
|
14
|
+
3. **A verified-date field on the user schema** (default `emailVerifiedAt`):
|
|
15
|
+
|
|
16
|
+
```ts
|
|
17
|
+
export const userSchema = v.object({
|
|
18
|
+
// ...
|
|
19
|
+
emailVerifiedAt: v.date().optional(),
|
|
20
|
+
});
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
If the schema strips it, `verifyEmail` throws naming the field instead of pretending it worked.
|
|
24
|
+
|
|
25
|
+
## Tokens
|
|
26
|
+
|
|
27
|
+
- 32 random bytes, base64url. Only the **SHA-256 hash** is stored; the raw token exists only in the notification.
|
|
28
|
+
- **Single use**, consumed with a conditional update — of two concurrent uses, exactly one succeeds.
|
|
29
|
+
- **Expiring**: verification `24h`, reset `60m` by default.
|
|
30
|
+
- **Purpose-bound**: a verification token is never accepted by `resetPassword`, and vice versa.
|
|
31
|
+
- A new reset request **invalidates the user's earlier unused reset tokens**. Verification tokens are not invalidated by a resend.
|
|
32
|
+
- Unknown, wrong-purpose, expired and used tokens all throw one `InvalidOneTimeTokenError` (`400`, `EC008`).
|
|
33
|
+
|
|
34
|
+
## Email verification
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { requireVerifiedEmail, sendEmailVerification, verifyEmail } from "@warlock.js/auth";
|
|
38
|
+
import { type RequestHandler } from "@warlock.js/core";
|
|
39
|
+
|
|
40
|
+
// after User.create(...) in your register controller
|
|
41
|
+
await sendEmailVerification(user);
|
|
42
|
+
|
|
43
|
+
export const verifyEmailController: RequestHandler = async ({ request, response }) => {
|
|
44
|
+
const user = await verifyEmail(request.input("token")); // throws InvalidOneTimeTokenError
|
|
45
|
+
return response.success({ user });
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
router.post("/auth/verify-email", verifyEmailController, {
|
|
49
|
+
middleware: [tokenConsumeThrottleMiddleware()],
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
router.post("/auth/verify-email/resend", resendController, {
|
|
53
|
+
middleware: [authMiddleware("user"), tokenIssueThrottleMiddleware({ by: ["ip"] })],
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// Opt-in guard, AFTER authMiddleware: 403 EmailNotVerifiedError (EC007)
|
|
57
|
+
router.post("/orders", createOrder, {
|
|
58
|
+
middleware: [authMiddleware("user"), requireVerifiedEmail()],
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`isEmailVerified(user)` answers the same question in code.
|
|
63
|
+
|
|
64
|
+
## Password reset
|
|
65
|
+
|
|
66
|
+
```ts
|
|
67
|
+
import { requestPasswordReset, resetPassword } from "@warlock.js/auth";
|
|
68
|
+
|
|
69
|
+
export const forgotPasswordController: RequestHandler = async ({ request, response }) => {
|
|
70
|
+
await requestPasswordReset(User, request.input("email"));
|
|
71
|
+
// Same answer whether or not the account exists.
|
|
72
|
+
return response.success({ message: "If that account exists, we sent a reset link." });
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
export const resetPasswordController: RequestHandler = async ({ request, response }) => {
|
|
76
|
+
// Validate strength FIRST — the token is consumed before the password is written.
|
|
77
|
+
await resetPassword(request.input("token"), request.input("password"));
|
|
78
|
+
return response.success({ message: "Password updated. Please log in again." });
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
router.post("/auth/forgot-password", forgotPasswordController, {
|
|
82
|
+
middleware: [tokenIssueThrottleMiddleware()], // 3 / 1h per email + per IP
|
|
83
|
+
});
|
|
84
|
+
router.post("/auth/reset-password", resetPasswordController, {
|
|
85
|
+
middleware: [tokenConsumeThrottleMiddleware()], // 10 failures / 15m per IP
|
|
86
|
+
});
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`resetPassword` writes the password, then calls `authService.revokeAllTokens(user)`: every refresh token is revoked and every access token deleted, which also kills cookie sessions (a cookie holds an access token). It emits `password.reset`; `requestPasswordReset` emits `password.resetRequested`.
|
|
90
|
+
|
|
91
|
+
**Password hashing.** By default auth saves `hashPassword(plain)` and checks it with `verifyPassword`, the same check login uses. If your model hashes on save (`useHashedPassword()`), that first write gets hashed twice and fails the check, so auth saves the plaintext and lets your transformer hash it once. If neither write passes the check, it throws. Plaintext is never the first thing written. To write it yourself, set `auth.passwordReset.setPassword`.
|
|
92
|
+
|
|
93
|
+
## Throttling
|
|
94
|
+
|
|
95
|
+
Both presets wrap `loginThrottleMiddleware` and accept its options:
|
|
96
|
+
|
|
97
|
+
| Preset | Tracks | Counts | Default |
|
|
98
|
+
| --- | --- | --- | --- |
|
|
99
|
+
| `tokenIssueThrottleMiddleware` | email + IP | **every** request (a reset request's success is the anti-enumeration answer, so failure-aware counting would never trip) | 3 / 1h, 1h lock |
|
|
100
|
+
| `tokenConsumeThrottleMiddleware` | IP | failures only, cleared on success | 10 / 15m, 15m lock |
|
|
101
|
+
|
|
102
|
+
## Configuration (`src/config/auth.ts`)
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
const authConfigurations: AuthConfigurations = {
|
|
106
|
+
// ...
|
|
107
|
+
verification: {
|
|
108
|
+
expiresIn: "24h",
|
|
109
|
+
field: "emailVerifiedAt",
|
|
110
|
+
url: (token) => `${env("APP_URL")}/verify-email?token=${token}`,
|
|
111
|
+
notification: myVerificationNotification, // optional replacement
|
|
112
|
+
},
|
|
113
|
+
passwordReset: {
|
|
114
|
+
expiresIn: "60m",
|
|
115
|
+
identifierField: "email",
|
|
116
|
+
url: (token) => `${env("APP_URL")}/reset-password?token=${token}`,
|
|
117
|
+
notification: myResetNotification,
|
|
118
|
+
setPassword: async (user, plain) => { /* optional */ },
|
|
119
|
+
},
|
|
120
|
+
oneTimeToken: { model: AppOneTimeToken }, // optional model override
|
|
121
|
+
};
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
The default notifications are `defineNotification` objects (`type: "auth.email-verification"` / `"auth.password-reset"`, `via: ["mail"]`). To replace one, pass anything with a `send(user, { token, expiresAt, url? })` method, for example your own `defineNotification<OneTimeTokenNotificationData>({...})`. `notifications` still has to be installed and configured.
|
|
125
|
+
|
|
126
|
+
## Gotchas
|
|
127
|
+
|
|
128
|
+
- **Without `url` config, the email contains the raw token**, not a link. Set `url` for anything user-facing.
|
|
129
|
+
- **Timing isn't equalised.** An unknown email skips the database write and the send, so the response can come back measurably faster. The throttle limits probing, but it doesn't hide the timing difference.
|
|
130
|
+
- **Channel send failures don't throw.** `@warlock.js/notifications` only rethrows configuration errors (such as a missing `mail` channel). An SMTP failure goes to its `failed` event, so observe it there.
|
|
131
|
+
- `auth.cleanup` hard-deletes expired and consumed `one_time_tokens` rows (never trashed, even on MongoDB).
|
|
132
|
+
|
|
133
|
+
## See also
|
|
134
|
+
|
|
135
|
+
- [`@warlock.js/auth/register-user/SKILL.md`](@warlock.js/auth/register-user/SKILL.md) — where `sendEmailVerification` is usually called
|
|
136
|
+
- [`@warlock.js/auth/throttle-login-attempts/SKILL.md`](@warlock.js/auth/throttle-login-attempts/SKILL.md) — the underlying throttle
|
|
137
|
+
- [`@warlock.js/notifications/configure-notifications/SKILL.md`](@warlock.js/notifications/configure-notifications/SKILL.md) — mail channel setup
|