@ovixa/auth-client 0.1.1 → 0.1.3

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/CHANGELOG.md CHANGED
@@ -5,6 +5,23 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/).
7
7
 
8
+ ## [0.1.3] - 2026-01-29
9
+
10
+ ### Added
11
+
12
+ - `auth.exchangeOAuthCode(code)` - Exchange OAuth authorization code for tokens, completing the OAuth 2.0 Authorization Code flow
13
+
14
+ ### Fixed
15
+
16
+ - OAuth flow now works correctly with the auth server's secure authorization code pattern
17
+
18
+ ## [0.1.2] - 2026-01-28
19
+
20
+ ### Added
21
+
22
+ - `auth.admin.deleteUser(realmId, userId)` - Delete users within a realm using client_secret authentication
23
+ - `auth.deleteMe()` - Allow authenticated users to delete their own account
24
+
8
25
  ## [0.1.1] - 2026-01-28
9
26
 
10
27
  ### Added
package/README.md CHANGED
@@ -141,6 +141,15 @@ await auth.forgotPassword({
141
141
  });
142
142
  ```
143
143
 
144
+ ### Email Branding
145
+
146
+ Verification and password reset emails automatically display your realm's `display_name` as the brand name. To customize the branding in emails:
147
+
148
+ 1. Set `display_name` when creating your realm
149
+ 2. Emails will show your brand (e.g., "Linkdrop") instead of "Ovixa"
150
+
151
+ If no `display_name` is set, emails default to "Ovixa".
152
+
144
153
  #### `resetPassword(options)`
145
154
 
146
155
  Set a new password using a reset token.
@@ -195,6 +204,45 @@ Invalidate the cached JWKS to force a refresh on next verification.
195
204
  auth.clearJwksCache();
196
205
  ```
197
206
 
207
+ ### Admin Operations
208
+
209
+ Admin operations require `clientSecret` to be configured. These operations allow server-side management of users within the realm boundary.
210
+
211
+ **Important:** Never expose `clientSecret` to client-side code.
212
+
213
+ #### `admin.deleteUser(options)`
214
+
215
+ Delete a user from your realm. This permanently deletes the user and all associated data (tokens, OAuth accounts).
216
+
217
+ ```typescript
218
+ const auth = new OvixaAuth({
219
+ authUrl: 'https://auth.ovixa.io',
220
+ realmId: 'your-realm-id',
221
+ clientSecret: process.env.OVIXA_CLIENT_SECRET, // Required
222
+ });
223
+
224
+ // Delete a user
225
+ await auth.admin.deleteUser({ userId: 'user-id-to-delete' });
226
+ ```
227
+
228
+ **Error Handling:**
229
+
230
+ ```typescript
231
+ try {
232
+ await auth.admin.deleteUser({ userId });
233
+ } catch (error) {
234
+ if (error instanceof OvixaAuthError) {
235
+ if (error.code === 'NOT_FOUND') {
236
+ console.error('User not found');
237
+ } else if (error.code === 'FORBIDDEN') {
238
+ console.error('User does not belong to this realm');
239
+ } else if (error.code === 'REALM_UNAUTHORIZED') {
240
+ console.error('Invalid client secret');
241
+ }
242
+ }
243
+ }
244
+ ```
245
+
198
246
  ### OAuth
199
247
 
200
248
  #### `getOAuthUrl(options)`
