Skip to content

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

7.2 KB
Raw Blame
/**
 * Background script handler for save prompt state persistence.
 * Stores save prompt state in memory so it survives content script navigation.
 * Also tracks the last autofilled credential per tab for the "Add URL" feature.
 */

import { extractRootDomain } from '@aliasvault/client/rust/RustCore';

import type { SavePromptPersistedState, LastAutofilledCredential } from '@/utils/loginDetector';

/** In-memory storage for save prompt state, keyed by tab ID */
const savePromptStateByTab: Map<number, SavePromptPersistedState> = new Map();

/** Timeout handles for auto-clearing state after expiry */
const stateExpiryTimers: Map<number, ReturnType<typeof setTimeout>> = new Map();

/** In-memory storage for last autofilled credential, keyed by tab ID */
const lastAutofilledByTab: Map<number, LastAutofilledCredential> = new Map();

/** Timeout handles for auto-clearing autofill state after expiry */
const autofillExpiryTimers: Map<number, ReturnType<typeof setTimeout>> = new Map();

/** How long to remember the last autofilled credential (5 minutes, to allow for extended prompt focus) */
const AUTOFILL_STATE_EXPIRY_MS = 5 * 60 * 1000;

/**
 * Store save prompt state for a tab.
 * @param data - The state data and tab ID.
 * @returns Success response.
 */
export function handleStoreSavePromptState(
  data: { tabId: number; state: SavePromptPersistedState }
): { success: boolean } {
  const { tabId, state } = data;

  // Clear any existing expiry timer for this tab
  const existingTimer = stateExpiryTimers.get(tabId);
  if (existingTimer) {
    clearTimeout(existingTimer);
  }

  // Store the state
  savePromptStateByTab.set(tabId, state);

  // Set up auto-expiry based on remaining time
  if (state.remainingTimeMs > 0) {
    const timer = setTimeout(() => {
      savePromptStateByTab.delete(tabId);
      stateExpiryTimers.delete(tabId);
    }, state.remainingTimeMs + 1000); // Add 1s buffer

    stateExpiryTimers.set(tabId, timer);
  }

  return { success: true };
}

/**
 * Whether a save prompt stored on `stateDomain` may be shown on `currentDomain` (same host or same root domain).
 * @param stateDomain - The hostname the prompt was persisted on.
 * @param currentDomain - The hostname of the page asking for the prompt.
 * @returns True when the prompt may be restored.
 */
export async function isRelatedDomain(stateDomain: string, currentDomain: string): Promise<boolean> {
  if (stateDomain === currentDomain) {
    return true;
  }
  if (!stateDomain || !currentDomain) {
    return false;
  }
  const [stateRoot, currentRoot] = await Promise.all([extractRootDomain(stateDomain), extractRootDomain(currentDomain)]);
  return stateRoot === currentRoot;
}

/**
 * Get save prompt state for a tab, or null when it expired or belongs to an unrelated domain.
 * @param data - The tab ID and the hostname of the page asking.
 * @returns The stored state or null.
 */
export async function handleGetSavePromptState(
  data: { tabId: number; currentDomain: string }
): Promise<{ success: boolean; state: SavePromptPersistedState | null }> {
  const { tabId, currentDomain } = data;
  const state = savePromptStateByTab.get(tabId) || null;

  if (state) {
    // Calculate adjusted remaining time
    const elapsedSinceSave = Date.now() - state.savedAt;
    const adjustedRemainingTime = state.remainingTimeMs - elapsedSinceSave;

    if (adjustedRemainingTime <= 0 || !(await isRelatedDomain(state.domain, currentDomain))) {
      // Timer expired or the tab navigated to an unrelated site, clean up
      handleClearSavePromptState({ tabId });
      return { success: true, state: null };
    }

    // Return state with adjusted remaining time
    return {
      success: true,
      state: {
        ...state,
        remainingTimeMs: adjustedRemainingTime,
      },
    };
  }

  return { success: true, state: null };
}

/**
 * Clear save prompt state for a tab.
 * @param data - The tab ID.
 * @returns Success response.
 */
export function handleClearSavePromptState(
  data: { tabId: number }
): { success: boolean } {
  const { tabId } = data;

  savePromptStateByTab.delete(tabId);

  const timer = stateExpiryTimers.get(tabId);
  if (timer) {
    clearTimeout(timer);
    stateExpiryTimers.delete(tabId);
  }

  return { success: true };
}

/**
 * Store last autofilled credential for a tab.
 * @param data - The tab ID and credential info.
 * @returns Success response.
 */
export function handleStoreLastAutofilled(
  data: { tabId: number; credential: LastAutofilledCredential }
): { success: boolean } {
  const { tabId, credential } = data;

  // Clear any existing expiry timer for this tab
  const existingTimer = autofillExpiryTimers.get(tabId);
  if (existingTimer) {
    clearTimeout(existingTimer);
  }

  // Store the credential
  lastAutofilledByTab.set(tabId, credential);

  // Set up auto-expiry
  const timer = setTimeout(() => {
    lastAutofilledByTab.delete(tabId);
    autofillExpiryTimers.delete(tabId);
  }, AUTOFILL_STATE_EXPIRY_MS);

  autofillExpiryTimers.set(tabId, timer);

  return { success: true };
}

/**
 * Get last autofilled credential for a tab.
 * @param data - The tab ID and optional domain to match.
 * @returns The stored credential or null.
 */
export function handleGetLastAutofilled(
  data: { tabId: number; domain?: string; username?: string }
): { success: boolean; credential: LastAutofilledCredential | null } {
  const { tabId, domain, username } = data;
  const credential = lastAutofilledByTab.get(tabId) || null;

  if (credential) {
    // Sanity check: Check if the credential has expired, if so, clear it immediately.
    if (Date.now() - credential.timestamp > AUTOFILL_STATE_EXPIRY_MS) {
      lastAutofilledByTab.delete(tabId);
      const timer = autofillExpiryTimers.get(tabId);
      if (timer) {
        clearTimeout(timer);
        autofillExpiryTimers.delete(tabId);
      }
      return { success: true, credential: null };
    }

    // If domain is provided, check for exact match (both values come from window.location.hostname)
    if (domain && credential.domain.toLowerCase() !== domain.toLowerCase()) {
      return { success: true, credential: null };
    }

    // If username is provided, check if it matches
    if (username && credential.username.toLowerCase() !== username.toLowerCase()) {
      return { success: true, credential: null };
    }

    return { success: true, credential };
  }

  return { success: true, credential: null };
}

/**
 * Clear last autofilled credential for a tab.
 * @param data - The tab ID.
 * @returns Success response.
 */
export function handleClearLastAutofilled(
  data: { tabId: number }
): { success: boolean } {
  const { tabId } = data;

  lastAutofilledByTab.delete(tabId);

  const timer = autofillExpiryTimers.get(tabId);
  if (timer) {
    clearTimeout(timer);
    autofillExpiryTimers.delete(tabId);
  }

  return { success: true };
}

/**
 * Clear the save prompt and last-autofilled state for every tab. Called on vault lock and logout.
 */
export function clearAllSavePromptState(): void {
  for (const timer of stateExpiryTimers.values()) {
    clearTimeout(timer);
  }

  for (const timer of autofillExpiryTimers.values()) {
    clearTimeout(timer);
  }

  savePromptStateByTab.clear();
  stateExpiryTimers.clear();
  lastAutofilledByTab.clear();
  autofillExpiryTimers.clear();
}