@basaltkit/auth 1.3.1 → 1.4.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @basaltkit/auth
2
2
 
3
- Complete authentication for Basalt applications: user registration and login, JWT tokens with secure renewal, sessions, email verification, password recovery, two-factor authentication (MFA/TOTP), and API keys — all with ready-to-use HTTP routes.
3
+ Complete authentication for Basalt applications: user registration and login, JWT tokens with secure renewal, sessions, email verification, password recovery, two-factor authentication (MFA/TOTP), social login (Google, GitHub, or any OpenID Connect provider), and API keys — all with ready-to-use HTTP routes.
4
4
 
5
5
  You need this module whenever your application has users who log in.
6
6
 
@@ -10,7 +10,7 @@ When an application has user accounts, it needs to answer two questions on every
10
10
 
11
11
  `@basaltkit/auth` handles all of this for you. Passwords are never stored in plain text — only an irreversibly scrambled version (**hash**, using the scrypt algorithm). Login returns a pair of tokens: an **access token** (short-lived JWT, 15 minutes by default, sent with every request) and a **refresh token** (long-lived, 30 days, used only to obtain a new access token). If a refresh token is used twice — a typical sign of theft — the entire token "family" is automatically revoked.
12
12
 
13
- It also includes, with nothing extra to install: account lockout after too many failed attempts, email verification and password recovery via single-use links, MFA via authenticator app (Google Authenticator, etc.) with recovery codes, and API keys for programmatic access (scripts, integrations).
13
+ It also includes, with nothing extra to install: account lockout after too many failed attempts, email verification and password recovery via single-use links, MFA via authenticator app (Google Authenticator, etc.) with recovery codes, social login (OAuth 2.0 / OpenID Connect), and API keys for programmatic access (scripts, integrations).
14
14
 
15
15
  ## Installation
16
16
 
@@ -162,6 +162,65 @@ Flow (all routes require login):
162
162
  3. From then on, `POST /auth/login` requires the extra `mfaCode` field (TOTP code or a recovery code). Correct password without a code → `AUTH_MFA_REQUIRED` error.
163
163
  4. `GET /auth/mfa/status` and `POST /auth/mfa/disable` (with `{ code }`) complete the cycle.
164
164
 
165
+ ### Social login (OAuth)
166
+
167
+ Sign in with Google, GitHub, or any OpenID Connect provider via the OAuth 2.0
168
+ authorization-code flow — no SDK, and cookieless (the CSRF `state` is HMAC-signed
169
+ and stateless). Register `oauthPlugin` with your providers and `oauthRoutes` with
170
+ your app's **base URL**:
171
+
172
+ ```ts
173
+ import {
174
+ authPlugin, authRoutes, oauthPlugin, oauthRoutes, googleProvider, githubProvider,
175
+ } from '@basaltkit/auth'
176
+ import { fastifyPlugin } from '@basaltkit/fastify'
177
+
178
+ createApp({
179
+ plugins: [
180
+ authPlugin({ users, secret: process.env.AUTH_SECRET! }),
181
+ oauthPlugin({
182
+ secret: process.env.AUTH_SECRET!, // signs the stateless `state`
183
+ providers: [
184
+ googleProvider({ clientId: env.GOOGLE_ID, clientSecret: env.GOOGLE_SECRET }),
185
+ githubProvider({ clientId: env.GITHUB_ID, clientSecret: env.GITHUB_SECRET }),
186
+ ],
187
+ }),
188
+ fastifyPlugin({
189
+ routes: [
190
+ ...authRoutes(),
191
+ // callbackBaseUrl is your app's BASE url — the module appends
192
+ // /auth/oauth/:provider/callback itself.
193
+ ...oauthRoutes({ callbackBaseUrl: 'https://app.example.com' }),
194
+ ],
195
+ }),
196
+ ],
197
+ })
198
+ ```
199
+
200
+ Two routes are added per provider:
201
+
202
+ - `GET /auth/oauth/:provider` → 302 to the provider's consent screen.
203
+ - `GET /auth/oauth/:provider/callback` → verifies the `state`, exchanges the code,
204
+ and logs the user in. Returns JSON `{ user, accessToken, refreshToken }`; pass
205
+ `successRedirect` to `oauthRoutes` to bounce the browser back to your SPA with
206
+ the tokens in the URL fragment instead.
207
+
208
+ **Register the redirect URI with each provider exactly** as
209
+ `${callbackBaseUrl}/auth/oauth/:provider/callback` — e.g.
210
+ `https://app.example.com/auth/oauth/github/callback`. It must match
211
+ character-for-character, or the provider rejects it with *"redirect_uri is not
212
+ associated with this application"*.
213
+
214
+ New accounts are created **passwordless** and a provider-verified email flips
215
+ `emailVerified`. Accounts are matched by email, so only trust providers that
216
+ return a **verified** address (Google and the built-in GitHub driver both do).
217
+ `Auth.socialLogin(email)` is the underlying primitive for custom providers.
218
+
219
+ **Enterprise SSO (OIDC):** any OpenID Connect IdP (Okta, Entra ID, Auth0,
220
+ Keycloak…) plugs in via `oidcProvider({ clientId, clientSecret, authorizationUrl,
221
+ tokenUrl, userinfoUrl })`, or let `discoverOidcProvider(issuerUrl, keys)` read the
222
+ endpoints from the IdP's `.well-known/openid-configuration`.
223
+
165
224
  ### API keys
