@basaltkit/auth 2.0.0 → 2.1.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/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,7 +7,7 @@ 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
13
  export { ApiKeys, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.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
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },
@@ -29,8 +29,8 @@
29
29
  "typescript": "^7.0.2",
30
30
  "vitest": "^4.1.11",
31
31
  "zod": "^4.5.4",
32
- "@basaltkit/fastify": "^2.0.0",
33
- "@basaltkit/tsconfig": "^0.24.0"
32
+ "@basaltkit/tsconfig": "^0.24.0",
33
+ "@basaltkit/fastify": "^2.0.0"
34
34
  },
35
35
  "publishConfig": {
36
36
  "access": "public"