use std::path::{Path, PathBuf};
use std::sync::Arc;
use adk_core::principal::SubjectRef;
use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
use adk_drivers::email::{ImapSmtpEmail, MailEndpoint, Mailbox, SenderPolicy, SystemTxtLookup};
use adk_payments::wallet::{
BillingAccount, Debit, DebitRequest, Funding, ProviderBillingRail, RailPayment, StatementEntry,
Wallet, WalletPolicy, WalletProvider,
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::project::{ProjectPaths, read_json, secret_in};
use super::site::{EmailOptions, ProbeOptions, SiteOptions};
fn config(error: impl std::fmt::Display) -> AdkError {
AdkError::config(error.to_string())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MailSecurityConfig {
Tls,
Starttls,
Plain,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MailServerConfig {
pub host: String,
pub port: u16,
pub security: MailSecurityConfig,
}
impl MailServerConfig {
fn endpoint(&self) -> Result<MailEndpoint> {
match self.security {
MailSecurityConfig::Tls => MailEndpoint::tls(&self.host, self.port),
MailSecurityConfig::Starttls => MailEndpoint::starttls(&self.host, self.port),
MailSecurityConfig::Plain => MailEndpoint::plain(&self.host, self.port),
}
.map_err(config)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SenderPolicyConfig {
pub dkim_selector: String,
pub spf_mechanism: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct EmailConfig {
pub imap: MailServerConfig,
pub smtp: MailServerConfig,
pub username: String,
pub password: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub from_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mailbox: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sender_policy: Option<SenderPolicyConfig>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct UpkeepConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lockfile: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub advisories: Option<PathBuf>,
#[serde(default)]
pub certificate: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WalletConfig {
pub policy: WalletPolicy,
#[serde(default)]
pub billing: Vec<String>,
}
#[derive(Debug, Clone)]
pub struct FileBillingAccount {
provider: String,
dir: PathBuf,
}
impl FileBillingAccount {
pub fn new(provider: impl Into<String>, dir: impl Into<PathBuf>) -> Self {
Self { provider: provider.into(), dir: dir.into() }
}
fn lines(path: &Path) -> Result<Vec<StatementEntry>> {
match std::fs::read_to_string(path) {
Ok(text) => text
.lines()
.filter(|line| !line.trim().is_empty())
.map(|line| {
serde_json::from_str(line)
.map_err(|e| config(format!("{}: {e}", path.display())))
})
.collect(),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
Err(error) => Err(config(format!("{}: {error}", path.display()))),
}
}
}
#[async_trait]
impl BillingAccount for FileBillingAccount {
fn provider(&self) -> &str {
&self.provider
}
async fn charge(&self, payment: &RailPayment) -> Result<String> {
use std::io::Write as _;
let path = self.dir.join("charges.jsonl");
let reference = format!("{}-{}", self.provider, payment.payment_id);
if Self::lines(&path)?.iter().any(|line| line.id == reference) {
return Ok(reference);
}
let entry = StatementEntry {
id: reference.clone(),
reference: Some(payment.payment_id.clone()),
kind: adk_payments::wallet::StatementKind::Debit,
amount: payment.amount,
currency: payment.currency.clone(),
payee: Some(payment.payee.id.clone()),
at: Utc::now(),
};
std::fs::create_dir_all(&self.dir).map_err(config)?;
let mut file =
std::fs::OpenOptions::new().create(true).append(true).open(&path).map_err(config)?;
writeln!(file, "{}", serde_json::to_string(&entry).map_err(config)?).map_err(config)?;
Ok(reference)
}
async fn invoice(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<Vec<StatementEntry>> {
Ok(Self::lines(&self.dir.join("invoice.jsonl"))?
.into_iter()
.filter(|line| from <= line.at && line.at < to)
.collect())
}
}
#[derive(Debug, Clone)]
pub struct NoStoredValue {
currency: String,
}
impl NoStoredValue {
pub fn new(currency: impl Into<String>) -> Self {
Self { currency: currency.into().to_ascii_uppercase() }
}
}
#[async_trait]
impl WalletProvider for NoStoredValue {
fn name(&self) -> &str {
"none"
}
fn funding(&self) -> Funding {
Funding::StoredValue
}
fn currency(&self) -> &str {
&self.currency
}
async fn balance(&self) -> Result<u64> {
Ok(0)
}
async fn debit(&self, request: &DebitRequest) -> Result<Debit> {
Err(AdkError::new(
ErrorComponent::Guardrail,
ErrorCategory::ResourceExhausted,
adk_payments::wallet::WALLET_INSUFFICIENT_FUNDS_CODE,
format!(
"the wallet holds no funds, so it cannot pay {} {}; payments go through the \
providers that bill the owner's accounts",
request.amount, request.currency
),
))
}
async fn void(&self, _debit: &Debit) -> Result<()> {
Ok(())
}
async fn statement(
&self,
_from: DateTime<Utc>,
_to: DateTime<Utc>,
) -> Result<Vec<StatementEntry>> {
Ok(Vec::new())
}
}
pub async fn configure(paths: &ProjectPaths, options: &mut SiteOptions) -> Result<Vec<String>> {
let mut set = Vec::new();
let domain = || -> Result<String> {
let text = std::fs::read_to_string(paths.root().join("site.toml"))
.map_err(|e| config(format!("{}: {e}", paths.root().join("site.toml").display())))?;
Ok(adk_site::content::SiteConfig::from_toml(&text).map_err(config)?.domain)
};
if let Some(email) = read_json::<EmailConfig>(&paths.root().join("email.json"))? {
let password = secret_in(paths, "email.json", &email.password)?;
let mut driver = ImapSmtpEmail::new(
email.imap.endpoint()?,
email.smtp.endpoint()?,
&email.username,
password.expose(),
)
.map_err(config)?;
if let Some(mailbox) = &email.mailbox {
driver = driver.with_mailbox(mailbox.clone());
}
let address = email.from.clone().unwrap_or_else(|| email.username.clone());
let mut from = Mailbox::new(&address);
if let Some(name) = &email.from_name {
from = from.with_name(name.clone());
}
let domain_auth = match &email.sender_policy {
Some(policy) => {
let sender = address.rsplit('@').next().unwrap_or_default().to_string();
let lookup = SystemTxtLookup::new().map_err(config)?;
Some((
Arc::new(lookup) as Arc<dyn adk_drivers::email::TxtLookup>,
SenderPolicy::new(sender, &policy.dkim_selector, &policy.spf_mechanism),
))
}
None => None,
};
options.email = Some(EmailOptions { driver: Arc::new(driver), from, domain_auth });
set.push(format!("email as {address}"));
}
if let Some(upkeep) = read_json::<UpkeepConfig>(&paths.root().join("upkeep.json"))? {
match (&upkeep.lockfile, &upkeep.advisories) {
(Some(lockfile), Some(advisories)) => {
options.advisories = Some((
paths.root().join(lockfile),
Arc::new(crate::upkeep::AdvisoryDatabase::new(paths.root().join(advisories))),
));
set.push(format!(
"advisories from {} against {}",
advisories.display(),
lockfile.display()
));
}
(None, None) => {}
_ => {
return Err(config(
"upkeep.json: name both the `lockfile` and the `advisories` database",
));
}
}
if upkeep.certificate {
let origin = url::Url::parse(&format!("https://{}", domain()?)).map_err(config)?;
let only =
std::collections::BTreeSet::from([adk_site::migrate::http::origin_of(&origin)]);
let http = adk_site::migrate::http::HttpClient::builder()
.egress(adk_site::migrate::http::EgressScope::Only(only))
.build()
.map_err(config)?;
options.certificate =
Some(Arc::new(crate::upkeep::OriginCertificate::new(Arc::new(http), origin)));
set.push("the origin's certificate".to_string());
}
}
if let Some(wallet) = read_json::<WalletConfig>(&paths.root().join("wallet.json"))? {
wallet.policy.validate()?;
let id = domain()?.replace('.', "-");
let currency = wallet.policy.currency.clone();
let mut builder =
Wallet::builder(id, wallet.policy.clone(), Arc::new(NoStoredValue::new(¤cy)));
for provider in &wallet.billing {
let dir = paths.data().join("wallet").join(provider);
builder = builder.rail(Arc::new(ProviderBillingRail::new(Arc::new(
FileBillingAccount::new(provider.clone(), dir),
))));
}
std::fs::create_dir_all(paths.data()).map_err(config)?;
let pool = sqlx::SqlitePool::connect(&paths.database("wallet")).await.map_err(config)?;
let store = adk_payments::wallet::SqliteWalletStore::new(pool);
store.migrate().await?;
let mut builder = builder.store(Arc::new(store));
if !options.owner.is_empty() {
builder = builder.owner(SubjectRef::human(options.owner.clone()));
}
options.wallet = Some(builder.build()?);
set.push(format!("the wallet, billed through {}", wallet.billing.join(", ")));
}
let claim =
domain().ok().map(|domain| paths.data().join("claims").join(format!("{domain}.json")));
if options.probe.is_none() && claim.is_some_and(|claim| claim.exists()) {
options.probe = Some(ProbeOptions::system());
set.push("the Guardian's probe of the claimed domain".to_string());
}
Ok(set)
}
type SecretRef = String;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct ChannelsConfig {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub telegram: Option<TelegramChannel>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub whatsapp: Option<WhatsAppChannel>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub slack: Option<SlackChannel>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub discord: Option<DiscordChannel>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub matrix: Option<MatrixChannel>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct TelegramChannel {
pub token: SecretRef,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WhatsAppChannel {
pub phone_number_id: String,
pub access_token: SecretRef,
pub app_secret: SecretRef,
pub verify_token: SecretRef,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub template: Option<WhatsAppTemplate>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WhatsAppTemplate {
pub name: String,
pub language: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SlackChannel {
pub app_token: SecretRef,
pub bot_token: SecretRef,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DiscordChannel {
pub token: SecretRef,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct MatrixChannel {
pub homeserver: String,
pub access_token: SecretRef,
}
#[derive(Clone, Default)]
pub struct ChatConfig {
pub telegram: Option<adk_core::CredentialSecret>,
pub whatsapp: Option<WhatsAppSecrets>,
pub slack: Option<(adk_core::CredentialSecret, adk_core::CredentialSecret)>,
pub discord: Option<adk_core::CredentialSecret>,
pub matrix: Option<(String, adk_core::CredentialSecret)>,
}
#[derive(Clone, Debug)]
pub struct WhatsAppSecrets {
pub phone_number_id: String,
pub access_token: adk_core::CredentialSecret,
pub app_secret: adk_core::CredentialSecret,
pub verify_token: adk_core::CredentialSecret,
pub template: Option<(String, String)>,
}
impl std::fmt::Debug for ChatConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ChatConfig").field("platforms", &self.platforms()).finish_non_exhaustive()
}
}
impl ChatConfig {
pub fn platforms(&self) -> Vec<&'static str> {
[
("Telegram", self.telegram.is_some()),
("WhatsApp", self.whatsapp.is_some()),
("Slack", self.slack.is_some()),
("Discord", self.discord.is_some()),
("Matrix", self.matrix.is_some()),
]
.into_iter()
.filter_map(|(name, set)| set.then_some(name))
.collect()
}
}
pub fn chat(paths: &ProjectPaths) -> Result<Option<ChatConfig>> {
const FILE: &str = "channels.json";
let Some(channels) = read_json::<ChannelsConfig>(&paths.root().join(FILE))? else {
return Ok(None);
};
let secret = |source: &str| secret_in(paths, FILE, source);
let whatsapp = match &channels.whatsapp {
Some(w) => Some(WhatsAppSecrets {
phone_number_id: w.phone_number_id.clone(),
access_token: secret(&w.access_token)?,
app_secret: secret(&w.app_secret)?,
verify_token: secret(&w.verify_token)?,
template: w.template.as_ref().map(|t| (t.name.clone(), t.language.clone())),
}),
None => None,
};
Ok(Some(ChatConfig {
telegram: channels.telegram.as_ref().map(|t| secret(&t.token)).transpose()?,
whatsapp,
slack: match &channels.slack {
Some(s) => Some((secret(&s.app_token)?, secret(&s.bot_token)?)),
None => None,
},
discord: channels.discord.as_ref().map(|d| secret(&d.token)).transpose()?,
matrix: match &channels.matrix {
Some(m) => Some((m.homeserver.clone(), secret(&m.access_token)?)),
None => None,
},
}))
}