All files / src/services/auth authService.ts

69.87% Statements 116/166
62.06% Branches 54/87
76.92% Functions 20/26
70.62% Lines 113/160

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635                                                                                            10x                                                       30x 29x               10x 10x 10x 10x                   10x 10x   10x 10x 10x 10x       6x   10x                                               5x 5x 5x 5x         10x       5x     5x           5x           5x       5x     5x                                                                                                                             5x 5x 5x                                                                                                                               5x   5x 1x                         4x 4x                                                           2x         2x                       4x 4x 4x 3x 3x   3x 1x 1x     2x       1x       1x         1x 1x                           2x 2x                                                   6x   6x 6x         6x 6x 6x 6x 6x 6x 6x     6x 2x 1x 1x 1x 1x       6x       6x 6x 6x 5x   5x 5x 5x 5x 2x           5x 5x   1x 1x             3x 3x 3x 2x   2x 1x                     1x       3x           1x                         6x 6x 6x   3x 3x   3x     1x                                       7x                 7x 7x 7x       7x       7x   7x                                         8x       8x     2x         1x         1x         1x         1x         2x               104x  
/**
 * Authentication Service Implementation
 * Story 1.2: AWS Cognito Integration
 * Story 1.2.1: "Remember me" session persistence via Amplify storage configuration
 *
 * Amplify V6 handles all token storage internally. We configure the storage location
 * (localStorage vs sessionStorage) to control session persistence.
 */
 
import { ensureAmplifyConfigured } from '@/config/amplify';
import {
  UserContext,
  LoginCredentials,
  SignUpData,
  AuthError,
  TokenRefreshResponse,
  MfaChallenge,
  UserPreferences,
  CognitoTokenClaims,
  UserRole,
} from '@/types/auth';
 
interface SignInResult {
  success: boolean;
  user?: UserContext;
  accessToken?: string;
  error?: AuthError;
  mfaChallenge?: MfaChallenge;
  /**
   * Set when Cognito returns a next-step that the user can complete inline (no
   * separate MFA channel). Today only `CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED`
   * — emitted when a user signs in for the first time with the temporary password
   * issued by `issueInvitationCredentials`. The caller (AuthContext / LoginForm)
   * switches to a "set new password" panel and calls `confirmNewPassword(...)`.
   */
  pendingChallenge?: 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED';
}
 
interface SignUpResult {
  success: boolean;
  requiresConfirmation: boolean;
  error?: AuthError;
}
 
// Adapter to make localStorage/sessionStorage compatible with Amplify's KeyValueStorageInterface
function createStorageAdapter(storage: Storage) {
  return {
    setItem(key: string, value: string): Promise<void> {
      return Promise.resolve(storage.setItem(key, value));
    },
    getItem(key: string): Promise<string | null> {
      return Promise.resolve(storage.getItem(key));
    },
    removeItem(key: string): Promise<void> {
      return Promise.resolve(storage.removeItem(key));
    },
    clear(): Promise<void> {
      return Promise.resolve(storage.clear());
    },
  };
}
 
class AuthService {
  /**
   * Lazily ensure Amplify is configured, then return its auth module.
   *
   * Public-homepage performance (perf/public-homepage-followup #2): authService is reachable
   * from the eager app root (AuthProvider), so a static `import 'aws-amplify/auth'` here would
   * drag aws-amplify (~426 KB) onto every page including the anonymous homepage. Instead each
   * method awaits this helper, which configures Amplify on first use and dynamically imports
   * the auth module so it lands in a lazy chunk. AuthProvider/apiClient gate their callers on
   * `hasCognitoSession()`, so anonymous visitors never reach here.
   */
  private async amplifyAuth() {
    await ensureAmplifyConfigured();
    return import('aws-amplify/auth');
  }
 
