@basaltkit/auth 1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Machize Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,335 @@
1
+ # @basaltkit/auth
2
+
3
+ Complete authentication for Basalt applications: user registration and login, JWT tokens with secure renewal, sessions, email verification, password recovery, two-factor authentication (MFA/TOTP), and API keys — all with ready-to-use HTTP routes.
4
+
5
+ You need this module whenever your application has users who log in.
6
+
7
+ ## What this module solves
8
+
9
+ When an application has user accounts, it needs to answer two questions on every request: "who are you?" (authentication) and "how do you prove it?". Doing this by hand is difficult and dangerous — storing passwords securely, generating and validating **tokens** (small digital "tickets" that prove identity without sending the password on every request), preventing brute-force attacks, and so on.
10
+
11
+ `@basaltkit/auth` handles all of this for you. Passwords are never stored in plain text — only an irreversibly scrambled version (**hash**, using the scrypt algorithm). Login returns a pair of tokens: an **access token** (short-lived JWT, 15 minutes by default, sent with every request) and a **refresh token** (long-lived, 30 days, used only to obtain a new access token). If a refresh token is used twice — a typical sign of theft — the entire token "family" is automatically revoked.
12
+
13
+ It also includes, with nothing extra to install: account lockout after too many failed attempts, email verification and password recovery via single-use links, MFA via authenticator app (Google Authenticator, etc.) with recovery codes, and API keys for programmatic access (scripts, integrations).
14
+
15
+ ## Installation
16
+
17
+ ```bash
18
+ pnpm add @basaltkit/auth
19
+ ```
20
+
21
+ Requirements: `@basaltkit/core` and `@basaltkit/fastify` (installed automatically as dependencies) and `zod` (peer dependency — install with `pnpm add zod`).
22
+
23
+ ## Get started in 5 minutes
24
+
25
+ Step by step to get registration and login working:
26
+
27
+ 1. **Create the application** with the auth plugin and the ready-made routes:
28
+
29
+ ```ts
30
+ import { createApp } from '@basaltkit/core'
31
+ import { fastifyPlugin } from '@basaltkit/fastify'
32
+ import { authPlugin, authRoutes, MemoryUserSource } from '@basaltkit/auth'
33
+
34
+ const app = await createApp({
35
+ plugins: [
36
+ authPlugin({
37
+ users: new MemoryUserSource(), // in production: your database
38
+ secret: process.env.AUTH_SECRET!, // secret that signs the tokens
39
+ }),
40
+ fastifyPlugin({ routes: authRoutes() }),
41
+ ],
42
+ }).boot()
43
+ ```
44
+
45
+ 2. **Register a user** (the `POST /auth/register` route already exists):
46
+
47
+ ```bash
48
+ curl -X POST http://localhost:3000/auth/register \
49
+ -H 'content-type: application/json' \
50
+ -d '{"email":"ada@example.com","password":"secretpassword1"}'
51
+ ```
52
+
53
+ 3. **Log in** and receive the tokens:
54
+
55
+ ```bash
56
+ curl -X POST http://localhost:3000/auth/login \
57
+ -H 'content-type: application/json' \
58
+ -d '{"email":"ada@example.com","password":"secretpassword1"}'
59
+ # → { "user": {...}, "accessToken": "...", "refreshToken": "..." }
60
+ ```
61
+
62
+ 4. **Use the access token** to reach protected routes:
63
+
64
+ ```bash
65
+ curl http://localhost:3000/auth/me \
66
+ -H 'authorization: Bearer YOUR_ACCESS_TOKEN_HERE'
67
+ ```
68
+
69
+ 5. **Protect your own routes** with `meta: { auth: true }`:
70
+
71
+ ```ts
72
+ import { ctx } from '@basaltkit/core'
73
+ import { route } from '@basaltkit/fastify'
74
+
75
+ const myRoute = route({
76
+ method: 'GET',
77
+ url: '/dashboard',
78
+ meta: { auth: true }, // not logged in → 401 AUTH_REQUIRED
79
+ async handler() {
80
+ return { hello: ctx().user?.email }
81
+ },
82
+ })
83
+ ```
84
+
85
+ > **Note:** `MemoryUserSource` stores users in memory — great for experimenting, but everything disappears when the process restarts. In production, implement the `UserSource` interface over your database (see below).
86
+
87
+ ## Usage guide
88
+
89
+ ### Connecting to your database (UserSource)
90
+
91
+ The module doesn't impose any database. You provide an object that fulfills the `UserSource` interface:
92
+
93
+ ```ts
94
+ import type { UserSource, AuthUser, UserPatch } from '@basaltkit/auth'
95
+
96
+ const users: UserSource = {
97
+ async findByEmail(email) { /* SELECT ... WHERE email = ? */ return null },
98
+ async findById(id) { /* SELECT ... WHERE id = ? */ return null },
99
+ async create(data) {
100
+ // data = { email, passwordHash } — the hash is already computed
101
+ return { id: 'new-id', ...data } as AuthUser
102
+ },
103
+ // Optional, but required for email verification and password reset:
104
+ async update(id, patch: UserPatch) { /* UPDATE ... */ return null },
105
+ }
106
+ ```
107
+
108
+ ### Register, login, and logout (by code)
109
+
110
+ All operations are also available programmatically through the `Auth` class:
111
+
112
+ ```ts
113
+ import { Auth, MemoryUserSource } from '@basaltkit/auth'
114
+
115
+ const auth = new Auth({ users: new MemoryUserSource(), secret: 'a-strong-secret' })
116
+
117
+ const user = await auth.register('ada@example.com', 'secretpassword1')
118
+ const { tokens } = await auth.login('ada@example.com', 'secretpassword1')
119
+ const renewed = await auth.refresh(tokens.refreshToken) // new token pair
120
+ await auth.revoke(renewed.refreshToken) // logout: invalidates the token family
121
+ ```
122
+
123
+ ### Protecting routes
124
+
125
+ `authPlugin` automatically registers:
126
+
127
+ - An **enricher** that reads the `Authorization: Bearer <jwt>` or `x-session-id` header and places the user in `ctx().user` (of type `PublicUser` — never includes the password hash).
128
+ - A **guard** that rejects with 401 any route with `meta: { auth: true }` without an authenticated user.
129
+
130
+ A request with no credentials stays anonymous (no error); an explicit invalid token returns 401.
131
+
132
+ ### Password recovery
133
+
134
+ The flow has two steps. The module generates a **single-use token** (valid for 1 hour by default) and emits a hook — your application sends the email with the link:
135
+
136
+ ```ts
137
+ // 1. Listen to the hook and send the email (do this once, at startup)
138
+ app.hooks.on('auth:password_reset_requested', async ({ user, token }) => {
139
+ await sendEmail(user.email, `https://app.example.com/reset?token=${token}`)
140
+ })
141
+ ```
142
+
143
+ Ready-made routes: `POST /auth/password/forgot` (body `{ email }` — always responds 200, so as not to reveal whether the email exists) and `POST /auth/password/reset` (body `{ token, password }`). After the reset, **all of the user's sessions and refresh tokens are revoked**.
144
+
145
+ Email verification works the same way: hook `auth:verify_requested`, routes `POST /auth/verify/request` and `POST /auth/verify` (token valid for 24 hours by default).
146
+
147
+ ### MFA — two-factor authentication (TOTP)
148
+
149
+ **TOTP** is the 6-digit code generated by apps like Google Authenticator. Register the routes:
150
+
151
+ ```ts
152
+ import { authRoutes, mfaRoutes } from '@basaltkit/auth'
153
+ import { fastifyPlugin } from '@basaltkit/fastify'
154
+
155
+ fastifyPlugin({ routes: [...authRoutes(), ...mfaRoutes()] })
156
+ ```
157
+
158
+ Flow (all routes require login):
159
+
160
+ 1. `POST /auth/mfa/enroll` → returns `{ secret, otpauthUri }`; show the `otpauthUri` as a QR code.
161
+ 2. `POST /auth/mfa/activate` with `{ code }` (code from the app) → activates and returns `{ recoveryCodes }` — 10 single-use recovery codes, **shown only once**.
162
+ 3. From then on, `POST /auth/login` requires the extra `mfaCode` field (TOTP code or a recovery code). Correct password without a code → `AUTH_MFA_REQUIRED` error.
163
+ 4. `GET /auth/mfa/status` and `POST /auth/mfa/disable` (with `{ code }`) complete the cycle.
164
+
165
+ ### API keys
166
+
167
+ For programmatic access (scripts, CI, integrations) without interactive login. A key has the format `mk_live_...`, is shown **only once** when created, and only its SHA-256 hash is stored.
168
+
169
+ ```ts
170
+ import { createApp } from '@basaltkit/core'
171
+ import { fastifyPlugin, route } from '@basaltkit/fastify'
172
+ import {
173
+ authPlugin, authRoutes, apiKeysPlugin, apiKeyRoutes, MemoryUserSource,
174
+ } from '@basaltkit/auth'
175
+
176
+ const users = new MemoryUserSource()
177
+ const app = await createApp({
178
+ plugins: [
179
+ authPlugin({ users, secret: process.env.AUTH_SECRET! }),
180
+ apiKeysPlugin({ users }), // authenticates keys and enforces scopes
181
+ fastifyPlugin({
182
+ routes: [
183
+ ...authRoutes(),
184
+ ...apiKeyRoutes(), // POST/GET /apikeys, DELETE /apikeys/:id
185
+ route({
186
+ method: 'GET',
187
+ url: '/reports',
188
+ meta: { scopes: ['reports:read'] }, // requires a key with this scope
189
+ async handler() { return { ok: true } },
190
+ }),
191
+ ],
192
+ }),
193
+ ],
194
+ }).boot()
195
+ ```
196
+
197
+ The key is presented in the `Authorization: Bearer mk_live_...` or `x-api-key` header. A **scope** is a granular permission on the key (e.g. `reports:read`); `*` means all. After authenticating, `ctx().apiKey` contains `{ id, scopes, tenantId?, userId? }`.
198
+
199
+ ### Brute-force lockout (LoginThrottle)
200
+
201
+ Active by default: 5 failed attempts per email within a 15-minute window → `AUTH_LOCKED` error (HTTP 429). A successful login clears the counter.
202
+
203
+ ```ts
204
+ import { authPlugin, LoginThrottle, MemoryUserSource } from '@basaltkit/auth'
205
+
206
+ authPlugin({
207
+ users: new MemoryUserSource(),
208
+ secret: process.env.AUTH_SECRET!,
209
+ loginThrottle: new LoginThrottle({ maxAttempts: 3, windowMs: 10 * 60_000 }),
210
+ // or loginThrottle: false to disable (not recommended)
211
+ })
212
+ ```
213
+
214
+ ### Hooks (events)
215
+
216
+ The application can react to authentication events: `auth:registered`, `auth:login`, `auth:login_failed`, `auth:logout`, `auth:verify_requested`, `auth:email_verified`, `auth:password_reset_requested`, `auth:password_reset`, `auth:mfa_enabled`, `auth:mfa_disabled`, `auth:apikey_issued`, `auth:apikey_revoked`.
217
+
218
+ ## API reference
219
+
220
+ ### `authPlugin(options)` and the `Auth` class
221
+
222
+ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same minus `hooks`):
223
+
224
+ | Name | Type | Required? | Default | Description |
225
+ |---|---|---|---|---|
226
+ | `users` | `UserSource` | Yes | — | Where users come from (your DB). |
227
+ | `secret` | `string` | Yes | — | Secret that signs the JWTs (HS256). |
228
+ | `hasher` | `PasswordHasher` | No | `ScryptPasswordHasher` | Password hashing algorithm. |
229
+ | `sessions` | `SessionStore` | No | `MemorySessionStore` | Session storage. |
230
+ | `refreshTokens` | `RefreshTokenStore` | No | `MemoryRefreshTokenStore` | Refresh token storage. |
231
+ | `accessTtl` | `DurationInput` | No | `'15m'` | Access token validity. |
232
+ | `refreshTtl` | `DurationInput` | No | `'30d'` | Refresh token validity. |
233
+ | `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
234
+ | `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
235
+ | `tokens` | `AuthTokenStore` | No | `MemoryAuthTokenStore` | Verification/reset tokens. |
236
+ | `verificationTtl` | `DurationInput` | No | `'24h'` | Email verification link validity. |
237
+ | `resetTtl` | `DurationInput` | No | `'1h'` | Password reset link validity. |
238
+ | `mfa` | `MfaStore` | No | `MemoryMfaStore` | Per-user MFA state. |
239
+ | `mfaIssuer` | `string` | No | `'Basalt'` | Name shown in the authenticator app. |
240
+ | `hooks` | `HookBus` | No | — | Only on the `Auth` class; the plugin injects it. |
241
+
242
+ `Auth` class methods:
243
+
244
+ | Method | Description |
245
+ |---|---|
246
+ | `register(email, password)` | Creates the account; throws `EmailTakenError` if the email already exists. |
247
+ | `login(email, password, mfaCode?)` | Returns `{ user, tokens }`; applies throttle and MFA. |
248
+ | `attempt(email, password)` | Checks credentials without side effects; `null` on failure. |
249
+ | `refresh(refreshToken)` | New token pair; detects reuse and revokes the family. |
250
+ | `revoke(refreshToken)` | Logout for token-based clients. |
251
+ | `verifyAccess(accessToken)` | Validates the JWT and returns the claims. |
252
+ | `createSession(userId)` / `sessionUser(sessionId)` / `logout(sessionId)` | Cookie/header-based sessions. |
253
+ | `requestEmailVerification(email)` / `verifyEmail(token)` | Email verification. |
254
+ | `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
255
+ | `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
256
+ | `isMfaEnabled(userId)` / `mfaStatus(userId)` / `verifyMfaCode(userId, code)` | MFA state and verification. |
257
+
258
+ ### Ready-made routes
259
+
260
+ - `authRoutes()`: `POST /auth/register`, `POST /auth/login`, `POST /auth/refresh`, `POST /auth/logout`, `GET /auth/me`, `POST /auth/verify/request`, `POST /auth/verify`, `POST /auth/password/forgot`, `POST /auth/password/reset`. These are regular routes — you can omit or replace any of them.
261
+ - `apiKeyRoutes()`: `POST /apikeys`, `GET /apikeys`, `DELETE /apikeys/:id` (all require login; scoped to the current tenant/user).
262
+ - `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
263
+
264
+ ### `apiKeysPlugin(options)` and the `ApiKeys` class
265
+
266
+ Options (`ApiKeysPluginOptions`):
267
+
268
+ | Name | Type | Required? | Default | Description |
269
+ |---|---|---|---|---|
270
+ | `store` | `ApiKeyStore` | No | `MemoryApiKeyStore` | Key storage. |
271
+ | `header` | `string` | No | `'x-api-key'` | Alternative header to Bearer. |
272
+ | `users` | `UserSource` | No | — | If given, a key with `userId` also populates `ctx().user`. |
273
+ | `now` | `() => number` | No | `Date.now` | Injectable clock (tests). |
274
+
275
+ `ApiKeys` methods: `issue(input)` (returns `{ record, key }` — the plain-text key only appears here), `verify(presented)`, `list(filter)`, `get(id)`, `revoke(id)`. Helper `scopesSatisfy(granted, required)`.
276
+
277
+ ### Exported utilities
278
+
279
+ | Export | Description |
280
+ |---|---|
281
+ | `signJwt(claims, { secret, expiresIn? })` / `verifyJwt(token, secret)` | Dependency-free HS256 JWT. Advanced. |
282
+ | `ScryptPasswordHasher` / `PasswordHasher` | Password hashing (scrypt, memory-hard). Advanced. |
283
+ | `LoginThrottle` (`maxAttempts` def. 5, `windowMs` def. 15 min, `clock`) | Anti brute-force. |
284
+ | `generateTotpSecret`, `totp`, `verifyTotp`, `otpauthUri`, `base32Encode`, `base32Decode` | TOTP primitives (RFC 6238). Advanced. |
285
+ | `publicUser(user)` | Converts `AuthUser` → `PublicUser` (removes the hash). |
286
+ | `AUTH`, `API_KEYS` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance. |
287
+ | In-memory stores | `MemoryUserSource`, `MemorySessionStore`, `MemoryRefreshTokenStore`, `MemoryAuthTokenStore`, `MemoryApiKeyStore`, `MemoryMfaStore` — dev/testing. |
288
+
289
+ ### Exported errors
290
+
291
+ | Error | Code | HTTP |
292
+ |---|---|---|
293
+ | `InvalidCredentialsError` | `AUTH_INVALID_CREDENTIALS` | 401 |
294
+ | `EmailTakenError` | `AUTH_EMAIL_TAKEN` | 409 |
295
+ | `RefreshInvalidError` / `RefreshReusedError` | `AUTH_REFRESH_INVALID` / `AUTH_REFRESH_REUSED` | 401 |
296
+ | `AuthRequiredError` | `AUTH_REQUIRED` | 401 |
297
+ | `TokenInvalidError` / `TokenExpiredError` | `AUTH_TOKEN_INVALID` / `AUTH_TOKEN_EXPIRED` | 401 |
298
+ | `AuthTokenInvalidError` (verification/reset links) | `AUTH_TOKEN_INVALID` | 400 |
299
+ | `UserUpdateUnsupportedError` | `AUTH_UPDATE_UNSUPPORTED` | 500 |
300
+ | `MfaRequiredError` / `MfaInvalidCodeError` / `MfaNotEnrolledError` | `AUTH_MFA_*` | 401/401/400 |
301
+ | `AccountLockedError` | `AUTH_LOCKED` | 429 |
302
+ | `ScopeRequiredError` | `AUTH_SCOPE_REQUIRED` | 403 |
303
+
304
+ ## Common issues and solutions (FAQ)
305
+
306
+ **"Users disappear when I restart the server."** You're using `MemoryUserSource` (and in-memory stores). Implement `UserSource` (and the other stores) over your database.
307
+
308
+ **"401 AUTH_TOKEN_EXPIRED shortly after login."** The access token lasts 15 minutes by design. The client should call `POST /auth/refresh` with the refresh token to get a new pair — don't increase `accessTtl` to long values.
309
+
310
+ **"401 AUTH_REFRESH_REUSED."** The same refresh token was used twice. Each refresh returns a new token that replaces the previous one; always keep the most recent one. If this happens without a client bug, it may indicate token theft — the user will need to log in again (intentional behavior).
311
+
312
+ **"AUTH_UPDATE_UNSUPPORTED on email verification / reset."** Your `UserSource` doesn't implement the optional `update()` method. It's required for these two flows.
313
+
314
+ **"The email with the link is never sent."** The module doesn't send emails — it emits the `auth:verify_requested` and `auth:password_reset_requested` hooks with the token; your application listens to them and sends the email.
315
+
316
+ **"429 AUTH_LOCKED in tests."** The throttle is active by default. In tests, pass `loginThrottle: false`.
317
+
318
+ **"My API key doesn't work with authPlugin."** Correct: bearers prefixed with `mk_` are ignored by `authPlugin` and handled by `apiKeysPlugin` — register both.
319
+
320
+ ## How it connects to other modules
321
+
322
+ - **@basaltkit/core** — provides the app, the container, the request context (`ctx()`), and hooks; auth sets `ctx().user` and `ctx().apiKey`.
323
+ - **@basaltkit/fastify** — the HTTP adapter that runs the enrichers/guards and serves the ready-made routes.
324
+ - **@basaltkit/permissions** — answers "what can you do?"; its `meta.can` guard uses the `ctx().user` that auth sets.
325
+ - **@basaltkit/tenancy** — defines `ctx().tenant`; API keys created within a tenant are scoped to that tenant.
326
+ - **@basaltkit/teams** — the `meta.teamRole` guard combines `ctx().user` (auth) with `ctx().tenant` (tenancy).
327
+
328
+ ## Security best practices
329
+
330
+ - **The `secret` is the vault's key.** Use a long, random value (e.g. `openssl rand -base64 48`), store it in an environment variable, and never put it in code or in git. If it leaks, anyone can forge tokens.
331
+ - **Always use HTTPS.** Plain-text tokens on an unencrypted connection can be intercepted.
332
+ - **Don't increase `accessTtl`.** Short access tokens limit the damage from a stolen token; renewal via refresh token already provides convenience for the user.
333
+ - **Show the API key and recovery codes only once** — that's how the module works; don't store them in plain text on your side.
334
+ - **Don't disable `loginThrottle` in production**, and keep the "always 200" responses on the forgot/verify routes (already the default), so as not to reveal which emails have an account.
335
+ - **In a cluster (multiple machines)**, use shared stores (database/Redis) instead of the `Memory*` ones, or sessions and lockouts won't be shared across processes.