@appweaver/skill 0.0.0-stage → 3.0.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.
@@ -0,0 +1,1185 @@
1
+ # Security
2
+
3
+ Appweaver provides a comprehensive security system with multiple authentication methods, role-based authorization,
4
+ OAuth2 social login, two-factor authentication, reCAPTCHA, Cloudflare Turnstile, and account management. All security
5
+ features are configurable and can be enabled/disabled independently.
6
+
7
+ ---
8
+
9
+ ## Authentication methods
10
+
11
+ Appweaver supports four authentication methods that can be used independently or combined:
12
+
13
+ | Method | Config flag | Header/mechanism |
14
+ |--------------|----------------------------|--------------------------------------|
15
+ | JWT (Bearer) | Always enabled | `Authorization: Bearer <token>` |
16
+ | HTTP Basic | `SECURITY_BASIC_ENABLED` | `Authorization: Basic <base64>` |
17
+ | API Key | `SECURITY_API_KEY_ENABLED` | `x-api-key: <id><delimiter><secret>` |
18
+ | OAuth2 | Per-provider flags | Browser redirect flow |
19
+
20
+ When multiple methods are enabled, the authentication middleware tries each in order. A request is authenticated if any
21
+ one method succeeds. If no credentials are present for any method, a 401 error is returned.
22
+
23
+ ### Route authentication configuration
24
+
25
+ Routes specify which auth methods they accept:
26
+
27
+ ```ts
28
+ const config = {
29
+ // Accept only JWT
30
+ create: {
31
+ auth: ['jwt']
32
+ },
33
+
34
+ // Accept JWT or API key
35
+ query: {
36
+ auth: ['jwt', 'apiKey']
37
+ },
38
+
39
+ // Public route (no auth required)
40
+ find: {
41
+ public: true
42
+ }
43
+ };
44
+ ```
45
+
46
+ ---
47
+
48
+ ## JWT authentication
49
+
50
+ JWT is the primary authentication method. Appweaver uses RSA (RS256) by default but supports symmetric HMAC (HS256)
51
+ if `SECURITY_JWT_SECRET` is set.
52
+
53
+ ### Key management
54
+
55
+ - RSA 2048-bit key pair generated automatically when the key files are missing and `SECURITY_JWT_AUTO_GENERATE_KEYS`
56
+ is `true`, its default in the `dev`, `local` and `test` environments only: in production every instance would sign
57
+ with keys of its own, so without the keys or a secret the application fails to start with `CONFIGURATION_INVALID`
58
+ - Keys stored at `SECURITY_JWT_PUBLIC_KEY_PATH` and `SECURITY_JWT_PRIVATE_KEY_PATH` (default: `./storage/__keys__/`)
59
+ - Generated keys are written with owner-only permissions (`0600` for the private key, `0700` for its directory)
60
+ - The default `STORAGE_RESERVED_PATHS` value (`['__keys__']`) makes the `__keys__` directory unusable by the file
61
+ storage layer, so uploads can never overwrite the default key location
62
+ - If `SECURITY_JWT_SECRET` is set, HMAC signing is used instead of RSA; the secret takes 32 characters or more
63
+ (`openssl rand -base64 48`), a shorter one being brute-forced offline from any issued token
64
+
65
+ ### Token lifetimes and refresh rotation
66
+
67
+ The access token lives `SECURITY_JWT_EXPIRES_IN` (`15m`), the refresh token `SECURITY_JWT_REFRESH_EXPIRES_IN` (`30d`).
68
+ A refresh token carries an ID (`jti`) and the session it belongs to (`sid`), and is used once: `POST /auth/refresh`
69
+ answers a new pair, and the `Memory` provider keeps the IDs of the current refresh tokens of every session under
70
+ `refresh:<sid>` for the refresh lifetime (`redis` to share it between instances). The token a refresh replaced is
71
+ accepted once more within 15 seconds, for a concurrent refresh (two tabs): it forks the session into two chains, and
72
+ each new token goes on with its own, so both clients keep refreshing. A session keeps at most 10 chains, dropping the
73
+ one refreshed least recently, and the chains whose token expired. Any other use of a replaced token means it was
74
+ copied: the session ends, the user is signed out of every session
75
+ (`logoutAt`) and the refresh answers `401 AUTH_REFRESH_TOKEN_REUSED`. A token of a session the `Memory` no longer
76
+ holds (expired, evicted, or without `sid`) answers `401 AUTH_INVALID_TOKEN`, without a sign-out. A
77
+ client keeps the last refresh token it received, and refreshes once at a time.
78
+
79
+ A refresh issues the tokens of the scope a sign-in of the user would have now: the `enroll` scope once a forced user
80
+ has to enrol a method (the grace period ended, or a role of `forcedRoles` was added), the `twoFactor` scope when the
81
+ user has to pass 2FA and the session did not (the refresh token of a session that passed 2FA, or skipped it on a
82
+ trusted device, carries `tfa`), ending the session. A client handles the answer of a refresh like the one of a login.
83
+ The tokens carry their issue time in milliseconds (`iatMs`), so a token issued before a logout, even within the same
84
+ second, is refused.
85
+
86
+ ### Token types and scopes
87
+
88
+ | Scope | Purpose | Access |
89
+ |-------------|-----------------------|-------------------------------------------------------------------------------------------|
90
+ | `Auth` | Full API access | All routes except `/refresh`, `/two-factor/challenge`, `/two-factor/verify` |
91
+ | `Refresh` | Token renewal only | Only `POST /auth/refresh` |
92
+ | `TwoFactor` | 2FA verification only | Only `POST /auth/account/two-factor/challenge` and `POST /auth/account/two-factor/verify` |
93
+
94
+ ### JWT payload
95
+
96
+ ```json
97
+ {
98
+ "scope": "auth | refresh | twoFactor",
99
+ "source": "password | apiKey | basic | oauth2Google | oauth2Facebook | oauth2X | oauth2Github | oauth2Gitlab | oauth2Linkedin | oauth2Apple | oauth2Microsoft | oauth2Custom",
100
+ "username": "User email (e.g. admin@example.com)",
101
+ "sub": "User ID (e.g. 123)",
102
+ "iat": "Issued at, in seconds (e.g. 1774623924)",
103
+ "exp": "Expiration, in seconds (e.g. 1777215924)"
104
+ }
105
+ ```
106
+
107
+ ### Token validation
108
+
109
+ On every authenticated request, the server:
110
+
111
+ 1. Verifies the JWT signature
112
+ 2. Loads the user by `sub` (user ID), from the cache when possible. Every update or delete of the auth user, through
113
+ the auth service (logout, password change or reset) or the resource routes, evicts the cached user regardless of
114
+ the cache invalidation strategy
115
+ 3. Checks that the user is enabled
116
+ 4. Rejects tokens issued before the user's `logoutAt` (compared in whole seconds)
117
+ 5. Checks that the token scope allows access to the requested URL
118
+
119
+ ### Auth routes
120
+
121
+ The auth routes are at `security.routePrefix` (`/auth`) and the account routes at `security.account.routePrefix`
122
+ (`/auth/account`), never under the `server.apiPrefix` (`/api`) of the resource routes: a test signs in with
123
+ `POST /auth/login` and `{ username, password }`, not `/api/auth/login`.
124
+
125
+ | Method | Path | Auth | Description |
126
+ |--------|-------------------------|---------------------|-------------------------------------------------------------------------------------------------------------|
127
+ | `POST` | `/auth/login` | Public | Login with email and password. Returns access + refresh tokens. Rate limited: 12/min per IP, shared. |
128
+ | `POST` | `/auth/refresh` | JWT (Refresh scope) | Exchange a refresh token for a new access token. Rate limited: 12/window. |
129
+ | `POST` | `/auth/logout` | JWT | Logout. Sets `logoutAt` timestamp to invalidate all existing tokens. |
130
+ | `GET` | `/auth/me` | JWT | Get the current authenticated user's profile. |
131
+ | `POST` | `/auth/change-password` | Any | Change password. Requires current password + new password. Invalidates all tokens. Rate limited: 12/window. |
132
+ | `POST` | `/auth/exchange-token` | Public | Exchange a one-time token (OTT) for JWT access + refresh tokens. Rate limited: 12/window. |
133
+
134
+ The routes taking a password (`/auth/change-password`, `/auth/exchange-token`) have a secure rate limit: while its
135
+ store fails (Redis down), they answer `503` `MEMORY_UNAVAILABLE` instead of letting the requests through, unless
136
+ `rateLimit.secureSkipOnError`. The login is counted by `checkLoginRateLimit` of `@appweaver/web` instead, 12 sign-ins
137
+ of an IP address per minute (`LOGIN_RATE_LIMIT`) in the `Memory` provider, shared by every route signing a user in with
138
+ a password, the password form of the MCP clients included ([mcp.md](./mcp.md#password-sign-in)), so a second way in
139
+ never doubles the guesses. It fails the same way while the store fails, and counts nothing without `rateLimit.enabled`
140
+ or for an address of `rateLimit.allowList`. A route of the application signing a user in with a password calls it before
141
+ `AuthService.login`:
142
+
143
+ ```ts
144
+ await checkLoginRateLimit(request); // RATE_LIMITED (429) past the limit
145
+ ```
146
+
147
+ `/auth/exchange-token` exchanges the one-time tokens of the OAuth2 sign-in and of the 2FA verification, so it is
148
+ registered only with an enabled OAuth2 provider or 2FA, by `registerExchangeTokenRoute` of `@appweaver/web` (once,
149
+ whichever registers it first).
150
+
151
+ A failed login responds with the same `400` "Invalid user credentials" error whether the user does not exist, is
152
+ disabled, or gave a wrong password, so the response does not reveal which accounts exist. HTTP Basic authentication
153
+ answers the same failures with its `401` challenge instead.
154
+
155
+ ---
156
+
157
+ ## HTTP Basic authentication
158
+
159
+ When enabled, requests with an `Authorization: Basic` header are authenticated against the user database.
160
+
161
+ **Configuration:**
162
+
163
+ ```json
164
+ {
165
+ "config": {
166
+ "security": {
167
+ "basic": {
168
+ "enabled": true,
169
+ "realm": "My App",
170
+ "proxyMode": false
171
+ }
172
+ }
173
+ }
174
+ }
175
+ ```
176
+
177
+ Uses `@fastify/basic-auth` plugin. Extracts Base64-encoded `username:password` from the header and validates against the
178
+ user's stored password hash. A user who has to pass 2FA (a user with a method, or every user when it is forced) is
179
+ rejected with `AUTH_FORBIDDEN`, since the password alone would skip the second factor; such a user authenticates with a
180
+ JWT or an API key.
181
+
182
+ ---
183
+
184
+ ## API key authentication
185
+
186
+ API keys provide long-lived, per-user credentials for programmatic access.
187
+
188
+ ### How it works
189
+
190
+ 1. A user signed in with a JWT creates an API key via the CRUD endpoints of `/api-keys`
191
+ 2. The server generates a 64-character random secret of letters and digits and stores its SHA256 hash
192
+ 3. The full key is returned once as `{id}{delimiter}{secret}` (e.g. `42AKa1b2c3d4...`)
193
+ 4. Subsequent reads show only a masked version of the secret, its first and last 4 characters: `a1b2...e5f6`
194
+ 5. On each request, the server extracts the key from the header, parses `id` and `secret`, hashes the secret, and
195
+ compares against the stored hash
196
+
197
+ ### API key format
198
+
199
+ ```
200
+ {id}{SECURITY_API_KEY_DELIMITER}{secret}
201
+ ```
202
+
203
+ Default delimiter is `AK`, so a key looks like: `42AKa1b2c3d4e5f6...`
204
+
205
+ ### API key model
206
+
207
+ | Field | Type | Description |
208
+ |---------------|---------------|------------------------------------------------------|
209
+ | `id` | int | Auto-generated ID. |
210
+ | `key` | string | Whole at creation only, then masked (`a1b2...e5f6`). |
211
+ | `keyHash` | string | SHA256 hash of the key (stored, hidden from API). |
212
+ | `name` | string? | Optional friendly name. |
213
+ | `description` | string? | Optional description. |
214
+ | `enabled` | boolean | Whether the key is active. |
215
+ | `expiresAt` | dateTime? | Optional expiration date. Enforced on every request. |
216
+ | `roles` | Role[]? | The roles of its optional scope. |
217
+ | `permissions` | Permission[]? | The permissions of its optional scope. |
218
+
219
+ ### API key scope
220
+
221
+ A key has the full access of its owner unless it lists a scope, its optional `roles` and `permissions` given by id:
222
+
223
+ ```ts
224
+ // POST /api/api-keys, with the JWT of the owner
225
+ const _ = {
226
+ name: 'CI deploys',
227
+ roles: [3],
228
+ permissions: [12, { id: 15 }]
229
+ };
230
+ ```
231
+
232
+ - A role or permission the owner does not hold fails with `403` `AUTH_API_KEY_PERMISSION_DENIED`, whose details list
233
+ the ids not held (`{ roles, permissions }`). Only a call with a current user is checked.
234
+ - On every request the owner is narrowed to the roles the key lists, and to the permissions it lists among those roles
235
+ (all the roles of the owner when it lists none), matched against the current roles of the owner, so a key loses
236
+ what its owner loses.
237
+ - The narrowed user is the auth user of the request, so the route `roles` and `permissions`, `hasRole`,
238
+ `hasPermission` and the policies apply the scope unchanged. A key listing permissions but no role passes no route
239
+ requiring a role.
240
+ - The key routes accept a JWT only, so a key never changes its own scope.
241
+
242
+ `scopeAuthUser(owner, { roles, permissions })` and `checkApiKeyScope(owner, input)` of `@appweaver/data` do the same
243
+ for an application exposing the keys through its own routes.
244
+
245
+ ### API key policy
246
+
247
+ - Users can only see and manage their own API keys
248
+ - `SECURITY_API_KEY_MAX_DURATION` limits how far in the future `expiresAt` can be set, and an update cannot change
249
+ `expiresAt` or the key
250
+
251
+ ### API key routes
252
+
253
+ `@appweaver/web` registers the routes of `/api-keys` (query, find, create, update, replace and delete, without the
254
+ aggregate and export ones) while API keys are enabled. They accept a JWT only, so a request authenticated with an API
255
+ key never manages the keys: a leaked key cannot create new ones that outlive its revocation.
256
+
257
+ `SECURITY_API_KEY_ROUTES_ENABLED=false` leaves them out, so an application exposes its own, with another path, roles
258
+ or operations, or none. The service and the policy of `@appweaver/data` still generate, hash and mask the keys and
259
+ limit every user to their own:
260
+
261
+ ```ts
262
+ // src/resources/api-key/routes.ts
263
+ import { createRoutes } from '@appweaver/web';
264
+
265
+ export default createRoutes({
266
+ modelName: 'ApiKey',
267
+ actions: ['find', 'query', 'create', 'update', 'delete'],
268
+ defaults: { auth: ['jwt'], roles: ['Developer'] }
269
+ });
270
+ ```
271
+
272
+ **Configuration:**
273
+
274
+ ```json
275
+ {
276
+ "config": {
277
+ "security": {
278
+ "apiKey": {
279
+ "enabled": true,
280
+ "headerName": "x-api-key",
281
+ "delimiter": "AK",
282
+ "maxDuration": 7776000000
283
+ }
284
+ }
285
+ }
286
+ }
287
+ ```
288
+
289
+ ---
290
+
291
+ ## OAuth2 authentication
292
+
293
+ Appweaver supports OAuth2 login with Google, Facebook, X, GitHub, GitLab, LinkedIn, Apple, Microsoft, and a custom
294
+ OpenID Connect provider. All of them are built from the same `createOAuth2Plugin` factory and follow the same flow.
295
+
296
+ ### OAuth2 flow
297
+
298
+ ```
299
+ 1. Client redirects to:
300
+ GET /auth/login/{provider}?redirectToUrl=https://myapp.com/dashboard
301
+
302
+ 2. Server validates redirectToUrl against SECURITY_ALLOWED_REDIRECT_HOSTS
303
+
304
+ 3. Server generates a state token (OTT) and redirects to provider:
305
+ -> https://accounts.google.com/o/oauth2/v2/auth?
306
+ client_id=...&
307
+ redirect_uri=https://myapi.com/auth/login/google/callback&
308
+ state={stateToken}&
309
+ scope=profile email&
310
+ response_type=code
311
+
312
+ 4. User authenticates with the provider
313
+
314
+ 5. Provider redirects back to callback:
315
+ GET /auth/login/{provider}/callback?code={authCode}&state={stateToken}
316
+
317
+ 6. Server verifies the state token (one-time use)
318
+ 7. Server exchanges the code for an access token with the provider
319
+ 8. Server fetches user info from the provider
320
+ 9. Server finds the user by email and invokes the optional checkOAuth2User callback
321
+ (aborts with an error when the callback returns a string or an Error).
322
+ New users are registered unless SECURITY_OAUTH2_REGISTRATION_ENABLED=false
323
+ 10. Server generates an authentication OTT, flagging it when the password has to be confirmed
324
+ 11. Server redirects to the original URL with the token:
325
+ -> https://myapp.com/dashboard?token={ott}[&passwordRequired=true]
326
+ 12. Client exchanges the OTT for JWT tokens, adding the password when it was asked for:
327
+ POST /auth/exchange-token { token: "{ott}", password: "..." }
328
+ -> { accessToken, refreshToken }
329
+ 13. Server records the provider account in the ConnectedAccount table
330
+ ```
331
+
332
+ ### Providers
333
+
334
+ Every provider is disabled by default and enabled with `SECURITY_OAUTH2_<NAME>_ENABLED` plus `_CLIENT_ID` and
335
+ `_CLIENT_SECRET` (JSON: `security.oauth2.<name>`). Enabling one registers `GET /auth/login/<name>` and
336
+ `/auth/login/<name>/callback`. Register the callback URL `{APP_HOSTNAME}{SECURITY_ROUTE_PREFIX}/login/<name>/callback`
337
+ with the provider.
338
+
339
+ | `<name>` | Scopes | User info source |
340
+ |-------------|-------------------------------------------|---------------------------------------------|
341
+ | `google` | `profile`, `email` | `googleapis.com/oauth2/v2/userinfo` |
342
+ | `facebook` | `public_profile`, `email` | `graph.facebook.com/me` |
343
+ | `x` | `users.read`, `tweet.read` | `api.x.com/2/users/me` |
344
+ | `github` | `read:user`, `user:email` | `api.github.com/user` |
345
+ | `gitlab` | `read_user` | `gitlab.com/api/v4/user` |
346
+ | `linkedin` | `openid`, `profile`, `email` | `api.linkedin.com/v2/userinfo` |
347
+ | `apple` | `name`, `email` | the `id_token` (no endpoint) |
348
+ | `microsoft` | `openid`, `profile`, `email`, `User.Read` | `graph.microsoft.com/v1.0/me` |
349
+ | `custom` | `openid`, `profile`, `email` | `{issuer}/protocol/openid-connect/userinfo` |
350
+
351
+ ### Provider anomalies
352
+
353
+ - **X only releases the email address to approved apps.** The `confirmed_email` field is requested explicitly, but X
354
+ serves it solely to apps granted the email permission in the developer portal — without it the call fails and the
355
+ login is rejected with a 403.
356
+ - **Apple's callback is a `POST`** (`response_mode=form_post`), the identity comes from the `id_token`, and the client
357
+ secret is an ES256 JWT signed at startup from `teamId`/`keyId`/the `.p8` key — expiring after
358
+ `clientSecretExpiresIn` seconds, so a longer-running process needs a restart. Set `clientSecret` directly to use your
359
+ own. The name is sent **only on the first authorization**; later logins yield empty `firstName`/`lastName`.
360
+ - **GitHub** falls back to `/user/emails` for the primary-verified address when the profile email is private and rejects
361
+ accounts with no verified address.
362
+ - **GitLab** self-managed instances need `SECURITY_OAUTH2_GITLAB_BASE_URL` and `_USER_INFO_URL`.
363
+ - **Microsoft** uses `SECURITY_OAUTH2_MICROSOFT_TENANT` (default `common`) in its endpoints, and its Graph photo is an
364
+ authenticated binary, so it arrives as `avatarFile` instead of `avatarUrl`.
365
+ - **Custom** targets any OpenID Connect provider (Keycloak, Auth0, …) and needs `issuer` instead of preset endpoints.
366
+
367
+ ### Authorization parameters
368
+
369
+ `security.oauth2.<name>.authorizationParams` adds query parameters to the authorization request of a provider, e.g.
370
+ to show the account chooser after a logout instead of signing the user straight back in:
371
+
372
+ ```dotenv
373
+ SECURITY_OAUTH2_GOOGLE_AUTHORIZATION_PARAMS=prompt:select_account
374
+ SECURITY_OAUTH2_FACEBOOK_AUTHORIZATION_PARAMS=auth_type:reauthenticate
375
+ ```
376
+
377
+ `prompt` works with Google, Microsoft, GitHub and OpenID Connect providers (`custom`); Facebook uses `auth_type`.
378
+ Parameters the flow sets itself (`client_id`, `redirect_uri`, `state`, `scope`, ...) fail the startup.
379
+
380
+ ### Account takeover protection
381
+
382
+ An OAuth2 sign-in matches an existing user by email, so a provider account carrying someone else's address must not by
383
+ itself unlock a password-protected account. The first time a provider is linked to a user that has a `passwordHash`, the
384
+ redirect carries `&passwordRequired=true` and `POST /auth/exchange-token` rejects the token unless
385
+ `{ token, password }` is sent. The one-time token is spent either way, so a wrong password means restarting the flow.
386
+
387
+ Confirmation happens once: the pairing is stored in `ConnectedAccount` and later sign-ins pass through. Users without a
388
+ password, and users being registered by the current sign-in, are never asked. There is no flag to switch this off — the
389
+ check only ever fires where skipping it would hand the account over. Without a `ConnectedAccount` table there is nowhere
390
+ to record the confirmation, so the password is asked on every sign-in instead.
391
+
392
+ A user **without a password** has nothing to confirm the link with, so a provider account is linked to them only when
393
+ the provider verified the address (`UserInfo.emailVerified`), or the provider account is already linked to them;
394
+ otherwise the callback fails with `403 OAUTH2_EMAIL_UNVERIFIED`. The providers report it as follows:
395
+
396
+ | Provider | `emailVerified` |
397
+ |-------------------------|------------------------------------------------------------------------|
398
+ | Google | `verified_email` (v2 user info) or `email_verified` (OpenID Connect) |
399
+ | Apple, LinkedIn, custom | the `email_verified` claim (`true` or `"true"`), unverified without it |
400
+ | GitLab | `confirmed_at` of the user |
401
+ | GitHub, X | always: they return only a verified (confirmed) address |
402
+ | Facebook | never: the Graph API does not say whether it confirmed the address |
403
+ | Microsoft | never: Microsoft Graph does not say, and a tenant sets `mail` freely |
404
+
405
+ A user registered by an OAuth2 sign-in gets `verifiedEmail` from the provider, so a Facebook or Microsoft user verifies
406
+ the address through the account routes like a password user. A local `verifiedEmail: false` does not block the sign-in
407
+ of an existing user; the exchange marks the address verified only when the provider verified it.
408
+
409
+ Whoever registers first with an address the provider did not verify may be someone else than its owner (pre-account
410
+ takeover). So when the owner proves an address that was unverified, the accounts linked before are unlinked: a sign-in
411
+ with a provider that verified it, on an account without a password or without the password confirming it, unlinks
412
+ every other provider account of the user and signs out every session, and a password reset unlinks every provider
413
+ account (and marks the address verified). A user who linked a Facebook or Microsoft account before verifying the
414
+ address through the account routes keeps it. A provider of an
415
+ application (`createOAuth2Plugin`) returns `emailVerified` from its `extractUserInfo`, unverified when left out.
416
+
417
+ ### Connected accounts
418
+
419
+ `ConnectedAccount` pairs a provider account with a local user: `provider`, `providerAccountId`, `scope`, `lastLoginAt`
420
+ (`createdAt` holds the link date) and a relation to the auth model, unique on `[provider, providerAccountId]`. A
421
+ provider account belongs to one user only — relinking it elsewhere fails with a 403, also when two first sign-ins race
422
+ to create the link.
423
+
424
+ The table exists when any OAuth2 provider is enabled; `ConnectedAccount` in `database.keepTables` keeps it after
425
+ disabling OAuth2, like `ApiKey` does for the API keys.
426
+
427
+ ### OAuth2 registration control and hooks
428
+
429
+ **Disable OAuth2 registration** — set `SECURITY_OAUTH2_REGISTRATION_ENABLED=false` (JSON:
430
+ `security.oauth2.registrationEnabled`) to prevent new users from being created during OAuth2 login. Only users that
431
+ already exist in the database (matched by email) can then log in via OAuth2; unknown emails receive a 403 error.
432
+
433
+ **`checkOAuth2User` callback** — an optional callback on `createAuthService` invoked on every OAuth2 login, before a
434
+ user is registered or authenticated. It receives the auth source, the user info extracted from the provider, and the
435
+ existing auth user (or `null` when the user would be newly registered). Return nothing to proceed, or return a string
436
+ or an `Error` to abort the flow with an `OAUTH2_USER_REJECTED` error (403), or an `AppweaverError`, i.e. an
437
+ `ApplicationError`, which is thrown as it is:
438
+
439
+ ```ts
440
+ // src/resources/user/service.ts
441
+ import { ApplicationError, AuthSource } from '@appweaver/common';
442
+ import { defineErrors } from '@appweaver/common';
443
+ import { createAuthService } from '@appweaver/data';
444
+
445
+ const UserErrors = defineErrors({
446
+ CompanyAccountRequired: { status: 403, title: 'Company account required' }
447
+ });
448
+
449
+ export default createAuthService({
450
+ modelName: 'User',
451
+ checkOAuth2User: (source, userInfo, authUser) => {
452
+ if (!userInfo.email.endsWith('@mycompany.com')) {
453
+ return new ApplicationError(
454
+ UserErrors.CompanyAccountRequired,
455
+ 'Only company accounts are allowed'
456
+ );
457
+ }
458
+ if (!authUser && source === AuthSource.OAuth2Facebook) {
459
+ return 'New accounts cannot be created via Facebook';
460
+ }
461
+ // Return nothing to proceed with registration/login
462
+ },
463
+ registrationData: (source, email, password, additionalData) => ({
464
+ email,
465
+ password,
466
+ name: `${additionalData?.firstName} ${additionalData?.lastName}`
467
+ })
468
+ });
469
+ ```
470
+
471
+ **User avatar** — `registrationData` and `registrationFiles` receive the provider's picture URL as
472
+ `additionalData.avatarUrl` and the downloaded image as `additionalData.avatarFile`
473
+ (`{ name, mimeType, size, data: Buffer }`). `SECURITY_OAUTH2_FETCH_AVATAR_ENABLED=false` (JSON:
474
+ `security.oauth2.fetchAvatarEnabled`) skips the download, leaving `avatarFile` `undefined`. The download is best-effort:
475
+ failures are logged and registration proceeds without the file. Since the URL comes from a profile, it is fetched only
476
+ over HTTPS, never from a local host, a private or special-purpose address (loopback, private networks, link-local and
477
+ cloud metadata, CGNAT, documentation, benchmarking, multicast and reserved ranges, and the IPv4 address an IPv6
478
+ address embeds: IPv4-mapped, IPv4-compatible, NAT64 and 6to4; Teredo refused), a host name being resolved and refused
479
+ when any of its addresses is such, the connection made to the checked address (so a second resolution cannot rebind
480
+ it), following at most 3 redirects to such URLs (the access token of Microsoft only to the URL itself), within 10
481
+ seconds and 5 MB, and kept only as a JPEG, PNG, GIF, WebP or AVIF image. On Bun, whose `fetch` cannot be made to connect
482
+ to the checked address, the avatar is never downloaded (`avatarFile` stays `undefined`, a warning logged).
483
+
484
+ **`registrationFiles` callback** — an optional callback on `createAuthService` that attaches the avatar (or any other
485
+ file) to a newly registered user. A file must be linked to an existing resource, so it cannot be part of the
486
+ registration payload and is stored right after the user record is created. Return a map of the model's **file fields**
487
+ to the files to store; nullish values are skipped, so nothing is stored unless the callback asks for it:
488
+
489
+ ```ts
490
+ // src/resources/user/service.ts
491
+ export default createAuthService({
492
+ modelName: 'User',
493
+ registrationData: (source, email, password, additionalData) => ({
494
+ email,
495
+ password,
496
+ firstName: additionalData?.firstName ?? ''
497
+ }),
498
+ registrationFiles: (source, additionalData) => ({
499
+ avatar: additionalData?.avatarFile
500
+ })
501
+ });
502
+ ```
503
+
504
+ The file is validated against the `files.avatar` config of the model (media type, size limit, name pattern, image
505
+ processing). Storing it is the best effort: a rejected file is logged and never fails the registration. Outside
506
+ registration, use [`FileService.saveBuffer()`](./storage.md#saving-an-in-memory-file).
507
+
508
+ ### Client-side OAuth2 integration example
509
+
510
+ ```ts
511
+ // 1. Redirect user to OAuth2 login
512
+ window.location.href =
513
+ 'https://api.myapp.com/auth/login/google?redirectToUrl=https://myapp.com/auth/callback';
514
+
515
+ // 2. On the callback page, extract the token from URL params
516
+ const params = new URLSearchParams(window.location.search);
517
+ const token = params.get('token');
518
+
519
+ // 3. Exchange the OTT for JWT tokens
520
+ const response = await fetch('https://api.myapp.com/auth/exchange-token', {
521
+ method: 'POST',
522
+ headers: { 'Content-Type': 'application/json' },
523
+ body: JSON.stringify({ token })
524
+ });
525
+
526
+ const { accessToken, refreshToken } = await response.json();
527
+
528
+ // 4. Use the access token for subsequent requests
529
+ fetch('https://api.myapp.com/api/products/query', {
530
+ headers: { Authorization: `Bearer ${accessToken}` }
531
+ });
532
+ ```
533
+
534
+ ### Redirect URL validation
535
+
536
+ All redirect URLs (for OAuth2, email verification, password reset) are validated against
537
+ `SECURITY_ALLOWED_REDIRECT_HOSTS`, by default the host of `APP_HOSTNAME` only. List the hosts of the clients:
538
+
539
+ ```json
540
+ {
541
+ "config": {
542
+ "security": {
543
+ "allowedRedirectHosts": ["myapp.com", "admin.myapp.com"]
544
+ }
545
+ }
546
+ }
547
+ ```
548
+
549
+ `['*']` allows any host, an open redirect: keep it for development.
550
+
551
+ ---
552
+
553
+ ## Authorization
554
+
555
+ ### Role-based access control (RBAC)
556
+
557
+ Appweaver uses a role-permission model:
558
+
559
+ - **Roles** have a unique name and contain zero or more **permissions**
560
+ - **Users** are assigned zero or more roles
561
+ - Routes can require specific roles or permissions
562
+
563
+ ### Route authorization
564
+
565
+ ```ts
566
+ // Require any of these roles (OR logic)
567
+ create: {
568
+ roles: ['Admin', 'Editor'];
569
+ }
570
+
571
+ // Require any of these permissions (OR logic)
572
+ update: {
573
+ permissions: ['product:update', 'product:manage'];
574
+ }
575
+ ```
576
+
577
+ ### Authorization check order
578
+
579
+ On every authenticated request:
580
+
581
+ 1. Verify user exists and is enabled
582
+ 2. Verify the token was not issued before `logoutAt`
583
+ 3. Verify JWT scope allows access to the URL
584
+ 4. Verify the user has required roles (if configured)
585
+ 5. Verify the user has required permissions (if configured)
586
+
587
+ ### Helper functions
588
+
589
+ ```ts
590
+ import { currentAuthUser } from '@appweaver/core';
591
+ import {
592
+ hasRole,
593
+ hasRoles,
594
+ hasPermission,
595
+ hasPermissions
596
+ } from '@appweaver/data';
597
+
598
+ const user = currentAuthUser();
599
+
600
+ hasRole(user, 'Admin'); // boolean
601
+ hasRoles(user, ['Admin', 'Editor']); // OR: has at least one
602
+ hasRoles(user, ['Admin', 'Editor'], 'and'); // AND: has all
603
+
604
+ hasPermission(user, 'product:create'); // boolean
605
+ hasPermissions(user, ['product:create', 'product:update']); // OR
606
+ hasPermissions(user, ['product:create', 'product:update'], 'and'); // AND
607
+ ```
608
+
609
+ ### Request context helpers
610
+
611
+ ```ts
612
+ import {
613
+ currentAuthUser,
614
+ currentAuthType,
615
+ currentAuthSource
616
+ } from '@appweaver/core';
617
+
618
+ const user = currentAuthUser(); // Current authenticated user
619
+ const type = currentAuthType(); // 'jwt' | 'apiKey' | 'basic'
620
+ const source = currentAuthSource(); // 'Password' | 'OAuth2Google' | 'ApiKey' | etc.
621
+ ```
622
+
623
+ ---
624
+
625
+ ## Two-factor authentication (2FA)
626
+
627
+ When enabled, 2FA adds a second verification step to a sign-in, by a password or by OAuth2. A user enables any of
628
+ three methods, each one once:
629
+
630
+ | Method | The code | Available with |
631
+ |---------|---------------------------------------------------------------------------------------------------|-------------------------------------------------|
632
+ | `Email` | Sent by email (`emails/two-factor-code` template), to a verified email address | A mailer (`@appweaver/nodemailer`, or `json`) |
633
+ | `Sms` | Sent by SMS (`sms.twoFactorCode` translation), to a verified phone number | An SMS sender (`@appweaver/twilio`, or `json`) |
634
+ | `Totp` | Generated by an authenticator app (TOTP of RFC 6238, Google Authenticator, Authy, 1Password, ...) | `security.account.twoFactor.totp.encryptionKey` |
635
+
636
+ The methods of a user are ordered, the first one being their default, and the `TwoFactorMethodType` enum of
637
+ `@appweaver/common` names them. The auth user carries the confirmed ones as `authUser.twoFactorMethods`, i.e.
638
+ `['Totp', 'Email']`, loaded with the user by `AuthService`. They are stored in the `TwoFactorMethod` framework model,
639
+ linked to the auth model and deleted with it, and managed by the 2FA routes only, never by the resource routes.
640
+
641
+ ### Configuration
642
+
643
+ ```json
644
+ {
645
+ "config": {
646
+ "security": {
647
+ "account": {
648
+ "twoFactor": {
649
+ "enabled": true,
650
+ "forced": false,
651
+ "forcedRoles": [],
652
+ "gracePeriod": "7d",
653
+ "challengeTtl": 300000,
654
+ "methods": ["Email", "Sms", "Totp"],
655
+ "defaultMethod": "Email",
656
+ "codeLength": 6,
657
+ "maxAttempts": 5,
658
+ "totp": {
659
+ "issuer": "My App",
660
+ "encryptionKey": "${TOTP_ENCRYPTION_KEY}"
661
+ }
662
+ }
663
+ }
664
+ }
665
+ }
666
+ }
667
+ ```
668
+
669
+ - `enabled` - Enable 2FA, off by default: its routes, the `/auth/exchange-token` route and the `TwoFactorMethod` and
670
+ `TwoFactorRecoveryCode` models exist only with it
671
+ - `forced` - Require 2FA of every user (or of the `forcedRoles`); see [forced 2FA](#forced-2fa) below
672
+ - `methods` - The methods users may enable, offered only with their service (see the table above)
673
+ - `maxAttempts` - Wrong codes of a challenge, revoked on the last one (`ACCOUNT_TWO_FACTOR_TOO_MANY_ATTEMPTS`)
674
+ - `totp.encryptionKey` - Encrypts the TOTP secrets in the database (AES-256-GCM); changing it makes the enabled TOTP
675
+ methods unusable
676
+
677
+ A user with a method, or every user when 2FA is forced, is challenged on every sign-in. A user whose methods became
678
+ unavailable (i.e. the SMS sender was removed) is still challenged, so 2FA never turns off on its own, and their
679
+ challenge fails with `ACCOUNT_TWO_FACTOR_METHOD_UNAVAILABLE` until the method is available again.
680
+
681
+ ### Forced 2FA
682
+
683
+ With `forced` (and `forcedRoles` for some roles only), a user without a method of their own:
684
+
685
+ - verifies with the `defaultMethod` when they have its verified channel: a verified email for `Email`, a verified phone
686
+ for `Sms` (never `Totp`, which needs a setup), so no code is ever sent to an unverified address;
687
+ - otherwise must enrol: the sign-in answers the tokens of the `enroll` scope with `twoFactorEnroll: true`, which reach
688
+ only the 2FA setup (`GET`/`POST /auth/account/two-factor/methods`, `/auth/account/two-factor/totp/setup`,
689
+ `/auth/account/two-factor/totp/confirm`), the email and phone
690
+ verification routes, `/auth/me` and `/auth/logout`, and are never refreshed into the `auth` scope (a refresh of a
691
+ session whose user has to enrol now answers them too). Once a method is enabled, the client
692
+ signs in again and passes the challenge;
693
+ - during the `gracePeriod` (a duration, from the creation of the account or `forcedSince`, the later) still signs in
694
+ fully, the tokens telling the end of it in `enrollBy`.
695
+
696
+ The startup fails when the `defaultMethod` has no service (no mailer for `Email`, no SMS sender for `Sms`). An
697
+ administrator (`resetRoles`, `['Admin']`) resets the 2FA of a user who lost every method with
698
+ `DELETE /auth/account/two-factor/users/:id`. API keys stay outside 2FA, basic auth refuses a user with 2FA or to enrol, and
699
+ the MCP sign-in refuses a user to enrol.
700
+
701
+ ### Sign-in flow with 2FA
702
+
703
+ ```
704
+ 1. POST /auth/login { username, password } (or the OAuth2 sign-in, then POST /auth/exchange-token)
705
+ -> 2FA required: tokens of the twoFactor scope, with the methods of the user { accessToken, ..., twoFactorMethods }
706
+ -> 2FA not required: tokens of the auth scope (full access)
707
+
708
+ 2. POST /auth/account/two-factor/challenge { method?, purpose? } (with the token of the twoFactor scope)
709
+ -> Without a method, the default one of the user (the first of twoFactorMethods), 'Recovery' for a recovery code
710
+ -> email / sms: sends a code; totp: waits for the code of the authenticator app
711
+ -> Returns { challengeId, expiresIn, method, destination, methods }
712
+ (destination: the masked address or number, i.e. "+385*******67", null for totp)
713
+
714
+ 3. POST /auth/account/two-factor/verify { challengeId, code } (with the token of the twoFactor scope)
715
+ -> A wrong code: ACCOUNT_TWO_FACTOR_CODE_INVALID with details.attemptsLeft
716
+ -> Returns { token } (one-time authentication token)
717
+
718
+ 4. POST /auth/exchange-token { token }
719
+ -> Returns the tokens of the auth scope, keeping the source of the sign-in (i.e. oauth2Google)
720
+ ```
721
+
722
+ Changing the password (`POST /auth/change-password`) returns the tokens of the `auth` scope, since the user passed 2FA
723
+ to call it. The refresh token of the tokens of the `twoFactor` scope keeps that scope and the expiration of the access token,
724
+ so `/auth/refresh` never turns them into the tokens of the `auth` scope without the challenge.
725
+
726
+ The challenge fails with `ACCOUNT_TWO_FACTOR_METHOD_UNAVAILABLE` for a method the application does not offer, and with
727
+ `ACCOUNT_TWO_FACTOR_METHOD_NOT_ENABLED` (`details.enabledMethods`) for one the user has not enabled. A challenge belongs to the
728
+ user it was sent to, and a TOTP code is accepted once, a later code of the same time step being rejected. The `purpose`
729
+ of a challenge (`authentication` by default) is the purpose of the one-time token it issues, so an application can
730
+ verify a sensitive action with 2FA and consume the token itself; the purposes of the framework's own tokens
731
+ (`emailVerification`, `passwordReset`, `phoneVerification`, `twoFactorVerification`) are rejected with `VALIDATION_FAILED`.
732
+
733
+ ### Managing the methods
734
+
735
+ The routes below take the token of the auth scope. Each one answering with the methods returns
736
+ `{ enabled, available }`, the enabled methods of the user in their order and the ones they may enable.
737
+
738
+ ```
739
+ GET /auth/account/two-factor/methods -> { enabled: ['Totp'], available: ['Email', 'Sms', 'Totp'] }
740
+ POST /auth/account/two-factor/methods { method: 'Email' } -> enables Email (needs a verified email address) or Sms
741
+ (needs a verified phone number), as the last method
742
+ POST /auth/account/two-factor/totp/setup -> { secret, otpauthUrl, expiresIn }, show otpauthUrl as a QR code
743
+ POST /auth/account/two-factor/totp/confirm { code } -> enables totp with a first code of the app, within setupTtl
744
+ PUT /auth/account/two-factor/methods/order { methods } -> every enabled method in the new order, the first is the default
745
+ DELETE /auth/account/two-factor/methods/:method { password } -> disables a method, the password required when the user has one
746
+ ```
747
+
748
+ `TwoFactorService` of `@appweaver/web` does the same in code: `availableMethods`, `listMethods`, `sendChallenge`,
749
+ `verifyChallenge`, `enableMethod`, `setupTotp`, `confirmTotp`, `orderMethods`, `disableMethod`,
750
+ `generateRecoveryCodes`, `resetTwoFactor` and `removeSmsMethod`.
751
+
752
+ ### Recovery codes
753
+
754
+ Recovery codes stand in for the 2FA methods of a user who lost them, i.e. a lost phone. A user with a method generates
755
+ `recoveryCodes.count` codes (10 by default) of `recoveryCodes.length` characters (16 by default, at most 128), shown in
756
+ groups of four (`7G2K-QX9M-4TZB-8HRW`, Crockford Base32 without `I`, `L`, `O` and `U`):
757
+
758
+ ```
759
+ POST /auth/account/two-factor/recovery-codes { password } -> { codes: [...], generatedAt }, shown only this once
760
+ ```
761
+
762
+ The password is required when the user has one, and a new set replaces the previous one. Only the SHA-256 of each code
763
+ is stored, in the `TwoFactorRecoveryCode` framework model, since the randomness of a code makes a slow hash pointless.
764
+ A code signs the user in once, by the challenge of the `Recovery` method, which sends nothing:
765
+
766
+ ```
767
+ 1. POST /auth/account/two-factor/challenge { method: 'Recovery' } (with the token of the twoFactor scope)
768
+ 2. POST /auth/account/two-factor/verify { challengeId, code: '7g2k qx9m 4tzb 8hrw' } (case, spaces and hyphens ignored)
769
+ 3. POST /auth/exchange-token { token }
770
+ ```
771
+
772
+ A used code is never accepted again, also by a concurrent verification, and a wrong one counts against the
773
+ `maxAttempts` of the challenge. The user is emailed about every used code (`emails/recovery-code-used`), unless
774
+ `recoveryCodes.notifyOnUse` is off, and a failing email never fails the sign-in. `Recovery` is a challenge method only,
775
+ never one of the enabled methods, so it is not ordered and never the default; a challenge for it fails with
776
+ `ACCOUNT_TWO_FACTOR_METHOD_NOT_ENABLED` without an unused code. Disabling the last method deletes the codes, and
777
+ `TwoFactorService.resetTwoFactor(authUserId)` removes every method and code of a user, i.e. for an administrator helping
778
+ a user who lost them all.
779
+
780
+ ### Remembered devices
781
+
782
+ With `security.account.twoFactor.rememberDevice.enabled` (off by default), a user who passed 2FA on a device may skip
783
+ it there on the next sign-ins. The verification asks for it, and the exchange answers a device token the client keeps
784
+ (i.e. in its secure storage) and sends with every sign-in:
785
+
786
+ ```
787
+ 1. POST /auth/account/two-factor/verify { challengeId, code, rememberDevice: true } -> { token }
788
+ 2. POST /auth/exchange-token { token } -> { accessToken, ..., deviceToken, deviceTokenExpiresIn }
789
+ 3. POST /auth/login { username, password, deviceToken } -> tokens of the auth scope, and a new deviceToken
790
+ ```
791
+
792
+ A valid token of that user skips the challenge of `POST /auth/login` and of the exchange of an OAuth2 sign-in
793
+ (`POST /auth/exchange-token { token, deviceToken }`), answering the tokens of the `auth` scope. With `rotate` (the
794
+ default) a new device token replaces the one sent, so a stolen copy stops working once the device signs in again; the
795
+ client stores the last one. The new token keeps the expiration of the device (`deviceTokenExpiresIn` is what is left of
796
+ it), so rotating never extends the trust, and of concurrent sign-ins with the same token only one replaces it. An unknown, expired or foreign token is ignored: the sign-in asks for 2FA as usual.
797
+
798
+ | Key | Default | Meaning |
799
+ |---------------------------------------|---------|----------------------------------------------------------------|
800
+ | `rememberDevice.enabled` | `false` | Issue and accept the device tokens |
801
+ | `rememberDevice.ttl` | `30d` | How long a device stays trusted |
802
+ | `rememberDevice.maxDevices` | `10` | The most devices of a user, the oldest forgotten beyond it |
803
+ | `rememberDevice.rotate` | `true` | Replace the token on every sign-in it skips 2FA for |
804
+
805
+ Only the SHA-256 of a token is stored, in the `TrustedDevice` framework model (with the 2FA models, kept by
806
+ `database.keepTables: ['TwoFactorMethod']`), with the user agent of the sign-in as its label. A logout keeps the
807
+ devices trusted; every device of a user is forgotten when the password is changed (`POST /auth/change-password`) or
808
+ reset, a 2FA method is enabled or disabled, the 2FA of the user is reset, or the user is disabled. A password changed
809
+ through the resource routes of the auth model leaves them: call `TrustedDeviceService.forgetAll` in the hook doing it. The
810
+ device is identified by its token alone, never fingerprinted. A remembered device never skips the enrolment of a forced
811
+ user, basic auth still refuses 2FA users, and the MCP sign-in page keeps asking for the code. The user lists and
812
+ forgets their devices:
813
+
814
+ ```
815
+ GET /auth/account/two-factor/devices -> { devices: [{ id, label, createdAt, lastUsedAt, expiresAt }] }
816
+ DELETE /auth/account/two-factor/devices/:id -> 204, 404 for a device of someone else
817
+ DELETE /auth/account/two-factor/devices -> 204
818
+ ```
819
+
820
+ `TrustedDeviceService` (`trust`, `use`, `list`, `forget`, `forgetAll`) does the same in code.
821
+
822
+ ### Phone verification
823
+
824
+ The SMS method needs a verified phone number (`phone`, `verifiedPhone` of the auth model, never accepted by the
825
+ resource routes):
826
+
827
+ ```
828
+ 1. POST /auth/account/send-verify-phone { phone: '+385911234567' } -> { challengeId, expiresIn }, a code by SMS
829
+ POST /auth/account/send-verify-phone {} -> the same, to the number of the user
830
+ 2. POST /auth/account/verify-phone { challengeId, code } -> { message }, the number is verified
831
+ ```
832
+
833
+ The number is in the E.164 format. Without one, the code goes to the `phone` of the user (i.e. stored by the
834
+ sign-up code of the application), and without that the request fails with `ACCOUNT_PHONE_NOT_SET`. A new number
835
+ replaces the current one only once verified. Verifying another number than the current one removes the `Sms` method of
836
+ the user, enabled again for the new number. The routes are registered only with an SMS sender
837
+ ([sms.md](./sms.md#account-messages)), and
838
+ `AccountService` answers `ACCOUNT_FEATURE_UNAVAILABLE` without one. `AccountService.sendPhoneVerification` and
839
+ `AccountService.verifyPhone` do the same in code.
840
+
841
+ ### 2FA routes
842
+
843
+ | Method | Path | Auth | Rate limit | Description |
844
+ |----------|--------------------------------------------|------------------|------------|----------------------------------------------------|
845
+ | `POST` | `/auth/account/two-factor/challenge` | JWT (twoFactor) | 10/15min | Send a 2FA challenge by a method. |
846
+ | `POST` | `/auth/account/two-factor/verify` | JWT (twoFactor) | 12/window | Verify a code, returns the OTT for token exchange. |
847
+ | `GET` | `/auth/account/two-factor/methods` | JWT (auth scope) | - | List the enabled and the available methods. |
848
+ | `POST` | `/auth/account/two-factor/methods` | JWT (auth scope) | - | Enable the email or SMS method. |
849
+ | `PUT` | `/auth/account/two-factor/methods/order` | JWT (auth scope) | - | Order the methods, the first is the default. |
850
+ | `DELETE` | `/auth/account/two-factor/methods/:method` | JWT (auth scope) | 12/window | Disable a method, with the password. |
851
+ | `POST` | `/auth/account/two-factor/totp/setup` | JWT (auth scope) | - | Start the setup of an authenticator app. |
852
+ | `POST` | `/auth/account/two-factor/totp/confirm` | JWT (auth scope) | 12/window | Confirm the setup with a first code. |
853
+ | `POST` | `/auth/account/two-factor/recovery-codes` | JWT (auth scope) | 12/window | Generate the recovery codes, with the password. |
854
+ | `GET` | `/auth/account/two-factor/devices` | JWT (auth scope) | - | List the trusted devices. |
855
+ | `DELETE` | `/auth/account/two-factor/devices/:id` | JWT (auth scope) | - | Forget a trusted device. |
856
+ | `DELETE` | `/auth/account/two-factor/devices` | JWT (auth scope) | - | Forget every trusted device. |
857
+ | `DELETE` | `/auth/account/two-factor/users/:id` | JWT (resetRoles) | - | Reset the 2FA of a user who lost every method. |
858
+ | `POST` | `/auth/account/send-verify-phone` | JWT (auth scope) | 5/15min | Send a phone verification code by SMS. |
859
+ | `POST` | `/auth/account/verify-phone` | JWT (auth scope) | 12/window | Verify the phone number. |
860
+
861
+ The 2FA routes are registered only with `security.account.twoFactor.enabled`, the TOTP setup only with the `Totp` method
862
+ available (its `encryptionKey` set), the recovery codes only with `recoveryCodes.enabled`, and the devices only with
863
+ `rememberDevice.enabled`. The phone verification
864
+ routes need an SMS sender, whether 2FA is enabled or not.
865
+
866
+ ---
867
+
868
+ ## reCAPTCHA
869
+
870
+ Appweaver integrates Google reCAPTCHA v3 for bot protection on sensitive endpoints.
871
+
872
+ ### Configuration
873
+
874
+ ```json
875
+ {
876
+ "config": {
877
+ "security": {
878
+ "recaptcha": {
879
+ "enabled": true,
880
+ "secret": "your-recaptcha-secret-key",
881
+ "headerName": "x-recaptcha-token",
882
+ "minScore": 0.4
883
+ }
884
+ }
885
+ }
886
+ }
887
+ ```
888
+
889
+ ### How it works
890
+
891
+ 1. Client gets a reCAPTCHA token from the Google reCAPTCHA v3 widget
892
+ 2. Client includes the token in the request header: `x-recaptcha-token: <token>`
893
+ 3. Server sends the token to Google's verification API along with the secret key and client IP
894
+ 4. Server validates:
895
+ - `success` flag is `true`
896
+ - `action` matches the expected action (if configured on the route)
897
+ - `score` is at or above `SECURITY_RECAPTCHA_MIN_SCORE`
898
+
899
+ ### Using reCAPTCHA on custom routes
900
+
901
+ ```ts
902
+ registerRoute(
903
+ async (router) => {
904
+ router.post('/contact', { handler: contactHandler });
905
+ },
906
+ { recaptcha: true, recaptchaAction: 'contact_form', public: true }
907
+ );
908
+ ```
909
+
910
+ On resource routes:
911
+
912
+ ```ts
913
+ createRoutes({
914
+ modelName: 'Comment',
915
+ create: { recaptcha: true, recaptchaAction: 'create_comment' }
916
+ });
917
+ ```
918
+
919
+ ### Routes with reCAPTCHA by default
920
+
921
+ - `POST /auth/account/send-reset-password` (action: `send-reset-password`)
922
+ - `POST /auth/account/reset-password` (action: `reset-password`)
923
+
924
+ ### Auth routes with a bot check
925
+
926
+ The login, the token refresh and the password change require a token only once opted in, each by its name in the
927
+ `authRoutes` of `security.recaptcha` or `security.turnstile` while that one is enabled, for the action of its name in
928
+ kebab-case: `login`, `refresh` and `change-password`. The route then documents the header and the `RECAPTCHA_*` or
929
+ `TURNSTILE_*` errors in its OpenAPI schema, and the login counts the attempt before verifying the token.
930
+
931
+ ```json
932
+ {
933
+ "security": {
934
+ "recaptcha": {
935
+ "enabled": true,
936
+ "secret": "...",
937
+ "authRoutes": ["login", "changePassword"]
938
+ },
939
+ "turnstile": {
940
+ "enabled": true,
941
+ "secret": "...",
942
+ "authRoutes": ["login"]
943
+ }
944
+ }
945
+ }
946
+ ```
947
+
948
+ The client passes the token with the request options, i.e. `client.auth.login(credentials, { headers:
949
+ { 'x-recaptcha-token': token } })`, and calls `refresh` with a new token each time. While the login requires a bot
950
+ check, the password form of the MCP sign-in is left out, since its page cannot run the widget.
951
+ `authRouteCaptcha(route)` of `@appweaver/web` returns the checks a route requires.
952
+
953
+ ---
954
+
955
+ ## Cloudflare Turnstile
956
+
957
+ Works like reCAPTCHA, with its own config, route options, header, and `TURNSTILE_*` error codes, so both can run side
958
+ by side.
959
+
960
+ ```json
961
+ {
962
+ "config": {
963
+ "security": {
964
+ "turnstile": {
965
+ "enabled": true,
966
+ "secret": "your-turnstile-secret-key"
967
+ }
968
+ }
969
+ }
970
+ }
971
+ ```
972
+
973
+ The client sends the widget token in the `x-turnstile-token` header, and the server verifies it with Cloudflare's
974
+ `siteverify` API. Enable it per route with `turnstile: true` or `turnstileAction` (also checks the widget's
975
+ `data-action`):
976
+
977
+ ```ts
978
+ registerRoute(handler, { turnstileAction: 'contact_form', public: true });
979
+ createRoutes({ modelName: 'Comment', create: { turnstile: true } });
980
+ ```
981
+
982
+ A rejected token fails with `TURNSTILE_INVALID` (Cloudflare `error-codes` in `details.errorCodes`), and a bad secret
983
+ or unreachable API with `TURNSTILE_UNAVAILABLE`. The password reset routes also verify it while Turnstile is enabled,
984
+ and the auth routes of its `authRoutes` (see [above](#auth-routes-with-a-bot-check)).
985
+
986
+ ---
987
+
988
+ ## Account management
989
+
990
+ The email verification and password reset routes are registered only with a mailer (`@appweaver/nodemailer`, or the
991
+ `json` one) and their `enabled` config, so an application without one offers neither in its API. Their emails are
992
+ described in [mailer.md](./mailer.md#account-emails).
993
+
994
+ ### Email verification
995
+
996
+ | Method | Path | Auth | Description |
997
+ |--------|---------------------------------------|--------|----------------------------------------------------------------------------------------------------------------------------------|
998
+ | `POST` | `/auth/account/send-verify-email` | JWT | Send verification email. Takes `redirectToUrl` and optional `verificationType` (`'auto'` or `'manual'`). Rate limited: 10/15min. |
999
+ | `POST` | `/auth/account/verify-email` | Public | Verify email with token from body. Rate limited: 12/window. |
1000
+ | `GET` | `/auth/account/verify-email-redirect` | Public | Auto-verify and redirect. Token from query param. Redirects to `{redirectToUrl}?status=ok\|error&message=...`. |
1001
+
1002
+ **Verification types:**
1003
+
1004
+ - `auto` (default) – Generates a link that auto-verifies on click and redirects with a status query parameter
1005
+ - `manual` - Generates a link where the client must POST the token to the verified endpoint
1006
+
1007
+ ### Password reset
1008
+
1009
+ | Method | Path | Auth | Bot check | Description |
1010
+ |--------|-------------------------------------|--------|-----------|---------------------------------------------------------------------------------------|
1011
+ | `POST` | `/auth/account/send-reset-password` | Public | Yes | Send password reset email. Takes `email` and `redirectToUrl`. Rate limited: 10/15min. |
1012
+ | `POST` | `/auth/account/reset-password` | Public | Yes | Reset password with token and new password. Rate limited: 12/window. |
1013
+
1014
+ The bot check is every enabled one of reCAPTCHA and Turnstile.
1015
+
1016
+ **Reset flow:**
1017
+
1018
+ 1. User requests reset: `POST /auth/account/send-reset-password { email, redirectToUrl }`
1019
+ 2. Server generates OTT, emails a link: `{redirectToUrl}?token={ott}`. The response is the same `200` when no enabled
1020
+ user with a password has that email, and nothing is sent, so the route does not reveal which addresses have an
1021
+ account. Only a redirect URL to a host that is not allowed is rejected (`400`).
1022
+ 3. User clicks a link, enters a new password
1023
+ 4. Client sends: `POST /auth/account/reset-password { token, newPassword }`
1024
+ 5. Server validates password complexity, updates hash, sets `logoutAt` (invalidates all sessions)
1025
+
1026
+ ---
1027
+
1028
+ ## One-time tokens (OTT)
1029
+
1030
+ One-time tokens are used internally for various verification flows. They are single-use, purpose-bound, and
1031
+ time-limited.
1032
+
1033
+ ### Purposes
1034
+
1035
+ | Purpose | TTL config | Used for |
1036
+ |-------------------------|-----------------------------------------------------|---------------------------------------|
1037
+ | `Authentication` | `SECURITY_EXCHANGE_TOKEN_TTL` (120s) | OAuth2 token exchange, 2FA completion |
1038
+ | `EmailVerification` | `SECURITY_ACCOUNT_VERIFY_EMAIL_TOKEN_TTL` (2h) | Email verification links |
1039
+ | `PasswordReset` | `SECURITY_ACCOUNT_RESET_PASSWORD_TOKEN_TTL` (30min) | Password reset links |
1040
+ | `TwoFactorVerification` | `SECURITY_ACCOUNT_TWO_FACTOR_CHALLENGE_TTL` (5min) | 2FA challenges |
1041
+ | `PhoneVerification` | `SECURITY_ACCOUNT_VERIFY_PHONE_CODE_TTL` (10min) | Phone verification codes |
1042
+ | `OAuth2State` | `SECURITY_OAUTH2_STATE_TTL` (10min) | CSRF protection in OAuth2 flow |
1043
+
1044
+ ### Storage
1045
+
1046
+ OTTs are stored in the security store set by `SECURITY_STORE_PROVIDER`. Only a hash of each token is stored.
1047
+
1048
+ - **`database`** (selected by `auto`): stores the tokens in the `OneTimeToken` model, which is added to the schema only
1049
+ while this store is configured (`auto` or `database`, or `database.keepTables` lists `OneTimeToken`) and the
1050
+ application has an auth model. The model has no routes.
1051
+ - **`memory`** (selected by name only): stores the tokens with a TTL in the `Memory` provider, as Redis keys with
1052
+ `MEMORY_PROVIDER=redis`, so the one-time token flows (OAuth2 login, 2FA, email verification, password reset) fail
1053
+ while Redis is unavailable. With the in-process memory the tokens are lost on a restart and not shared by the
1054
+ instances.
1055
+
1056
+ Switching the store adds or removes the `OneTimeToken` model, so run `weaver generate` and create a migration
1057
+ afterwards.
1058
+
1059
+ Both stores behave the same way:
1060
+
1061
+ - A token is consumed by its first successful use. Of concurrent uses of the same token only one succeeds, the others
1062
+ are rejected with `401`.
1063
+ - A token failing the content validation is kept, so it can be used again until it expires, unless the validation
1064
+ replaces its data or revokes it (`TokenValidationResult`): a wrong 2FA or phone verification code counts against
1065
+ the `SECURITY_ACCOUNT_TWO_FACTOR_MAX_ATTEMPTS` of its challenge, and the last one revokes it.
1066
+ - Expired tokens are rejected. The database store deletes them whenever a new token is created, the memory expires them
1067
+ on its own.
1068
+
1069
+ ---
1070
+
1071
+ ## Auth user model
1072
+
1073
+ The security module automatically adds the following fields to the user model. `verifiedEmail`, `phone` and
1074
+ `verifiedPhone` are never accepted as input of the resource routes:
1075
+
1076
+ | Field | Type | Default | Description |
1077
+ |-----------------|------------------|---------|---------------------------------------------------------------------|
1078
+ | `email` | string (unique) | - | User's email address. |
1079
+ | `passwordHash` | string? (hidden) | - | Argon2id password hash (never exposed in API). |
1080
+ | `verifiedEmail` | boolean | `false` | Whether the user's email is verified. |
1081
+ | `phone` | string? | - | The phone number (E.164), set by the phone verification or the app. |
1082
+ | `verifiedPhone` | boolean | `false` | Whether the phone number is verified. |
1083
+ | `enabled` | boolean | `true` | Whether the account is active. |
1084
+ | `logoutAt` | dateTime? | - | Timestamp used to invalidate tokens issued before this time. |
1085
+
1086
+ A model declaring `email` overrides only its `hidden`, `redact` (its values kept out of the audit log), `example`,
1087
+ `minLength`, `maxLength` and `pattern` (i.e. the addresses of a company domain), so it stays a required unique address in the email format, the one the sign-in, the
1088
+ password reset and the OAuth2 accounts look the user up by. A model declaring `phone` overrides only its `unique`,
1089
+ `hidden`, `redact` and `example`, so it stays an optional E.164 number the routes never write, the one the SMS 2FA and the phone
1090
+ verification rely on. Any other field of the table replaces a declared one of the same name, so a contact phone the
1091
+ users edit themselves is a field of another name.
1092
+
1093
+ ```ts
1094
+ export default createAuthModel({
1095
+ name: 'User',
1096
+ scalars: {
1097
+ email: { type: 'string', example: 'user@example.com' },
1098
+ phone: { type: 'string', unique: true, example: '+15035550123' }
1099
+ }
1100
+ });
1101
+ ```
1102
+
1103
+ **Relations:**
1104
+
1105
+ | Relation | Type | Description |
1106
+ |--------------------------|-------------------------|----------------------------------------------------------------------------------|
1107
+ | `roles` | Role[] | Assigned roles with nested permissions (always included in output). |
1108
+ | `apiKeys` | ApiKey[] | User's API keys (if API key auth is enabled). |
1109
+ | `twoFactorMethods` | TwoFactorMethod[] | The 2FA methods (if 2FA is enabled), managed by the 2FA routes, never in output. |
1110
+ | `twoFactorRecoveryCodes` | TwoFactorRecoveryCode[] | The hashes of the recovery codes (if 2FA is enabled), never in output. |
1111
+
1112
+ ---
1113
+
1114
+ ## Password handling
1115
+
1116
+ ### Hashing
1117
+
1118
+ Passwords are hashed with the native Argon2id function of Node.js (24.7+) and Bun (`node:crypto`), so hashing needs no
1119
+ native dependency. A hash has the standard PHC string form `$argon2id$v=19$m=19456,t=2,p=1$<salt>$<key>`, with a random
1120
+ 16-byte salt and a 32-byte key (both unpadded base64): `m` is the memory in KiB, `t` the number of passes, and `p` the
1121
+ parallelism, the OWASP minimum. Other Argon2 libraries (e.g. `argon2` on npm, `argon2-cffi` in Python) read and verify
1122
+ these hashes. Every hash keeps its own parameters, so raising them for new hashes leaves the existing ones valid, and a
1123
+ successful login replaces a hash made with outdated parameters. Use `hashPassword` and `checkPassword` from
1124
+ `@appweaver/data` to hash and verify passwords in seeders and custom flows, and `needsRehash` to tell whether a hash
1125
+ uses outdated parameters.
1126
+
1127
+ ### Complexity validation
1128
+
1129
+ Password validation is configurable via `SECURITY_PASSWORD_*` properties:
1130
+
1131
+ - Minimum length (default: 8)
1132
+ - Maximum length (default: 100)
1133
+ - Require an uppercase letter (default: true)
1134
+ - Require a lowercase letter (default: true)
1135
+ - Require a digit (default: true)
1136
+ - Require special character (default: true)
1137
+
1138
+ NIST SP 800-63B-4 recommends 15 characters when the password is the only factor and 8 with a second one (2FA).
1139
+
1140
+ ### Password checks
1141
+
1142
+ `registerPasswordCheck` of `@appweaver/data` adds a check every new password (a sign-up, a change, a reset) passes
1143
+ after its complexity, i.e. against the breached passwords of Have I Been Pwned. A reason it returns rejects the password
1144
+ with `AUTH_PASSWORD_WEAK`, the reason as its message:
1145
+
1146
+ ```ts
1147
+ import { createHash } from 'node:crypto';
1148
+ import { registerPasswordCheck } from '@appweaver/data';
1149
+
1150
+ registerPasswordCheck(async (password) => {
1151
+ const hash = createHash('sha1').update(password).digest('hex').toUpperCase();
1152
+ const response = await fetch(`https://api.pwnedpasswords.com/range/${hash.slice(0, 5)}`);
1153
+ const breached = (await response.text()).includes(`${hash.slice(5)}:`);
1154
+ return breached ? 'The password appeared in a data breach' : undefined;
1155
+ });
1156
+ ```
1157
+
1158
+ `validatePassword` runs the complexity and the checks, for a flow of the application setting a password itself.
1159
+
1160
+ ### Token invalidation on password change
1161
+
1162
+ Both `change-password` and `reset-password` set `logoutAt` to the current timestamp, which invalidates all existing JWT
1163
+ tokens across all devices. The `change-password` endpoint returns new tokens so the current session stays active.
1164
+
1165
+ ---
1166
+
1167
+ ## Rate limiting on security routes
1168
+
1169
+ | Endpoint | Limit |
1170
+ |---------------------------------------------------|-------------------|
1171
+ | `POST /auth/login` | 12 per window |
1172
+ | `POST /auth/refresh` | 12 per window |
1173
+ | `POST /auth/change-password` | 12 per window |
1174
+ | `POST /auth/exchange-token` | 12 per window |
1175
+ | `POST /auth/account/send-verify-email` | 10 per 15 minutes |
1176
+ | `POST /auth/account/verify-email` | 12 per window |
1177
+ | `POST /auth/account/send-reset-password` | 10 per 15 minutes |
1178
+ | `POST /auth/account/reset-password` | 12 per window |
1179
+ | `POST /auth/account/send-verify-phone` | 5 per 15 minutes |
1180
+ | `POST /auth/account/verify-phone` | 12 per window |
1181
+ | `POST /auth/account/two-factor/challenge` | 10 per 15 minutes |
1182
+ | `POST /auth/account/two-factor/verify` | 12 per window |
1183
+ | `POST /auth/account/two-factor/totp/confirm` | 12 per window |
1184
+ | `DELETE /auth/account/two-factor/methods/:method` | 12 per window |
1185
+ | `POST /auth/account/two-factor/recovery-codes` | 12 per window |