  /**
   * Configure session persistence based on "Remember me" preference
   * @param rememberMe - localStorage (persistent) or sessionStorage (temporary)
   */
  private async configureSessionPersistence(rememberMe: boolean): Promise<void> {
    const { cognitoUserPoolsTokenProvider } = await import('aws-amplify/auth/cognito');
    const storage = rememberMe ? localStorage : sessionStorage;
    const storageAdapter = createStorageAdapter(storage);
    cognitoUserPoolsTokenProvider.setKeyValueStorage(storageAdapter);
  }
  async signIn(credentials: LoginCredentials): Promise<SignInResult> {
    // Acquire (and configure) Amplify before configuring storage so the rememberMe choice
    // overrides ensureAmplifyConfigured()'s detect-based storage. `auth` is declared outside
    // the try so the UserAlreadyAuthenticatedException retry path in catch can reuse it.
    const {
      signIn: amplifySignIn,
      signOut: amplifySignOut,
      fetchAuthSession,
    } = await this.amplifyAuth();
    await this.configureSessionPersistence(credentials.rememberMe || false);
 
    try {
      console.log('[authService] signIn called with email:', credentials.email);
      console.log('[authService] Calling amplifySignIn');
      const result = await amplifySignIn({
        username: credentials.email,
        password: credentials.password,
      });
      console.log('[authService] amplifySignIn result:', { nextStep: result.nextStep?.signInStep });
 
      Iif (result.nextStep && result.nextStep.signInStep !== 'DONE') {
        const step = result.nextStep.signInStep;
        console.log('[authService] Sign-in next step:', step);
        // Epic 11 bug fix 2026-05-19 — surface the FORCE_CHANGE_PASSWORD challenge
        // distinctly so LoginForm can render an inline "set new password" panel.
        // Previously this was bucketed as "mfaChallenge" + success=false, which
        // looked identical to a generic auth failure to the caller and dropped the
        // user with no path forward.
        if (step === 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED') {
          return {
            success: false,
            pendingChallenge: 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED',
          };
        }
        return {
          success: false,
          mfaChallenge: {
            challengeName: step,
            challengeParameters: {},
            session: '',
          },
        };
      }
 
      console.log('[authService] Fetching auth session');
      const session = await fetchAuthSession();
      const tokens = session.tokens;
      console.log('[authService] Session tokens:', {
        hasIdToken: !!tokens?.idToken,
        hasAccessToken: !!tokens?.accessToken,
      });
 
      Iif (!tokens?.idToken) {
        throw new Error('No ID token found in session');
      }
 
      const userContext = this.extractUserContextFromToken(
        tokens.idToken.payload as unknown as CognitoTokenClaims
      );
      console.log('[authService] User context extracted:', {
        userId: userContext.userId,
        email: userContext.email,
        role: userContext.role,
      });
 
      return {
        success: true,
        user: userContext,
        accessToken: tokens.accessToken?.toString() || '',
      };
    } catch (error: unknown) {
      console.error('[authService] Error during sign in:', error);
 
      // Handle case where user is already signed in
      const errorCode =
        (error as { code?: string; name?: string }).code ||
        (error as { code?: string; name?: string }).name;
 
      Iif (errorCode === 'UserAlreadyAuthenticatedException') {
        console.log('[authService] User already authenticated, signing out and retrying...');
        try {
          // Sign out the existing user
          await amplifySignOut();
 
          // Retry sign in
          console.log('[authService] Retrying amplifySignIn after signout');
          const retryResult = await amplifySignIn({
            username: credentials.email,
            password: credentials.password,
          });
 
          if (retryResult.nextStep && retryResult.nextStep.signInStep !== 'DONE') {
            const step = retryResult.nextStep.signInStep;
            if (step === 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED') {
              return {
                success: false,
                pendingChallenge: 'CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED',
              };
            }
            return {
              success: false,
              mfaChallenge: {
                challengeName: step,
                challengeParameters: {},
                session: '',
              },
            };
          }
 
          const session = await fetchAuthSession();
          const tokens = session.tokens;
 
          if (!tokens?.idToken) {
            throw new Error('No ID token found in session', { cause: error });
          }
 
          const userContext = this.extractUserContextFromToken(
            tokens.idToken.payload as unknown as CognitoTokenClaims
          );
          console.log('[authService] Retry successful, user context:', {
            userId: userContext.userId,
            email: userContext.email,
            role: userContext.role,
          });
 
          return {
            success: true,
            user: userContext,
            accessToken: tokens.accessToken?.toString() || '',
          };
        } catch (retryError) {
          console.error('[authService] Retry failed:', retryError);
          const mappedError = this.mapCognitoError(retryError);
          console.log('[authService] Mapped retry error:', mappedError);
          return {
            success: false,
            error: mappedError,
          };
        }
      }
 
      const mappedError = this.mapCognitoError(error);
      console.log('[authService] Mapped error:', mappedError);
      return {
        success: false,
        error: mappedError,
      };
    }
  }
 
