Skip to content

Privacy-first password manager with built-in email aliasing. Fully encrypted and self-hostable.

7.3 KB
Raw Blame
import { isMobileLoginErrorCode, MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS, MobileLoginErrorCode, MobileLoginService } from '@aliasvault/client/auth/MobileLoginService';
import QRCode from 'qrcode';
import React, { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';

import ModalWrapper from '@/entrypoints/popup/components/Dialogs/ModalWrapper';

import type { WebApiService } from '@aliasvault/client/api/WebApiService';
import type { MobileLoginResult } from '@aliasvault/client/auth/MobileLoginService';

interface IMobileUnlockModalProps {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: (result: MobileLoginResult) => Promise<void>;
  webApi: WebApiService;
  mode?: 'login' | 'unlock';
}

/**
 * Modal component for mobile login/unlock via QR code scanning.
 */
const MobileUnlockModal: React.FC<IMobileUnlockModalProps> = ({
  isOpen,
  onClose,
  onSuccess,
  webApi,
  mode = 'login'
}) => {
  const { t } = useTranslation();
  const [qrCodeUrl, setQrCodeUrl] = useState<string | null>(null);
  const [verificationCode, setVerificationCode] = useState<string | null>(null);
  const [error, setError] = useState<MobileLoginErrorCode | null>(null);
  const [timeRemaining, setTimeRemaining] = useState<number>(MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS)
  const mobileLoginRef = useRef<MobileLoginService | null>(null);
  const countdownIntervalRef = useRef<NodeJS.Timeout | null>(null);

  /**
   * Get translated error message for error code.
   */
  const getErrorMessage = (errorCode: MobileLoginErrorCode): string => {
    switch (errorCode) {
      case MobileLoginErrorCode.TIMEOUT:
        return t('common.errors.mobileLoginRequestExpired');
      case MobileLoginErrorCode.DECLINED:
        return t('common.errors.mobileLoginRequestDeclined');
      case MobileLoginErrorCode.GENERIC:
      default:
        return t('common.errors.unknownError');
    }
  };

  // Countdown timer effect
  useEffect(() => {
    if (qrCodeUrl && timeRemaining > 0 && isOpen) {
      countdownIntervalRef.current = setInterval(() => {
        setTimeRemaining(prev => {
          if (prev <= 1) {
            if (countdownIntervalRef.current) {
              clearInterval(countdownIntervalRef.current);
            }
            return 0;
          }
          return prev - 1;
        });
      }, 1000);

      return (): void => {
        if (countdownIntervalRef.current) {
          clearInterval(countdownIntervalRef.current);
        }
      };
    }
  }, [qrCodeUrl, timeRemaining, isOpen]);

  // Initialize mobile login when modal opens
  useEffect(() => {
    if (!isOpen) {
      return;
    }

    /**
     * Initialize mobile login on modal open.
     */
    const initiateMobileLogin = async (): Promise<void> => {
      try {
        setError(null);
        setQrCodeUrl(null);
        setVerificationCode(null);
        setTimeRemaining(MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS);

        // Initialize mobile login utility
        if (!mobileLoginRef.current) {
          mobileLoginRef.current = new MobileLoginService(webApi);
        }

        // Initiate mobile login and get the QR code text plus the number the user taps in the mobile app
        const { qrPayload, verificationCode: code } = await mobileLoginRef.current.initiate();
        const qrDataUrl = await QRCode.toDataURL(qrPayload, {
          width: 300,
          margin: 2,
        });

        setQrCodeUrl(qrDataUrl);
        setVerificationCode(code);

        // Start polling for response
        mobileLoginRef.current.startPolling(
          async (result: MobileLoginResult) => {
            try {
              // Call success callback (parent handles loading state)
              await onSuccess(result);
              // Close modal after successful processing
              handleClose();
            } catch {
              // Show error if success handler fails and hide QR code
              setQrCodeUrl(null);
              setError(MobileLoginErrorCode.GENERIC);
            }
          },
          (errorCode) => {
            // Hide QR code when error occurs
            setQrCodeUrl(null);
            setError(errorCode);
          }
        );
      } catch (err) {
        // err is a MobileLoginErrorCode thrown by initiate()
        setError(isMobileLoginErrorCode(err) ? err : MobileLoginErrorCode.GENERIC);
      }
    };

    initiateMobileLogin();

    // Cleanup on unmount or when modal closes
    return (): void => {
      if (mobileLoginRef.current) {
        mobileLoginRef.current.cleanup();
      }
      if (countdownIntervalRef.current) {
        clearInterval(countdownIntervalRef.current);
      }
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen]);

  /**
   * Handle modal close.
   */
  const handleClose = (): void => {
    if (mobileLoginRef.current) {
      mobileLoginRef.current.cleanup();
    }
    if (countdownIntervalRef.current) {
      clearInterval(countdownIntervalRef.current);
    }
    setQrCodeUrl(null);
    setError(null);
    setTimeRemaining(MOBILE_LOGIN_REQUEST_LIFETIME_SECONDS);
    onClose();
  };

  /**
   * Format time remaining as MM:SS.
   */
  const formatTime = (seconds: number): string => {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins}:${secs.toString().padStart(2, '0')}`;
  };

  const title = mode === 'unlock' ? t('auth.unlockWithMobile') : t('auth.loginWithMobile');
  const description = t('auth.scanQrCode');

  return (
    <ModalWrapper
      isOpen={isOpen}
      onClose={handleClose}
      title={title}
      showHeaderBorder={false}
      bodyClassName="px-6 pb-6"
    >
      <div className="flex items-start justify-between gap-3 mb-4">
        <p className="text-sm text-gray-600 dark:text-gray-400">
          {description}
        </p>
        {qrCodeUrl && (
          <span className="flex-shrink-0 px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-700 text-xs font-medium tabular-nums text-gray-600 dark:text-gray-300">
            {formatTime(timeRemaining)}
          </span>
        )}
      </div>

      {error && (
        <div className="mb-4 p-3 bg-red-100 dark:bg-red-900/30 border border-red-400 dark:border-red-700 rounded text-red-700 dark:text-red-400 text-sm">
          {getErrorMessage(error)}
        </div>
      )}

      {qrCodeUrl && (
        <div className="flex flex-col items-center w-full max-w-[300px] mx-auto">
          <img src={qrCodeUrl} alt={t('common.qrCode')} className="w-full border-4 border-gray-200 dark:border-gray-600 rounded mb-3" />
          {verificationCode && (
            <div className="w-full flex items-center gap-3 p-3 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700/50">
              <div className="flex-shrink-0 flex items-center justify-center w-14 h-14 rounded-full border-2 border-primary-500 bg-white dark:bg-gray-800 text-2xl font-bold text-gray-900 dark:text-white">
                {verificationCode}
              </div>
              <p className="text-sm font-medium text-gray-700 dark:text-gray-300">
                {t('auth.mobileUnlockVerificationCode')}
              </p>
            </div>
          )}
        </div>
      )}

      {!qrCodeUrl && !error && (
        <div className="flex justify-center py-8">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-primary-600"></div>
        </div>
      )}
    </ModalWrapper>
  );
};

export default MobileUnlockModal;