166
225
 
167
226
  For programmatic access (scripts, CI, integrations) without interactive login. A key has the format `mk_live_...`, is shown **only once** when created, and only its SHA-256 hash is stored.
@@ -254,12 +313,14 @@ Options (`AuthOptions` / `AuthPluginOptions` — the plugin accepts the same min
254
313
  | `requestPasswordReset(email)` / `resetPassword(token, newPassword)` | Password recovery. |
255
314
  | `enrollMfa(userId)` / `activateMfa(userId, code)` / `disableMfa(userId, code)` | MFA lifecycle. |
256
315
  | `isMfaEnabled(userId)` / `mfaStatus(userId)` / `verifyMfaCode(userId, code)` | MFA state and verification. |
316
+ | `socialLogin(email, { emailVerified? })` | Find-or-create a passwordless account for an OAuth/OIDC identity; returns `{ user, tokens }`. |
257
317
 
258
318
  ### Ready-made routes
259
319
 
260
320
  - `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.
261
321
  - `apiKeyRoutes()`: `POST /apikeys`, `GET /apikeys`, `DELETE /apikeys/:id` (all require login; scoped to the current tenant/user).
262
322
  - `mfaRoutes()`: `POST /auth/mfa/enroll`, `POST /auth/mfa/activate`, `GET /auth/mfa/status`, `POST /auth/mfa/disable`.
323
+ - `oauthRoutes({ callbackBaseUrl, successRedirect? })`: `GET /auth/oauth/:provider` and `GET /auth/oauth/:provider/callback` for each configured provider.
263
324
 
264
325
  ### `apiKeysPlugin(options)` and the `ApiKeys` class
265
326
 
@@ -283,7 +344,9 @@ Options (`ApiKeysPluginOptions`):
283
344
  | `LoginThrottle` (`maxAttempts` def. 5, `windowMs` def. 15 min, `clock`) | Anti brute-force. |
284
345
  | `generateTotpSecret`, `totp`, `verifyTotp`, `otpauthUri`, `base32Encode`, `base32Decode` | TOTP primitives (RFC 6238). Advanced. |
285
346
  | `publicUser(user)` | Converts `AuthUser` → `PublicUser` (removes the hash). |
286
- | `AUTH`, `API_KEYS` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance. |
347
+ | `AUTH`, `API_KEYS`, `OAUTH` | Injection tokens: `container.get(AUTH)` returns the `Auth` instance; `OAUTH` returns the `OAuth` instance. |
348
+ | `oauthPlugin`, `oauthRoutes` | Social-login plugin (`{ secret, providers }`) and its routes (`{ callbackBaseUrl, successRedirect? }`). |
349
+ | `googleProvider`, `githubProvider`, `oidcProvider`, `discoverOidcProvider` | OAuth 2.0 / OpenID Connect providers. Each takes `{ clientId, clientSecret, scopes? }`. |
287
350
  | In-memory stores | `MemoryUserSource`, `MemorySessionStore`, `MemoryRefreshTokenStore`, `MemoryAuthTokenStore`, `MemoryApiKeyStore`, `MemoryMfaStore` — dev/testing. |
288
351
 
289
352
  ### Exported errors
@@ -300,6 +363,9 @@ Options (`ApiKeysPluginOptions`):
300
363
  | `MfaRequiredError` / `MfaInvalidCodeError` / `MfaNotEnrolledError` | `AUTH_MFA_*` | 401/401/400 |
301
364
  | `AccountLockedError` | `AUTH_LOCKED` | 429 |
302
365
  | `ScopeRequiredError` | `AUTH_SCOPE_REQUIRED` | 403 |
366
+ | `OAuthProviderUnknownError` | `AUTH_OAUTH_UNKNOWN_PROVIDER` | 404 |
367
+ | `OAuthStateInvalidError` | `AUTH_OAUTH_STATE_INVALID` | 400 |
368
+ | `OAuthExchangeError` | `AUTH_OAUTH_EXCHANGE_FAILED` | 502 |
303
369
 
304
370
  ## Common issues and solutions (FAQ)
305
371
 
@@ -317,6 +383,8 @@ Options (`ApiKeysPluginOptions`):
317
383
 
318
384
  **"My API key doesn't work with authPlugin."** Correct: bearers prefixed with `mk_` are ignored by `authPlugin` and handled by `apiKeysPlugin` — register both.
319
385
 
386
+ **"OAuth: redirect_uri is not associated with this application."** Your `callbackBaseUrl` must be the app's **base URL** (`https://app.example.com`), *not* the full callback path — the module appends `/auth/oauth/:provider/callback` itself. Passing the full callback URL doubles the path so it no longer matches what you registered. Register exactly `${callbackBaseUrl}/auth/oauth/:provider/callback` with the provider.
387
+
320
388
  ## How it connects to other modules
321
389
 
322
390
  - **@basaltkit/core** — provides the app, the container, the request context (`ctx()`), and hooks; auth sets `ctx().user` and `ctx().apiKey`.
package/dist/index.d.ts CHANGED
@@ -415,6 +415,20 @@ declare class Auth {
415
415
  private readonly enumerationSafeRegister;
416
416
  constructor(options: AuthOptions);
417
417
  register(email: string, password: string): Promise<PublicUser>;
418
+ /**
419
+ * Logs in an externally-authenticated user (e.g. from an OAuth provider),
420
+ * matched by email — find-or-create. A new account is created **passwordless**
421
+ * (a random, unusable password hash), so password login won't work for it
422
+ * until a password is set. A provider-verified email flips `emailVerified`.
423
+ * Returns the tokens and whether the account was just created.
424
+ */
425
+ socialLogin(email: string, options?: {
426
+ emailVerified?: boolean;
427
+ }): Promise<{
428
+ user: PublicUser;
429
+ tokens: TokenPair;
430
+ created: boolean;
431
+ }>;
418
432
  /**
419
433
  * Enumeration-safe registration for the public endpoint: creates the account
420
434
  * for a new email, or — when the email is already taken — does equivalent work
@@ -750,4 +764,145 @@ declare function apiKeyRoutes(): BasaltRoute[];
750
764
  */
751
765
  declare function mfaRoutes(): BasaltRoute[];
752
766
 
753
- export { API_KEYS, AUTH, AccountLockedError, type ApiKeyContext, type ApiKeyFilter, type ApiKeyInfo, type ApiKeyRecord, type ApiKeyStore, ApiKeys, type ApiKeysOptions, type ApiKeysPluginOptions, Auth, type AuthOptions, type AuthPluginOptions, AuthRequiredError, AuthTokenInvalidError, type AuthTokenPurpose, type AuthTokenRecord, type AuthTokenStore, type AuthUser, EmailTakenError, InvalidCredentialsError, type IssueApiKeyInput, type JwtClaims, LoginThrottle, type LoginThrottleOptions, MemoryApiKeyStore, MemoryAuthTokenStore, MemoryMfaStore, MemoryRefreshTokenStore, MemorySessionStore, MemoryTokenVersionStore, MemoryUserSource, MfaInvalidCodeError, MfaNotEnrolledError, type MfaRecord, MfaRequiredError, type MfaStore, type OtpauthUriInput, type PasswordHasher, type PublicUser, RefreshInvalidError, type RefreshRecord, RefreshReusedError, type RefreshTokenStore, ScopeRequiredError, ScryptPasswordHasher, type SessionRecord, type SessionStore, TokenExpiredError, TokenInvalidError, type TokenPair, type TokenVersionStore, type TotpOptions, type UserPatch, type UserSource, UserUpdateUnsupportedError, type VerifyTotpOptions, WeakJwtSecretError, apiKeyRoutes, apiKeysPlugin, authPlugin, authRoutes, base32Decode, base32Encode, generateTotpSecret, matchTotpStep, mfaRoutes, otpauthUri, publicUser, scopesSatisfy, signJwt, totp, verifyJwt, verifyTotp };
767
+ declare class OAuthProviderUnknownError extends BasaltError {
768
+ readonly status = 404;
769
+ constructor(name: string);
770
+ }
771
+ declare class OAuthStateInvalidError extends BasaltError {
772
+ readonly status = 400;
773
+ constructor();
774
+ }
775
+ declare class OAuthExchangeError extends BasaltError {
776
+ readonly status = 502;
777
+ constructor(detail: string);
778
+ }
779
+ /** The normalized profile a provider returns after a successful login. */
780
+ interface OAuthProfile {
781
+ /** Stable id at the provider (the `sub` / user id). */
782
+ subject: string;
783
+ email: string;
784
+ emailVerified?: boolean;
785
+ name?: string;
786
+ }
787
+ interface OAuthProvider {
788
+ name: string;
789
+ authorizeUrl: string;
790
+ tokenUrl: string;
791
+ clientId: string;
792
+ clientSecret: string;
793
+ scopes: string[];
794
+ /** Fetches and normalizes the user profile from an access token. */
795
+ fetchProfile(accessToken: string, doFetch: typeof fetch): Promise<OAuthProfile>;
796
+ }
797
+ interface ProviderKeys {
798
+ clientId: string;
799
+ clientSecret: string;
800
+ scopes?: string[];
801
+ }
802
+ /** Google (OpenID Connect). Default scopes: `openid email profile`. */
803
+ declare function googleProvider(keys: ProviderKeys): OAuthProvider;
804
+ /** GitHub. Default scopes: `read:user user:email` (needed for a verified email). */
805
+ declare function githubProvider(keys: ProviderKeys): OAuthProvider;
806
+ interface OidcConfig extends ProviderKeys {
807
+ /** Display name for this provider. Default: 'oidc'. */
808
+ name?: string;
809
+ authorizeUrl: string;
810
+ tokenUrl: string;
811
+ userInfoUrl: string;
812
+ }
813
+ /**
814
+ * A generic **OIDC** provider — enterprise SSO for any OpenID Connect IdP
815
+ * (Okta, Azure AD / Entra ID, Auth0, Google Workspace, Keycloak…). Pass the
816
+ * three endpoints from the IdP's `.well-known/openid-configuration`, or use
817
+ * {@link discoverOidcProvider} to fetch them for you. Maps the standard OIDC
818
+ * `userinfo` claims (`sub`, `email`, `email_verified`, `name`).
819
+ */
820
+ declare function oidcProvider(config: OidcConfig): OAuthProvider;
821
+ /**
822
+ * Builds an {@link oidcProvider} by fetching the IdP's OIDC discovery document
823
+ * (`${issuer}/.well-known/openid-configuration`). Await it at startup.
824
+ */
825
+ declare function discoverOidcProvider(config: {
826
+ name?: string;
827
+ /** The IdP issuer URL, e.g. `https://acme.okta.com` or `https://login.microsoftonline.com/<tenant>/v2.0`. */
828
+ issuer: string;
829
+ clientId: string;
830
+ clientSecret: string;
831
+ scopes?: string[];
832
+ fetch?: typeof fetch;
833
+ }): Promise<OAuthProvider>;
834
+ interface OAuthOptions {
835
+ /** Secret used to sign the CSRF `state` (typically your APP_SECRET). */
836
+ secret: string;
837
+ /** Injected fetch (tests). Default: global fetch. */
838
+ fetch?: typeof fetch;
839
+ /** Clock in ms (tests). Default: Date.now. */
840
+ now?: () => number;
841
+ /** How long a signed `state` stays valid, in ms. Default: 10 minutes. */
842
+ stateTtlMs?: number;
843
+ }
844
+ /**
845
+ * OAuth 2.0 authorization-code login. Server-side (confidential-client) flow:
846
+ * build an authorize URL with a signed, expiring `state`, then exchange the code
847
+ * for a token, fetch the profile, and log the user in via {@link Auth.socialLogin}.
848
+ * The `state` is HMAC-signed and stateless — no server storage, works cookieless.
849
+ */
850
+ declare class OAuth {
851
+ private readonly auth;
852
+ private readonly options;
853
+ private readonly providers;
854
+ private readonly doFetch;
855
+ private readonly now;
856
+ private readonly stateTtl;
857
+ constructor(auth: Auth, providers: OAuthProvider[], options: OAuthOptions);
858
+ names(): string[];
859
+ private provider;
860
+ /** The provider's authorization URL to redirect the browser to. */
861
+ authorizeUrl(name: string, redirectUri: string): string;
862
+ /** Verifies `state`, exchanges the code, fetches the profile, and logs in. */
863
+ callback(name: string, input: {
864
+ code: string;
865
+ state: string | undefined;
866
+ redirectUri: string;
867
+ }): Promise<{
868
+ user: PublicUser;
869
+ tokens: TokenPair;
870
+ created: boolean;
871
+ }>;
872
+ private exchangeCode;
873
+ private signState;
874
+ private verifyState;
875
+ }
876
+
877
+ declare const OAUTH: _basaltkit_core.Token<OAuth>;
878
+ interface OAuthPluginOptions extends Omit<OAuthOptions, never> {
879
+ providers: OAuthProvider[];
880
+ }
881
+ /**
882
+ * Registers the {@link OAuth} service (token {@link OAUTH}). Pair it with
883
+ * {@link oauthRoutes} and register both AFTER `authPlugin` — the service resolves
884
+ * `AUTH` to log users in.
885
+ */
886
+ declare function oauthPlugin(options: OAuthPluginOptions): _basaltkit_core.BasaltPlugin<unknown>;
887
+ interface OAuthRoutesOptions {
888
+ /**
889
+ * Base URL of your deployed app. The provider redirect_uri is built as
890
+ * `${callbackBaseUrl}/auth/oauth/:provider/callback` and must be registered
891
+ * with each provider.
892
+ */
893
+ callbackBaseUrl: string;
894
+ /**
895
+ * When set, the callback redirects the browser here after a successful login
896
+ * with `#access_token=…&refresh_token=…` in the fragment (for SPA flows).
897
+ * When omitted, the callback responds with JSON `{ user, accessToken, refreshToken }`.
898
+ */
899
+ successRedirect?: string;
900
+ }
901
+ /**
902
+ * Ready-made OAuth routes:
903
+ * - `GET /auth/oauth/:provider` → 302 to the provider's authorize URL.
904
+ * - `GET /auth/oauth/:provider/callback` → exchanges the code and logs in.
905
+ */
906
+ declare function oauthRoutes(options: OAuthRoutesOptions): BasaltRoute[];
907
+
908
+ export { API_KEYS, AUTH, AccountLockedError, type ApiKeyContext, type ApiKeyFilter, type ApiKeyInfo, type ApiKeyRecord, type ApiKeyStore, ApiKeys, type ApiKeysOptions, type ApiKeysPluginOptions, Auth, type AuthOptions, type AuthPluginOptions, AuthRequiredError, AuthTokenInvalidError, type AuthTokenPurpose, type AuthTokenRecord, type AuthTokenStore, type AuthUser, EmailTakenError, InvalidCredentialsError, type IssueApiKeyInput, type JwtClaims, LoginThrottle, type LoginThrottleOptions, MemoryApiKeyStore, MemoryAuthTokenStore, MemoryMfaStore, MemoryRefreshTokenStore, MemorySessionStore, MemoryTokenVersionStore, MemoryUserSource, MfaInvalidCodeError, MfaNotEnrolledError, type MfaRecord, MfaRequiredError, type MfaStore, OAUTH, OAuth, OAuthExchangeError, type OAuthOptions, type OAuthPluginOptions, type OAuthProfile, type OAuthProvider, OAuthProviderUnknownError, type OAuthRoutesOptions, OAuthStateInvalidError, type OtpauthUriInput, type PasswordHasher, type PublicUser, RefreshInvalidError, type RefreshRecord, RefreshReusedError, type RefreshTokenStore, ScopeRequiredError, ScryptPasswordHasher, type SessionRecord, type SessionStore, TokenExpiredError, TokenInvalidError, type TokenPair, type TokenVersionStore, type TotpOptions, type UserPatch, type UserSource, UserUpdateUnsupportedError, type VerifyTotpOptions, WeakJwtSecretError, apiKeyRoutes, apiKeysPlugin, authPlugin, authRoutes, base32Decode, base32Encode, discoverOidcProvider, generateTotpSecret, githubProvider, googleProvider, matchTotpStep, mfaRoutes, oauthPlugin, oauthRoutes, oidcProvider, otpauthUri, publicUser, scopesSatisfy, signJwt, totp, verifyJwt, verifyTotp };
package/dist/index.js CHANGED
@@ -512,6 +512,31 @@ var Auth = class {
512
512
  await this.hooks?.emit("auth:registered", { user: publicUser(user) });
513
513
  return publicUser(user);
514
514
  }
515
+ /**
516
+ * Logs in an externally-authenticated user (e.g. from an OAuth provider),
517
+ * matched by email — find-or-create. A new account is created **passwordless**
518
+ * (a random, unusable password hash), so password login won't work for it
519
+ * until a password is set. A provider-verified email flips `emailVerified`.
520
+ * Returns the tokens and whether the account was just created.
521
+ */
522
+ async socialLogin(email, options = {}) {
523
+ let user = await this.users.findByEmail(email);
524
+ let created = false;
525
+ if (!user) {
526
+ user = await this.users.create({
527
+ email,
528
+ passwordHash: await this.hasher.hash(randomBytes5(32).toString("hex"))
529
+ });
530
+ created = true;
531
+ await this.hooks?.emit("auth:registered", { user: publicUser(user) });
532
+ }
533
+ if (options.emailVerified && !user.emailVerified && this.users.update) {
534
+ user = await this.users.update(user.id, { emailVerified: true }) ?? user;
535
+ }
536
+ const tokens = await this.issueTokens(user.id);
537
+ await this.hooks?.emit("auth:login", { user: publicUser(user) });
538
+ return { user: publicUser(user), tokens, created };
539
+ }
515
540
  /**
516
541
  * Enumeration-safe registration for the public endpoint: creates the account
517
542
  * for a new email, or — when the email is already taken — does equivalent work
@@ -863,8 +888,8 @@ function authPlugin(options) {
863
888
  }
864
889
  };
865
890
  metadata.add("http:enrichers", enricher);
866
- const guard = ({ route: route2, context }) => {
867
- if (route2.meta?.["auth"] === true && !context.user) throw new AuthRequiredError();
891
+ const guard = ({ route: route3, context }) => {
892
+ if (route3.meta?.["auth"] === true && !context.user) throw new AuthRequiredError();
868
893
  };
869
894
  metadata.add("http:guards", guard);
870
895
  }
@@ -977,8 +1002,8 @@ function apiKeysPlugin(options = {}) {
977
1002
  }
978
1003
  };
979
1004
  metadata.add("http:enrichers", enricher);
980
- const guard = ({ route: route2, context }) => {
981
- const required = route2.meta?.["scopes"];
1005
+ const guard = ({ route: route3, context }) => {
1006
+ const required = route3.meta?.["scopes"];
982
1007
  if (!Array.isArray(required) || required.length === 0) return;
983
1008
  const granted = context.apiKey?.scopes ?? [];
984
1009
  for (const scope of required) {
@@ -1191,6 +1216,263 @@ function mfaRoutes() {
1191
1216
  })
1192
1217
  ];
1193
1218
  }
1219
+
1220
+ // src/oauth.ts
1221
+ import { createHmac as createHmac3, randomBytes as randomBytes7, timingSafeEqual as timingSafeEqual4 } from "crypto";
1222
+ import { BasaltError as BasaltError6 } from "@basaltkit/core";
1223
+ var OAuthProviderUnknownError = class extends BasaltError6 {
1224
+ status = 404;
1225
+ constructor(name) {
1226
+ super("AUTH_OAUTH_UNKNOWN_PROVIDER", `Unknown OAuth provider "${name}".`);
1227
+ }
1228
+ };
1229
+ var OAuthStateInvalidError = class extends BasaltError6 {
1230
+ status = 400;
1231
+ constructor() {
1232
+ super("AUTH_OAUTH_STATE_INVALID", "The OAuth state is missing, invalid, tampered with, or expired.");
1233
+ }
1234
+ };
1235
+ var OAuthExchangeError = class extends BasaltError6 {
1236
+ status = 502;
1237
+ constructor(detail) {
1238
+ super("AUTH_OAUTH_EXCHANGE_FAILED", `OAuth token/profile exchange failed: ${detail}`);
1239
+ }
1240
+ };
1241
+ function googleProvider(keys) {
1242
+ return {
1243
+ name: "google",
1244
+ authorizeUrl: "https://accounts.google.com/o/oauth2/v2/auth",
1245
+ tokenUrl: "https://oauth2.googleapis.com/token",
1246
+ clientId: keys.clientId,
1247
+ clientSecret: keys.clientSecret,
1248
+ scopes: keys.scopes ?? ["openid", "email", "profile"],
1249
+ async fetchProfile(accessToken, doFetch) {
1250
+ const res = await doFetch("https://openidconnect.googleapis.com/v1/userinfo", {
1251
+ headers: { authorization: `Bearer ${accessToken}` }
1252
+ });
1253
+ if (!res.ok) throw new OAuthExchangeError(`google userinfo HTTP ${res.status}`);
1254
+ const p = await res.json();
1255
+ return {
1256
+ subject: String(p.sub),
1257
+ email: String(p.email),
1258
+ emailVerified: p.email_verified === true,
1259
+ ...p.name ? { name: p.name } : {}
1260
+ };
1261
+ }
1262
+ };
1263
+ }
1264
+ function githubProvider(keys) {
1265
+ return {
1266
+ name: "github",
1267
+ authorizeUrl: "https://github.com/login/oauth/authorize",
1268
+ tokenUrl: "https://github.com/login/oauth/access_token",
1269
+ clientId: keys.clientId,
1270
+ clientSecret: keys.clientSecret,
1271
+ scopes: keys.scopes ?? ["read:user", "user:email"],
1272
+ async fetchProfile(accessToken, doFetch) {
1273
+ const headers = { authorization: `Bearer ${accessToken}`, accept: "application/vnd.github+json" };
1274
+ const userRes = await doFetch("https://api.github.com/user", { headers });
1275
+ if (!userRes.ok) throw new OAuthExchangeError(`github user HTTP ${userRes.status}`);
1276
+ const user = await userRes.json();
1277
+ let email = user.email ?? void 0;
1278
+ let emailVerified = false;
1279
+ const emailsRes = await doFetch("https://api.github.com/user/emails", { headers });
1280
+ if (emailsRes.ok) {
1281
+ const emails = await emailsRes.json();
1282
+ const primary = emails.find((e) => e.primary && e.verified) ?? emails.find((e) => e.verified);
1283
+ if (primary) {
1284
+ email = primary.email;
1285
+ emailVerified = true;
1286
+ }
1287
+ }
1288
+ if (!email) throw new OAuthExchangeError("github returned no usable email");
1289
+ return { subject: String(user.id), email, emailVerified, ...user.name ? { name: user.name } : {} };
1290
+ }
1291
+ };
1292
+ }
1293
+ function oidcProvider(config) {
1294
+ return {
1295
+ name: config.name ?? "oidc",
1296
+ authorizeUrl: config.authorizeUrl,
1297
+ tokenUrl: config.tokenUrl,
1298
+ clientId: config.clientId,
1299
+ clientSecret: config.clientSecret,
1300
+ scopes: config.scopes ?? ["openid", "email", "profile"],
1301
+ async fetchProfile(accessToken, doFetch) {
1302
+ const res = await doFetch(config.userInfoUrl, { headers: { authorization: `Bearer ${accessToken}` } });
1303
+ if (!res.ok) throw new OAuthExchangeError(`oidc userinfo HTTP ${res.status}`);
1304
+ const p = await res.json();
1305
+ return {
1306
+ subject: String(p.sub),
1307
+ email: String(p.email),
1308
+ emailVerified: p.email_verified === true,
1309
+ ...p.name ? { name: p.name } : {}
1310
+ };
1311
+ }
1312
+ };
1313
+ }
1314
+ async function discoverOidcProvider(config) {
1315
+ const doFetch = config.fetch ?? globalThis.fetch;
1316
+ const url = `${config.issuer.replace(/\/+$/, "")}/.well-known/openid-configuration`;
1317
+ const res = await doFetch(url);
1318
+ if (!res.ok) throw new OAuthExchangeError(`OIDC discovery HTTP ${res.status} for ${url}`);
1319
+ const meta = await res.json();
1320
+ if (!meta.authorization_endpoint || !meta.token_endpoint || !meta.userinfo_endpoint) {
1321
+ throw new OAuthExchangeError("OIDC discovery document is missing required endpoints");
1322
+ }
1323
+ return oidcProvider({
1324
+ ...config.name ? { name: config.name } : {},
1325
+ authorizeUrl: meta.authorization_endpoint,
1326
+ tokenUrl: meta.token_endpoint,
1327
+ userInfoUrl: meta.userinfo_endpoint,
1328
+ clientId: config.clientId,
1329
+ clientSecret: config.clientSecret,
1330
+ ...config.scopes ? { scopes: config.scopes } : {}
1331
+ });
1332
+ }
1333
+ var OAuth = class {
1334
+ constructor(auth2, providers, options) {
1335
+ this.auth = auth2;
1336
+ this.options = options;
1337
+ this.providers = new Map(providers.map((p) => [p.name, p]));
1338
+ this.doFetch = options.fetch ?? globalThis.fetch;
1339
+ this.now = options.now ?? Date.now;
1340
+ this.stateTtl = options.stateTtlMs ?? 10 * 6e4;
1341
+ }
1342
+ auth;
1343
+ options;
1344
+ providers;
1345
+ doFetch;
1346
+ now;
1347
+ stateTtl;
1348
+ names() {
1349
+ return [...this.providers.keys()];
1350
+ }
1351
+ provider(name) {
1352
+ const p = this.providers.get(name);
1353
+ if (!p) throw new OAuthProviderUnknownError(name);
1354
+ return p;
1355
+ }
1356
+ /** The provider's authorization URL to redirect the browser to. */
1357
+ authorizeUrl(name, redirectUri) {
1358
+ const p = this.provider(name);
1359
+ const state = this.signState({ n: randomBytes7(16).toString("hex"), e: this.now() + this.stateTtl, p: name });
1360
+ const params = new URLSearchParams({
1361
+ client_id: p.clientId,
1362
+ redirect_uri: redirectUri,
1363
+ response_type: "code",
1364
+ scope: p.scopes.join(" "),
1365
+ state
1366
+ });
1367
+ return `${p.authorizeUrl}?${params.toString()}`;
1368
+ }
1369
+ /** Verifies `state`, exchanges the code, fetches the profile, and logs in. */
1370
+ async callback(name, input) {
1371
+ const payload = this.verifyState(input.state);
1372
+ if (payload.p !== name) throw new OAuthStateInvalidError();
1373
+ const p = this.provider(name);
1374
+ const accessToken = await this.exchangeCode(p, input.code, input.redirectUri);
1375
+ const profile = await p.fetchProfile(accessToken, this.doFetch);
1376
+ if (!profile.email) throw new OAuthExchangeError("provider returned no email");
1377
+ return this.auth.socialLogin(profile.email, { emailVerified: profile.emailVerified === true });
1378
+ }
1379
+ async exchangeCode(p, code, redirectUri) {
1380
+ const res = await this.doFetch(p.tokenUrl, {
1381
+ method: "POST",
1382
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
1383
+ body: new URLSearchParams({
1384
+ grant_type: "authorization_code",
1385
+ code,
1386
+ redirect_uri: redirectUri,
1387
+ client_id: p.clientId,
1388
+ client_secret: p.clientSecret
1389
+ }).toString()
1390
+ });
1391
+ const text = await res.text();
1392
+ const json = text ? JSON.parse(text) : {};
1393
+ if (!res.ok || !json.access_token) {
1394
+ throw new OAuthExchangeError(json.error_description ?? json.error ?? `token endpoint HTTP ${res.status}`);
1395
+ }
1396
+ return json.access_token;
1397
+ }
1398
+ signState(payload) {
1399
+ const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
1400
+ const sig = createHmac3("sha256", this.options.secret).update(body).digest("base64url");
1401
+ return `${body}.${sig}`;
1402
+ }
1403
+ verifyState(state) {
1404
+ if (!state) throw new OAuthStateInvalidError();
1405
+ const dot = state.indexOf(".");
1406
+ if (dot < 0) throw new OAuthStateInvalidError();
1407
+ const body = state.slice(0, dot);
1408
+ const sig = state.slice(dot + 1);
1409
+ const expected = createHmac3("sha256", this.options.secret).update(body).digest("base64url");
1410
+ const a = Buffer.from(sig);
1411
+ const b = Buffer.from(expected);
1412
+ if (a.length !== b.length || !timingSafeEqual4(a, b)) throw new OAuthStateInvalidError();
1413
+ let payload;
1414
+ try {
1415
+ payload = JSON.parse(Buffer.from(body, "base64url").toString("utf8"));
1416
+ } catch {
1417
+ throw new OAuthStateInvalidError();
1418
+ }
1419
+ if (typeof payload.e !== "number" || this.now() > payload.e) throw new OAuthStateInvalidError();
1420
+ return payload;
1421
+ }
1422
+ };
1423
+
1424
+ // src/oauth-plugin.ts
1425
+ import { createToken as createToken3, ctx as ctx2, definePlugin as definePlugin3 } from "@basaltkit/core";
1426
+ import { route as route2 } from "@basaltkit/fastify";
1427
+ import { z as z2 } from "zod";
1428
+ var OAUTH = createToken3("auth.oauth");
1429
+ function oauthPlugin(options) {
1430
+ const { providers, ...oauthOptions } = options;
1431
+ return definePlugin3({
1432
+ name: "basalt:auth:oauth",
1433
+ register({ container }) {
1434
+ container.singleton(OAUTH, (c) => new OAuth(c.get(AUTH), providers, oauthOptions));
1435
+ }
1436
+ });
1437
+ }
1438
+ function oauthRoutes(options) {
1439
+ const oauth = () => ctx2().container.get(OAUTH);
1440
+ const base = options.callbackBaseUrl.replace(/\/+$/, "");
1441
+ const redirectUri = (provider) => `${base}/auth/oauth/${provider}/callback`;
1442
+ return [
1443
+ route2({
1444
+ method: "GET",
1445
+ url: "/auth/oauth/:provider",
1446
+ params: z2.object({ provider: z2.string() }),
1447
+ async handler({ params, reply }) {
1448
+ const url = oauth().authorizeUrl(params.provider, redirectUri(params.provider));
1449
+ return reply.code(302).header("location", url).send();
1450
+ }
1451
+ }),
1452
+ route2({
1453
+ method: "GET",
1454
+ url: "/auth/oauth/:provider/callback",
1455
+ params: z2.object({ provider: z2.string() }),
1456
+ query: z2.object({ code: z2.string(), state: z2.string() }),
1457
+ async handler({ params, query, reply }) {
1458
+ const { user, tokens } = await oauth().callback(params.provider, {
1459
+ code: query.code,
1460
+ state: query.state,
1461
+ redirectUri: redirectUri(params.provider)
1462
+ });
1463
+ if (options.successRedirect) {
1464
+ const url = new URL(options.successRedirect);
1465
+ url.hash = new URLSearchParams({
1466
+ access_token: tokens.accessToken,
1467
+ refresh_token: tokens.refreshToken
1468
+ }).toString();
1469
+ return reply.code(302).header("location", url.toString()).send();
1470
+ }
1471
+ return { user, ...tokens };
1472
+ }
1473
+ })
1474
+ ];
1475
+ }
1194
1476
  export {
1195
1477
  API_KEYS,
1196
1478
  AUTH,
@@ -1212,6 +1494,11 @@ export {
1212
1494
  MfaInvalidCodeError,
1213
1495
  MfaNotEnrolledError,
1214
1496
  MfaRequiredError,
1497
+ OAUTH,
1498
+ OAuth,
1499
+ OAuthExchangeError,
1500
+ OAuthProviderUnknownError,
1501
+ OAuthStateInvalidError,
1215
1502
  RefreshInvalidError,
1216
1503
  RefreshReusedError,
1217
1504
  ScopeRequiredError,
@@ -1226,9 +1513,15 @@ export {
1226
1513
  authRoutes,
1227
1514
  base32Decode,
1228
1515
  base32Encode,
1516
+ discoverOidcProvider,
1229
1517
  generateTotpSecret,
1518
+ githubProvider,
1519
+ googleProvider,
1230
1520
  matchTotpStep,
1231
1521
  mfaRoutes,
1522
+ oauthPlugin,
1523
+ oauthRoutes,
1524
+ oidcProvider,
1232
1525
  otpauthUri,
1233
1526
  publicUser,
1234
1527
  scopesSatisfy,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/auth",
3
- "version": "1.3.1",
3
+ "version": "1.4.1",
4
4
  "description": "Authentication for Basalt: password hashing, JWT with refresh rotation and reuse detection, sessions, ready-made /auth routes and route guards.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -15,7 +15,7 @@
15
15
  ],
16
16
  "dependencies": {
17
17
  "@basaltkit/core": "^1.0.0",
18
- "@basaltkit/fastify": "^1.3.0"
18
+ "@basaltkit/fastify": "^1.4.0"
19
19
  },
20
20
  "peerDependencies": {
21
21
  "zod": "^3.24.0 || ^4.0.0"