  /**
   * Complete the `CONFIRM_SIGN_IN_WITH_NEW_PASSWORD_REQUIRED` challenge.
   *
   * Called when a user signs in for the first time with the temporary password
   * issued by `issueInvitationCredentials` (CUMS, Story 11.E.2). Submits the
   * organizer-chosen new password to Cognito; on success, Cognito flips the user
   * to CONFIRMED + a permanent password, and we proceed exactly as a normal
   * successful sign-in (fetch session, extract user context).
   *
   * Epic 11 bug fix 2026-05-19. Mirrors the post-success branch of `signIn`.
   */
  async confirmNewPassword(newPassword: string): Promise<SignInResult> {
    try {
      console.log('[authService] confirmNewPassword called');
      const { confirmSignIn: amplifyConfirmSignIn, fetchAuthSession } = await this.amplifyAuth();
      const result = await amplifyConfirmSignIn({ challengeResponse: newPassword });
      console.log('[authService] confirmSignIn result:', { nextStep: result.nextStep?.signInStep });
 
      if (result.nextStep && result.nextStep.signInStep !== 'DONE') {
        // Unexpected — confirming the FORCE_CHANGE_PASSWORD challenge should land at DONE.
        // Surface as a generic error rather than silently dropping the user.
        return {
          success: false,
          error: {
            code: 'UNEXPECTED_NEXT_STEP',
            message: `Unexpected next step after confirmNewPassword: ${result.nextStep.signInStep}`,
          },
        };
      }
 
      const session = await fetchAuthSession();
      const tokens = session.tokens;
      if (!tokens?.idToken) {
        throw new Error('No ID token found in session');
      }
      const userContext = this.extractUserContextFromToken(
        tokens.idToken.payload as unknown as CognitoTokenClaims
      );
      return {
        success: true,
        user: userContext,
        accessToken: tokens.accessToken?.toString() || '',
      };
    } catch (error: unknown) {
      console.error('[authService] Error during confirmNewPassword:', error);
      const mappedError = this.mapCognitoError(error);
      return {
        success: false,
        error: mappedError,
      };
    }
  }
 
  /**
   * Sign up new user with Cognito
   */
  async signUp(signUpData: SignUpData): Promise<SignUpResult> {
    try {
      // Validate password match
      if (signUpData.password !== signUpData.confirmPassword) {
        return {
          success: false,
          requiresConfirmation: false,
          error: {
            code: 'PASSWORD_MISMATCH',
            message: 'Passwords do not match',
          },
        };
      }
 
      // ADR-001: Only send attributes allowed by Cognito writeAttributes configuration
      // Cognito = authentication only; Database = user profile data
      // See cognito-stack.ts:212-214 for writeAttributes configuration
      const { signUp: amplifySignUp } = await this.amplifyAuth();
      const result = await amplifySignUp({
        username: signUpData.email,
        password: signUpData.password,
        options: {
          userAttributes: {
            email: signUpData.email,
            // Store user profile data in preferences JSON (PostConfirmation Lambda will sync to DB)
            'custom:preferences': JSON.stringify({
              firstName: signUpData.firstName,
              lastName: signUpData.lastName,
              language: signUpData.language || 'en',
              newsletterOptIn: signUpData.newsletterOptIn || false,
              theme: 'light',
              notifications: {
                email: true,
                sms: false,
                push: true,
              },
              privacy: {
                showProfile: true,
                allowMessages: true,
              },
            }),
            // Story 12.1 AC4: `custom:companyId` is no longer written at signup.
            // Company is owned by `user_profiles.company_id` via the user-management
            // path (ADR-003/004); post-confirmation.ts never reads custom:companyId.
          },
        },
      });
 
      return {
        success: true,
        requiresConfirmation: !result.isSignUpComplete,
      };
    } catch (error: unknown) {
      return {
        success: false,
        requiresConfirmation: false,
        error: this.mapCognitoError(error),
      };
    }
  }
 
  /**
   * Get current authenticated user
   */
  async getCurrentUser(): Promise<UserContext | null> {
    try {
      const { getCurrentUser: amplifyGetCurrentUser, fetchAuthSession } = await this.amplifyAuth();
      await amplifyGetCurrentUser();
      const session = await fetchAuthSession();
      const tokens = session.tokens;
 
      if (!tokens?.idToken) {
        console.debug('[authService] No idToken found in session');
        return null;
      }
 
      return this.extractUserContextFromToken(
        tokens.idToken.payload as unknown as CognitoTokenClaims
      );
    } catch (error) {
      console.debug(
        '[authService] getCurrentUser failed:',
        error instanceof Error ? error.message : String(error)
      );
      return null;
    }
  }
 
  async signOut(): Promise<void> {
    const { signOut: amplifySignOut } = await this.amplifyAuth();
    await amplifySignOut();
  }
 
