use serde::{Deserialize, Serialize};
use super::{ActionAddress, Caller, RemoteActionTarget};
pub const PROVIDER: &str = "tilo.accounts";
pub const RESOURCE: &str = "accounts";
pub const LIST: &str = "list";
pub const WATCH: &str = "watch";
pub const ADD_MAIL: &str = "add-mail";
pub const ADD_MAIL_WITH_ITEM: &str = "add-mail-with-item";
pub const RECONNECT: &str = "reconnect";
pub const CHECK: &str = "check";
pub const REPLACE_PASSWORD: &str = "replace-password";
pub const REMOVE: &str = "remove";
pub const DISCOVER_CALENDARS: &str = "discover-calendars";
pub const SET_CALENDARS: &str = "set-calendars";
pub const FIND_SERVERS: &str = "find-servers";
pub const BEGIN_SIGN_IN: &str = "begin-sign-in";
pub const CANCEL_SIGN_IN: &str = "cancel-sign-in";
pub const SET_SERVICES: &str = "set-services";
#[must_use]
pub fn sign_in_grant_id(app: &str, workspace: &str) -> String {
format!("manifest:{app}:{workspace}:sign-ins")
}
#[must_use]
pub fn signs_in(caller: &Caller, app: &str, workspace: &str) -> bool {
let id = sign_in_grant_id(app, workspace);
caller.granted().iter().any(|grant| {
grant.id.as_str() == id
&& grant.grantee == tilo_action_policy::Grantee::app(app)
&& grant.answer == tilo_action_policy::Answer::Allow
})
}
pub const SIGN_INS: &str = "sign-ins";
pub const SET_FILES_MODE: &str = "set-files-mode";
pub const CLOUD_ACCOUNTS: &str = "cloud-accounts";
pub const CLOUD_CREDENTIAL: &str = "cloud-credential";
pub const REPORT_SYNC_VERB: &str = "report-sync";
pub const SYNC_NOW: &str = "sync-now";
pub const PAUSE_SYNC: &str = "pause-sync";
pub const RESUME_SYNC: &str = "resume-sync";
pub const BEGIN_CLOUD_SIGN_IN: &str = "begin-cloud-sign-in";
pub const SUBMIT_SIGN_IN_CODE: &str = "submit-sign-in-code";
pub const ACCOUNTS_RECORD_KIND: &str = "tilo.accounts";
pub const SAVE_ACCOUNT: &str = "save-account";
pub const REMOVE_ACCOUNT: &str = "remove-account";
pub const REPORT_SYNC: &str = "report-sync";
fn accounts_step(verb: &str) -> crate::ActionEffect {
crate::ActionEffect::new(tilo_app_id::apps::SETTINGS, ACCOUNTS_RECORD_KIND, verb)
}
#[must_use]
pub fn effects(resource: &str, action: &str) -> Vec<crate::ActionEffect> {
use super::person_vault::{KEEP_SEALED, KEEP_USES, REMOVE_SEALED, vault_step};
let (vault, accounts): (&[&str], &[&str]) = match (resource, action) {
(RESOURCE, ADD_MAIL | BEGIN_SIGN_IN) => {
(&[KEEP_SEALED, KEEP_USES, REMOVE_SEALED], &[SAVE_ACCOUNT])
}
(RESOURCE, REPLACE_PASSWORD) => (&[KEEP_SEALED], &[]),
(RESOURCE, BEGIN_CLOUD_SIGN_IN | SUBMIT_SIGN_IN_CODE) => (&[KEEP_SEALED], &[SAVE_ACCOUNT]),
(RESOURCE, REMOVE) => (&[REMOVE_SEALED], &[REMOVE_ACCOUNT]),
(RESOURCE, ADD_MAIL_WITH_ITEM | DISCOVER_CALENDARS) => {
(&[KEEP_USES, REMOVE_SEALED], &[SAVE_ACCOUNT])
}
(RESOURCE, RECONNECT | CHECK) => (&[KEEP_USES], &[REPORT_SYNC]),
(RESOURCE, SET_SERVICES) => (
&[KEEP_SEALED, KEEP_USES, REMOVE_SEALED],
&[SAVE_ACCOUNT, REMOVE_ACCOUNT],
),
(RESOURCE, SET_CALENDARS) => (&[REMOVE_SEALED], &[SAVE_ACCOUNT, REMOVE_ACCOUNT]),
(RESOURCE, SET_FILES_MODE) => (&[], &[SAVE_ACCOUNT]),
(RESOURCE, CLOUD_CREDENTIAL) => (&[KEEP_USES, KEEP_SEALED], &[]),
(RESOURCE, REPORT_SYNC_VERB) => (&[], &[REPORT_SYNC]),
_ => (&[], &[]),
};
vault
.iter()
.map(|verb| vault_step(verb))
.chain(accounts.iter().map(|verb| accounts_step(verb)))
.collect()
}
#[must_use]
pub fn target(action: &str) -> RemoteActionTarget {
RemoteActionTarget {
provider: PROVIDER.to_owned(),
address: ActionAddress::new(RESOURCE, action),
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Provider {
Google,
Microsoft,
Icloud,
Nextcloud,
#[default]
Other,
}
impl Provider {
#[must_use]
pub fn from_key(key: &str) -> Option<Self> {
serde_json::from_value(serde_json::Value::String(key.to_owned())).ok()
}
#[must_use]
pub const fn key(self) -> &'static str {
match self {
Self::Google => "google",
Self::Microsoft => "microsoft",
Self::Icloud => "icloud",
Self::Nextcloud => "nextcloud",
Self::Other => "other",
}
}
#[must_use]
pub const fn signs_in_on_its_page(self) -> bool {
matches!(self, Self::Google | Self::Microsoft | Self::Nextcloud)
}
#[must_use]
pub const fn offers(self) -> Services {
match self {
Self::Google | Self::Icloud => Services {
mail: true,
calendar: true,
files: false,
},
Self::Microsoft | Self::Other => Services {
mail: true,
calendar: false,
files: false,
},
Self::Nextcloud => Services {
mail: false,
calendar: true,
files: true,
},
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CloudKind {
GoogleDrive,
OneDrive,
Dropbox,
IcloudDrive,
Webdav,
}
impl CloudKind {
#[must_use]
pub const fn type_id(self) -> &'static str {
match self {
Self::GoogleDrive => "google-drive",
Self::OneDrive => "onedrive",
Self::Dropbox => "dropbox",
Self::IcloudDrive => "icloud-drive",
Self::Webdav => "webdav",
}
}
#[must_use]
pub const fn label(self) -> &'static str {
match self {
Self::GoogleDrive => "Google Drive",
Self::OneDrive => "OneDrive",
Self::Dropbox => "Dropbox",
Self::IcloudDrive => "iCloud Drive",
Self::Webdav => "WebDAV",
}
}
#[must_use]
pub const fn signs_in_on_its_page(self) -> bool {
matches!(self, Self::GoogleDrive | Self::OneDrive | Self::Dropbox)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Services {
#[serde(default)]
pub mail: bool,
#[serde(default)]
pub calendar: bool,
#[serde(default)]
pub files: bool,
}
impl Default for Services {
fn default() -> Self {
Self {
mail: true,
calendar: false,
files: false,
}
}
}
impl Services {
#[must_use]
pub const fn within(self, provider: Provider) -> Self {
let offered = provider.offers();
Self {
mail: self.mail && offered.mail,
calendar: self.calendar && offered.calendar,
files: self.files && offered.files,
}
}
#[must_use]
pub const fn none(self) -> bool {
!(self.mail || self.calendar || self.files)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MailAccount {
pub id: String,
pub address: String,
pub display_name: String,
pub incoming_host: String,
pub incoming_port: u16,
pub outgoing_host: String,
pub outgoing_port: u16,
pub has_secret: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub identities: Vec<String>,
#[serde(default)]
pub provider: Provider,
#[serde(default)]
pub services: Services,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub server: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SigningIn {
pub id: String,
pub provider: Provider,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub server: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub failed: Option<String>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MailAccounts {
pub accounts: Vec<MailAccount>,
#[serde(default)]
pub active: String,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub signing_in: Vec<SigningIn>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub signs_in_with: Vec<Provider>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FindServers {
pub address: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ServerAt {
pub name: String,
pub port: u16,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FoundServers {
pub provider: Provider,
pub incoming: ServerAt,
pub outgoing: ServerAt,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BeginSignIn {
pub provider: Provider,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub server: String,
#[serde(default)]
pub mail: bool,
#[serde(default)]
pub calendar: bool,
#[serde(default)]
pub files: bool,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub address: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub account: String,
}
impl BeginSignIn {
#[must_use]
pub const fn services(&self) -> Services {
Services {
mail: self.mail,
calendar: self.calendar,
files: self.files,
}
}
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BeginCloudSignIn {
pub kind: CloudKind,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub server: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub username: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub password: String,
}
impl std::fmt::Debug for BeginCloudSignIn {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BeginCloudSignIn")
.field("kind", &self.kind)
.field("name", &self.name)
.field("server", &self.server)
.field("username", &self.username)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignInStep {
pub id: String,
pub open: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub code: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubmitSignInCode {
pub sign_in: String,
pub code: String,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelSignIn {
pub sign_in: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetServices {
pub account: String,
#[serde(default)]
pub mail: bool,
#[serde(default)]
pub calendar: bool,
#[serde(default)]
pub files: bool,
}
impl SetServices {
#[must_use]
pub const fn services(&self) -> Services {
Services {
mail: self.mail,
calendar: self.calendar,
files: self.files,
}
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MailSignIn {
pub id: String,
pub title: String,
pub username: String,
pub places: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub account: Option<SignedInAccount>,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignedInAccount {
pub id: String,
pub kind: String,
pub name: String,
pub address: String,
pub server: String,
pub read_only: bool,
pub enabled: bool,
#[serde(default)]
pub settings: serde_json::Value,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MailSignIns {
pub sign_ins: Vec<MailSignIn>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetFilesMode {
pub account: String,
pub mode: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudAccount {
pub account: serde_json::Value,
#[serde(default)]
pub signed_in: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudAccounts {
pub accounts: Vec<CloudAccount>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudCredentialAt {
pub account: String,
#[serde(default)]
pub rejected: bool,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudCredential {
pub kind: CloudCredentialKind,
#[serde(default)]
pub username: String,
pub secret: String,
#[serde(default)]
pub headers: Vec<CloudHeader>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at_ms: Option<u64>,
}
impl std::fmt::Debug for CloudCredential {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("CloudCredential")
.field("kind", &self.kind)
.field("username", &self.username)
.field("headers", &self.headers.len())
.field("expires_at_ms", &self.expires_at_ms)
.finish_non_exhaustive()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum CloudCredentialKind {
Basic,
Bearer,
Session,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CloudHeader {
pub name: String,
pub value: String,
}
impl std::fmt::Debug for CloudHeader {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("CloudHeader")
.field("name", &self.name)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncReport {
pub account: String,
pub health: String,
#[serde(default)]
pub signed_in: bool,
#[serde(default)]
pub message: String,
}
#[must_use]
pub fn is_cloud_credential(asked: &RemoteActionTarget) -> bool {
*asked == target(CLOUD_CREDENTIAL)
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SyncControl {
pub account: String,
}
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddMailAccount {
pub address: String,
#[serde(default)]
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
#[serde(default)]
pub incoming_host: String,
#[serde(default = "default_imaps_port")]
pub incoming_port: u16,
#[serde(default)]
pub outgoing_host: String,
#[serde(default = "default_submissions_port")]
pub outgoing_port: u16,
#[serde(default)]
pub password: String,
#[serde(default)]
pub identities: Vec<String>,
#[serde(default)]
pub services: Services,
}
impl std::fmt::Debug for AddMailAccount {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("AddMailAccount")
.field("address", &self.address)
.field("display_name", &self.display_name)
.field("username", &self.username)
.field("incoming_host", &self.incoming_host)
.field("incoming_port", &self.incoming_port)
.field("outgoing_host", &self.outgoing_host)
.field("outgoing_port", &self.outgoing_port)
.field("services", &self.services)
.finish_non_exhaustive()
}
}
const fn default_imaps_port() -> u16 {
993
}
const fn default_submissions_port() -> u16 {
465
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct AddMailWithItem {
pub address: String,
#[serde(default)]
pub display_name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub username: Option<String>,
pub incoming_host: String,
#[serde(default = "default_imaps_port")]
pub incoming_port: u16,
pub outgoing_host: String,
#[serde(default = "default_submissions_port")]
pub outgoing_port: u16,
pub password: super::person_vault::ItemRef,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub reason: String,
}
#[cfg(test)]
mod tests {
#![allow(
clippy::unwrap_used,
clippy::panic,
reason = "in a test these are the assertion, not a hazard"
)]
use super::*;
#[test]
fn an_older_page_reads_past_a_field_added_since() {
let mut answered = serde_json::to_value(MailAccounts {
accounts: vec![MailAccount {
address: "ada@example.test".into(),
..MailAccount::default()
}],
..MailAccounts::default()
})
.unwrap();
answered["accounts"][0]["addedLater"] = serde_json::json!("anything");
answered["addedLater"] = serde_json::json!(1);
let read: MailAccounts = serde_json::from_value(answered).unwrap();
assert_eq!(read.accounts[0].address, "ada@example.test");
let source = include_str!("person_accounts.rs");
assert!(!source.contains(concat!("deny_unknown", "_fields")));
}
#[test]
fn nothing_read_back_carries_the_sign_in() {
let adding = AddMailAccount {
address: "ada@example.com".into(),
display_name: "Ada".into(),
username: None,
incoming_host: "imap.example.com".into(),
incoming_port: 993,
outgoing_host: "smtp.example.com".into(),
outgoing_port: 465,
password: "hunter2".into(),
identities: Vec::new(),
services: Services::default(),
};
let printed = format!("{adding:?}");
assert!(!printed.contains("hunter2"), "{printed}");
assert!(printed.contains("imap.example.com"), "{printed}");
let read = MailAccount {
id: "ada@example.com".into(),
address: "ada@example.com".into(),
display_name: "Ada".into(),
incoming_host: "imap.example.com".into(),
incoming_port: 993,
outgoing_host: "smtp.example.com".into(),
outgoing_port: 465,
has_secret: true,
identities: Vec::new(),
..Default::default()
};
let json = serde_json::to_value(&read).unwrap();
assert!(json.get("password").is_none());
assert_eq!(json["hasSecret"], serde_json::json!(true));
}
#[test]
fn a_mail_account_defaults_to_the_secure_ports() {
let adding: AddMailAccount = serde_json::from_value(serde_json::json!({
"address": "ada@example.com",
"incomingHost": "imap.example.com",
"outgoingHost": "smtp.example.com",
"password": "hunter2",
}))
.unwrap();
assert_eq!(adding.incoming_port, 993);
assert_eq!(adding.outgoing_port, 465);
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReplacePassword {
pub account: String,
pub password: String,
}
impl std::fmt::Debug for ReplacePassword {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ReplacePassword")
.field("account", &self.account)
.finish_non_exhaustive()
}
}
#[derive(Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetCalendars {
pub account: String,
#[serde(default)]
pub calendars: Vec<String>,
}