Skip to content

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

16.4 KB
Raw Blame
import { type AliasOwnerNotice, aliasOwnerErrorText, aliasOwnerNotice } from '@aliasvault/client/email/AliasOwner';
import { decryptEmailList } from '@aliasvault/client/email/EmailDecryption';
import { SpamOkClient } from '@aliasvault/client/email/SpamOkClient';
import { AppInfo } from '@aliasvault/client/platform/AppInfo';
import { sharingText } from '@aliasvault/client/sharing/SharingView';
import { mailboxPollDelayMs } from '@aliasvault/client/utilities/PollBackoff';
import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useLocation } from 'react-router-dom';

import Modal from '@/entrypoints/popup/components/Dialogs/Modal';
import { AttachmentIcon } from '@/entrypoints/popup/components/Icons/AttachmentIcon';
import Icon from '@/entrypoints/popup/components/Icons/Icon';
import { useDb } from '@/entrypoints/popup/context/DbContext';
import { useWebApi } from '@/entrypoints/popup/context/WebApiContext';

import { StorageKeys } from '@/utils/constants/storageKeys';
import { logExpected } from '@/utils/Diagnostics';
import { sendMessage } from '@/utils/messaging/ExtensionMessaging';

import type { ApiErrorResponse, Mailbox, MailboxEmail } from '@aliasvault/models/webapi';

import { storage } from '#imports';

/** Client for the SpamOK mailboxes of the public email domains. */
const spamOk = new SpamOkClient('av-chrome', AppInfo.VERSION);

type EmailPreviewProps = {
  email: string;
  manifestId: string;
}

/**
 * This component shows a preview of the latest emails in the inbox.
 */