  /**
   * Story 12.7 (SSO Phase 4): initiate Google federation via Amplify v6's hosted-UI
   * redirect. `signInWithRedirect` navigates the browser to the Cognito hosted UI
   * (using the dormant `loginWith.oauth` config in amplify.ts); on return, the
   * `/auth/callback` route completes the session through the SAME hydration path as
   * password login (ADR-010 D1 — federated sessions yield the same JWT shape). The
   * promise normally does not resolve in-page (the browser navigates away); a
   * redirect-initiation failure propagates so the caller can surface it (no swallow).
   * `provider` is typed `'Google'` — the only supported provider per ADR-010 D2.
   */
  async signInWithFederated(provider: 'Google'): Promise<void> {
    const { signInWithRedirect } = await this.amplifyAuth();
    await signInWithRedirect({ provider });
  }
 
  /**
   * Story 12.8 finding F7 (2026-06-04): on `/auth/callback`, Amplify v6 performs the OAuth
   * `?code=` → token exchange ASYNCHRONOUSLY after configure. Checking the session once
   * races that exchange — and the premature "no session" verdict makes the callback page
   * navigate to /login, which CANCELS the in-flight exchange. (Observed in prod right after
   * the auth.batbern.ch custom-domain switch made the exchange a little slower: every
   * federated login silently bounced back to /login while Cognito/DB provisioning had
   * actually succeeded.)
   *
   * Waits — bounded — for the exchange to settle: resolves true on the Hub
   * `signInWithRedirect`/`signedIn` event or as soon as tokens are present (a 500ms poll
   * covers an event fired before the listener attached); resolves false on
   * `signInWithRedirect_failure` or timeout. Never throws.
   *
   * Config-race fix (2026-06-05): the Hub listener is attached BEFORE `amplifyAuth()` —
   * `ensureAmplifyConfigured()` inside it runs `Amplify.configure()`, which synchronously
   * kicks off the OAuth code exchange. A fast exchange failure dispatches
   * `signInWithRedirect_failure` immediately; attaching the listener afterwards (the old
   * order) missed that event and burned the full timeout before surfacing the error.
   */
  async waitForFederatedSession(timeoutMs = 15000): Promise<boolean> {
    // Dynamic import keeps aws-amplify utils off the public-homepage bundle (same rationale
    // as amplifyAuth()).
    const { Hub } = await import('aws-amplify/utils');
 
    return new Promise<boolean>((resolve) => {
      let settled = false;
      let poller: ReturnType<typeof setInterval> | undefined;
 
      // `finish` closes over the const bindings below; it can only RUN after they are
      // initialised (events/timers fire asynchronously), so the forward references are safe.
      const finish = (ok: boolean) => {
        Iif (settled) return;
        settled = true;
        unsubscribe();
        clearTimeout(timer);
        if (poller !== undefined) clearInterval(poller);
        resolve(ok);
      };
 
      const unsubscribe = Hub.listen('auth', ({ payload }) => {
        if (payload.event === 'signInWithRedirect' || payload.event === 'signedIn') {
          finish(true);
        } else if (Epayload.event === 'signInWithRedirect_failure') {
          console.warn('[authService] signInWithRedirect_failure during callback processing');
          finish(false);
        }
      });
 
      const timer = setTimeout(() => finish(false), timeoutMs);
 
      // Listener is live — NOW configure Amplify (triggers the code exchange) and start
      // the token poll. A configure failure settles false instead of hanging to timeout.
      void (async () => {
        try {
          const { fetchAuthSession } = await this.amplifyAuth();
          Iif (settled) return;
 
          const checkTokens = async () => {
            try {
              const session = await fetchAuthSession();
              if (session.tokens?.idToken) {
                finish(true);
              }
            } catch {
              // Exchange still in flight (or transient) — keep waiting until event/timeout.
            }
          };
          poller = setInterval(() => void checkTokens(), 500);
          void checkTokens();
        } catch (error) {
          console.error('[authService] waitForFederatedSession: Amplify init failed', error);
          finish(false);
        }
      })();
    });
  }
 
  async refreshToken(): Promise<TokenRefreshResponse> {
    try {
      const { fetchAuthSession } = await this.amplifyAuth();
      const session = await fetchAuthSession({ forceRefresh: true });
      const tokens = session.tokens;
 
      if (!tokens?.accessToken) {
        return {
          success: false,
          accessToken: '',
          expiresIn: 0,
          error: {
            code: 'NO_TOKEN',
            message: 'No access token available',
          },
        };
      }
 
      const expiresIn = tokens.accessToken.payload.exp
        ? tokens.accessToken.payload.exp - Math.floor(Date.now() / 1000)
        : 0;
 
      return {
        success: true,
        accessToken: tokens.accessToken.toString(),
        expiresIn,
      };
    } catch (error: unknown) {
      return {
        success: false,
        accessToken: '',
        expiresIn: 0,
        error: this.mapCognitoError(error),
      };
    }
  }
 
