@basaltkit/auth 2.0.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 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>` or `x-session-id` header and places the user in `ctx().user` (of type `PublicUser` — never includes the password hash).
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/auth.d.ts CHANGED
@@ -62,6 +62,18 @@ export interface TokenPair {
62
62
  accessToken: string;
63
63
  refreshToken: string;
64
64
  }
65
+ export interface SessionCookieOptions {
66
+ /** Cookie name. Default: `basalt_session`. */
67
+ name?: string;
68
+ /** Cookie path. Default: `/`. */
69
+ path?: string;
70
+ /** Whether the browser may expose the cookie to JavaScript. Default: true. */
71
+ httpOnly?: boolean;
72
+ /** SameSite policy. Default: `Lax`. */
73
+ sameSite?: 'Strict' | 'Lax' | 'None';
74
+ /** Whether to require HTTPS. Defaults to production-only. */
75
+ secure?: boolean;
76
+ }
65
77
  export interface AuthOptions {
66
78
  users: UserSource;
67
79
  secret: string;
@@ -71,6 +83,7 @@ export interface AuthOptions {
71
83
  accessTtl?: DurationInput;
72
84
  refreshTtl?: DurationInput;
73
85
  sessionTtl?: DurationInput;
86
+ sessionCookie?: SessionCookieOptions;
74
87
  hooks?: HookBus;
75
88
  /** Brute-force lockout (per email). Enabled by default; pass `false` to disable. */
76
89
  loginThrottle?: LoginThrottle | false;
@@ -124,6 +137,7 @@ export declare class Auth {
124
137
  private readonly accessTtl;
125
138
  private readonly refreshTtl;
126
139
  private readonly sessionTtl;
140
+ private readonly sessionCookie;
127
141
  private readonly hooks;
128
142
  private readonly throttle;
129
143
  private readonly ipThrottle;
@@ -207,6 +221,9 @@ export declare class Auth {
207
221
  */
208
222
  revokeAllTokens(userId: string): Promise<void>;
209
223
  createSession(userId: string): Promise<SessionRecord>;
224
+ sessionCookieHeader(sessionId: string): string;
225
+ sessionIdFromCookie(cookieHeader?: string): string | null;
226
+ expiredSessionCookieHeader(): string;
210
227
  sessionUser(sessionId: string): Promise<AuthUser | null>;
211
228
  logout(sessionId: string): Promise<void>;
212
229
  /**
package/dist/auth.js CHANGED
@@ -97,6 +97,7 @@ export class Auth {
97
97
  accessTtl;
98
98
  refreshTtl;
99
99
  sessionTtl;
100
+ sessionCookie;
100
101
  hooks;
101
102
  throttle;
102
103
  ipThrottle;
@@ -124,6 +125,13 @@ export class Auth {
124
125
  this.accessTtl = options.accessTtl ?? '15m';
125
126
  this.refreshTtl = options.refreshTtl ?? '30d';
126
127
  this.sessionTtl = options.sessionTtl ?? '30d';
128
+ this.sessionCookie = {
129
+ name: options.sessionCookie?.name ?? 'basalt_session',
130
+ path: options.sessionCookie?.path ?? '/',
131
+ httpOnly: options.sessionCookie?.httpOnly ?? true,
132
+ sameSite: options.sessionCookie?.sameSite ?? 'Lax',
133
+ secure: options.sessionCookie?.secure ?? process.env['NODE_ENV'] === 'production',
134
+ };
127
135
  this.hooks = options.hooks;
128
136
  this.throttle = options.loginThrottle === false ? undefined : options.loginThrottle ?? new LoginThrottle();
129
137
  this.ipThrottle =
@@ -318,6 +326,27 @@ export class Auth {
318
326
  async createSession(userId) {
319
327
  return this.sessions.create(userId, parseDuration(this.sessionTtl));
320
328
  }
329
+ sessionCookieHeader(sessionId) {
330
+ const ttlMs = parseDuration(this.sessionTtl);
331
+ const cookie = this.sessionCookie;
332
+ const expires = new Date(Date.now() + ttlMs).toUTCString();
333
+ return `${cookie.name}=${encodeURIComponent(sessionId)}; Path=${cookie.path};${cookie.httpOnly ? ' HttpOnly;' : ''} SameSite=${cookie.sameSite}; Max-Age=${Math.max(1, Math.floor(ttlMs / 1000))}; Expires=${expires}${cookie.secure ? '; Secure' : ''}`;
334
+ }
335
+ sessionIdFromCookie(cookieHeader) {
336
+ if (!cookieHeader)
337
+ return null;
338
+ for (const part of cookieHeader.split(';')) {
339
+ const [name, ...rest] = part.trim().split('=');
340
+ if (name === this.sessionCookie.name && rest.length > 0) {
341
+ return decodeURIComponent(rest.join('='));
342
+ }
343
+ }
344
+ return null;
345
+ }
346
+ expiredSessionCookieHeader() {
347
+ const cookie = this.sessionCookie;
348
+ return `${cookie.name}=; Path=${cookie.path};${cookie.httpOnly ? ' HttpOnly;' : ''} SameSite=${cookie.sameSite}; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT${cookie.secure ? '; Secure' : ''}`;
349
+ }
321
350
  async sessionUser(sessionId) {
322
351
  const session = await this.sessions.find(sessionId);
323
352
  return session ? this.users.findById(session.userId) : null;
package/dist/index.d.ts CHANGED
@@ -7,10 +7,10 @@ declare module '@basaltkit/http' {
7
7
  auth?: boolean;
8
8
  }
9
9
  }
10
- export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, type AuthOptions, type TokenPair, } from './auth.js';
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/plugin.js CHANGED
@@ -8,7 +8,7 @@ export function authPlugin(options) {
8
8
  register({ container, hooks }) {
9
9
  container.singleton(AUTH, () => new Auth({ ...options, hooks }));
10
10
  const metadata = ensureMetadata(container);
11
- // Enricher: authenticates via Bearer JWT or x-session-id header.
11
+ // Enricher: authenticates via Bearer JWT, session cookie, or x-session-id header.
12
12
  // An explicitly provided invalid token is rejected (401); absence of
13
13
  // credentials just leaves the request anonymous.
14
14
  const enricher = async ({ request, context, container: c }) => {
@@ -30,6 +30,16 @@ export function authPlugin(options) {
30
30
  const user = await auth.sessionUser(sessionId);
31
31
  if (user)
32
32
  context.user = publicUser(user);
33
+ return;
34
+ }
35
+ const cookie = request.headers.cookie;
36
+ if (typeof cookie === 'string') {
37
+ const cookieSessionId = auth.sessionIdFromCookie(cookie);
38
+ if (cookieSessionId) {
39
+ const user = await auth.sessionUser(cookieSessionId);
40
+ if (user)
41
+ context.user = publicUser(user);
42
+ }
33
43
  }
34
44
  };
35
45
  metadata.add('http:enrichers', enricher);
package/dist/routes.js CHANGED
@@ -40,8 +40,12 @@ export function authRoutes(options = {}) {
40
40
  method: 'POST',
41
41
  url: '/auth/login',
42
42
  body: credentials.extend({ mfaCode: z.string().optional() }),
43
- async handler({ body, request }) {
43
+ async handler({ body, request, reply }) {
44
44
  const { user, tokens } = await auth().login(body.email, body.password, body.mfaCode, request.ip ? { ip: request.ip } : {});
45
+ const session = await auth().createSession(user.id);
46
+ const sessionCookie = auth().sessionCookieHeader(session.id);
47
+ if (sessionCookie)
48
+ reply.header('set-cookie', sessionCookie);
45
49
  return { user, ...tokens };
46
50
  },
47
51
  }),
@@ -57,8 +61,14 @@ export function authRoutes(options = {}) {
57
61
  method: 'POST',
58
62
  url: '/auth/logout',
59
63
  body: z.object({ refreshToken: z.string() }),
60
- async handler({ body, reply }) {
64
+ async handler({ body, request, reply }) {
61
65
  await auth().revoke(body.refreshToken);
66
+ const sessionId = auth().sessionIdFromCookie(request.headers.cookie);
67
+ if (sessionId)
68
+ await auth().logout(sessionId);
69
+ const expiredCookie = auth().expiredSessionCookieHeader();
70
+ if (expiredCookie)
71
+ reply.header('set-cookie', expiredCookie);
62
72
  return reply.code(204).send();
63
73
  },
64
74
  }),
@@ -144,6 +154,7 @@ export function apiKeyRoutes() {
144
154
  body: z.object({
145
155
  name: z.string().min(1).max(100),
146
156
  scopes: z.array(z.string().min(1)).optional(),
157
+ expiresAt: z.number().int().positive().optional(),
147
158
  }),
148
159
  async handler({ body, reply }) {
149
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.0.0",
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/core": "^1.3.1",
22
- "@basaltkit/http": "^2.0.0"
21
+ "@basaltkit/http": "^2.0.0",
22
+ "@basaltkit/core": "^1.3.1"
23
23
  },
24
24
  "peerDependencies": {
25
25
  "zod": "^4.0.0"