@basaltkit/auth 1.8.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 +17 -0
- package/dist/auth.js +29 -0
- package/dist/index.d.ts +8 -2
- package/dist/index.js +1 -1
- package/dist/plugin.js +11 -1
- package/dist/routes.d.ts +22 -1
- package/dist/routes.js +28 -5
- package/package.json +7 -7
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
|
@@ -1,12 +1,18 @@
|
|
|
1
1
|
export { ScryptPasswordHasher, type PasswordHasher } from './hashing.js';
|
|
2
2
|
export { signJwt, verifyJwt, TokenInvalidError, TokenExpiredError, type JwtClaims, } from './jwt.js';
|
|
3
3
|
export { MemoryUserSource, MemorySessionStore, MemoryRefreshTokenStore, MemoryAuthTokenStore, MemoryApiKeyStore, MemoryMfaStore, MemoryTokenVersionStore, type TokenVersionStore, type AuthUser, type PublicUser, type UserSource, type UserPatch, type SessionStore, type SessionRecord, type RefreshTokenStore, type RefreshRecord, type AuthTokenStore, type AuthTokenRecord, type AuthTokenPurpose, type ApiKeyStore, type ApiKeyRecord, type ApiKeyInfo, type ApiKeyFilter, type MfaStore, type MfaRecord, } from './stores.js';
|
|
4
|
-
|
|
4
|
+
declare module '@basaltkit/http' {
|
|
5
|
+
interface RouteMeta {
|
|
6
|
+
/** `true` requires a session; `false` opts a route out. */
|
|
7
|
+
auth?: boolean;
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
export { Auth, publicUser, InvalidCredentialsError, EmailTakenError, WeakJwtSecretError, RefreshInvalidError, RefreshReusedError, AuthRequiredError, AuthTokenInvalidError, UserUpdateUnsupportedError, MfaRequiredError, MfaInvalidCodeError, MfaNotEnrolledError, type AuthOptions, type SessionCookieOptions, type TokenPair, } from './auth.js';
|
|
5
11
|
export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, matchTotpStep, otpauthUri, type TotpOptions, type VerifyTotpOptions, type OtpauthUriInput, } from './totp.js';
|
|
6
12
|
export { authPlugin, AUTH, type AuthPluginOptions } from './plugin.js';
|
|
7
13
|
export { ApiKeys, ScopeRequiredError, scopesSatisfy, type ApiKeysOptions, type IssueApiKeyInput, type ApiKeyContext, } from './apikeys.js';
|
|
8
14
|
export { apiKeysPlugin, API_KEYS, type ApiKeysPluginOptions } from './apikeys-plugin.js';
|
|
9
|
-
export { authRoutes, apiKeyRoutes, mfaRoutes } from './routes.js';
|
|
15
|
+
export { authRoutes, apiKeyRoutes, mfaRoutes, type AuthRoutesOptions, type PasswordPolicy, } from './routes.js';
|
|
10
16
|
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, type OAuthProvider, type OAuthProfile, type OAuthOptions, } from './oauth.js';
|
|
11
17
|
export { oauthPlugin, oauthRoutes, OAUTH, type OAuthPluginOptions, type OAuthRoutesOptions, } from './oauth-plugin.js';
|
|
12
18
|
export { LoginThrottle, AccountLockedError, type LoginThrottleOptions } from './throttle.js';
|
package/dist/index.js
CHANGED
|
@@ -6,7 +6,7 @@ export { base32Encode, base32Decode, generateTotpSecret, totp, verifyTotp, match
|
|
|
6
6
|
export { authPlugin, AUTH } from './plugin.js';
|
|
7
7
|
export { ApiKeys, ScopeRequiredError, scopesSatisfy, } from './apikeys.js';
|
|
8
8
|
export { apiKeysPlugin, API_KEYS } from './apikeys-plugin.js';
|
|
9
|
-
export { authRoutes, apiKeyRoutes, mfaRoutes } from './routes.js';
|
|
9
|
+
export { authRoutes, apiKeyRoutes, mfaRoutes, } from './routes.js';
|
|
10
10
|
export { OAuth, googleProvider, githubProvider, oidcProvider, discoverOidcProvider, stripTrailingSlashes, OAuthProviderUnknownError, OAuthStateInvalidError, OAuthExchangeError, } from './oauth.js';
|
|
11
11
|
export { oauthPlugin, oauthRoutes, OAUTH, } from './oauth-plugin.js';
|
|
12
12
|
export { LoginThrottle, AccountLockedError } from './throttle.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.d.ts
CHANGED
|
@@ -1,4 +1,25 @@
|
|
|
1
1
|
import { type BasaltRoute } from '@basaltkit/http';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
/**
|
|
4
|
+
* How strong a password has to be.
|
|
5
|
+
*
|
|
6
|
+
* The rule was `min(8)`, fixed, with no way to change it — the 2012 minimum, in
|
|
7
|
+
* routes an application either uses as they are or replaces wholesale. One that
|
|
8
|
+
* needed more reached into the route's Zod object and swapped the field,
|
|
9
|
+
* depending on the internal shape of a body it does not own.
|
|
10
|
+
*
|
|
11
|
+
* A whole schema and not just a number, because the interesting rules are not
|
|
12
|
+
* lengths: "at least one symbol", "not the email address", "not in a breach
|
|
13
|
+
* list". An option taking only a number would send those applications straight
|
|
14
|
+
* back to patching.
|
|
15
|
+
*/
|
|
16
|
+
export interface PasswordPolicy {
|
|
17
|
+
minLength?: number;
|
|
18
|
+
}
|
|
19
|
+
export interface AuthRoutesOptions {
|
|
20
|
+
/** A minimum length, or the schema itself. Default: `min(8)`. */
|
|
21
|
+
password?: PasswordPolicy | z.ZodType<string>;
|
|
22
|
+
}
|
|
2
23
|
/**
|
|
3
24
|
* Ready-made auth routes — register them in fastifyPlugin({ routes }):
|
|
4
25
|
* register · login · refresh · logout · me, plus email verification
|
|
@@ -6,7 +27,7 @@ import { type BasaltRoute } from '@basaltkit/http';
|
|
|
6
27
|
* (`/auth/password/forgot`, `/auth/password/reset`).
|
|
7
28
|
* Every one is a plain BasaltRoute: replace or omit any of them freely.
|
|
8
29
|
*/
|
|
9
|
-
export declare function authRoutes(): BasaltRoute[];
|
|
30
|
+
export declare function authRoutes(options?: AuthRoutesOptions): BasaltRoute[];
|
|
10
31
|
/**
|
|
11
32
|
* CRUD routes for API keys, all requiring a logged-in user (`meta.auth`). Keys
|
|
12
33
|
* are scoped to the caller's tenant (`ctx().tenant`) and user; a caller only
|
package/dist/routes.js
CHANGED
|
@@ -3,7 +3,15 @@ import { route } from '@basaltkit/http';
|
|
|
3
3
|
import { z } from 'zod';
|
|
4
4
|
import { AUTH } from './plugin.js';
|
|
5
5
|
import { API_KEYS } from './apikeys-plugin.js';
|
|
6
|
-
const
|
|
6
|
+
const DEFAULT_PASSWORD = z.string().min(8);
|
|
7
|
+
const passwordSchema = (policy) => {
|
|
8
|
+
if (!policy)
|
|
9
|
+
return DEFAULT_PASSWORD;
|
|
10
|
+
if (typeof policy.safeParse === 'function')
|
|
11
|
+
return policy;
|
|
12
|
+
const { minLength } = policy;
|
|
13
|
+
return minLength === undefined ? DEFAULT_PASSWORD : z.string().min(minLength);
|
|
14
|
+
};
|
|
7
15
|
const auth = () => ctx().container.get(AUTH);
|
|
8
16
|
const apiKeys = () => ctx().container.get(API_KEYS);
|
|
9
17
|
/**
|
|
@@ -13,7 +21,9 @@ const apiKeys = () => ctx().container.get(API_KEYS);
|
|
|
13
21
|
* (`/auth/password/forgot`, `/auth/password/reset`).
|
|
14
22
|
* Every one is a plain BasaltRoute: replace or omit any of them freely.
|
|
15
23
|
*/
|
|
16
|
-
export function authRoutes() {
|
|
24
|
+
export function authRoutes(options = {}) {
|
|
25
|
+
const password = passwordSchema(options.password);
|
|
26
|
+
const credentials = z.object({ email: z.string().email(), password });
|
|
17
27
|
return [
|
|
18
28
|
route({
|
|
19
29
|
method: 'POST',
|
|
@@ -30,8 +40,12 @@ export function authRoutes() {
|
|
|
30
40
|
method: 'POST',
|
|
31
41
|
url: '/auth/login',
|
|
32
42
|
body: credentials.extend({ mfaCode: z.string().optional() }),
|
|
33
|
-
async handler({ body, request }) {
|
|
43
|
+
async handler({ body, request, reply }) {
|
|
34
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);
|
|
35
49
|
return { user, ...tokens };
|
|
36
50
|
},
|
|
37
51
|
}),
|
|
@@ -47,8 +61,14 @@ export function authRoutes() {
|
|
|
47
61
|
method: 'POST',
|
|
48
62
|
url: '/auth/logout',
|
|
49
63
|
body: z.object({ refreshToken: z.string() }),
|
|
50
|
-
async handler({ body, reply }) {
|
|
64
|
+
async handler({ body, request, reply }) {
|
|
51
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);
|
|
52
72
|
return reply.code(204).send();
|
|
53
73
|
},
|
|
54
74
|
}),
|
|
@@ -93,7 +113,10 @@ export function authRoutes() {
|
|
|
93
113
|
route({
|
|
94
114
|
method: 'POST',
|
|
95
115
|
url: '/auth/password/reset',
|
|
96
|
-
|
|
116
|
+
// The same policy as register. Covering register and leaving reset behind
|
|
117
|
+
// would let anyone walk a strong password back down to eight characters
|
|
118
|
+
// through "forgot password" — a loophole worse than having no option.
|
|
119
|
+
body: z.object({ token: z.string(), password }),
|
|
97
120
|
async handler({ body }) {
|
|
98
121
|
await auth().resetPassword(body.token, body.password);
|
|
99
122
|
return { ok: true };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@basaltkit/auth",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"engines": {
|
|
5
5
|
"node": ">=22.5.0"
|
|
6
6
|
},
|
|
@@ -19,18 +19,18 @@
|
|
|
19
19
|
],
|
|
20
20
|
"dependencies": {
|
|
21
21
|
"@basaltkit/core": "^1.3.1",
|
|
22
|
-
"@basaltkit/http": "^
|
|
22
|
+
"@basaltkit/http": "^2.0.0"
|
|
23
23
|
},
|
|
24
24
|
"peerDependencies": {
|
|
25
|
-
"zod": "^
|
|
25
|
+
"zod": "^4.0.0"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
|
-
"@types/node": "^26.
|
|
28
|
+
"@types/node": "^26.4.0",
|
|
29
29
|
"typescript": "^7.0.2",
|
|
30
30
|
"vitest": "^4.1.11",
|
|
31
|
-
"zod": "^
|
|
32
|
-
"@basaltkit/
|
|
33
|
-
"@basaltkit/
|
|
31
|
+
"zod": "^4.5.4",
|
|
32
|
+
"@basaltkit/tsconfig": "^0.24.0",
|
|
33
|
+
"@basaltkit/fastify": "^2.0.0"
|
|
34
34
|
},
|
|
35
35
|
"publishConfig": {
|
|
36
36
|
"access": "public"
|