@basaltkit/auth 1.4.0 → 1.4.1
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/README.md +71 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @basaltkit/auth
|
|
2
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.
|
|
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), social login (Google, GitHub, or any OpenID Connect provider), and API keys — all with ready-to-use HTTP routes.
|
|
4
4
|
|
|
5
5
|
You need this module whenever your application has users who log in.
|
|
6
6
|
|
|
@@ -10,7 +10,7 @@ When an application has user accounts, it needs to answer two questions on every
|
|
|
10
10
|
|
|
11
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
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).
|
|
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, social login (OAuth 2.0 / OpenID Connect), and API keys for programmatic access (scripts, integrations).
|
|
14
14
|
|
|
15
15
|
## Installation
|
|
16
16
|
|
|
@@ -162,6 +162,65 @@ Flow (all routes require login):
|
|
|
162
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
163
|
4. `GET /auth/mfa/status` and `POST /auth/mfa/disable` (with `{ code }`) complete the cycle.
|
|
164
164
|
|
|
165
|
+
### Social login (OAuth)
|
|
166
|
+
|
|
167
|
+
Sign in with Google, GitHub, or any OpenID Connect provider via the OAuth 2.0
|
|
168
|
+
authorization-code flow — no SDK, and cookieless (the CSRF `state` is HMAC-signed
|
|
169
|
+
and stateless). Register `oauthPlugin` with your providers and `oauthRoutes` with
|
|
170
|
+
your app's **base URL**:
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
import {
|
|
174
|
+
authPlugin, authRoutes, oauthPlugin, oauthRoutes, googleProvider, githubProvider,
|
|
175
|
+
} from '@basaltkit/auth'
|
|
176
|
+
import { fastifyPlugin } from '@basaltkit/fastify'
|
|
177
|
+
|
|
178
|
+
createApp({
|
|
179
|
+
plugins: [
|
|
180
|
+
authPlugin({ users, secret: process.env.AUTH_SECRET! }),
|
|
181
|
+
oauthPlugin({
|
|
182
|
+
secret: process.env.AUTH_SECRET!, // signs the stateless `state`
|
|
183
|
+
providers: [
|
|
184
|
+
googleProvider({ clientId: env.GOOGLE_ID, clientSecret: env.GOOGLE_SECRET }),
|
|
185
|
+
githubProvider({ clientId: env.GITHUB_ID, clientSecret: env.GITHUB_SECRET }),
|
|
186
|
+
],
|
|
187
|
+
}),
|
|
188
|
+
fastifyPlugin({
|
|
189
|
+
routes: [
|
|
190
|
+
...authRoutes(),
|
|
191
|
+
// callbackBaseUrl is your app's BASE url — the module appends
|
|
192
|
+
// /auth/oauth/:provider/callback itself.
|
|
193
|
+
...oauthRoutes({ callbackBaseUrl: 'https://app.example.com' }),
|
|
194
|
+
],
|
|
195
|
+
}),
|
|
196
|
+
],
|
|
197
|
+
})
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Two routes are added per provider:
|
|
201
|
+
|
|
202
|
+
- `GET /auth/oauth/:provider` → 302 to the provider's consent screen.
|
|
203
|
+
- `GET /auth/oauth/:provider/callback` → verifies the `state`, exchanges the code,
|
|
204
|
+
and logs the user in. Returns JSON `{ user, accessToken, refreshToken }`; pass
|
|
205
|
+
`successRedirect` to `oauthRoutes` to bounce the browser back to your SPA with
|
|
206
|
+
the tokens in the URL fragment instead.
|
|
207
|
+
|
|
208
|
+
**Register the redirect URI with each provider exactly** as
|
|
209
|
+
`${callbackBaseUrl}/auth/oauth/:provider/callback` — e.g.
|
|
210
|
+
`https://app.example.com/auth/oauth/github/callback`. It must match
|
|
211
|
+
character-for-character, or the provider rejects it with *"redirect_uri is not
|
|
212
|
+
associated with this application"*.
|
|
213
|
+
|
|
214
|
+
New accounts are created **passwordless** and a provider-verified email flips
|
|
215
|
+
`emailVerified`. Accounts are matched by email, so only trust providers that
|
|
216
|
+
return a **verified** address (Google and the built-in GitHub driver both do).
|
|
217
|
+
`Auth.socialLogin(email)` is the underlying primitive for custom providers.
|
|
218
|
+
|
|
219
|
+
**Enterprise SSO (OIDC):** any OpenID Connect IdP (Okta, Entra ID, Auth0,
|
|
220
|
+
Keycloak…) plugs in via `oidcProvider({ clientId, clientSecret, authorizationUrl,
|
|
221
|
+
tokenUrl, userinfoUrl })`, or let `discoverOidcProvider(issuerUrl, keys)` read the
|
|
222
|
+
endpoints from the IdP's `.well-known/openid-configuration`.
|
|
223
|
+
|
|
165
224
|
### API keys
|
|
166
225
|
|
|
167
226
|
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.
|
|
@@ -254,12 +313,14 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
254
313
|
| `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
|
|
255
314
|
| `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
|
|
256
315
|
| `isMfaEnabled(userId)` / `mfaStatus(userId)` / `verifyMfaCode(userId, code)` | MFA state and verification. |
|
|
316
|
+
| `socialLogin(email, { emailVerified? })` | Find-or-create a passwordless account for an OAuth/OIDC identity; returns `{ user, tokens }`. |
|
|
257
317
|
|
|
258
318
|
### Ready-made routes
|
|
259
319
|
|
|
260
320
|
- `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
321
|
- `apiKeyRoutes()`: `POST /apikeys`, `GET /apikeys`, `DELETE /apikeys/:id` (all require login; scoped to the current tenant/user).
|
|
262
322
|
- `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
|
|
323
|
+
- `oauthRoutes({ callbackBaseUrl, successRedirect? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider.
|
|
263
324
|
|
|
264
325
|
### `apiKeysPlugin(options)` and the `ApiKeys` class
|
|
265
326
|
|
|
@@ -283,7 +344,9 @@ Options (`ApiKeysPluginOptions`):
|
|
|
283
344
|
| `LoginThrottle` (`maxAttempts` def. 5, `windowMs` def. 15 min, `clock`) | Anti brute-force. |
|
|
284
345
|
| `generateTotpSecret`, `totp`, `verifyTotp`, `otpauthUri`, `base32Encode`, `base32Decode` | TOTP primitives (RFC 6238). Advanced. |
|
|
285
346
|
| `publicUser(user)` | Converts `AuthUser` → `PublicUser` (removes the hash). |
|
|
286
|
-
| `AUTH`, `API_KEYS` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance. |
|
|
347
|
+
| `AUTH`, `API_KEYS`, `OAUTH` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance; `OAUTH` returns the `OAuth` instance. |
|
|
348
|
+
| `oauthPlugin`, `oauthRoutes` | Social-login plugin (`{ secret, providers }`) and its routes (`{ callbackBaseUrl, successRedirect? }`). |
|
|
349
|
+
| `googleProvider`, `githubProvider`, `oidcProvider`, `discoverOidcProvider` | OAuth 2.0 / OpenID Connect providers. Each takes `{ clientId, clientSecret, scopes? }`. |
|
|
287
350
|
| In-memory stores | `MemoryUserSource`, `MemorySessionStore`, `MemoryRefreshTokenStore`, `MemoryAuthTokenStore`, `MemoryApiKeyStore`, `MemoryMfaStore` — dev/testing. |
|
|
288
351
|
|
|
289
352
|
### Exported errors
|
|
@@ -300,6 +363,9 @@ Options (`ApiKeysPluginOptions`):
|
|
|
300
363
|
| `MfaRequiredError` / `MfaInvalidCodeError` / `MfaNotEnrolledError` | `AUTH_MFA_*` | 401/401/400 |
|
|
301
364
|
| `AccountLockedError` | `AUTH_LOCKED` | 429 |
|
|
302
365
|
| `ScopeRequiredError` | `AUTH_SCOPE_REQUIRED` | 403 |
|
|
366
|
+
| `OAuthProviderUnknownError` | `AUTH_OAUTH_UNKNOWN_PROVIDER` | 404 |
|
|
367
|
+
| `OAuthStateInvalidError` | `AUTH_OAUTH_STATE_INVALID` | 400 |
|
|
368
|
+
| `OAuthExchangeError` | `AUTH_OAUTH_EXCHANGE_FAILED` | 502 |
|
|
303
369
|
|
|
304
370
|
## Common issues and solutions (FAQ)
|
|
305
371
|
|
|
@@ -317,6 +383,8 @@ Options (`ApiKeysPluginOptions`):
|
|
|
317
383
|
|
|
318
384
|
**"My API key doesn't work with authPlugin."** Correct: bearers prefixed with `mk_` are ignored by `authPlugin` and handled by `apiKeysPlugin` — register both.
|
|
319
385
|
|
|
386
|
+
**"OAuth: redirect_uri is not associated with this application."** Your `callbackBaseUrl` must be the app's **base URL** (`https://app.example.com`), *not* the full callback path — the module appends `/auth/oauth/:provider/callback` itself. Passing the full callback URL doubles the path so it no longer matches what you registered. Register exactly `${callbackBaseUrl}/auth/oauth/:provider/callback` with the provider.
|
|
387
|
+
|
|
320
388
|
## How it connects to other modules
|
|
321
389
|
|
|
322
390
|
- **@basaltkit/core** — provides the app, the container, the request context (`ctx()`), and hooks; auth sets `ctx().user` and `ctx().apiKey`.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@basaltkit/auth",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.1",
|
|
4
4
|
"description": "Authentication for Basalt: password hashing, JWT with refresh rotation and reuse detection, sessions, ready-made /auth routes and route guards.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|