@basaltkit/auth 2.1.0 → 2.2.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/README.md +33 -2
- package/dist/apikeys.d.ts +5 -0
- package/dist/apikeys.js +12 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/routes.js +1 -0
- package/dist/stores.d.ts +2 -0
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -65,6 +65,35 @@ curl -X POST http://localhost:3000/auth/login \
|
|
|
65
65
|
# → { "user": {...}, "accessToken": "...", "refreshToken": "..." }
|
|
66
66
|
```
|
|
67
67
|
|
|
68
|
+
For browser clients, the same login response also sets an `HttpOnly` session
|
|
69
|
+
cookie named `basalt_session`. Browsers send it automatically on same-origin
|
|
70
|
+
requests, so browser code does not need to read or store the JWT in
|
|
71
|
+
`localStorage`:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
curl -c cookies.txt -X POST http://localhost:3000/auth/login \
|
|
75
|
+
-H 'content-type: application/json' \
|
|
76
|
+
-d '{"email":"ada@example.com","password":"secretpassword1"}'
|
|
77
|
+
|
|
78
|
+
curl -b cookies.txt http://localhost:3000/auth/me
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
The cookie defaults to `HttpOnly`, `SameSite=Lax`, `Path=/`, and `Secure` in
|
|
82
|
+
production. Customize its public attributes when mounting the plugin:
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
authPlugin({
|
|
86
|
+
users,
|
|
87
|
+
secret: process.env.AUTH_SECRET!,
|
|
88
|
+
sessionCookie: {
|
|
89
|
+
name: 'app_session',
|
|
90
|
+
path: '/app',
|
|
91
|
+
sameSite: 'Strict',
|
|
92
|
+
secure: true,
|
|
93
|
+
},
|
|
94
|
+
})
|
|
95
|
+
```
|
|
96
|
+
|
|
68
97
|
4. **Use the access token** to reach protected routes:
|
|
69
98
|
|
|
70
99
|
```bash
|
|
@@ -130,7 +159,7 @@ await auth.revoke(renewed.refreshToken) // logout: invalidates the token family
|
|
|
130
159
|
|
|
131
160
|
`authPlugin` automatically registers:
|
|
132
161
|
|
|
133
|
-
- An **enricher** that reads the `Authorization: Bearer <jwt
|
|
162
|
+
- An **enricher** that reads the `Authorization: Bearer <jwt>`, the configured session cookie, or `x-session-id` and places the user in `ctx().user` (of type `PublicUser` — never includes the password hash).
|
|
134
163
|
- A **guard** that rejects with 401 any route with `meta: { auth: true }` without an authenticated user.
|
|
135
164
|
|
|
136
165
|
A request with no credentials stays anonymous (no error); an explicit invalid token returns 401.
|
|
@@ -389,6 +418,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
389
418
|
| `accessTtl` | `DurationInput` | No | `'15m'` | Access token validity. |
|
|
390
419
|
| `refreshTtl` | `DurationInput` | No | `'30d'` | Refresh token validity. |
|
|
391
420
|
| `sessionTtl` | `DurationInput` | No | `'30d'` | Session validity. |
|
|
421
|
+
| `sessionCookie` | `SessionCookieOptions` | No | `basalt_session`, `HttpOnly`, `SameSite=Lax`, `Path=/` | Browser session cookie attributes. `Secure` defaults to production only. |
|
|
392
422
|
| `loginThrottle` | `LoginThrottle \| false` | No | active (5/15min) | Anti brute-force lockout; `false` disables it. |
|
|
393
423
|
| `tokens` | `AuthTokenStore` | No | `MemoryAuthTokenStore` | Verification/reset tokens. `markUsed` must be a **compare-and-swap** — see below. |
|
|
394
424
|
| `verificationTtl` | `DurationInput` | No | `'24h'` | Email verification link validity. |
|
|
@@ -417,7 +447,7 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
|
|
|
417
447
|
### Ready-made routes
|
|
418
448
|
|
|
419
449
|
- `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.
|
|
420
|
-
- `apiKeyRoutes()`: `POST /apikeys`, `GET /apikeys`, `DELETE /apikeys/:id` (all require login; scoped to the current tenant/user).
|
|
450
|
+
- `apiKeyRoutes()`: `POST /apikeys`, `GET /apikeys`, `DELETE /apikeys/:id` (all require login; scoped to the current tenant/user). `POST /apikeys` accepts an optional `expiresAt` Unix timestamp in milliseconds; expired keys are rejected and omitted from listings.
|
|
421
451
|
- `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
|
|
422
452
|
- `oauthRoutes({ callbackBaseUrl, successRedirect? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider.
|
|
423
453
|
|
|
@@ -504,6 +534,7 @@ If you implement your own store, do the same. Returning `void` keeps the older r
|
|
|
504
534
|
|
|
505
535
|
- **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.
|
|
506
536
|
- **Always use HTTPS.** Plain-text tokens on an unencrypted connection can be intercepted.
|
|
537
|
+
- **Use the browser session cookie for browser UIs.** It is `HttpOnly` by default; keep JWTs out of `localStorage` and use same-origin requests so the browser sends the cookie automatically.
|
|
507
538
|
- **Don't increase `accessTtl`.** Short access tokens limit the damage from a stolen token; renewal via refresh token already provides convenience for the user.
|
|
508
539
|
- **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.
|
|
509
540
|
- **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.
|
package/dist/apikeys.d.ts
CHANGED
|
@@ -5,6 +5,10 @@ export declare class ScopeRequiredError extends BasaltError {
|
|
|
5
5
|
readonly status = 403;
|
|
6
6
|
constructor(scope: string);
|
|
7
7
|
}
|
|
8
|
+
export declare class ApiKeyExpirationError extends BasaltError {
|
|
9
|
+
readonly status = 400;
|
|
10
|
+
constructor();
|
|
11
|
+
}
|
|
8
12
|
/** True when `granted` covers `required` (an exact match or the `*` wildcard). */
|
|
9
13
|
export declare const scopesSatisfy: (granted: readonly string[], required: readonly string[]) => boolean;
|
|
10
14
|
export interface IssueApiKeyInput {
|
|
@@ -12,6 +16,7 @@ export interface IssueApiKeyInput {
|
|
|
12
16
|
scopes?: string[] | undefined;
|
|
13
17
|
tenantId?: string;
|
|
14
18
|
userId?: string;
|
|
19
|
+
expiresAt?: number | undefined;
|
|
15
20
|
}
|
|
16
21
|
export interface ApiKeysOptions {
|
|
17
22
|
store?: ApiKeyStore;
|
package/dist/apikeys.js
CHANGED
|
@@ -8,6 +8,12 @@ export class ScopeRequiredError extends BasaltError {
|
|
|
8
8
|
super('AUTH_SCOPE_REQUIRED', `This action requires the "${scope}" scope.`);
|
|
9
9
|
}
|
|
10
10
|
}
|
|
11
|
+
export class ApiKeyExpirationError extends BasaltError {
|
|
12
|
+
status = 400;
|
|
13
|
+
constructor() {
|
|
14
|
+
super('AUTH_APIKEY_EXPIRATION_INVALID', 'API key expiration must be a future timestamp.');
|
|
15
|
+
}
|
|
16
|
+
}
|
|
11
17
|
/** The prefix on every key. `mk` = Basalt key, `live` = environment. */
|
|
12
18
|
const KEY_PREFIX = 'mk_live_';
|
|
13
19
|
/** SHA-256 is safe here: API keys are high-entropy, so no slow hash is needed. */
|
|
@@ -34,6 +40,9 @@ export class ApiKeys {
|
|
|
34
40
|
}
|
|
35
41
|
/** Mints a key. Returns the record plus the plaintext `key` (shown once). */
|
|
36
42
|
async issue(input) {
|
|
43
|
+
if (input.expiresAt !== undefined && (!Number.isInteger(input.expiresAt) || input.expiresAt <= this.now())) {
|
|
44
|
+
throw new ApiKeyExpirationError();
|
|
45
|
+
}
|
|
37
46
|
const secret = randomBytes(24).toString('base64url');
|
|
38
47
|
const key = `${KEY_PREFIX}${secret}`;
|
|
39
48
|
const record = {
|
|
@@ -43,6 +52,7 @@ export class ApiKeys {
|
|
|
43
52
|
hash: hashKey(key),
|
|
44
53
|
scopes: input.scopes ?? ['*'],
|
|
45
54
|
createdAt: this.now(),
|
|
55
|
+
...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),
|
|
46
56
|
...(input.tenantId !== undefined ? { tenantId: input.tenantId } : {}),
|
|
47
57
|
...(input.userId !== undefined ? { userId: input.userId } : {}),
|
|
48
58
|
};
|
|
@@ -62,13 +72,13 @@ export class ApiKeys {
|
|
|
62
72
|
if (!presented.startsWith(KEY_PREFIX))
|
|
63
73
|
return null;
|
|
64
74
|
const record = await this.store.findByHash(hashKey(presented));
|
|
65
|
-
if (!record || record.revokedAt !== undefined)
|
|
75
|
+
if (!record || record.revokedAt !== undefined || (record.expiresAt !== undefined && record.expiresAt <= this.now()))
|
|
66
76
|
return null;
|
|
67
77
|
await this.store.touch(record.id, this.now());
|
|
68
78
|
return record;
|
|
69
79
|
}
|
|
70
80
|
async list(filter) {
|
|
71
|
-
return (await this.store.list(filter)).map(strip);
|
|
81
|
+
return (await this.store.list(filter)).filter((record) => record.expiresAt === undefined || record.expiresAt > this.now()).map(strip);
|
|
72
82
|
}
|
|
73
83
|
/** Revokes a key by id. No-op if unknown or already revoked. */
|
|
74
84
|
async revoke(id) {
|
package/dist/index.d.ts
CHANGED
|
@@ -10,7 +10,7 @@ declare module '@basaltkit/http' {
|
|
|
10
10
|
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, type AuthOptions, type SessionCookieOptions, type TokenPair, } from './auth.js';
|
|
11
11
|
export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, type TotpOptions, type VerifyTotpOptions, type OtpauthUriInput, } from './totp.js';
|
|
12
12
|
export { authPlugin, AUTH, type AuthPluginOptions } from './plugin.js';
|
|
13
|
-
export { ApiKeys, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
|
|
13
|
+
export { ApiKeys, ApiKeyExpirationError, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
|
|
14
14
|
export { apiKeysPlugin, API_KEYS, type ApiKeysPluginOptions } from './apikeys-plugin.js';
|
|
15
15
|
export { authRoutes, apiKeyRoutes, mfaRoutes, type AuthRoutesOptions, type PasswordPolicy, } from './routes.js';
|
|
16
16
|
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, type OAuthProvider, type OAuthProfile, type OAuthOptions, } from './oauth.js';
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAu
|
|
|
4
4
|
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, } from './auth.js';
|
|
5
5
|
export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, } from './totp.js';
|
|
6
6
|
export { authPlugin, AUTH } from './plugin.js';
|
|
7
|
-
export { ApiKeys, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
|
|
7
|
+
export { ApiKeys, ApiKeyExpirationError, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
|
|
8
8
|
export { apiKeysPlugin, API_KEYS } from './apikeys-plugin.js';
|
|
9
9
|
export { authRoutes, apiKeyRoutes, mfaRoutes, } from './routes.js';
|
|
10
10
|
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, } from './oauth.js';
|
package/dist/routes.js
CHANGED
|
@@ -154,6 +154,7 @@ export function apiKeyRoutes() {
|
|
|
154
154
|
body: z.object({
|
|
155
155
|
name: z.string().min(1).max(100),
|
|
156
156
|
scopes: z.array(z.string().min(1)).optional(),
|
|
157
|
+
expiresAt: z.number().int().positive().optional(),
|
|
157
158
|
}),
|
|
158
159
|
async handler({ body, reply }) {
|
|
159
160
|
const { record, key } = await apiKeys().issue({ ...body, ...scope() });
|
package/dist/stores.d.ts
CHANGED
|
@@ -83,6 +83,8 @@ export interface ApiKeyRecord {
|
|
|
83
83
|
/** Granted scopes; `*` means all. */
|
|
84
84
|
scopes: string[];
|
|
85
85
|
createdAt: number;
|
|
86
|
+
/** Unix timestamp in milliseconds; omitted means the key never expires. */
|
|
87
|
+
expiresAt?: number;
|
|
86
88
|
lastUsedAt?: number;
|
|
87
89
|
revokedAt?: number;
|
|
88
90
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@basaltkit/auth",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.2.0",
|
|
4
4
|
"engines": {
|
|
5
5
|
"node": ">=22.5.0"
|
|
6
6
|
},
|
|
@@ -18,8 +18,8 @@
|
|
|
18
18
|
"dist"
|
|
19
19
|
],
|
|
20
20
|
"dependencies": {
|
|
21
|
-
"@basaltkit/
|
|
22
|
-
"@basaltkit/
|
|
21
|
+
"@basaltkit/http": "^2.0.0",
|
|
22
|
+
"@basaltkit/core": "^1.3.1"
|
|
23
23
|
},
|
|
24
24
|
"peerDependencies": {
|
|
25
25
|
"zod": "^4.0.0"
|
|
@@ -29,8 +29,8 @@
|
|
|
29
29
|
"typescript": "^7.0.2",
|
|
30
30
|
"vitest": "^4.1.11",
|
|
31
31
|
"zod": "^4.5.4",
|
|
32
|
-
"@basaltkit/
|
|
33
|
-
"@basaltkit/
|
|
32
|
+
"@basaltkit/fastify": "^2.0.0",
|
|
33
|
+
"@basaltkit/tsconfig": "^0.24.0"
|
|
34
34
|
},
|
|
35
35
|
"publishConfig": {
|
|
36
36
|
"access": "public"
|