export const EmailPreview: React.FC<EmailPreviewProps> = ({ email, manifestId }) => {
  const { t } = useTranslation();
  const [emails, setEmails] = useState<MailboxEmail[]>([]);
  const [displayedEmails, setDisplayedEmails] = useState<MailboxEmail[]>([]);
  const [loading, setLoading] = useState(true);
  const [lastEmailId, setLastEmailId] = useState<number>(0);
  const [isSpamOk, setIsSpamOk] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [isSupportedDomain, setIsSupportedDomain] = useState(false);
  const [displayedCount, setDisplayedCount] = useState(2);
  const [ownerNotice, setOwnerNotice] = useState<AliasOwnerNotice | null>(null);
  const [showMoveConfirm, setShowMoveConfirm] = useState(false);
  const webApi = useWebApi();
  const dbContext = useDb();
  const location = useLocation();
  const consecutiveFailuresRef = useRef(0);
  const emailsPerLoad = 3;
  const canLoadMore = displayedCount < emails.length;

  /**
   * Updates the displayed emails based on the current count.
   */
  const updateDisplayedEmails = (allEmails: MailboxEmail[], count: number) : void => {
    const displayed = allEmails.slice(0, count);
    setDisplayedEmails(displayed);
  };

  /**
   * Loads more emails.
   */
  const loadMoreEmails = (): void => {
    const newCount = Math.min(displayedCount + emailsPerLoad, emails.length);
    setDisplayedCount(newCount);
    updateDisplayedEmails(emails, newCount);
  };

  /**
   * Checks if the email is a public domain.
   */
  const isPublicDomain = async (emailAddress: string): Promise<boolean> => {
    // Get metadata from storage
    const publicEmailDomains = await storage.getItem<string[]>(StorageKeys.PUBLIC_EMAIL_DOMAINS) ?? [];
    return publicEmailDomains.some(domain => emailAddress.toLowerCase().endsWith(`@${domain.toLowerCase()}`));
  };

  /**
   * Checks if the email is a private domain.
   */
  const isPrivateDomain = async (emailAddress: string): Promise<boolean> => {
    // Get metadata from storage
    const privateEmailDomains = await storage.getItem<string[]>(StorageKeys.PRIVATE_EMAIL_DOMAINS) ?? [];
    return privateEmailDomains.some(domain => emailAddress.toLowerCase().endsWith(`@${domain.toLowerCase()}`));
  };

  useEffect(() => {
    let cancelled = false;
    let timer: ReturnType<typeof setTimeout> | null = null;

    /**
     * Record that a poll failed for the incremental backoff to work.
     * @param reason - what did not work
     * @param error - the underlying error, when there is one
     */
    const markPollFailed = (reason: string, error?: unknown): void => {
      if (consecutiveFailuresRef.current === 0) {
        logExpected(`[EmailPreview] ${reason}`, error);
      }
      consecutiveFailuresRef.current++;
    };

    /**
     * Loads the latest emails from the server and decrypts them locally if needed.
     */
    const loadEmails = async (): Promise<void> => {
      try {
        // Check if we are in offline mode
        if (dbContext.isOffline) {
          setLoading(false);
          return;
        }

        setError(null);
        const isPublic = await isPublicDomain(email);
        const isPrivate = await isPrivateDomain(email);

        // Check if the email is routable (has active claim and is not manually disabled/paused, so still actively receiving mail for).
        const isRoutable = !isPrivate || (dbContext.sqliteClient?.items.isEmailAddressRoutable(email) ?? false);
        const isSupported = (isPublic || isPrivate) && isRoutable;

        setIsSpamOk(isPublic);
        setIsSupportedDomain(isSupported);

        if (!isSupported) {
          return;
        }

        if (isPublic) {
          // For public domains (SpamOK), use the SpamOK API directly
          const emailPrefix = email.split('@')[0];
          const allMails = await spamOk.getMailbox(emailPrefix);
          if (!allMails) {
            markPollFailed('The mailbox request failed');
            setError(t('common.errors.unknownError'));
            return;
          }

          if (loading && allMails.length > 0) {
            setLastEmailId(allMails[0].id);
          }

          // Only update emails if they actually changed to preserve displayedCount
          setEmails(prevEmails => {
            const emailsChanged = JSON.stringify(prevEmails.map(e => e.id)) !== JSON.stringify(allMails.map((e: MailboxEmail) => e.id));
            if (emailsChanged) {
              updateDisplayedEmails(allMails, displayedCount);
              return allMails;
            }
            return prevEmails;
          });
          consecutiveFailuresRef.current = 0;
        } else if (isPrivate) {
          // For private domains, use existing encrypted email logic
          try {
            /**
             * We use authFetch here because we don't want to the inner method to throw an error if HTTP status is not 200.
             * Instead we want to catch the error ourselves.
             */
            const response = await webApi.authFetch(`EmailBox/${email}`, { method: 'GET' }, true, false);
            try {
              const data = response as Mailbox;
              setOwnerNotice(aliasOwnerNotice(email, data, manifestId, dbContext.sqliteClient!.getPersonalManifestId(), dbContext.sqliteClient!.folders.getAll()));

              // Store all emails, sorted by date
              const allMails = data.mails
                .toSorted((a, b) => new Date(b.dateSystem).getTime() - new Date(a.dateSystem).getTime());

              if (allMails) {
                // Loop through all emails and decrypt them locally
                const decryptedEmails: MailboxEmail[] = await decryptEmailList(
                  allMails,
                  data.publicKeys,
                  dbContext.sqliteClient!.encryptionKeys.getAll()
                );

                if (loading && decryptedEmails.length > 0) {
                  setLastEmailId(decryptedEmails[0].id);
                }

                // Only update emails if they actually changed to preserve displayedCount
                setEmails(prevEmails => {
                  const emailsChanged = JSON.stringify(prevEmails.map(e => e.id)) !== JSON.stringify(decryptedEmails.map(e => e.id));
                  if (emailsChanged) {
                    updateDisplayedEmails(decryptedEmails, displayedCount);
                    return decryptedEmails;
                  }
                  return prevEmails;
                });

                // Clear any previous error on successful load
                setError(null);
                consecutiveFailuresRef.current = 0;
              }
            } catch {
              // Try to parse as error response instead
              const apiErrorResponse = response as ApiErrorResponse;

              /*
               * Suppress errors while vault has unsynced changes (e.g., after item creation)
               * The server may not know about newly created items/aliases yet
               */
              if (dbContext.shouldSuppressEmailErrors()) {
                // Don't set error, keep loading state - will retry on next interval
                return;
              }

              markPollFailed(`The server rejected the mailbox request: ${apiErrorResponse?.code ?? 'unknown'}`);
              setError(aliasOwnerErrorText(apiErrorResponse?.code) ?? t('apiErrors.' + apiErrorResponse?.code, { defaultValue: t('common.errors.unknownErrorTryAgain') }));
              return;
            }
          } catch (err) {
            // Suppress errors while vault has unsynced changes
            if (dbContext.shouldSuppressEmailErrors()) {
              return;
            }

            markPollFailed('The mailbox request failed', err);
            setError(t('common.errors.unknownError'));
            return;
          }
        }
      } catch (err) {
        markPollFailed('Loading the mailbox failed', err);
        setError(t('common.errors.unknownError'));
      }
      setLoading(false);
    };

    /**
     * Poll, then schedule the next poll.
     */
    const poll = async (): Promise<void> => {
      await loadEmails();
      if (cancelled) {
        return;
      }
      timer = setTimeout(poll, mailboxPollDelayMs(consecutiveFailuresRef.current));
    };

    void poll();

    return () : void => {
      cancelled = true;
      if (timer) {
        clearTimeout(timer);
      }
    };
  }, [email, manifestId, loading, webApi, dbContext, t, displayedCount]);

  /**
   * Move the alias to this item's vault, then reload so the notice goes away.
   */
  const moveHere = async (): Promise<void> => {
    setShowMoveConfirm(false);
    if (!ownerNotice?.transfer) {
      return;
    }
    const result = await sendMessage('EMAIL_CLAIM_TRANSFER', ownerNotice.transfer);
    if (!result.success) {
      setError(aliasOwnerErrorText(result.apiErrorCode) ?? (result.apiErrorCode ? t('apiErrors.' + result.apiErrorCode, { defaultValue: t('common.errors.unknownErrorTryAgain') }) : result.error ?? t('common.errors.unknownErrorTryAgain')));
      return;
    }
    setOwnerNotice(null);
    setLoading(true);
  };

  const ownerNoticeBlock = ownerNotice && (
    <div className="mb-2 p-3 bg-amber-50 dark:bg-amber-500/10 border border-amber-300 dark:border-amber-500/40 rounded">
      <p className="text-sm text-amber-900 dark:text-amber-100">{ownerNotice.notice}</p>
      {ownerNotice.transfer && (
        <button
          id="move-alias-here"
          onClick={() => setShowMoveConfirm(true)}
          className="mt-2 py-1 px-3 bg-primary-600 hover:bg-primary-700 text-white rounded-md text-sm"
        >
          {sharingText.aliasOwner.moveHere}
        </button>
      )}
      <Modal
        isOpen={showMoveConfirm}
        onClose={() => setShowMoveConfirm(false)}
        onConfirm={() => void moveHere()}
        title={sharingText.aliasOwner.moveHere}
        message={ownerNotice.moveConfirm}
        confirmText={t('common.confirm')}
        cancelText={t('common.cancel')}
      />
    </div>
  );

  // Don't render anything if the domain is not supported
  if (!isSupportedDomain) {
    return null;
  }

  // Show offline message if in offline mode
  if (dbContext.isOffline) {
    return (
      <div className="text-gray-500 dark:text-gray-400 mb-4">
        <div className="flex items-center gap-2 mb-2">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t('common.recentEmails')}</h2>
        </div>
        <p className="text-sm">{t('emails.offlineMessage')}</p>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-gray-500 dark:text-gray-400 mb-4">
        <div className="flex items-center gap-2 mb-2">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t('common.recentEmails')}</h2>
        </div>
        <div className="p-3 bg-red-50 dark:bg-red-900/30 border border-red-200 dark:border-red-800 rounded">
          <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
        </div>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="text-gray-500 dark:text-gray-400 mb-4">
        <div className="flex items-center gap-2 mb-2">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t('common.recentEmails')}</h2>
          <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
        </div>
        {t('common.loadingEmails')}
      </div>
    );
  }
  if (emails.length === 0) {
    return (
      <div className="text-gray-500 dark:text-gray-400 mb-4 text-sm">
        <div className="flex items-center gap-2 mb-2">
          <h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t('common.recentEmails')}</h2>
          <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
        </div>
        {ownerNoticeBlock}
        {t('emails.noEmails')}
      </div>
    );
  }

  return (
    <div className="space-y-2 mb-4">
      <div className="flex items-center gap-2 mb-2">
        <h2 className="text-xl font-semibold text-gray-900 dark:text-white">{t('common.recentEmails')}</h2>
        <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse" />
      </div>
      {ownerNoticeBlock}

      {displayedEmails.map((mail) => (
        isSpamOk ? (
          <a
            key={mail.id}
            href={`https://spamok.com/${encodeURIComponent(email.split('@')[0])}/${mail.id}`}
            target="_blank"
            rel="noopener noreferrer"
            className={`flex justify-between items-center p-2 ps-3 pe-3 rounded cursor-pointer bg-white dark:bg-gray-800 shadow hover:shadow-md transition-all border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700 ${
              mail.id > lastEmailId ? 'bg-yellow-50 dark:bg-yellow-900/30' : ''
            }`}
          >
            <div className="truncate flex-1">
              <span className="text-sm text-gray-900 dark:text-white">
                {mail.subject.substring(0, 30)}{mail.subject.length > 30 ? '...' : ''}
              </span>
            </div>
            <div className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 ml-2 flex-shrink-0">
              {mail.hasAttachments && <AttachmentIcon className="w-3.5 h-3.5" />}
              <span>{new Date(mail.dateSystem).toLocaleDateString()}</span>
            </div>
          </a>
        ) : (
          <Link
            key={mail.id}
            // Carry where we came from so the email's back/delete (incl. popped-out window) returns here, not the emails list.
            to={`/emails/${mail.id}?returnTo=${encodeURIComponent(`${location.pathname}${location.search}`)}`}
            className={`flex justify-between items-center p-2 ps-3 pe-3 rounded cursor-pointer bg-white dark:bg-gray-800 shadow hover:shadow-md transition-all border border-gray-200 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-700 ${
              mail.id > lastEmailId ? 'bg-yellow-50 dark:bg-yellow-900/30' : ''
            }`}
          >
            <span className="truncate flex-1">
              <span className="text-sm text-gray-900 dark:text-white">
                {mail.subject.substring(0, 30)}{mail.subject.length > 30 ? '...' : ''}
              </span>
            </span>
            <span className="flex items-center gap-1 text-xs text-gray-500 dark:text-gray-400 ml-2 flex-shrink-0">
              {mail.hasAttachments && <AttachmentIcon className="w-3.5 h-3.5" />}
              <span>{new Date(mail.dateSystem).toLocaleDateString()}</span>
            </span>
          </Link>
        )
      ))}

      {canLoadMore && (
        <button
          onClick={loadMoreEmails}
          className="w-full mt-2 py-1 px-3 bg-gray-50 dark:bg-gray-800 hover:bg-gray-100 dark:hover:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-md transition-colors duration-200 text-sm text-gray-600 dark:text-gray-300 hover:text-gray-800 dark:hover:text-gray-100 flex items-center justify-center gap-1"
        >
          <span>{t('common.loadMore')}</span>
          <Icon name="chevron-down" className="w-3 h-3" />
        </button>
      )}
    </div>
  );
};