@basaltkit/auth 1.6.0 → 1.6.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/dist/jwt.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ import { BasaltError, type DurationInput } from '@basaltkit/core';
2
+ export declare class TokenInvalidError extends BasaltError {
3
+ readonly status = 401;
4
+ constructor();
5
+ }
6
+ export declare class TokenExpiredError extends BasaltError {
7
+ readonly status = 401;
8
+ constructor();
9
+ }
10
+ export interface JwtClaims {
11
+ sub: string;
12
+ iat: number;
13
+ exp?: number;
14
+ /** Access-token version — checked against TokenVersionStore for revocation. */
15
+ tv?: number;
16
+ [claim: string]: unknown;
17
+ }
18
+ /** Signs a compact HS256 JWT — no dependencies, node:crypto only. */
19
+ export declare function signJwt(claims: Record<string, unknown> & {
20
+ sub: string;
21
+ }, options: {
22
+ secret: string;
23
+ expiresIn?: DurationInput;
24
+ }): string;
25
+ /** Verifies signature and expiry; returns the claims. */
26
+ export declare function verifyJwt(token: string, secret: string): JwtClaims;
package/dist/jwt.js ADDED
@@ -0,0 +1,57 @@
1
+ import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ import { BasaltError, parseDuration } from '@basaltkit/core';
3
+ export class TokenInvalidError extends BasaltError {
4
+ status = 401;
5
+ constructor() {
6
+ super('AUTH_TOKEN_INVALID', 'The token is invalid.');
7
+ }
8
+ }
9
+ export class TokenExpiredError extends BasaltError {
10
+ status = 401;
11
+ constructor() {
12
+ super('AUTH_TOKEN_EXPIRED', 'The token has expired.');
13
+ }
14
+ }
15
+ const encode = (value) => Buffer.from(JSON.stringify(value)).toString('base64url');
16
+ /** Signs a compact HS256 JWT — no dependencies, node:crypto only. */
17
+ export function signJwt(claims, options) {
18
+ const now = Math.floor(Date.now() / 1000);
19
+ const payload = {
20
+ iat: now,
21
+ ...(options.expiresIn !== undefined
22
+ ? { exp: now + Math.ceil(parseDuration(options.expiresIn) / 1000) }
23
+ : {}),
24
+ ...claims,
25
+ };
26
+ const head = encode({ alg: 'HS256', typ: 'JWT' });
27
+ const body = encode(payload);
28
+ const signature = createHmac('sha256', options.secret)
29
+ .update(`${head}.${body}`)
30
+ .digest('base64url');
31
+ return `${head}.${body}.${signature}`;
32
+ }
33
+ /** Verifies signature and expiry; returns the claims. */
34
+ export function verifyJwt(token, secret) {
35
+ const parts = token.split('.');
36
+ if (parts.length !== 3)
37
+ throw new TokenInvalidError();
38
+ const [head, body, signature] = parts;
39
+ const expected = createHmac('sha256', secret).update(`${head}.${body}`).digest();
40
+ const received = Buffer.from(signature, 'base64url');
41
+ if (expected.length !== received.length || !timingSafeEqual(expected, received)) {
42
+ throw new TokenInvalidError();
43
+ }
44
+ let claims;
45
+ try {
46
+ claims = JSON.parse(Buffer.from(body, 'base64url').toString());
47
+ }
48
+ catch {
49
+ throw new TokenInvalidError();
50
+ }
51
+ if (typeof claims.sub !== 'string')
52
+ throw new TokenInvalidError();
53
+ if (claims.exp !== undefined && claims.exp <= Math.floor(Date.now() / 1000)) {
54
+ throw new TokenExpiredError();
55
+ }
56
+ return claims;
57
+ }
@@ -0,0 +1,32 @@
1
+ import { type BasaltRoute } from '@basaltkit/fastify';
2
+ import { OAuth, type OAuthOptions, type OAuthProvider } from './oauth.js';
3
+ export declare const OAUTH: import("@basaltkit/core").Token<OAuth>;
4
+ export interface OAuthPluginOptions extends Omit<OAuthOptions, never> {
5
+ providers: OAuthProvider[];
6
+ }
7
+ /**
8
+ * Registers the {@link OAuth} service (token {@link OAUTH}). Pair it with
9
+ * {@link oauthRoutes} and register both AFTER `authPlugin` — the service resolves
10
+ * `AUTH` to log users in.
11
+ */
12
+ export declare function oauthPlugin(options: OAuthPluginOptions): import("@basaltkit/core").BasaltPlugin<unknown>;
13
+ export interface OAuthRoutesOptions {
14
+ /**
15
+ * Base URL of your deployed app. The provider redirect_uri is built as
16
+ * `${callbackBaseUrl}/auth/oauth/:provider/callback` and must be registered
17
+ * with each provider.
18
+ */
19
+ callbackBaseUrl: string;
20
+ /**
21
+ * When set, the callback redirects the browser here after a successful login
22
+ * with `#access_token=…&refresh_token=…` in the fragment (for SPA flows).
23
+ * When omitted, the callback responds with JSON `{ user, accessToken, refreshToken }`.
24
+ */
25
+ successRedirect?: string;
26
+ }
27
+ /**
28
+ * Ready-made OAuth routes:
29
+ * - `GET /auth/oauth/:provider` → 302 to the provider's authorize URL.
30
+ * - `GET /auth/oauth/:provider/callback` → exchanges the code and logs in.
31
+ */
32
+ export declare function oauthRoutes(options: OAuthRoutesOptions): BasaltRoute[];
@@ -0,0 +1,63 @@
1
+ import { createToken, ctx, definePlugin } from '@basaltkit/core';
2
+ import { route } from '@basaltkit/fastify';
3
+ import { z } from 'zod';
4
+ import { AUTH } from './plugin.js';
5
+ import { OAuth, stripTrailingSlashes } from './oauth.js';
6
+ export const OAUTH = createToken('auth.oauth');
7
+ /**
8
+ * Registers the {@link OAuth} service (token {@link OAUTH}). Pair it with
9
+ * {@link oauthRoutes} and register both AFTER `authPlugin` — the service resolves
10
+ * `AUTH` to log users in.
11
+ */
12
+ export function oauthPlugin(options) {
13
+ const { providers, ...oauthOptions } = options;
14
+ return definePlugin({
15
+ name: 'basalt:auth:oauth',
16
+ register({ container }) {
17
+ container.singleton(OAUTH, (c) => new OAuth(c.get(AUTH), providers, oauthOptions));
18
+ },
19
+ });
20
+ }
21
+ /**
22
+ * Ready-made OAuth routes:
23
+ * - `GET /auth/oauth/:provider` → 302 to the provider's authorize URL.
24
+ * - `GET /auth/oauth/:provider/callback` → exchanges the code and logs in.
25
+ */
26
+ export function oauthRoutes(options) {
27
+ const oauth = () => ctx().container.get(OAUTH);
28
+ const base = stripTrailingSlashes(options.callbackBaseUrl);
29
+ const redirectUri = (provider) => `${base}/auth/oauth/${provider}/callback`;
30
+ return [
31
+ route({
32
+ method: 'GET',
33
+ url: '/auth/oauth/:provider',
34
+ params: z.object({ provider: z.string() }),
35
+ async handler({ params, reply }) {
36
+ const url = oauth().authorizeUrl(params.provider, redirectUri(params.provider));
37
+ return reply.code(302).header('location', url).send();
38
+ },
39
+ }),
40
+ route({
41
+ method: 'GET',
42
+ url: '/auth/oauth/:provider/callback',
43
+ params: z.object({ provider: z.string() }),
44
+ query: z.object({ code: z.string(), state: z.string() }),
45
+ async handler({ params, query, reply }) {
46
+ const { user, tokens } = await oauth().callback(params.provider, {
47
+ code: query.code,
48
+ state: query.state,
49
+ redirectUri: redirectUri(params.provider),
50
+ });
51
+ if (options.successRedirect) {
52
+ const url = new URL(options.successRedirect);
53
+ url.hash = new URLSearchParams({
54
+ access_token: tokens.accessToken,
55
+ refresh_token: tokens.refreshToken,
56
+ }).toString();
57
+ return reply.code(302).header('location', url.toString()).send();
58
+ }
59
+ return { user, ...tokens };
60
+ },
61
+ }),
62
+ ];
63
+ }
@@ -0,0 +1,115 @@
1
+ import { BasaltError } from '@basaltkit/core';
2
+ import type { Auth, TokenPair } from './auth.js';
3
+ import type { PublicUser } from './stores.js';
4
+ /** Strip trailing '/' without a backtracking regex (avoids ReDoS on long runs). */
5
+ export declare function stripTrailingSlashes(s: string): string;
6
+ export declare class OAuthProviderUnknownError extends BasaltError {
7
+ readonly status = 404;
8
+ constructor(name: string);
9
+ }
10
+ export declare class OAuthStateInvalidError extends BasaltError {
11
+ readonly status = 400;
12
+ constructor();
13
+ }
14
+ export declare class OAuthExchangeError extends BasaltError {
15
+ readonly status = 502;
16
+ constructor(detail: string);
17
+ }
18
+ /** The normalized profile a provider returns after a successful login. */
19
+ export interface OAuthProfile {
20
+ /** Stable id at the provider (the `sub` / user id). */
21
+ subject: string;
22
+ email: string;
23
+ emailVerified?: boolean;
24
+ name?: string;
25
+ }
26
+ export interface OAuthProvider {
27
+ name: string;
28
+ authorizeUrl: string;
29
+ tokenUrl: string;
30
+ clientId: string;
31
+ clientSecret: string;
32
+ scopes: string[];
33
+ /** Fetches and normalizes the user profile from an access token. */
34
+ fetchProfile(accessToken: string, doFetch: typeof fetch): Promise<OAuthProfile>;
35
+ }
36
+ interface ProviderKeys {
37
+ clientId: string;
38
+ clientSecret: string;
39
+ scopes?: string[];
40
+ }
41
+ /** Google (OpenID Connect). Default scopes: `openid email profile`. */
42
+ export declare function googleProvider(keys: ProviderKeys): OAuthProvider;
43
+ /** GitHub. Default scopes: `read:user user:email` (needed for a verified email). */
44
+ export declare function githubProvider(keys: ProviderKeys): OAuthProvider;
45
+ interface OidcConfig extends ProviderKeys {
46
+ /** Display name for this provider. Default: 'oidc'. */
47
+ name?: string;
48
+ authorizeUrl: string;
49
+ tokenUrl: string;
50
+ userInfoUrl: string;
51
+ }
52
+ /**
53
+ * A generic **OIDC** provider — enterprise SSO for any OpenID Connect IdP
54
+ * (Okta, Azure AD / Entra ID, Auth0, Google Workspace, Keycloak…). Pass the
55
+ * three endpoints from the IdP's `.well-known/openid-configuration`, or use
56
+ * {@link discoverOidcProvider} to fetch them for you. Maps the standard OIDC
57
+ * `userinfo` claims (`sub`, `email`, `email_verified`, `name`).
58
+ */
59
+ export declare function oidcProvider(config: OidcConfig): OAuthProvider;
60
+ /**
61
+ * Builds an {@link oidcProvider} by fetching the IdP's OIDC discovery document
62
+ * (`${issuer}/.well-known/openid-configuration`). Await it at startup.
63
+ */
64
+ export declare function discoverOidcProvider(config: {
65
+ name?: string;
66
+ /** The IdP issuer URL, e.g. `https://acme.okta.com` or `https://login.microsoftonline.com/<tenant>/v2.0`. */
67
+ issuer: string;
68
+ clientId: string;
69
+ clientSecret: string;
70
+ scopes?: string[];
71
+ fetch?: typeof fetch;
72
+ }): Promise<OAuthProvider>;
73
+ export interface OAuthOptions {
74
+ /** Secret used to sign the CSRF `state` (typically your APP_SECRET). */
75
+ secret: string;
76
+ /** Injected fetch (tests). Default: global fetch. */
77
+ fetch?: typeof fetch;
78
+ /** Clock in ms (tests). Default: Date.now. */
79
+ now?: () => number;
80
+ /** How long a signed `state` stays valid, in ms. Default: 10 minutes. */
81
+ stateTtlMs?: number;
82
+ }
83
+ /**
84
+ * OAuth 2.0 authorization-code login. Server-side (confidential-client) flow:
85
+ * build an authorize URL with a signed, expiring `state`, then exchange the code
86
+ * for a token, fetch the profile, and log the user in via {@link Auth.socialLogin}.
87
+ * The `state` is HMAC-signed and stateless — no server storage, works cookieless.
88
+ */
89
+ export declare class OAuth {
90
+ private readonly auth;
91
+ private readonly options;
92
+ private readonly providers;
93
+ private readonly doFetch;
94
+ private readonly now;
95
+ private readonly stateTtl;
96
+ constructor(auth: Auth, providers: OAuthProvider[], options: OAuthOptions);
97
+ names(): string[];
98
+ private provider;
99
+ /** The provider's authorization URL to redirect the browser to. */
100
+ authorizeUrl(name: string, redirectUri: string): string;
101
+ /** Verifies `state`, exchanges the code, fetches the profile, and logs in. */
102
+ callback(name: string, input: {
103
+ code: string;
104
+ state: string | undefined;
105
+ redirectUri: string;
106
+ }): Promise<{
107
+ user: PublicUser;
108
+ tokens: TokenPair;
109
+ created: boolean;
110
+ }>;
111
+ private exchangeCode;
112
+ private signState;
113
+ private verifyState;
114
+ }
115
+ export {};
package/dist/oauth.js ADDED
@@ -0,0 +1,242 @@
1
+ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
2
+ import { BasaltError } from '@basaltkit/core';
3
+ /** Strip trailing '/' without a backtracking regex (avoids ReDoS on long runs). */
4
+ export function stripTrailingSlashes(s) {
5
+ let end = s.length;
6
+ while (end > 0 && s.charCodeAt(end - 1) === 47 /* '/' */)
7
+ end--;
8
+ return s.slice(0, end);
9
+ }
10
+ export class OAuthProviderUnknownError extends BasaltError {
11
+ status = 404;
12
+ constructor(name) {
13
+ super('AUTH_OAUTH_UNKNOWN_PROVIDER', `Unknown OAuth provider "${name}".`);
14
+ }
15
+ }
16
+ export class OAuthStateInvalidError extends BasaltError {
17
+ status = 400;
18
+ constructor() {
19
+ super('AUTH_OAUTH_STATE_INVALID', 'The OAuth state is missing, invalid, tampered with, or expired.');
20
+ }
21
+ }
22
+ export class OAuthExchangeError extends BasaltError {
23
+ status = 502;
24
+ constructor(detail) {
25
+ super('AUTH_OAUTH_EXCHANGE_FAILED', `OAuth token/profile exchange failed: ${detail}`);
26
+ }
27
+ }
28
+ /** Google (OpenID Connect). Default scopes: `openid email profile`. */
29
+ export function googleProvider(keys) {
30
+ return {
31
+ name: 'google',
32
+ authorizeUrl: 'https://accounts.google.com/o/oauth2/v2/auth',
33
+ tokenUrl: 'https://oauth2.googleapis.com/token',
34
+ clientId: keys.clientId,
35
+ clientSecret: keys.clientSecret,
36
+ scopes: keys.scopes ?? ['openid', 'email', 'profile'],
37
+ async fetchProfile(accessToken, doFetch) {
38
+ const res = await doFetch('https://openidconnect.googleapis.com/v1/userinfo', {
39
+ headers: { authorization: `Bearer ${accessToken}` },
40
+ });
41
+ if (!res.ok)
42
+ throw new OAuthExchangeError(`google userinfo HTTP ${res.status}`);
43
+ const p = (await res.json());
44
+ return {
45
+ subject: String(p.sub),
46
+ email: String(p.email),
47
+ emailVerified: p.email_verified === true,
48
+ ...(p.name ? { name: p.name } : {}),
49
+ };
50
+ },
51
+ };
52
+ }
53
+ /** GitHub. Default scopes: `read:user user:email` (needed for a verified email). */
54
+ export function githubProvider(keys) {
55
+ return {
56
+ name: 'github',
57
+ authorizeUrl: 'https://github.com/login/oauth/authorize',
58
+ tokenUrl: 'https://github.com/login/oauth/access_token',
59
+ clientId: keys.clientId,
60
+ clientSecret: keys.clientSecret,
61
+ scopes: keys.scopes ?? ['read:user', 'user:email'],
62
+ async fetchProfile(accessToken, doFetch) {
63
+ const headers = { authorization: `Bearer ${accessToken}`, accept: 'application/vnd.github+json' };
64
+ const userRes = await doFetch('https://api.github.com/user', { headers });
65
+ if (!userRes.ok)
66
+ throw new OAuthExchangeError(`github user HTTP ${userRes.status}`);
67
+ const user = (await userRes.json());
68
+ // GitHub often hides the email on /user; the primary verified one comes from /user/emails.
69
+ let email = user.email ?? undefined;
70
+ let emailVerified = false;
71
+ const emailsRes = await doFetch('https://api.github.com/user/emails', { headers });
72
+ if (emailsRes.ok) {
73
+ const emails = (await emailsRes.json());
74
+ const primary = emails.find((e) => e.primary && e.verified) ?? emails.find((e) => e.verified);
75
+ if (primary) {
76
+ email = primary.email;
77
+ emailVerified = true;
78
+ }
79
+ }
80
+ if (!email)
81
+ throw new OAuthExchangeError('github returned no usable email');
82
+ return { subject: String(user.id), email, emailVerified, ...(user.name ? { name: user.name } : {}) };
83
+ },
84
+ };
85
+ }
86
+ /**
87
+ * A generic **OIDC** provider — enterprise SSO for any OpenID Connect IdP
88
+ * (Okta, Azure AD / Entra ID, Auth0, Google Workspace, Keycloak…). Pass the
89
+ * three endpoints from the IdP's `.well-known/openid-configuration`, or use
90
+ * {@link discoverOidcProvider} to fetch them for you. Maps the standard OIDC
91
+ * `userinfo` claims (`sub`, `email`, `email_verified`, `name`).
92
+ */
93
+ export function oidcProvider(config) {
94
+ return {
95
+ name: config.name ?? 'oidc',
96
+ authorizeUrl: config.authorizeUrl,
97
+ tokenUrl: config.tokenUrl,
98
+ clientId: config.clientId,
99
+ clientSecret: config.clientSecret,
100
+ scopes: config.scopes ?? ['openid', 'email', 'profile'],
101
+ async fetchProfile(accessToken, doFetch) {
102
+ const res = await doFetch(config.userInfoUrl, { headers: { authorization: `Bearer ${accessToken}` } });
103
+ if (!res.ok)
104
+ throw new OAuthExchangeError(`oidc userinfo HTTP ${res.status}`);
105
+ const p = (await res.json());
106
+ return {
107
+ subject: String(p.sub),
108
+ email: String(p.email),
109
+ emailVerified: p.email_verified === true,
110
+ ...(p.name ? { name: p.name } : {}),
111
+ };
112
+ },
113
+ };
114
+ }
115
+ /**
116
+ * Builds an {@link oidcProvider} by fetching the IdP's OIDC discovery document
117
+ * (`${issuer}/.well-known/openid-configuration`). Await it at startup.
118
+ */
119
+ export async function discoverOidcProvider(config) {
120
+ const doFetch = config.fetch ?? globalThis.fetch;
121
+ const url = `${stripTrailingSlashes(config.issuer)}/.well-known/openid-configuration`;
122
+ const res = await doFetch(url);
123
+ if (!res.ok)
124
+ throw new OAuthExchangeError(`OIDC discovery HTTP ${res.status} for ${url}`);
125
+ const meta = (await res.json());
126
+ if (!meta.authorization_endpoint || !meta.token_endpoint || !meta.userinfo_endpoint) {
127
+ throw new OAuthExchangeError('OIDC discovery document is missing required endpoints');
128
+ }
129
+ return oidcProvider({
130
+ ...(config.name ? { name: config.name } : {}),
131
+ authorizeUrl: meta.authorization_endpoint,
132
+ tokenUrl: meta.token_endpoint,
133
+ userInfoUrl: meta.userinfo_endpoint,
134
+ clientId: config.clientId,
135
+ clientSecret: config.clientSecret,
136
+ ...(config.scopes ? { scopes: config.scopes } : {}),
137
+ });
138
+ }
139
+ /**
140
+ * OAuth 2.0 authorization-code login. Server-side (confidential-client) flow:
141
+ * build an authorize URL with a signed, expiring `state`, then exchange the code
142
+ * for a token, fetch the profile, and log the user in via {@link Auth.socialLogin}.
143
+ * The `state` is HMAC-signed and stateless — no server storage, works cookieless.
144
+ */
145
+ export class OAuth {
146
+ auth;
147
+ options;
148
+ providers;
149
+ doFetch;
150
+ now;
151
+ stateTtl;
152
+ constructor(auth, providers, options) {
153
+ this.auth = auth;
154
+ this.options = options;
155
+ this.providers = new Map(providers.map((p) => [p.name, p]));
156
+ this.doFetch = options.fetch ?? globalThis.fetch;
157
+ this.now = options.now ?? Date.now;
158
+ this.stateTtl = options.stateTtlMs ?? 10 * 60_000;
159
+ }
160
+ names() {
161
+ return [...this.providers.keys()];
162
+ }
163
+ provider(name) {
164
+ const p = this.providers.get(name);
165
+ if (!p)
166
+ throw new OAuthProviderUnknownError(name);
167
+ return p;
168
+ }
169
+ /** The provider's authorization URL to redirect the browser to. */
170
+ authorizeUrl(name, redirectUri) {
171
+ const p = this.provider(name);
172
+ const state = this.signState({ n: randomBytes(16).toString('hex'), e: this.now() + this.stateTtl, p: name });
173
+ const params = new URLSearchParams({
174
+ client_id: p.clientId,
175
+ redirect_uri: redirectUri,
176
+ response_type: 'code',
177
+ scope: p.scopes.join(' '),
178
+ state,
179
+ });
180
+ return `${p.authorizeUrl}?${params.toString()}`;
181
+ }
182
+ /** Verifies `state`, exchanges the code, fetches the profile, and logs in. */
183
+ async callback(name, input) {
184
+ const payload = this.verifyState(input.state);
185
+ if (payload.p !== name)
186
+ throw new OAuthStateInvalidError();
187
+ const p = this.provider(name);
188
+ const accessToken = await this.exchangeCode(p, input.code, input.redirectUri);
189
+ const profile = await p.fetchProfile(accessToken, this.doFetch);
190
+ if (!profile.email)
191
+ throw new OAuthExchangeError('provider returned no email');
192
+ return this.auth.socialLogin(profile.email, { emailVerified: profile.emailVerified === true });
193
+ }
194
+ async exchangeCode(p, code, redirectUri) {
195
+ const res = await this.doFetch(p.tokenUrl, {
196
+ method: 'POST',
197
+ headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
198
+ body: new URLSearchParams({
199
+ grant_type: 'authorization_code',
200
+ code,
201
+ redirect_uri: redirectUri,
202
+ client_id: p.clientId,
203
+ client_secret: p.clientSecret,
204
+ }).toString(),
205
+ });
206
+ const text = await res.text();
207
+ const json = text ? JSON.parse(text) : {};
208
+ if (!res.ok || !json.access_token) {
209
+ throw new OAuthExchangeError(json.error_description ?? json.error ?? `token endpoint HTTP ${res.status}`);
210
+ }
211
+ return json.access_token;
212
+ }
213
+ signState(payload) {
214
+ const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
215
+ const sig = createHmac('sha256', this.options.secret).update(body).digest('base64url');
216
+ return `${body}.${sig}`;
217
+ }
218
+ verifyState(state) {
219
+ if (!state)
220
+ throw new OAuthStateInvalidError();
221
+ const dot = state.indexOf('.');
222
+ if (dot < 0)
223
+ throw new OAuthStateInvalidError();
224
+ const body = state.slice(0, dot);
225
+ const sig = state.slice(dot + 1);
226
+ const expected = createHmac('sha256', this.options.secret).update(body).digest('base64url');
227
+ const a = Buffer.from(sig);
228
+ const b = Buffer.from(expected);
229
+ if (a.length !== b.length || !timingSafeEqual(a, b))
230
+ throw new OAuthStateInvalidError();
231
+ let payload;
232
+ try {
233
+ payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
234
+ }
235
+ catch {
236
+ throw new OAuthStateInvalidError();
237
+ }
238
+ if (typeof payload.e !== 'number' || this.now() > payload.e)
239
+ throw new OAuthStateInvalidError();
240
+ return payload;
241
+ }
242
+ }
@@ -0,0 +1,56 @@
1
+ import { Auth, type AuthOptions } from './auth.js';
2
+ import type { PublicUser } from './stores.js';
3
+ declare module '@basaltkit/core' {
4
+ interface RequestContext {
5
+ /** The authenticated user of the current request, set by auth. */
6
+ user?: PublicUser;
7
+ }
8
+ interface BasaltHooks {
9
+ 'auth:registered': {
10
+ user: PublicUser;
11
+ };
12
+ /**
13
+ * Someone tried to register an email that already has an account. Emitted by
14
+ * the enumeration-safe register endpoint so the app can email the address
15
+ * ("you already have an account — sign in or reset your password") instead of
16
+ * revealing existence in the HTTP response. Only the email is provided.
17
+ */
18
+ 'auth:register_existing_email': {
19
+ email: string;
20
+ };
21
+ 'auth:login': {
22
+ user: PublicUser;
23
+ };
24
+ 'auth:login_failed': {
25
+ email: string;
26
+ };
27
+ 'auth:logout': {
28
+ user: PublicUser;
29
+ };
30
+ /** Email verification requested — the app emails the token as a link. */
31
+ 'auth:verify_requested': {
32
+ user: PublicUser;
33
+ token: string;
34
+ };
35
+ 'auth:email_verified': {
36
+ user: PublicUser;
37
+ };
38
+ /** Password reset requested — the app emails the token as a link. */
39
+ 'auth:password_reset_requested': {
40
+ user: PublicUser;
41
+ token: string;
42
+ };
43
+ 'auth:password_reset': {
44
+ user: PublicUser;
45
+ };
46
+ 'auth:mfa_enabled': {
47
+ user: PublicUser;
48
+ };
49
+ 'auth:mfa_disabled': {
50
+ user: PublicUser;
51
+ };
52
+ }
53
+ }
54
+ export declare const AUTH: import("@basaltkit/core").Token<Auth>;
55
+ export type AuthPluginOptions = Omit<AuthOptions, 'hooks'>;
56
+ export declare function authPlugin(options: AuthPluginOptions): import("@basaltkit/core").BasaltPlugin<unknown>;
package/dist/plugin.js ADDED
@@ -0,0 +1,44 @@
1
+ import { createToken, definePlugin, ensureMetadata } from '@basaltkit/core';
2
+ import { Auth, AuthRequiredError } from './auth.js';
3
+ import { publicUser } from './auth.js';
4
+ export const AUTH = createToken('auth');
5
+ export function authPlugin(options) {
6
+ return definePlugin({
7
+ name: 'basalt:auth',
8
+ register({ container, hooks }) {
9
+ container.singleton(AUTH, () => new Auth({ ...options, hooks }));
10
+ const metadata = ensureMetadata(container);
11
+ // Enricher: authenticates via Bearer JWT or x-session-id header.
12
+ // An explicitly provided invalid token is rejected (401); absence of
13
+ // credentials just leaves the request anonymous.
14
+ const enricher = async ({ request, context, container: c }) => {
15
+ const auth = c.get(AUTH);
16
+ const header = request.headers.authorization;
17
+ const bearer = typeof header === 'string' && header.startsWith('Bearer ')
18
+ ? header.slice('Bearer '.length)
19
+ : undefined;
20
+ // `mk_`-prefixed bearers are API keys — left to apiKeysPlugin.
21
+ if (bearer && !bearer.startsWith('mk_')) {
22
+ const claims = await auth.verifyAccessToken(bearer);
23
+ const user = await auth.users.findById(claims.sub);
24
+ if (user)
25
+ context.user = publicUser(user);
26
+ return;
27
+ }
28
+ const sessionId = request.headers['x-session-id'];
29
+ if (typeof sessionId === 'string') {
30
+ const user = await auth.sessionUser(sessionId);
31
+ if (user)
32
+ context.user = publicUser(user);
33
+ }
34
+ };
35
+ metadata.add('http:enrichers', enricher);
36
+ // Guard: routes declaring meta.auth require an authenticated user.
37
+ const guard = ({ route, context }) => {
38
+ if (route.meta?.['auth'] === true && !context.user)
39
+ throw new AuthRequiredError();
40
+ };
41
+ metadata.add('http:guards', guard);
42
+ },
43
+ });
44
+ }
@@ -0,0 +1,23 @@
1
+ import { type BasaltRoute } from '@basaltkit/fastify';
2
+ /**
3
+ * Ready-made auth routes — register them in fastifyPlugin({ routes }):
4
+ * register · login · refresh · logout · me, plus email verification
5
+ * (`/auth/verify/request`, `/auth/verify`) and password reset
6
+ * (`/auth/password/forgot`, `/auth/password/reset`).
7
+ * Every one is a plain BasaltRoute: replace or omit any of them freely.
8
+ */
9
+ export declare function authRoutes(): BasaltRoute[];
10
+ /**
11
+ * CRUD routes for API keys, all requiring a logged-in user (`meta.auth`). Keys
12
+ * are scoped to the caller's tenant (`ctx().tenant`) and user; a caller only
13
+ * ever sees or revokes keys within that scope. Register alongside
14
+ * {@link authRoutes} and pair with `apiKeysPlugin`.
15
+ */
16
+ export declare function apiKeyRoutes(): BasaltRoute[];
17
+ /**
18
+ * MFA (TOTP) self-service routes, all requiring a logged-in user: enroll,
19
+ * activate (returns one-time recovery codes), status, and disable. Register
20
+ * alongside {@link authRoutes} and enable MFA at login via the optional
21
+ * `mfaCode` field on `POST /auth/login`.
22
+ */
23
+ export declare function mfaRoutes(): BasaltRoute[];