Skip to content

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

3.2 KB
Raw Blame
//! The email routing set a push sends.

use std::collections::{HashMap, HashSet};

use serde_json::Value;

use super::db::value_string;
use super::types::{ClaimedEmailAddress, EmailRoutingPush, ManifestRevision};
use crate::vault_codec::row::{is_deleted, rows_of, str_col, truthy};
use crate::vault_codec::Manifest;
use crate::vault_model::names::{DELETED_AT_COL, FIELD_KEY_COL, FIELD_VALUES_TABLE, ID_COL, ITEMS_TABLE, ITEM_ID_COL};

/// The field key of an item's login email.
const FIELD_KEY_LOGIN_EMAIL: &str = "login.email";

/// Build the routing set from the canonicalized manifests, the user's own included, read at `manifest_revisions`.
pub(crate) fn build_email_routing(manifests: &[Manifest], private_email_domains: &[String], manifest_revisions: &HashMap<String, i64>) -> EmailRoutingPush {
    let mut by_pair: HashMap<String, ClaimedEmailAddress> = HashMap::new();
    let mut order: Vec<String> = Vec::new();

    for manifest in manifests {
        let live_item_ids: HashSet<String> = rows_of(&manifest.tables, ITEMS_TABLE)
            .iter()
            .filter(|row| !is_deleted(row) && row.get(DELETED_AT_COL).is_none_or(Value::is_null))
            .filter_map(|row| row.get(ID_COL).map(value_string))
            .collect();

        for field_value in rows_of(&manifest.tables, FIELD_VALUES_TABLE) {
            if str_col(field_value, FIELD_KEY_COL) != Some(FIELD_KEY_LOGIN_EMAIL) || is_deleted(field_value) {
                continue;
            }
            let item_id = field_value.get(ITEM_ID_COL).map(value_string).unwrap_or_default();
            if !live_item_ids.contains(&item_id) {
                continue;
            }

            let address = field_value.get("Value").and_then(Value::as_str).map(|value| value.trim().to_lowercase()).unwrap_or_default();
            let domain = match address.split_once('@') {
                Some((_, domain)) if !domain.is_empty() => domain.to_string(),
                _ => continue,
            };
            if !private_email_domains.iter().any(|candidate| candidate.trim().eq_ignore_ascii_case(&domain)) {
                continue;
            }

            let paused = truthy(field_value.get("IsDisabled"));
            let pair_key = format!("{}\0{}", address, manifest.manifest_id);
            match by_pair.get_mut(&pair_key) {
                // Several items in one manifest may carry the same address; one of them still wanting mail keeps it routed.
                Some(existing) => existing.paused = existing.paused && paused,
                None => {
                    order.push(pair_key.clone());
                    by_pair.insert(pair_key, ClaimedEmailAddress { address, manifest_id: manifest.manifest_id.clone(), paused });
                }
            }
        }
    }

    EmailRoutingPush {
        email_address_list: order.into_iter().filter_map(|key| by_pair.remove(&key)).collect(),
        covered_manifest_ids: manifests.iter().map(|manifest| manifest.manifest_id.clone()).collect(),
        base_revisions: manifests
            .iter()
            .map(|manifest| ManifestRevision { manifest_id: manifest.manifest_id.clone(), revision: manifest_revisions.get(&manifest.manifest_id).copied().unwrap_or(0), encrypted_name: None, key_version: 0 })
            .collect(),
    }
}