@@ -418,23 +466,25 @@ try {
418
466
 
419
467
  ### Error Codes
420
468
 
421
- | Code | Description |
422
- | ------------------------- | -------------------------------------------- |
423
- | `INVALID_CREDENTIALS` | Wrong email or password |
424
- | `EMAIL_NOT_VERIFIED` | User must verify email before login |
425
- | `PASSWORD_RESET_REQUIRED` | Account flagged for mandatory password reset |
426
- | `INVALID_TOKEN` | Token is invalid or malformed |
427
- | `TOKEN_EXPIRED` | Token has expired |
428
- | `INVALID_SIGNATURE` | Token signature verification failed |
429
- | `INVALID_ISSUER` | Token issuer doesn't match |
430
- | `INVALID_AUDIENCE` | Token audience doesn't match |
431
- | `RATE_LIMITED` | Too many requests |
432
- | `NETWORK_ERROR` | Failed to reach auth service |
433
- | `BAD_REQUEST` | Invalid request parameters |
434
- | `UNAUTHORIZED` | Authentication required |
435
- | `FORBIDDEN` | Access denied |
436
- | `NOT_FOUND` | Resource not found |
437
- | `SERVER_ERROR` | Auth service error |
469
+ | Code | Description |
470
+ | ------------------------- | ----------------------------------------------------- |
471
+ | `INVALID_CREDENTIALS` | Wrong email or password |
472
+ | `EMAIL_NOT_VERIFIED` | User must verify email before login |
473
+ | `PASSWORD_RESET_REQUIRED` | Account flagged for mandatory password reset |
474
+ | `INVALID_TOKEN` | Token is invalid or malformed |
475
+ | `TOKEN_EXPIRED` | Token has expired |
476
+ | `INVALID_SIGNATURE` | Token signature verification failed |
477
+ | `INVALID_ISSUER` | Token issuer doesn't match |
478
+ | `INVALID_AUDIENCE` | Token audience doesn't match |
479
+ | `RATE_LIMITED` | Too many requests |
480
+ | `NETWORK_ERROR` | Failed to reach auth service |
481
+ | `BAD_REQUEST` | Invalid request parameters |
482
+ | `UNAUTHORIZED` | Authentication required |
483
+ | `FORBIDDEN` | Access denied (e.g., user belongs to different realm) |
484
+ | `NOT_FOUND` | Resource not found |
485
+ | `SERVER_ERROR` | Auth service error |
486
+ | `REALM_UNAUTHORIZED` | Invalid or missing realm client secret |
487
+ | `CLIENT_SECRET_REQUIRED` | Admin operation attempted without clientSecret config |
438
488
 
439
489
  ### Handling `PASSWORD_RESET_REQUIRED`
440
490
 
@@ -415,7 +415,8 @@ var OvixaAuth = class {
415
415
  * Generate an OAuth authorization URL.
416
416
  *
417
417
  * Redirect the user to this URL to start the OAuth flow. After authentication,
418
- * the user will be redirected back to your `redirectUri` with tokens.
418
+ * the user will be redirected back to your `redirectUri` with an authorization code.
419
+ * Use `exchangeOAuthCode()` to exchange the code for tokens.
419
420
  *
420
421
  * @param options - OAuth URL options
421
422
  * @returns The full OAuth authorization URL
@@ -429,6 +430,10 @@ var OvixaAuth = class {
429
430
  *
430
431
  * // Redirect user to start OAuth flow
431
432
  * window.location.href = googleAuthUrl;
433
+ *
434
+ * // In your callback handler:
435
+ * // const code = new URLSearchParams(window.location.search).get('code');
436
+ * // const tokens = await auth.exchangeOAuthCode(code);
432
437
  * ```
433
438
  */
434
439
  getOAuthUrl(options) {
@@ -437,6 +442,51 @@ var OvixaAuth = class {
437
442
  url.searchParams.set("redirect_uri", options.redirectUri);
438
443
  return url.toString();
439
444
  }
445
+ /**
446
+ * Exchange an OAuth authorization code for tokens.
447
+ *
448
+ * After the OAuth flow completes, the user is redirected back to your app with
449
+ * an authorization code in the URL query params. Use this method to exchange
450
+ * that code for access and refresh tokens.
451
+ *
452
+ * Note: Authorization codes expire after 60 seconds.
453
+ *
454
+ * @param code - The authorization code from the OAuth callback URL
455
+ * @returns Token response with access and refresh tokens
456
+ * @throws {OvixaAuthError} If the exchange fails
457
+ *
458
+ * @example
459
+ * ```typescript
460
+ * // In your OAuth callback handler
461
+ * const code = new URLSearchParams(window.location.search).get('code');
462
+ *
463
+ * if (code) {
464
+ * try {
465
+ * const tokens = await auth.exchangeOAuthCode(code);
466
+ * console.log('OAuth successful!', tokens.access_token);
467
+ *
468
+ * // Check if this is a new user (first-time OAuth login)
469
+ * if (tokens.is_new_user) {
470
+ * // Show onboarding flow
471
+ * }
472
+ * } catch (error) {
473
+ * if (error instanceof OvixaAuthError) {
474
+ * if (error.code === 'INVALID_CODE') {
475
+ * console.error('Invalid or expired authorization code');
476
+ * }
477
+ * }
478
+ * }
479
+ * }
480
+ * ```
481
+ */
482
+ async exchangeOAuthCode(code) {
483
+ const url = `${this.config.authUrl}/oauth/token`;
484
+ const body = {
485
+ code,
486
+ realm_id: this.config.realmId
487
+ };
488
+ return this.makeRequest(url, body);
489
+ }
440
490
  /**
441
491
  * Transform a token response into an AuthResult with user and session data.
442
492
  *
@@ -475,6 +525,74 @@ var OvixaAuth = class {
475
525
  }
476
526
  return result;
477
527
  }
528
+ /**
529
+ * Delete the current user's own account.
530
+ *
531
+ * This permanently deletes the user's account and all associated data.
532
+ * Password re-authentication is required to prevent accidental deletion.
533
+ *
534
+ * @param options - Delete account options
535
+ * @returns Success response
536
+ * @throws {OvixaAuthError} If deletion fails
537
+ *
538
+ * @example
539
+ * ```typescript
540
+ * try {
541
+ * await auth.deleteMyAccount({
542
+ * accessToken: session.accessToken,
543
+ * password: 'current-password',
544
+ * });
545
+ * console.log('Account deleted successfully');
546
+ * // Clear local session storage
547
+ * } catch (error) {
548
+ * if (error instanceof OvixaAuthError) {
549
+ * if (error.code === 'INVALID_CREDENTIALS') {
550
+ * console.error('Incorrect password');
551
+ * } else if (error.code === 'UNAUTHORIZED') {
552
+ * console.error('Invalid or expired access token');
553
+ * }
554
+ * }
555
+ * }
556
+ * ```
557
+ */
558
+ async deleteMyAccount(options) {
559
+ const url = `${this.config.authUrl}/me`;
560
+ try {
561
+ const response = await fetch(url, {
562
+ method: "DELETE",
563
+ headers: {
564
+ "Content-Type": "application/json",
565
+ Authorization: `Bearer ${options.accessToken}`
566
+ },
567
+ body: JSON.stringify({
568
+ password: options.password
569
+ })
570
+ });
571
+ if (!response.ok) {
572
+ const errorBody = await response.json().catch(() => ({}));
573
+ const errorData = errorBody;
574
+ let errorCode;
575
+ let errorMessage;
576
+ if (typeof errorData.error === "object" && errorData.error) {
577
+ errorCode = errorData.error.code || this.mapHttpStatusToErrorCode(response.status);
578
+ errorMessage = errorData.error.message || "Request failed";
579
+ } else {
580
+ errorCode = this.mapHttpStatusToErrorCode(response.status);
581
+ errorMessage = typeof errorData.error === "string" ? errorData.error : "Request failed";
582
+ }
583
+ throw new OvixaAuthError(errorMessage, errorCode, response.status);
584
+ }
585
+ return await response.json();
586
+ } catch (error) {
587
+ if (error instanceof OvixaAuthError) {
588
+ throw error;
589
+ }
590
+ if (error instanceof Error) {
591
+ throw new OvixaAuthError(`Network error: ${error.message}`, "NETWORK_ERROR");
592
+ }
593
+ throw new OvixaAuthError("Request failed", "REQUEST_FAILED");
594
+ }
595
+ }
478
596
  /**
479
597
  * Make an authenticated POST request to the auth service.
480
598
  */
@@ -535,10 +653,129 @@ var OvixaAuth = class {
535
653
  return "UNKNOWN_ERROR";
536
654
  }
537
655
  }
656
+ /**
657
+ * Get the admin API interface for realm-scoped operations.
658
+ *
659
+ * Admin operations require clientSecret to be configured.
660
+ * These operations allow managing users within the realm boundary.
661
+ *
662
+ * @returns OvixaAuthAdmin interface for admin operations
663
+ * @throws {OvixaAuthError} If clientSecret is not configured
664
+ *
665
+ * @example
666
+ * ```typescript
667
+ * const auth = new OvixaAuth({
668
+ * authUrl: 'https://auth.ovixa.io',
669
+ * realmId: 'your-realm',
670
+ * clientSecret: process.env.OVIXA_CLIENT_SECRET,
671
+ * });
672
+ *
673
+ * // Delete a user from the realm
674
+ * await auth.admin.deleteUser({ userId: 'user-id-to-delete' });
675
+ * ```
676
+ */
677
+ get admin() {
678
+ if (!this.config.clientSecret) {
679
+ throw new OvixaAuthError(
680
+ "clientSecret is required for admin operations",
681
+ "CLIENT_SECRET_REQUIRED"
682
+ );
683
+ }
684
+ return new OvixaAuthAdmin(this.config);
685
+ }
686
+ };
687
+ var OvixaAuthAdmin = class {
688
+ config;
689
+ constructor(config) {
690
+ this.config = config;
691
+ }
692
+ /**
693
+ * Delete a user from the realm.
694
+ *
695
+ * This permanently deletes the user and all associated data (tokens, OAuth accounts).
696
+ * The user must belong to this realm.
697
+ *
698
+ * @param options - Delete user options
699
+ * @returns Success response
700
+ * @throws {OvixaAuthError} If deletion fails
701
+ *
702
+ * @example
703
+ * ```typescript
704
+ * try {
705
+ * await auth.admin.deleteUser({ userId: 'user-id-to-delete' });
706
+ * console.log('User deleted successfully');
707
+ * } catch (error) {
708
+ * if (error instanceof OvixaAuthError) {
709
+ * if (error.code === 'NOT_FOUND') {
710
+ * console.error('User not found');
711
+ * } else if (error.code === 'FORBIDDEN') {
712
+ * console.error('User does not belong to this realm');
713
+ * }
714
+ * }
715
+ * }
716
+ * ```
717
+ */
718
+ async deleteUser(options) {
719
+ const url = `${this.config.authUrl}/realms/${this.config.realmId}/users/${options.userId}`;
720
+ try {
721
+ const response = await fetch(url, {
722
+ method: "DELETE",
723
+ headers: {
724
+ Authorization: `RealmSecret ${this.config.clientSecret}`
725
+ }
726
+ });
727
+ if (!response.ok) {
728
+ const errorBody = await response.json().catch(() => ({}));
729
+ const errorData = errorBody;
730
+ let errorCode;
731
+ let errorMessage;
732
+ if (typeof errorData.error === "object" && errorData.error) {
733
+ errorCode = errorData.error.code || this.mapHttpStatusToErrorCode(response.status);
734
+ errorMessage = errorData.error.message || "Request failed";
735
+ } else {
736
+ errorCode = this.mapHttpStatusToErrorCode(response.status);
737
+ errorMessage = typeof errorData.error === "string" ? errorData.error : "Request failed";
738
+ }
739
+ throw new OvixaAuthError(errorMessage, errorCode, response.status);
740
+ }
741
+ return await response.json();
742
+ } catch (error) {
743
+ if (error instanceof OvixaAuthError) {
744
+ throw error;
745
+ }
746
+ if (error instanceof Error) {
747
+ throw new OvixaAuthError(`Network error: ${error.message}`, "NETWORK_ERROR");
748
+ }
749
+ throw new OvixaAuthError("Request failed", "REQUEST_FAILED");
750
+ }
751
+ }
752
+ /**
753
+ * Map HTTP status codes to error codes.
754
+ */
755
+ mapHttpStatusToErrorCode(status) {
756
+ switch (status) {
757
+ case 400:
758
+ return "BAD_REQUEST";
759
+ case 401:
760
+ return "UNAUTHORIZED";
761
+ case 403:
762
+ return "FORBIDDEN";
763
+ case 404:
764
+ return "NOT_FOUND";
765
+ case 429:
766
+ return "RATE_LIMITED";
767
+ case 500:
768
+ case 502:
769
+ case 503:
770
+ return "SERVER_ERROR";
771
+ default:
772
+ return "UNKNOWN_ERROR";
773
+ }
774
+ }
538
775
  };
539
776
 
540
777
  export {
541
778
  OvixaAuthError,
542
779
  OvixaAuth
543
780
  };
544
- //# sourceMappingURL=chunk-UHRF6AFJ.js.map
781
+ //# sourceMappingURL=chunk-CUACHOKT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @ovixa/auth-client\n *\n * Client SDK for Ovixa Auth service.\n * Provides authentication, token verification, and session management.\n */\n\nimport {\n createRemoteJWKSet,\n jwtVerify,\n type JWTPayload,\n type JWTVerifyResult,\n type JWTHeaderParameters,\n} from 'jose';\n\n/**\n * Configuration options for the OvixaAuth client.\n */\nexport interface AuthClientConfig {\n /** The base URL of the Ovixa Auth service */\n authUrl: string;\n /** The realm ID to authenticate against */\n realmId: string;\n /** Your application's client secret (for server-side use only) */\n clientSecret?: string;\n /** Cache duration for JWKS in milliseconds (defaults to 1 hour) */\n jwksCacheTtl?: number;\n}\n\n/**\n * JWT claims for an Ovixa access token.\n */\nexport interface AccessTokenPayload extends JWTPayload {\n /** Subject (user ID) */\n sub: string;\n /** User's email address */\n email: string;\n /** Whether the user's email has been verified */\n email_verified: boolean;\n /** Issued at timestamp */\n iat: number;\n /** Expiration timestamp */\n exp: number;\n /** Issuer */\n iss: string;\n /** Audience (realm ID) */\n aud: string;\n}\n\n/**\n * Result of a successful token verification.\n */\nexport interface VerifyResult {\n /** The decoded token payload */\n payload: AccessTokenPayload;\n /** The protected header */\n protectedHeader: JWTHeaderParameters;\n}\n\n/**\n * Token response from the auth service.\n */\nexport interface TokenResponse {\n /** The access token (JWT) */\n access_token: string;\n /** The refresh token (JWT) */\n refresh_token: string;\n /** Token type (always \"Bearer\") */\n token_type: 'Bearer';\n /** Access token expiration time in seconds */\n expires_in: number;\n /** Whether this is a new user (only present in OAuth callback) */\n is_new_user?: boolean;\n}\n\n/**\n * User information extracted from token payload.\n */\nexport interface User {\n /** User ID (UUID) */\n id: string;\n /** User's email address */\n email: string;\n /** Whether the email has been verified */\n emailVerified: boolean;\n}\n\n/**\n * Session information containing tokens and expiry.\n */\nexport interface Session {\n /** The access token (JWT) */\n accessToken: string;\n /** The refresh token for obtaining new access tokens */\n refreshToken: string;\n /** When the access token expires */\n expiresAt: Date;\n}\n\n/**\n * Combined authentication result with user and session data.\n */\nexport interface AuthResult {\n /** The authenticated user */\n user: User;\n /** The session tokens */\n session: Session;\n /** Whether this is a new user (only set for OAuth flows) */\n isNewUser?: boolean;\n}\n\n/**\n * Options for signup.\n */\nexport interface SignupOptions {\n /** User's email address */\n email: string;\n /** Password meeting requirements */\n password: string;\n /** Optional redirect URI after email verification */\n redirectUri?: string;\n}\n\n/**\n * Response from signup endpoint.\n */\nexport interface SignupResponse {\n /** Whether the operation succeeded */\n success: boolean;\n /** Status message */\n message: string;\n}\n\n/**\n * Options for login.\n */\nexport interface LoginOptions {\n /** User's email address */\n email: string;\n /** User's password */\n password: string;\n}\n\n/**\n * Options for email verification.\n */\nexport interface VerifyEmailOptions {\n /** Verification token from email */\n token: string;\n}\n\n/**\n * Options for resending verification email.\n */\nexport interface ResendVerificationOptions {\n /** User's email address */\n email: string;\n /** Optional redirect URI after verification */\n redirectUri?: string;\n}\n\n/**\n * Generic success response.\n */\nexport interface SuccessResponse {\n /** Whether the operation succeeded */\n success: boolean;\n /** Optional status message */\n message?: string;\n}\n\n/**\n * Options for forgot password request.\n */\nexport interface ForgotPasswordOptions {\n /** User's email address */\n email: string;\n /** Optional redirect URI for password reset page */\n redirectUri?: string;\n}\n\n/**\n * Options for password reset.\n */\nexport interface ResetPasswordOptions {\n /** Reset token from email */\n token: string;\n /** New password */\n password: string;\n}\n\n/**\n * Supported OAuth providers.\n */\nexport type OAuthProvider = 'google' | 'github';\n\n/**\n * Options for generating OAuth URL.\n */\nexport interface GetOAuthUrlOptions {\n /** OAuth provider */\n provider: OAuthProvider;\n /** Redirect URI after OAuth completes */\n redirectUri: string;\n}\n\n/**\n * Options for deleting a user (admin operation).\n */\nexport interface DeleteUserOptions {\n /** The ID of the user to delete */\n userId: string;\n}\n\n/**\n * Options for deleting the current user's own account.\n */\nexport interface DeleteMyAccountOptions {\n /** The user's current access token */\n accessToken: string;\n /** The user's current password (for re-authentication) */\n password: string;\n}\n\n/**\n * Error thrown by OvixaAuth operations.\n */\nexport class OvixaAuthError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly statusCode?: number\n ) {\n super(message);\n this.name = 'OvixaAuthError';\n }\n}\n\ninterface InternalConfig {\n authUrl: string;\n realmId: string;\n clientSecret?: string;\n jwksCacheTtl: number;\n}\n\n/** Default JWKS cache TTL: 1 hour */\nconst DEFAULT_JWKS_CACHE_TTL = 60 * 60 * 1000;\n\n/**\n * Custom fetch function that adds cache headers for JWKS requests.\n * Used to implement client-side caching behavior.\n */\ntype JWKSFetcher = ReturnType<typeof createRemoteJWKSet>;\n\ninterface JWKSCache {\n fetcher: JWKSFetcher;\n createdAt: number;\n}\n\n/**\n * OvixaAuth client for authenticating with the Ovixa Auth service.\n *\n * @example\n * ```typescript\n * const auth = new OvixaAuth({\n * authUrl: 'https://auth.ovixa.io',\n * realmId: 'your-realm-id',\n * clientSecret: 'your-client-secret', // Optional, for server-side use\n * });\n *\n * // Verify a token\n * const result = await auth.verifyToken(accessToken);\n * console.log(result.payload.email);\n *\n * // Refresh tokens\n * const tokens = await auth.refreshToken(refreshToken);\n * ```\n */\nexport class OvixaAuth {\n private config: InternalConfig;\n private jwksCache: JWKSCache | null = null;\n\n constructor(config: AuthClientConfig) {\n // Normalize authUrl by removing trailing slash\n const authUrl = config.authUrl.replace(/\\/$/, '');\n\n this.config = {\n authUrl,\n realmId: config.realmId,\n clientSecret: config.clientSecret,\n jwksCacheTtl: config.jwksCacheTtl ?? DEFAULT_JWKS_CACHE_TTL,\n };\n }\n\n /** Get the configured auth URL */\n get authUrl(): string {\n return this.config.authUrl;\n }\n\n /** Get the configured realm ID */\n get realmId(): string {\n return this.config.realmId;\n }\n\n /**\n * Get the JWKS URL for the auth service.\n */\n get jwksUrl(): string {\n return `${this.config.authUrl}/.well-known/jwks.json`;\n }\n\n /**\n * Get the JWKS fetcher, creating a new one if necessary.\n * The fetcher is cached based on the configured TTL.\n */\n private getJwksFetcher(): JWKSFetcher {\n const now = Date.now();\n\n // Return cached fetcher if still valid\n if (this.jwksCache && now - this.jwksCache.createdAt < this.config.jwksCacheTtl) {\n return this.jwksCache.fetcher;\n }\n\n // Create new JWKS fetcher\n const jwksUrl = new URL(this.jwksUrl);\n const fetcher = createRemoteJWKSet(jwksUrl, {\n // jose library has its own internal caching, but we add our own TTL layer\n // to control when to refresh the JWKS set\n cacheMaxAge: this.config.jwksCacheTtl,\n });\n\n this.jwksCache = {\n fetcher,\n createdAt: now,\n };\n\n return fetcher;\n }\n\n /**\n * Verify an access token and return the decoded payload.\n *\n * This method fetches the public key from the JWKS endpoint (with caching)\n * and verifies the token's signature and claims.\n *\n * @param token - The access token (JWT) to verify\n * @returns The verified token payload and header\n * @throws {OvixaAuthError} If verification fails\n *\n * @example\n * ```typescript\n * try {\n * const result = await auth.verifyToken(accessToken);\n * console.log('User ID:', result.payload.sub);\n * console.log('Email:', result.payload.email);\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * console.error('Token verification failed:', error.code);\n * }\n * }\n * ```\n */\n async verifyToken(token: string): Promise<VerifyResult> {\n try {\n const jwks = this.getJwksFetcher();\n\n const result: JWTVerifyResult<AccessTokenPayload> = await jwtVerify(token, jwks, {\n algorithms: ['RS256'],\n issuer: this.config.authUrl,\n // Audience is the realm for this application\n audience: this.config.realmId,\n });\n\n // Validate required claims\n const payload = result.payload;\n if (!payload.sub || !payload.email || payload.email_verified === undefined) {\n throw new OvixaAuthError('Token is missing required claims', 'INVALID_CLAIMS');\n }\n\n return {\n payload: payload as AccessTokenPayload,\n protectedHeader: result.protectedHeader,\n };\n } catch (error) {\n if (error instanceof OvixaAuthError) {\n throw error;\n }\n\n // Handle jose library errors\n if (error instanceof Error) {\n const message = error.message;\n\n if (message.includes('expired')) {\n throw new OvixaAuthError('Token has expired', 'TOKEN_EXPIRED');\n }\n if (message.includes('signature')) {\n throw new OvixaAuthError('Invalid token signature', 'INVALID_SIGNATURE');\n }\n if (message.includes('issuer')) {\n throw new OvixaAuthError('Invalid token issuer', 'INVALID_ISSUER');\n }\n if (message.includes('audience')) {\n throw new OvixaAuthError('Invalid token audience', 'INVALID_AUDIENCE');\n }\n if (message.includes('malformed')) {\n throw new OvixaAuthError('Malformed token', 'MALFORMED_TOKEN');\n }\n\n throw new OvixaAuthError(`Token verification failed: ${message}`, 'VERIFICATION_FAILED');\n }\n\n throw new OvixaAuthError('Token verification failed', 'VERIFICATION_FAILED');\n }\n }\n\n /**\n * Refresh an access token using a refresh token.\n *\n * This method exchanges a valid refresh token for a new access token\n * and a new refresh token (token rotation).\n *\n * @param refreshToken - The refresh token to exchange\n * @returns New token response with access and refresh tokens\n * @throws {OvixaAuthError} If the refresh fails\n *\n * @example\n * ```typescript\n * try {\n * const tokens = await auth.refreshToken(currentRefreshToken);\n * // Store the new tokens\n * saveTokens(tokens.access_token, tokens.refresh_token);\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * // Refresh token is invalid or expired - user must re-authenticate\n * redirectToLogin();\n * }\n * }\n * ```\n */\n async refreshToken(refreshToken: string): Promise<TokenResponse> {\n const url = `${this.config.authUrl}/token/refresh`;\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n refresh_token: refreshToken,\n }),\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({}));\n const errorMessage = (errorBody as { error?: string }).error || 'Token refresh failed';\n const errorCode = this.mapHttpStatusToErrorCode(response.status);\n\n throw new OvixaAuthError(errorMessage, errorCode, response.status);\n }\n\n const data = (await response.json()) as TokenResponse;\n return data;\n } catch (error) {\n if (error instanceof OvixaAuthError) {\n throw error;\n }\n\n if (error instanceof Error) {\n throw new OvixaAuthError(`Network error: ${error.message}`, 'NETWORK_ERROR');\n }\n\n throw new OvixaAuthError('Token refresh failed', 'REFRESH_FAILED');\n }\n }\n\n /**\n * Invalidate the cached JWKS fetcher.\n * Call this if you need to force a refresh of the public keys.\n */\n clearJwksCache(): void {\n this.jwksCache = null;\n }\n\n /**\n * Create a new user account.\n *\n * After signup, a verification email is sent. The user must verify their\n * email before they can log in.\n *\n * @param options - Signup options\n * @returns Signup response indicating success\n * @throws {OvixaAuthError} If signup fails\n *\n * @example\n * ```typescript\n * try {\n * await auth.signup({\n * email: 'user@example.com',\n * password: 'SecurePassword123!',\n * redirectUri: 'https://myapp.com/verify-callback',\n * });\n * console.log('Verification email sent!');\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * if (error.code === 'EMAIL_ALREADY_EXISTS') {\n * console.error('Email is already registered');\n * }\n * }\n * }\n * ```\n */\n async signup(options: SignupOptions): Promise<SignupResponse> {\n const url = `${this.config.authUrl}/signup`;\n\n const body: Record<string, string> = {\n email: options.email,\n password: options.password,\n realm_id: this.config.realmId,\n };\n\n if (options.redirectUri) {\n body.redirect_uri = options.redirectUri;\n }\n\n return this.makeRequest<SignupResponse>(url, body);\n }\n\n /**\n * Authenticate a user with email and password.\n *\n * @param options - Login options\n * @returns Token response with access and refresh tokens\n * @throws {OvixaAuthError} If login fails\n *\n * @example\n * ```typescript\n * try {\n * const tokens = await auth.login({\n * email: 'user@example.com',\n * password: 'SecurePassword123!',\n * });\n * console.log('Logged in!', tokens.access_token);\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * if (error.code === 'EMAIL_NOT_VERIFIED') {\n * console.error('Please verify your email first');\n * } else if (error.code === 'INVALID_CREDENTIALS') {\n * console.error('Invalid email or password');\n * }\n * }\n * }\n * ```\n */\n async login(options: LoginOptions): Promise<TokenResponse> {\n const url = `${this.config.authUrl}/login`;\n\n const body = {\n email: options.email,\n password: options.password,\n realm_id: this.config.realmId,\n };\n\n return this.makeRequest<TokenResponse>(url, body);\n }\n\n /**\n * Verify an email address using a verification token.\n *\n * This is the API flow that returns tokens. For browser redirect flow,\n * use `GET /verify` directly.\n *\n * @param options - Verification options\n * @returns Token response with access and refresh tokens\n * @throws {OvixaAuthError} If verification fails\n *\n * @example\n * ```typescript\n * // Get token from URL query params after clicking email link\n * const token = new URLSearchParams(window.location.search).get('token');\n *\n * try {\n * const tokens = await auth.verifyEmail({ token });\n * console.log('Email verified! Logged in.');\n * } catch (error) {\n * if (error instanceof OvixaAuthError && error.code === 'INVALID_TOKEN') {\n * console.error('Invalid or expired verification link');\n * }\n * }\n * ```\n */\n async verifyEmail(options: VerifyEmailOptions): Promise<TokenResponse> {\n const url = `${this.config.authUrl}/verify`;\n\n const body = {\n token: options.token,\n realm_id: this.config.realmId,\n type: 'email_verification',\n };\n\n return this.makeRequest<TokenResponse>(url, body);\n }\n\n /**\n * Resend a verification email for an unverified account.\n *\n * @param options - Resend options\n * @returns Success response\n * @throws {OvixaAuthError} If request fails\n *\n * @example\n * ```typescript\n * await auth.resendVerification({\n * email: 'user@example.com',\n * redirectUri: 'https://myapp.com/verify-callback',\n * });\n * console.log('Verification email sent!');\n * ```\n */\n async resendVerification(options: ResendVerificationOptions): Promise<SuccessResponse> {\n const url = `${this.config.authUrl}/verify/resend`;\n\n const body: Record<string, string> = {\n email: options.email,\n realm_id: this.config.realmId,\n };\n\n if (options.redirectUri) {\n body.redirect_uri = options.redirectUri;\n }\n\n return this.makeRequest<SuccessResponse>(url, body);\n }\n\n /**\n * Request a password reset email.\n *\n * Note: This endpoint always returns success to prevent email enumeration.\n *\n * @param options - Forgot password options\n * @returns Success response\n * @throws {OvixaAuthError} If request fails\n *\n * @example\n * ```typescript\n * await auth.forgotPassword({\n * email: 'user@example.com',\n * redirectUri: 'https://myapp.com/reset-password',\n * });\n * console.log('If the email exists, a reset link has been sent.');\n * ```\n */\n async forgotPassword(options: ForgotPasswordOptions): Promise<SuccessResponse> {\n const url = `${this.config.authUrl}/forgot-password`;\n\n const body: Record<string, string> = {\n email: options.email,\n realm_id: this.config.realmId,\n };\n\n if (options.redirectUri) {\n body.redirect_uri = options.redirectUri;\n }\n\n return this.makeRequest<SuccessResponse>(url, body);\n }\n\n /**\n * Reset password using a reset token.\n *\n * @param options - Reset password options\n * @returns Success response\n * @throws {OvixaAuthError} If reset fails\n *\n * @example\n * ```typescript\n * // Get token from URL query params\n * const token = new URLSearchParams(window.location.search).get('token');\n *\n * try {\n * await auth.resetPassword({\n * token,\n * password: 'NewSecurePassword123!',\n * });\n * console.log('Password reset successfully!');\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * if (error.code === 'INVALID_TOKEN') {\n * console.error('Invalid or expired reset link');\n * } else if (error.code === 'WEAK_PASSWORD') {\n * console.error('Password does not meet requirements');\n * }\n * }\n * }\n * ```\n */\n async resetPassword(options: ResetPasswordOptions): Promise<SuccessResponse> {\n const url = `${this.config.authUrl}/reset-password`;\n\n const body = {\n token: options.token,\n password: options.password,\n realm_id: this.config.realmId,\n };\n\n return this.makeRequest<SuccessResponse>(url, body);\n }\n\n /**\n * Revoke a refresh token (logout).\n *\n * @param refreshToken - The refresh token to revoke\n * @returns Success response\n * @throws {OvixaAuthError} If logout fails\n *\n * @example\n * ```typescript\n * await auth.logout(currentRefreshToken);\n * // Clear local token storage\n * localStorage.removeItem('refresh_token');\n * localStorage.removeItem('access_token');\n * ```\n */\n async logout(refreshToken: string): Promise<SuccessResponse> {\n const url = `${this.config.authUrl}/logout`;\n\n const body = {\n refresh_token: refreshToken,\n };\n\n return this.makeRequest<SuccessResponse>(url, body);\n }\n\n /**\n * Generate an OAuth authorization URL.\n *\n * Redirect the user to this URL to start the OAuth flow. After authentication,\n * the user will be redirected back to your `redirectUri` with an authorization code.\n * Use `exchangeOAuthCode()` to exchange the code for tokens.\n *\n * @param options - OAuth URL options\n * @returns The full OAuth authorization URL\n *\n * @example\n * ```typescript\n * const googleAuthUrl = auth.getOAuthUrl({\n * provider: 'google',\n * redirectUri: 'https://myapp.com/auth/callback',\n * });\n *\n * // Redirect user to start OAuth flow\n * window.location.href = googleAuthUrl;\n *\n * // In your callback handler:\n * // const code = new URLSearchParams(window.location.search).get('code');\n * // const tokens = await auth.exchangeOAuthCode(code);\n * ```\n */\n getOAuthUrl(options: GetOAuthUrlOptions): string {\n const url = new URL(`${this.config.authUrl}/oauth/${options.provider}`);\n url.searchParams.set('realm_id', this.config.realmId);\n url.searchParams.set('redirect_uri', options.redirectUri);\n return url.toString();\n }\n\n /**\n * Exchange an OAuth authorization code for tokens.\n *\n * After the OAuth flow completes, the user is redirected back to your app with\n * an authorization code in the URL query params. Use this method to exchange\n * that code for access and refresh tokens.\n *\n * Note: Authorization codes expire after 60 seconds.\n *\n * @param code - The authorization code from the OAuth callback URL\n * @returns Token response with access and refresh tokens\n * @throws {OvixaAuthError} If the exchange fails\n *\n * @example\n * ```typescript\n * // In your OAuth callback handler\n * const code = new URLSearchParams(window.location.search).get('code');\n *\n * if (code) {\n * try {\n * const tokens = await auth.exchangeOAuthCode(code);\n * console.log('OAuth successful!', tokens.access_token);\n *\n * // Check if this is a new user (first-time OAuth login)\n * if (tokens.is_new_user) {\n * // Show onboarding flow\n * }\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * if (error.code === 'INVALID_CODE') {\n * console.error('Invalid or expired authorization code');\n * }\n * }\n * }\n * }\n * ```\n */\n async exchangeOAuthCode(code: string): Promise<TokenResponse> {\n const url = `${this.config.authUrl}/oauth/token`;\n\n const body = {\n code,\n realm_id: this.config.realmId,\n };\n\n return this.makeRequest<TokenResponse>(url, body);\n }\n\n /**\n * Transform a token response into an AuthResult with user and session data.\n *\n * This method decodes the access token to extract user information and\n * creates a structured result object.\n *\n * @param tokenResponse - The token response from login, verify, or refresh\n * @returns AuthResult with user and session data\n * @throws {OvixaAuthError} If the access token cannot be decoded\n *\n * @example\n * ```typescript\n * const tokens = await auth.login({ email, password });\n * const result = await auth.toAuthResult(tokens);\n *\n * console.log('User ID:', result.user.id);\n * console.log('Email:', result.user.email);\n * console.log('Expires at:', result.session.expiresAt);\n * ```\n */\n async toAuthResult(tokenResponse: TokenResponse): Promise<AuthResult> {\n // Verify and decode the access token\n const verified = await this.verifyToken(tokenResponse.access_token);\n\n const user: User = {\n id: verified.payload.sub,\n email: verified.payload.email,\n emailVerified: verified.payload.email_verified,\n };\n\n const session: Session = {\n accessToken: tokenResponse.access_token,\n refreshToken: tokenResponse.refresh_token,\n expiresAt: new Date(Date.now() + tokenResponse.expires_in * 1000),\n };\n\n const result: AuthResult = { user, session };\n\n if (tokenResponse.is_new_user !== undefined) {\n result.isNewUser = tokenResponse.is_new_user;\n }\n\n return result;\n }\n\n /**\n * Delete the current user's own account.\n *\n * This permanently deletes the user's account and all associated data.\n * Password re-authentication is required to prevent accidental deletion.\n *\n * @param options - Delete account options\n * @returns Success response\n * @throws {OvixaAuthError} If deletion fails\n *\n * @example\n * ```typescript\n * try {\n * await auth.deleteMyAccount({\n * accessToken: session.accessToken,\n * password: 'current-password',\n * });\n * console.log('Account deleted successfully');\n * // Clear local session storage\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * if (error.code === 'INVALID_CREDENTIALS') {\n * console.error('Incorrect password');\n * } else if (error.code === 'UNAUTHORIZED') {\n * console.error('Invalid or expired access token');\n * }\n * }\n * }\n * ```\n */\n async deleteMyAccount(options: DeleteMyAccountOptions): Promise<SuccessResponse> {\n const url = `${this.config.authUrl}/me`;\n\n try {\n const response = await fetch(url, {\n method: 'DELETE',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${options.accessToken}`,\n },\n body: JSON.stringify({\n password: options.password,\n }),\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({}));\n const errorData = errorBody as { error?: { code?: string; message?: string } | string };\n\n let errorCode: string;\n let errorMessage: string;\n\n if (typeof errorData.error === 'object' && errorData.error) {\n errorCode = errorData.error.code || this.mapHttpStatusToErrorCode(response.status);\n errorMessage = errorData.error.message || 'Request failed';\n } else {\n errorCode = this.mapHttpStatusToErrorCode(response.status);\n errorMessage = typeof errorData.error === 'string' ? errorData.error : 'Request failed';\n }\n\n throw new OvixaAuthError(errorMessage, errorCode, response.status);\n }\n\n return (await response.json()) as SuccessResponse;\n } catch (error) {\n if (error instanceof OvixaAuthError) {\n throw error;\n }\n\n if (error instanceof Error) {\n throw new OvixaAuthError(`Network error: ${error.message}`, 'NETWORK_ERROR');\n }\n\n throw new OvixaAuthError('Request failed', 'REQUEST_FAILED');\n }\n }\n\n /**\n * Make an authenticated POST request to the auth service.\n */\n private async makeRequest<T>(url: string, body: Record<string, unknown>): Promise<T> {\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({}));\n const errorData = errorBody as { error?: { code?: string; message?: string } | string };\n\n let errorCode: string;\n let errorMessage: string;\n\n if (typeof errorData.error === 'object' && errorData.error) {\n errorCode = errorData.error.code || this.mapHttpStatusToErrorCode(response.status);\n errorMessage = errorData.error.message || 'Request failed';\n } else {\n errorCode = this.mapHttpStatusToErrorCode(response.status);\n errorMessage = typeof errorData.error === 'string' ? errorData.error : 'Request failed';\n }\n\n throw new OvixaAuthError(errorMessage, errorCode, response.status);\n }\n\n return (await response.json()) as T;\n } catch (error) {\n if (error instanceof OvixaAuthError) {\n throw error;\n }\n\n if (error instanceof Error) {\n throw new OvixaAuthError(`Network error: ${error.message}`, 'NETWORK_ERROR');\n }\n\n throw new OvixaAuthError('Request failed', 'REQUEST_FAILED');\n }\n }\n\n /**\n * Map HTTP status codes to error codes.\n */\n private mapHttpStatusToErrorCode(status: number): string {\n switch (status) {\n case 400:\n return 'BAD_REQUEST';\n case 401:\n return 'UNAUTHORIZED';\n case 403:\n return 'FORBIDDEN';\n case 404:\n return 'NOT_FOUND';\n case 429:\n return 'RATE_LIMITED';\n case 500:\n case 502:\n case 503:\n return 'SERVER_ERROR';\n default:\n return 'UNKNOWN_ERROR';\n }\n }\n\n /**\n * Get the admin API interface for realm-scoped operations.\n *\n * Admin operations require clientSecret to be configured.\n * These operations allow managing users within the realm boundary.\n *\n * @returns OvixaAuthAdmin interface for admin operations\n * @throws {OvixaAuthError} If clientSecret is not configured\n *\n * @example\n * ```typescript\n * const auth = new OvixaAuth({\n * authUrl: 'https://auth.ovixa.io',\n * realmId: 'your-realm',\n * clientSecret: process.env.OVIXA_CLIENT_SECRET,\n * });\n *\n * // Delete a user from the realm\n * await auth.admin.deleteUser({ userId: 'user-id-to-delete' });\n * ```\n */\n get admin(): OvixaAuthAdmin {\n if (!this.config.clientSecret) {\n throw new OvixaAuthError(\n 'clientSecret is required for admin operations',\n 'CLIENT_SECRET_REQUIRED'\n );\n }\n return new OvixaAuthAdmin(this.config);\n }\n}\n\n/**\n * Admin API interface for realm-scoped operations.\n *\n * This class provides methods for managing users within the realm boundary.\n * All operations are authenticated using the realm's client_secret.\n *\n * @example\n * ```typescript\n * // Access via OvixaAuth.admin\n * await auth.admin.deleteUser({ userId: 'user-id' });\n * ```\n */\nclass OvixaAuthAdmin {\n private config: InternalConfig;\n\n constructor(config: InternalConfig) {\n this.config = config;\n }\n\n /**\n * Delete a user from the realm.\n *\n * This permanently deletes the user and all associated data (tokens, OAuth accounts).\n * The user must belong to this realm.\n *\n * @param options - Delete user options\n * @returns Success response\n * @throws {OvixaAuthError} If deletion fails\n *\n * @example\n * ```typescript\n * try {\n * await auth.admin.deleteUser({ userId: 'user-id-to-delete' });\n * console.log('User deleted successfully');\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * if (error.code === 'NOT_FOUND') {\n * console.error('User not found');\n * } else if (error.code === 'FORBIDDEN') {\n * console.error('User does not belong to this realm');\n * }\n * }\n * }\n * ```\n */\n async deleteUser(options: DeleteUserOptions): Promise<SuccessResponse> {\n const url = `${this.config.authUrl}/realms/${this.config.realmId}/users/${options.userId}`;\n\n try {\n const response = await fetch(url, {\n method: 'DELETE',\n headers: {\n Authorization: `RealmSecret ${this.config.clientSecret}`,\n },\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({}));\n const errorData = errorBody as { error?: { code?: string; message?: string } | string };\n\n let errorCode: string;\n let errorMessage: string;\n\n if (typeof errorData.error === 'object' && errorData.error) {\n errorCode = errorData.error.code || this.mapHttpStatusToErrorCode(response.status);\n errorMessage = errorData.error.message || 'Request failed';\n } else {\n errorCode = this.mapHttpStatusToErrorCode(response.status);\n errorMessage = typeof errorData.error === 'string' ? errorData.error : 'Request failed';\n }\n\n throw new OvixaAuthError(errorMessage, errorCode, response.status);\n }\n\n return (await response.json()) as SuccessResponse;\n } catch (error) {\n if (error instanceof OvixaAuthError) {\n throw error;\n }\n\n if (error instanceof Error) {\n throw new OvixaAuthError(`Network error: ${error.message}`, 'NETWORK_ERROR');\n }\n\n throw new OvixaAuthError('Request failed', 'REQUEST_FAILED');\n }\n }\n\n /**\n * Map HTTP status codes to error codes.\n */\n private mapHttpStatusToErrorCode(status: number): string {\n switch (status) {\n case 400:\n return 'BAD_REQUEST';\n case 401:\n return 'UNAUTHORIZED';\n case 403:\n return 'FORBIDDEN';\n case 404:\n return 'NOT_FOUND';\n case 429:\n return 'RATE_LIMITED';\n case 500:\n case 502:\n case 503:\n return 'SERVER_ERROR';\n default:\n return 'UNKNOWN_ERROR';\n }\n }\n}\n"],"mappings":";AAOA;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AAsNA,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YACE,SACgB,MACA,YAChB;AACA,UAAM,OAAO;AAHG;AACA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAUA,IAAM,yBAAyB,KAAK,KAAK;AAgClC,IAAM,YAAN,MAAgB;AAAA,EACb;AAAA,EACA,YAA8B;AAAA,EAEtC,YAAY,QAA0B;AAEpC,UAAM,UAAU,OAAO,QAAQ,QAAQ,OAAO,EAAE;AAEhD,SAAK,SAAS;AAAA,MACZ;AAAA,MACA,SAAS,OAAO;AAAA,MAChB,cAAc,OAAO;AAAA,MACrB,cAAc,OAAO,gBAAgB;AAAA,IACvC;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,UAAkB;AACpB,WAAO,KAAK,OAAO;AAAA,EACrB;AAAA;AAAA,EAGA,IAAI,UAAkB;AACpB,WAAO,KAAK,OAAO;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,UAAkB;AACpB,WAAO,GAAG,KAAK,OAAO,OAAO;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,iBAA8B;AACpC,UAAM,MAAM,KAAK,IAAI;AAGrB,QAAI,KAAK,aAAa,MAAM,KAAK,UAAU,YAAY,KAAK,OAAO,cAAc;AAC/E,aAAO,KAAK,UAAU;AAAA,IACxB;AAGA,UAAM,UAAU,IAAI,IAAI,KAA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@@ -140,4 +140,4 @@ export {
140
140
  setAuthCookies,
141
141
  clearAuthCookies
142
142
  };
143
- //# sourceMappingURL=chunk-Y5NJCTZO.js.map
143
+ //# sourceMappingURL=chunk-DIZJA4PY.js.map
package/dist/index.d.ts CHANGED
@@ -181,6 +181,22 @@ interface GetOAuthUrlOptions {
181
181
  /** Redirect URI after OAuth completes */
182
182
  redirectUri: string;
183
183
  }
184
+ /**
185
+ * Options for deleting a user (admin operation).
186
+ */
187
+ interface DeleteUserOptions {
188
+ /** The ID of the user to delete */
189
+ userId: string;
190
+ }
191
+ /**
192
+ * Options for deleting the current user's own account.
193
+ */
194
+ interface DeleteMyAccountOptions {
195
+ /** The user's current access token */
196
+ accessToken: string;
197
+ /** The user's current password (for re-authentication) */
198
+ password: string;
199
+ }
184
200
  /**
185
201
  * Error thrown by OvixaAuth operations.
186
202
  */
@@ -189,6 +205,12 @@ declare class OvixaAuthError extends Error {
189
205
  readonly statusCode?: number | undefined;
190
206
  constructor(message: string, code: string, statusCode?: number | undefined);
191
207
  }
208
+ interface InternalConfig {
209
+ authUrl: string;
210
+ realmId: string;
211
+ clientSecret?: string;
212
+ jwksCacheTtl: number;
213
+ }
192
214
  /**
193
215
  * OvixaAuth client for authenticating with the Ovixa Auth service.
194
216
  *
@@ -447,7 +469,8 @@ declare class OvixaAuth {
447
469
  * Generate an OAuth authorization URL.
448
470
  *
449
471
  * Redirect the user to this URL to start the OAuth flow. After authentication,
450
- * the user will be redirected back to your `redirectUri` with tokens.
472
+ * the user will be redirected back to your `redirectUri` with an authorization code.
473
+ * Use `exchangeOAuthCode()` to exchange the code for tokens.
451
474
  *
452
475
  * @param options - OAuth URL options
453
476
  * @returns The full OAuth authorization URL
@@ -461,9 +484,51 @@ declare class OvixaAuth {
461
484
  *
462
485
  * // Redirect user to start OAuth flow
463
486
  * window.location.href = googleAuthUrl;
487
+ *
488
+ * // In your callback handler:
489
+ * // const code = new URLSearchParams(window.location.search).get('code');
490
+ * // const tokens = await auth.exchangeOAuthCode(code);
464
491
  * ```
465
492
  */
466
493
  getOAuthUrl(options: GetOAuthUrlOptions): string;
494
+ /**
495
+ * Exchange an OAuth authorization code for tokens.
496
+ *
497
+ * After the OAuth flow completes, the user is redirected back to your app with
498
+ * an authorization code in the URL query params. Use this method to exchange
499
+ * that code for access and refresh tokens.
500
+ *
501
+ * Note: Authorization codes expire after 60 seconds.
502
+ *
503
+ * @param code - The authorization code from the OAuth callback URL
504
+ * @returns Token response with access and refresh tokens
505
+ * @throws {OvixaAuthError} If the exchange fails
506
+ *
507
+ * @example
508
+ * ```typescript
509
+ * // In your OAuth callback handler
510
+ * const code = new URLSearchParams(window.location.search).get('code');
511
+ *
512
+ * if (code) {
513
+ * try {
514
+ * const tokens = await auth.exchangeOAuthCode(code);
515
+ * console.log('OAuth successful!', tokens.access_token);
516
+ *
517
+ * // Check if this is a new user (first-time OAuth login)
518
+ * if (tokens.is_new_user) {
519
+ * // Show onboarding flow
520
+ * }
521
+ * } catch (error) {
522
+ * if (error instanceof OvixaAuthError) {
523
+ * if (error.code === 'INVALID_CODE') {
524
+ * console.error('Invalid or expired authorization code');
525
+ * }
526
+ * }
527
+ * }
528
+ * }
529
+ * ```
530
+ */
531
+ exchangeOAuthCode(code: string): Promise<TokenResponse>;
467
532
  /**
468
533
  * Transform a token response into an AuthResult with user and session data.
469
534
  *
@@ -485,6 +550,37 @@ declare class OvixaAuth {
485
550
  * ```
486
551
  */
487
552
  toAuthResult(tokenResponse: TokenResponse): Promise<AuthResult>;
553
+ /**
554
+ * Delete the current user's own account.
555
+ *
556
+ * This permanently deletes the user's account and all associated data.
557
+ * Password re-authentication is required to prevent accidental deletion.
558
+ *
559
+ * @param options - Delete account options
560
+ * @returns Success response
561
+ * @throws {OvixaAuthError} If deletion fails
562
+ *
563
+ * @example
564
+ * ```typescript
565
+ * try {
566
+ * await auth.deleteMyAccount({
567
+ * accessToken: session.accessToken,
568
+ * password: 'current-password',
569
+ * });
570
+ * console.log('Account deleted successfully');
571
+ * // Clear local session storage
572
+ * } catch (error) {
573
+ * if (error instanceof OvixaAuthError) {
574
+ * if (error.code === 'INVALID_CREDENTIALS') {
575
+ * console.error('Incorrect password');
576
+ * } else if (error.code === 'UNAUTHORIZED') {
577
+ * console.error('Invalid or expired access token');
578
+ * }
579
+ * }
580
+ * }
581
+ * ```
582
+ */
583
+ deleteMyAccount(options: DeleteMyAccountOptions): Promise<SuccessResponse>;
488
584
  /**
489
585
  * Make an authenticated POST request to the auth service.
490
586
  */
@@ -493,6 +589,75 @@ declare class OvixaAuth {
493
589
  * Map HTTP status codes to error codes.
494
590
  */
495
591
  private mapHttpStatusToErrorCode;
592
+ /**
593
+ * Get the admin API interface for realm-scoped operations.
594
+ *
595
+ * Admin operations require clientSecret to be configured.
596
+ * These operations allow managing users within the realm boundary.
597
+ *
598
+ * @returns OvixaAuthAdmin interface for admin operations
599
+ * @throws {OvixaAuthError} If clientSecret is not configured
600
+ *
601
+ * @example
602
+ * ```typescript
603
+ * const auth = new OvixaAuth({
604
+ * authUrl: 'https://auth.ovixa.io',
605
+ * realmId: 'your-realm',
606
+ * clientSecret: process.env.OVIXA_CLIENT_SECRET,
607
+ * });
608
+ *
609
+ * // Delete a user from the realm
610
+ * await auth.admin.deleteUser({ userId: 'user-id-to-delete' });
611
+ * ```
612
+ */
613
+ get admin(): OvixaAuthAdmin;
614
+ }
615
+ /**
616
+ * Admin API interface for realm-scoped operations.
617
+ *
618
+ * This class provides methods for managing users within the realm boundary.
619
+ * All operations are authenticated using the realm's client_secret.
620
+ *
621
+ * @example
622
+ * ```typescript
623
+ * // Access via OvixaAuth.admin
624
+ * await auth.admin.deleteUser({ userId: 'user-id' });
625
+ * ```
626
+ */
627
+ declare class OvixaAuthAdmin {
628
+ private config;
629
+ constructor(config: InternalConfig);
630
+ /**
631
+ * Delete a user from the realm.
632
+ *
633
+ * This permanently deletes the user and all associated data (tokens, OAuth accounts).
634
+ * The user must belong to this realm.
635
+ *
636
+ * @param options - Delete user options
637
+ * @returns Success response
638
+ * @throws {OvixaAuthError} If deletion fails
639
+ *
640
+ * @example
641
+ * ```typescript
642
+ * try {
643
+ * await auth.admin.deleteUser({ userId: 'user-id-to-delete' });
644
+ * console.log('User deleted successfully');
645
+ * } catch (error) {
646
+ * if (error instanceof OvixaAuthError) {
647
+ * if (error.code === 'NOT_FOUND') {
648
+ * console.error('User not found');
649
+ * } else if (error.code === 'FORBIDDEN') {
650
+ * console.error('User does not belong to this realm');
651
+ * }
652
+ * }
653
+ * }
654
+ * ```
655
+ */
656
+ deleteUser(options: DeleteUserOptions): Promise<SuccessResponse>;
657
+ /**
658
+ * Map HTTP status codes to error codes.
659
+ */
660
+ private mapHttpStatusToErrorCode;
496
661
  }
497
662
 
498
- export { type AccessTokenPayload, type AuthClientConfig, type AuthResult, type ForgotPasswordOptions, type GetOAuthUrlOptions, type LoginOptions, type OAuthProvider, OvixaAuth, OvixaAuthError, type ResendVerificationOptions, type ResetPasswordOptions, type Session, type SignupOptions, type SignupResponse, type SuccessResponse, type TokenResponse, type User, type VerifyEmailOptions, type VerifyResult };
663
+ export { type AccessTokenPayload, type AuthClientConfig, type AuthResult, type DeleteMyAccountOptions, type DeleteUserOptions, type ForgotPasswordOptions, type GetOAuthUrlOptions, type LoginOptions, type OAuthProvider, OvixaAuth, OvixaAuthError, type ResendVerificationOptions, type ResetPasswordOptions, type Session, type SignupOptions, type SignupResponse, type SuccessResponse, type TokenResponse, type User, type VerifyEmailOptions, type VerifyResult };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  OvixaAuth,
3
3
  OvixaAuthError
4
- } from "./chunk-UHRF6AFJ.js";
4
+ } from "./chunk-CUACHOKT.js";
5
5
  export {
6
6
  OvixaAuth,
7
7
  OvixaAuthError
@@ -3,8 +3,8 @@ import {
3
3
  clearAuthCookies,
4
4
  isPublicRoute,
5
5
  setAuthCookies
6
- } from "../chunk-Y5NJCTZO.js";
7
- import "../chunk-UHRF6AFJ.js";
6
+ } from "../chunk-DIZJA4PY.js";
7
+ import "../chunk-CUACHOKT.js";
8
8
 
9
9
  // src/middleware/astro.ts
10
10
  var AstroCookieAdapter = class {
@@ -3,8 +3,8 @@ import {
3
3
  clearAuthCookies,
4
4
  isPublicRoute,
5
5
  setAuthCookies
6
- } from "../chunk-Y5NJCTZO.js";
7
- import "../chunk-UHRF6AFJ.js";
6
+ } from "../chunk-DIZJA4PY.js";
7
+ import "../chunk-CUACHOKT.js";
8
8
 
9
9
  // src/middleware/express.ts
10
10
  var ExpressCookieAdapter = class {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ovixa/auth-client",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "description": "Client SDK for Ovixa Auth service",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["/**\n * @ovixa/auth-client\n *\n * Client SDK for Ovixa Auth service.\n * Provides authentication, token verification, and session management.\n */\n\nimport {\n createRemoteJWKSet,\n jwtVerify,\n type JWTPayload,\n type JWTVerifyResult,\n type JWTHeaderParameters,\n} from 'jose';\n\n/**\n * Configuration options for the OvixaAuth client.\n */\nexport interface AuthClientConfig {\n /** The base URL of the Ovixa Auth service */\n authUrl: string;\n /** The realm ID to authenticate against */\n realmId: string;\n /** Your application's client secret (for server-side use only) */\n clientSecret?: string;\n /** Cache duration for JWKS in milliseconds (defaults to 1 hour) */\n jwksCacheTtl?: number;\n}\n\n/**\n * JWT claims for an Ovixa access token.\n */\nexport interface AccessTokenPayload extends JWTPayload {\n /** Subject (user ID) */\n sub: string;\n /** User's email address */\n email: string;\n /** Whether the user's email has been verified */\n email_verified: boolean;\n /** Issued at timestamp */\n iat: number;\n /** Expiration timestamp */\n exp: number;\n /** Issuer */\n iss: string;\n /** Audience (realm ID) */\n aud: string;\n}\n\n/**\n * Result of a successful token verification.\n */\nexport interface VerifyResult {\n /** The decoded token payload */\n payload: AccessTokenPayload;\n /** The protected header */\n protectedHeader: JWTHeaderParameters;\n}\n\n/**\n * Token response from the auth service.\n */\nexport interface TokenResponse {\n /** The access token (JWT) */\n access_token: string;\n /** The refresh token (JWT) */\n refresh_token: string;\n /** Token type (always \"Bearer\") */\n token_type: 'Bearer';\n /** Access token expiration time in seconds */\n expires_in: number;\n /** Whether this is a new user (only present in OAuth callback) */\n is_new_user?: boolean;\n}\n\n/**\n * User information extracted from token payload.\n */\nexport interface User {\n /** User ID (UUID) */\n id: string;\n /** User's email address */\n email: string;\n /** Whether the email has been verified */\n emailVerified: boolean;\n}\n\n/**\n * Session information containing tokens and expiry.\n */\nexport interface Session {\n /** The access token (JWT) */\n accessToken: string;\n /** The refresh token for obtaining new access tokens */\n refreshToken: string;\n /** When the access token expires */\n expiresAt: Date;\n}\n\n/**\n * Combined authentication result with user and session data.\n */\nexport interface AuthResult {\n /** The authenticated user */\n user: User;\n /** The session tokens */\n session: Session;\n /** Whether this is a new user (only set for OAuth flows) */\n isNewUser?: boolean;\n}\n\n/**\n * Options for signup.\n */\nexport interface SignupOptions {\n /** User's email address */\n email: string;\n /** Password meeting requirements */\n password: string;\n /** Optional redirect URI after email verification */\n redirectUri?: string;\n}\n\n/**\n * Response from signup endpoint.\n */\nexport interface SignupResponse {\n /** Whether the operation succeeded */\n success: boolean;\n /** Status message */\n message: string;\n}\n\n/**\n * Options for login.\n */\nexport interface LoginOptions {\n /** User's email address */\n email: string;\n /** User's password */\n password: string;\n}\n\n/**\n * Options for email verification.\n */\nexport interface VerifyEmailOptions {\n /** Verification token from email */\n token: string;\n}\n\n/**\n * Options for resending verification email.\n */\nexport interface ResendVerificationOptions {\n /** User's email address */\n email: string;\n /** Optional redirect URI after verification */\n redirectUri?: string;\n}\n\n/**\n * Generic success response.\n */\nexport interface SuccessResponse {\n /** Whether the operation succeeded */\n success: boolean;\n /** Optional status message */\n message?: string;\n}\n\n/**\n * Options for forgot password request.\n */\nexport interface ForgotPasswordOptions {\n /** User's email address */\n email: string;\n /** Optional redirect URI for password reset page */\n redirectUri?: string;\n}\n\n/**\n * Options for password reset.\n */\nexport interface ResetPasswordOptions {\n /** Reset token from email */\n token: string;\n /** New password */\n password: string;\n}\n\n/**\n * Supported OAuth providers.\n */\nexport type OAuthProvider = 'google' | 'github';\n\n/**\n * Options for generating OAuth URL.\n */\nexport interface GetOAuthUrlOptions {\n /** OAuth provider */\n provider: OAuthProvider;\n /** Redirect URI after OAuth completes */\n redirectUri: string;\n}\n\n/**\n * Error thrown by OvixaAuth operations.\n */\nexport class OvixaAuthError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n public readonly statusCode?: number\n ) {\n super(message);\n this.name = 'OvixaAuthError';\n }\n}\n\ninterface InternalConfig {\n authUrl: string;\n realmId: string;\n clientSecret?: string;\n jwksCacheTtl: number;\n}\n\n/** Default JWKS cache TTL: 1 hour */\nconst DEFAULT_JWKS_CACHE_TTL = 60 * 60 * 1000;\n\n/**\n * Custom fetch function that adds cache headers for JWKS requests.\n * Used to implement client-side caching behavior.\n */\ntype JWKSFetcher = ReturnType<typeof createRemoteJWKSet>;\n\ninterface JWKSCache {\n fetcher: JWKSFetcher;\n createdAt: number;\n}\n\n/**\n * OvixaAuth client for authenticating with the Ovixa Auth service.\n *\n * @example\n * ```typescript\n * const auth = new OvixaAuth({\n * authUrl: 'https://auth.ovixa.io',\n * realmId: 'your-realm-id',\n * clientSecret: 'your-client-secret', // Optional, for server-side use\n * });\n *\n * // Verify a token\n * const result = await auth.verifyToken(accessToken);\n * console.log(result.payload.email);\n *\n * // Refresh tokens\n * const tokens = await auth.refreshToken(refreshToken);\n * ```\n */\nexport class OvixaAuth {\n private config: InternalConfig;\n private jwksCache: JWKSCache | null = null;\n\n constructor(config: AuthClientConfig) {\n // Normalize authUrl by removing trailing slash\n const authUrl = config.authUrl.replace(/\\/$/, '');\n\n this.config = {\n authUrl,\n realmId: config.realmId,\n clientSecret: config.clientSecret,\n jwksCacheTtl: config.jwksCacheTtl ?? DEFAULT_JWKS_CACHE_TTL,\n };\n }\n\n /** Get the configured auth URL */\n get authUrl(): string {\n return this.config.authUrl;\n }\n\n /** Get the configured realm ID */\n get realmId(): string {\n return this.config.realmId;\n }\n\n /**\n * Get the JWKS URL for the auth service.\n */\n get jwksUrl(): string {\n return `${this.config.authUrl}/.well-known/jwks.json`;\n }\n\n /**\n * Get the JWKS fetcher, creating a new one if necessary.\n * The fetcher is cached based on the configured TTL.\n */\n private getJwksFetcher(): JWKSFetcher {\n const now = Date.now();\n\n // Return cached fetcher if still valid\n if (this.jwksCache && now - this.jwksCache.createdAt < this.config.jwksCacheTtl) {\n return this.jwksCache.fetcher;\n }\n\n // Create new JWKS fetcher\n const jwksUrl = new URL(this.jwksUrl);\n const fetcher = createRemoteJWKSet(jwksUrl, {\n // jose library has its own internal caching, but we add our own TTL layer\n // to control when to refresh the JWKS set\n cacheMaxAge: this.config.jwksCacheTtl,\n });\n\n this.jwksCache = {\n fetcher,\n createdAt: now,\n };\n\n return fetcher;\n }\n\n /**\n * Verify an access token and return the decoded payload.\n *\n * This method fetches the public key from the JWKS endpoint (with caching)\n * and verifies the token's signature and claims.\n *\n * @param token - The access token (JWT) to verify\n * @returns The verified token payload and header\n * @throws {OvixaAuthError} If verification fails\n *\n * @example\n * ```typescript\n * try {\n * const result = await auth.verifyToken(accessToken);\n * console.log('User ID:', result.payload.sub);\n * console.log('Email:', result.payload.email);\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * console.error('Token verification failed:', error.code);\n * }\n * }\n * ```\n */\n async verifyToken(token: string): Promise<VerifyResult> {\n try {\n const jwks = this.getJwksFetcher();\n\n const result: JWTVerifyResult<AccessTokenPayload> = await jwtVerify(token, jwks, {\n algorithms: ['RS256'],\n issuer: this.config.authUrl,\n // Audience is the realm for this application\n audience: this.config.realmId,\n });\n\n // Validate required claims\n const payload = result.payload;\n if (!payload.sub || !payload.email || payload.email_verified === undefined) {\n throw new OvixaAuthError('Token is missing required claims', 'INVALID_CLAIMS');\n }\n\n return {\n payload: payload as AccessTokenPayload,\n protectedHeader: result.protectedHeader,\n };\n } catch (error) {\n if (error instanceof OvixaAuthError) {\n throw error;\n }\n\n // Handle jose library errors\n if (error instanceof Error) {\n const message = error.message;\n\n if (message.includes('expired')) {\n throw new OvixaAuthError('Token has expired', 'TOKEN_EXPIRED');\n }\n if (message.includes('signature')) {\n throw new OvixaAuthError('Invalid token signature', 'INVALID_SIGNATURE');\n }\n if (message.includes('issuer')) {\n throw new OvixaAuthError('Invalid token issuer', 'INVALID_ISSUER');\n }\n if (message.includes('audience')) {\n throw new OvixaAuthError('Invalid token audience', 'INVALID_AUDIENCE');\n }\n if (message.includes('malformed')) {\n throw new OvixaAuthError('Malformed token', 'MALFORMED_TOKEN');\n }\n\n throw new OvixaAuthError(`Token verification failed: ${message}`, 'VERIFICATION_FAILED');\n }\n\n throw new OvixaAuthError('Token verification failed', 'VERIFICATION_FAILED');\n }\n }\n\n /**\n * Refresh an access token using a refresh token.\n *\n * This method exchanges a valid refresh token for a new access token\n * and a new refresh token (token rotation).\n *\n * @param refreshToken - The refresh token to exchange\n * @returns New token response with access and refresh tokens\n * @throws {OvixaAuthError} If the refresh fails\n *\n * @example\n * ```typescript\n * try {\n * const tokens = await auth.refreshToken(currentRefreshToken);\n * // Store the new tokens\n * saveTokens(tokens.access_token, tokens.refresh_token);\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * // Refresh token is invalid or expired - user must re-authenticate\n * redirectToLogin();\n * }\n * }\n * ```\n */\n async refreshToken(refreshToken: string): Promise<TokenResponse> {\n const url = `${this.config.authUrl}/token/refresh`;\n\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n refresh_token: refreshToken,\n }),\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({}));\n const errorMessage = (errorBody as { error?: string }).error || 'Token refresh failed';\n const errorCode = this.mapHttpStatusToErrorCode(response.status);\n\n throw new OvixaAuthError(errorMessage, errorCode, response.status);\n }\n\n const data = (await response.json()) as TokenResponse;\n return data;\n } catch (error) {\n if (error instanceof OvixaAuthError) {\n throw error;\n }\n\n if (error instanceof Error) {\n throw new OvixaAuthError(`Network error: ${error.message}`, 'NETWORK_ERROR');\n }\n\n throw new OvixaAuthError('Token refresh failed', 'REFRESH_FAILED');\n }\n }\n\n /**\n * Invalidate the cached JWKS fetcher.\n * Call this if you need to force a refresh of the public keys.\n */\n clearJwksCache(): void {\n this.jwksCache = null;\n }\n\n /**\n * Create a new user account.\n *\n * After signup, a verification email is sent. The user must verify their\n * email before they can log in.\n *\n * @param options - Signup options\n * @returns Signup response indicating success\n * @throws {OvixaAuthError} If signup fails\n *\n * @example\n * ```typescript\n * try {\n * await auth.signup({\n * email: 'user@example.com',\n * password: 'SecurePassword123!',\n * redirectUri: 'https://myapp.com/verify-callback',\n * });\n * console.log('Verification email sent!');\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * if (error.code === 'EMAIL_ALREADY_EXISTS') {\n * console.error('Email is already registered');\n * }\n * }\n * }\n * ```\n */\n async signup(options: SignupOptions): Promise<SignupResponse> {\n const url = `${this.config.authUrl}/signup`;\n\n const body: Record<string, string> = {\n email: options.email,\n password: options.password,\n realm_id: this.config.realmId,\n };\n\n if (options.redirectUri) {\n body.redirect_uri = options.redirectUri;\n }\n\n return this.makeRequest<SignupResponse>(url, body);\n }\n\n /**\n * Authenticate a user with email and password.\n *\n * @param options - Login options\n * @returns Token response with access and refresh tokens\n * @throws {OvixaAuthError} If login fails\n *\n * @example\n * ```typescript\n * try {\n * const tokens = await auth.login({\n * email: 'user@example.com',\n * password: 'SecurePassword123!',\n * });\n * console.log('Logged in!', tokens.access_token);\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * if (error.code === 'EMAIL_NOT_VERIFIED') {\n * console.error('Please verify your email first');\n * } else if (error.code === 'INVALID_CREDENTIALS') {\n * console.error('Invalid email or password');\n * }\n * }\n * }\n * ```\n */\n async login(options: LoginOptions): Promise<TokenResponse> {\n const url = `${this.config.authUrl}/login`;\n\n const body = {\n email: options.email,\n password: options.password,\n realm_id: this.config.realmId,\n };\n\n return this.makeRequest<TokenResponse>(url, body);\n }\n\n /**\n * Verify an email address using a verification token.\n *\n * This is the API flow that returns tokens. For browser redirect flow,\n * use `GET /verify` directly.\n *\n * @param options - Verification options\n * @returns Token response with access and refresh tokens\n * @throws {OvixaAuthError} If verification fails\n *\n * @example\n * ```typescript\n * // Get token from URL query params after clicking email link\n * const token = new URLSearchParams(window.location.search).get('token');\n *\n * try {\n * const tokens = await auth.verifyEmail({ token });\n * console.log('Email verified! Logged in.');\n * } catch (error) {\n * if (error instanceof OvixaAuthError && error.code === 'INVALID_TOKEN') {\n * console.error('Invalid or expired verification link');\n * }\n * }\n * ```\n */\n async verifyEmail(options: VerifyEmailOptions): Promise<TokenResponse> {\n const url = `${this.config.authUrl}/verify`;\n\n const body = {\n token: options.token,\n realm_id: this.config.realmId,\n type: 'email_verification',\n };\n\n return this.makeRequest<TokenResponse>(url, body);\n }\n\n /**\n * Resend a verification email for an unverified account.\n *\n * @param options - Resend options\n * @returns Success response\n * @throws {OvixaAuthError} If request fails\n *\n * @example\n * ```typescript\n * await auth.resendVerification({\n * email: 'user@example.com',\n * redirectUri: 'https://myapp.com/verify-callback',\n * });\n * console.log('Verification email sent!');\n * ```\n */\n async resendVerification(options: ResendVerificationOptions): Promise<SuccessResponse> {\n const url = `${this.config.authUrl}/verify/resend`;\n\n const body: Record<string, string> = {\n email: options.email,\n realm_id: this.config.realmId,\n };\n\n if (options.redirectUri) {\n body.redirect_uri = options.redirectUri;\n }\n\n return this.makeRequest<SuccessResponse>(url, body);\n }\n\n /**\n * Request a password reset email.\n *\n * Note: This endpoint always returns success to prevent email enumeration.\n *\n * @param options - Forgot password options\n * @returns Success response\n * @throws {OvixaAuthError} If request fails\n *\n * @example\n * ```typescript\n * await auth.forgotPassword({\n * email: 'user@example.com',\n * redirectUri: 'https://myapp.com/reset-password',\n * });\n * console.log('If the email exists, a reset link has been sent.');\n * ```\n */\n async forgotPassword(options: ForgotPasswordOptions): Promise<SuccessResponse> {\n const url = `${this.config.authUrl}/forgot-password`;\n\n const body: Record<string, string> = {\n email: options.email,\n realm_id: this.config.realmId,\n };\n\n if (options.redirectUri) {\n body.redirect_uri = options.redirectUri;\n }\n\n return this.makeRequest<SuccessResponse>(url, body);\n }\n\n /**\n * Reset password using a reset token.\n *\n * @param options - Reset password options\n * @returns Success response\n * @throws {OvixaAuthError} If reset fails\n *\n * @example\n * ```typescript\n * // Get token from URL query params\n * const token = new URLSearchParams(window.location.search).get('token');\n *\n * try {\n * await auth.resetPassword({\n * token,\n * password: 'NewSecurePassword123!',\n * });\n * console.log('Password reset successfully!');\n * } catch (error) {\n * if (error instanceof OvixaAuthError) {\n * if (error.code === 'INVALID_TOKEN') {\n * console.error('Invalid or expired reset link');\n * } else if (error.code === 'WEAK_PASSWORD') {\n * console.error('Password does not meet requirements');\n * }\n * }\n * }\n * ```\n */\n async resetPassword(options: ResetPasswordOptions): Promise<SuccessResponse> {\n const url = `${this.config.authUrl}/reset-password`;\n\n const body = {\n token: options.token,\n password: options.password,\n realm_id: this.config.realmId,\n };\n\n return this.makeRequest<SuccessResponse>(url, body);\n }\n\n /**\n * Revoke a refresh token (logout).\n *\n * @param refreshToken - The refresh token to revoke\n * @returns Success response\n * @throws {OvixaAuthError} If logout fails\n *\n * @example\n * ```typescript\n * await auth.logout(currentRefreshToken);\n * // Clear local token storage\n * localStorage.removeItem('refresh_token');\n * localStorage.removeItem('access_token');\n * ```\n */\n async logout(refreshToken: string): Promise<SuccessResponse> {\n const url = `${this.config.authUrl}/logout`;\n\n const body = {\n refresh_token: refreshToken,\n };\n\n return this.makeRequest<SuccessResponse>(url, body);\n }\n\n /**\n * Generate an OAuth authorization URL.\n *\n * Redirect the user to this URL to start the OAuth flow. After authentication,\n * the user will be redirected back to your `redirectUri` with tokens.\n *\n * @param options - OAuth URL options\n * @returns The full OAuth authorization URL\n *\n * @example\n * ```typescript\n * const googleAuthUrl = auth.getOAuthUrl({\n * provider: 'google',\n * redirectUri: 'https://myapp.com/auth/callback',\n * });\n *\n * // Redirect user to start OAuth flow\n * window.location.href = googleAuthUrl;\n * ```\n */\n getOAuthUrl(options: GetOAuthUrlOptions): string {\n const url = new URL(`${this.config.authUrl}/oauth/${options.provider}`);\n url.searchParams.set('realm_id', this.config.realmId);\n url.searchParams.set('redirect_uri', options.redirectUri);\n return url.toString();\n }\n\n /**\n * Transform a token response into an AuthResult with user and session data.\n *\n * This method decodes the access token to extract user information and\n * creates a structured result object.\n *\n * @param tokenResponse - The token response from login, verify, or refresh\n * @returns AuthResult with user and session data\n * @throws {OvixaAuthError} If the access token cannot be decoded\n *\n * @example\n * ```typescript\n * const tokens = await auth.login({ email, password });\n * const result = await auth.toAuthResult(tokens);\n *\n * console.log('User ID:', result.user.id);\n * console.log('Email:', result.user.email);\n * console.log('Expires at:', result.session.expiresAt);\n * ```\n */\n async toAuthResult(tokenResponse: TokenResponse): Promise<AuthResult> {\n // Verify and decode the access token\n const verified = await this.verifyToken(tokenResponse.access_token);\n\n const user: User = {\n id: verified.payload.sub,\n email: verified.payload.email,\n emailVerified: verified.payload.email_verified,\n };\n\n const session: Session = {\n accessToken: tokenResponse.access_token,\n refreshToken: tokenResponse.refresh_token,\n expiresAt: new Date(Date.now() + tokenResponse.expires_in * 1000),\n };\n\n const result: AuthResult = { user, session };\n\n if (tokenResponse.is_new_user !== undefined) {\n result.isNewUser = tokenResponse.is_new_user;\n }\n\n return result;\n }\n\n /**\n * Make an authenticated POST request to the auth service.\n */\n private async makeRequest<T>(url: string, body: Record<string, unknown>): Promise<T> {\n try {\n const response = await fetch(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const errorBody = await response.json().catch(() => ({}));\n const errorData = errorBody as { error?: { code?: string; message?: string } | string };\n\n let errorCode: string;\n let errorMessage: string;\n\n if (typeof errorData.error === 'object' && errorData.error) {\n errorCode = errorData.error.code || this.mapHttpStatusToErrorCode(response.status);\n errorMessage = errorData.error.message || 'Request failed';\n } else {\n errorCode = this.mapHttpStatusToErrorCode(response.status);\n errorMessage = typeof errorData.error === 'string' ? errorData.error : 'Request failed';\n }\n\n throw new OvixaAuthError(errorMessage, errorCode, response.status);\n }\n\n return (await response.json()) as T;\n } catch (error) {\n if (error instanceof OvixaAuthError) {\n throw error;\n }\n\n if (error instanceof Error) {\n throw new OvixaAuthError(`Network error: ${error.message}`, 'NETWORK_ERROR');\n }\n\n throw new OvixaAuthError('Request failed', 'REQUEST_FAILED');\n }\n }\n\n /**\n * Map HTTP status codes to error codes.\n */\n private mapHttpStatusToErrorCode(status: number): string {\n switch (status) {\n case 400:\n return 'BAD_REQUEST';\n case 401:\n return 'UNAUTHORIZED';\n case 403:\n return 'FORBIDDEN';\n case 404:\n return 'NOT_FOUND';\n case 429:\n return 'RATE_LIMITED';\n case 500:\n case 502:\n case 503:\n return 'SERVER_ERROR';\n default:\n return 'UNKNOWN_ERROR';\n }\n }\n}\n"],"mappings":";AAOA;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AAoMA,IAAM,iBAAN,cAA6B,MAAM;AAAA,EACxC,YACE,SACgB,MACA,YAChB;AACA,UAAM,OAAO;AAHG;AACA;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;AAUA,IAAM,yBAAyB,KAAK,KAAK;AAgClC,IAAM,YAAN,MAAgB;AAAA,EACb;AAAA,EACA,YAA8B;AAAA,EAEtC,YAAY,QAA0B;AAEpC,UAAM,UAAU,OAAO,QAAQ,QAAQ,OAAO,EAAE;AAEhD,SAAK,SAAS;AAAA,MACZ;AAAA,MACA,SAAS,OAAO;AAAA,MAChB,cAAc,OAAO;AAAA,MACrB,cAAc,OAAO,gBAAgB;AAAA,IACvC;AAAA,EACF;AAAA;AAAA,EAGA,IAAI,UAAkB;AACpB,WAAO,KAAK,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