  /**
   * Check if JWT token is expired
   */
  isTokenExpired(token: string): boolean {
    try {
      const parts = token.split('.');
      if (parts.length !== 3) return true;
 
      const payload = JSON.parse(atob(parts[1]));
      const currentTime = Math.floor(Date.now() / 1000);
 
      return payload.exp <= currentTime;
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (_error) {
      return true;
    }
  }
 
  /**
   * Extract user context from Cognito ID token
   * Story 1.2.6: Updated to read custom:role claim (ADR-001 migration)
   */
  private extractUserContextFromToken(tokenPayload: CognitoTokenClaims): UserContext {
    // Story 12.1 (ADR-001 "minimal target footprint"): company + preferences are
    // business data owned by `user_profiles`, NOT identity/authorization, so they are
    // no longer sourced from the token. `AuthContext.hydrateUserFromDb` fills `companyId`
    // + `preferences` from GET /users/me. The token carries only identity (sub, email) +
    // authorization (custom:role, custom:username).
    //
    // Default to a COMPLETE UserPreferences object (not `{}`): the type requires all
    // fields and downstream consumers read `preferences.language`/`.theme` directly, so
    // the contract must hold even when DB hydration is skipped (no `/users/me`
    // preferences row) or fails transiently. Hydration overrides these with the DB
    // values when available.
    const preferences: UserPreferences = {
      language: 'en',
      theme: 'light',
      notifications: { email: true, sms: false, push: true },
      privacy: { showProfile: true, allowMessages: true },
    };
 
    // Extract roles from custom:role claim (singular)
    // Format: "ORGANIZER,SPEAKER" -> ['organizer', 'speaker']
    const rolesString = tokenPayload['custom:role'];
    const roles: UserRole[] = rolesString
      ? rolesString.split(',').map((r) => r.trim().toLowerCase() as UserRole)
      : [];
 
    // Primary role is first in list, fallback to 'attendee' if empty
    const primaryRole: UserRole = roles[0] || 'attendee';
 
    // Story 1.16.2: Prefer custom:username (from database) over cognito:username (UUID)
    // PreTokenGeneration Lambda sets custom:username from database user_profiles.username
    const username = tokenPayload['custom:username'] || '';
 
    return {
      userId: tokenPayload.sub,
      username, // Story 1.16.2: Public meaningful username (e.g., "john.doe")
      email: tokenPayload.email,
      emailVerified: tokenPayload.email_verified,
      role: primaryRole,
      roles: roles,
      companyId: undefined, // Story 12.1: hydrated from GET /users/me (was custom:companyId)
      companyName: tokenPayload['custom:companyName'] || undefined, // Story 8.0: resolved from JWT if present
      preferences, // Story 12.1: hydrated from GET /users/me (was custom:preferences)
      issuedAt: tokenPayload.iat,
      expiresAt: tokenPayload.exp,
      tokenId: tokenPayload.sub,
    };
  }
 
  /**
   * Map Cognito errors to application errors
   */
  private mapCognitoError(error: unknown): AuthError {
    const errorCode =
      (error as { code?: string; name?: string }).code ||
      (error as { code?: string; name?: string }).name ||
      'UNKNOWN_ERROR';
 
    switch (errorCode) {
      case 'NotAuthorizedException':
      case 'UserNotFoundException':
        return {
          code: 'INVALID_CREDENTIALS',
          message: 'Invalid email or password',
        };
      case 'UserNotConfirmedException':
        return {
          code: 'USER_NOT_CONFIRMED',
          message: 'Please confirm your email address',
        };
      case 'TooManyRequestsException':
        return {
          code: 'TOO_MANY_REQUESTS',
          message: 'Too many attempts. Please try again later',
        };
      case 'InvalidPasswordException':
        return {
          code: 'INVALID_PASSWORD',
          message: 'Password does not meet requirements',
        };
      case 'UsernameExistsException':
        return {
          code: 'EMAIL_EXISTS',
          message: 'An account with this email already exists',
        };
      default:
        return {
          code: errorCode,
          message: (error as { message?: string }).message || 'An unexpected error occurred',
        };
    }
  }
}
 
export const authService = new AuthService();