1use std::path::{Path, PathBuf};
17use std::sync::Arc;
18
19use adk_core::principal::SubjectRef;
20use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
21use adk_drivers::email::{ImapSmtpEmail, MailEndpoint, Mailbox, SenderPolicy, SystemTxtLookup};
22use adk_payments::wallet::{
23 BillingAccount, Debit, DebitRequest, Funding, ProviderBillingRail, RailPayment, StatementEntry,
24 Wallet, WalletPolicy, WalletProvider,
25};
26use async_trait::async_trait;
27use chrono::{DateTime, Utc};
28use serde::{Deserialize, Serialize};
29
30use super::project::{ProjectPaths, read_json, secret_in};
31use super::site::{EmailOptions, ProbeOptions, SiteOptions};
32
33fn config(error: impl std::fmt::Display) -> AdkError {
34 AdkError::config(error.to_string())
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum MailSecurityConfig {
41 Tls,
43 Starttls,
45 Plain,
47}
48
49#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase", deny_unknown_fields)]
52pub struct MailServerConfig {
53 pub host: String,
55 pub port: u16,
57 pub security: MailSecurityConfig,
59}
60
61impl MailServerConfig {
62 fn endpoint(&self) -> Result<MailEndpoint> {
63 match self.security {
64 MailSecurityConfig::Tls => MailEndpoint::tls(&self.host, self.port),
65 MailSecurityConfig::Starttls => MailEndpoint::starttls(&self.host, self.port),
66 MailSecurityConfig::Plain => MailEndpoint::plain(&self.host, self.port),
67 }
68 .map_err(config)
69 }
70}
71
72#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(rename_all = "camelCase", deny_unknown_fields)]
75pub struct SenderPolicyConfig {
76 pub dkim_selector: String,
78 pub spf_mechanism: String,
81}
82
83#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(rename_all = "camelCase", deny_unknown_fields)]
97pub struct EmailConfig {
98 pub imap: MailServerConfig,
100 pub smtp: MailServerConfig,
102 pub username: String,
104 pub password: String,
106 #[serde(default, skip_serializing_if = "Option::is_none")]
108 pub from: Option<String>,
109 #[serde(default, skip_serializing_if = "Option::is_none")]
111 pub from_name: Option<String>,
112 #[serde(default, skip_serializing_if = "Option::is_none")]
114 pub mailbox: Option<String>,
115 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub sender_policy: Option<SenderPolicyConfig>,
118}
119
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase", deny_unknown_fields)]
127pub struct UpkeepConfig {
128 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub lockfile: Option<PathBuf>,
131 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub advisories: Option<PathBuf>,
135 #[serde(default)]
137 pub certificate: bool,
138}
139
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase", deny_unknown_fields)]
166pub struct WalletConfig {
167 pub policy: WalletPolicy,
169 #[serde(default)]
171 pub billing: Vec<String>,
172}
173
174#[derive(Debug, Clone)]
178pub struct FileBillingAccount {
179 provider: String,
180 dir: PathBuf,
181}
182
183impl FileBillingAccount {
184 pub fn new(provider: impl Into<String>, dir: impl Into<PathBuf>) -> Self {
186 Self { provider: provider.into(), dir: dir.into() }
187 }
188
189 fn lines(path: &Path) -> Result<Vec<StatementEntry>> {
190 match std::fs::read_to_string(path) {
191 Ok(text) => text
192 .lines()
193 .filter(|line| !line.trim().is_empty())
194 .map(|line| {
195 serde_json::from_str(line)
196 .map_err(|e| config(format!("{}: {e}", path.display())))
197 })
198 .collect(),
199 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Vec::new()),
200 Err(error) => Err(config(format!("{}: {error}", path.display()))),
201 }
202 }
203}
204
205#[async_trait]
206impl BillingAccount for FileBillingAccount {
207 fn provider(&self) -> &str {
208 &self.provider
209 }
210
211 async fn charge(&self, payment: &RailPayment) -> Result<String> {
212 use std::io::Write as _;
213 let path = self.dir.join("charges.jsonl");
214 let reference = format!("{}-{}", self.provider, payment.payment_id);
215 if Self::lines(&path)?.iter().any(|line| line.id == reference) {
216 return Ok(reference);
217 }
218 let entry = StatementEntry {
219 id: reference.clone(),
220 reference: Some(payment.payment_id.clone()),
221 kind: adk_payments::wallet::StatementKind::Debit,
222 amount: payment.amount,
223 currency: payment.currency.clone(),
224 payee: Some(payment.payee.id.clone()),
225 at: Utc::now(),
226 };
227 std::fs::create_dir_all(&self.dir).map_err(config)?;
228 let mut file =
229 std::fs::OpenOptions::new().create(true).append(true).open(&path).map_err(config)?;
230 writeln!(file, "{}", serde_json::to_string(&entry).map_err(config)?).map_err(config)?;
231 Ok(reference)
232 }
233
234 async fn invoice(&self, from: DateTime<Utc>, to: DateTime<Utc>) -> Result<Vec<StatementEntry>> {
235 Ok(Self::lines(&self.dir.join("invoice.jsonl"))?
236 .into_iter()
237 .filter(|line| from <= line.at && line.at < to)
238 .collect())
239 }
240}
241
242#[derive(Debug, Clone)]
245pub struct NoStoredValue {
246 currency: String,
247}
248
249impl NoStoredValue {
250 pub fn new(currency: impl Into<String>) -> Self {
252 Self { currency: currency.into().to_ascii_uppercase() }
253 }
254}
255
256#[async_trait]
257impl WalletProvider for NoStoredValue {
258 fn name(&self) -> &str {
259 "none"
260 }
261
262 fn funding(&self) -> Funding {
263 Funding::StoredValue
264 }
265
266 fn currency(&self) -> &str {
267 &self.currency
268 }
269
270 async fn balance(&self) -> Result<u64> {
271 Ok(0)
272 }
273
274 async fn debit(&self, request: &DebitRequest) -> Result<Debit> {
275 Err(AdkError::new(
276 ErrorComponent::Guardrail,
277 ErrorCategory::ResourceExhausted,
278 adk_payments::wallet::WALLET_INSUFFICIENT_FUNDS_CODE,
279 format!(
280 "the wallet holds no funds, so it cannot pay {} {}; payments go through the \
281 providers that bill the owner's accounts",
282 request.amount, request.currency
283 ),
284 ))
285 }
286
287 async fn void(&self, _debit: &Debit) -> Result<()> {
288 Ok(())
289 }
290
291 async fn statement(
292 &self,
293 _from: DateTime<Utc>,
294 _to: DateTime<Utc>,
295 ) -> Result<Vec<StatementEntry>> {
296 Ok(Vec::new())
297 }
298}
299
300pub async fn configure(paths: &ProjectPaths, options: &mut SiteOptions) -> Result<Vec<String>> {
327 let mut set = Vec::new();
328 let domain = || -> Result<String> {
329 let text = std::fs::read_to_string(paths.root().join("site.toml"))
330 .map_err(|e| config(format!("{}: {e}", paths.root().join("site.toml").display())))?;
331 Ok(adk_site::content::SiteConfig::from_toml(&text).map_err(config)?.domain)
332 };
333
334 if let Some(email) = read_json::<EmailConfig>(&paths.root().join("email.json"))? {
335 let password = secret_in(paths, "email.json", &email.password)?;
336 let mut driver = ImapSmtpEmail::new(
337 email.imap.endpoint()?,
338 email.smtp.endpoint()?,
339 &email.username,
340 password.expose(),
341 )
342 .map_err(config)?;
343 if let Some(mailbox) = &email.mailbox {
344 driver = driver.with_mailbox(mailbox.clone());
345 }
346 let address = email.from.clone().unwrap_or_else(|| email.username.clone());
347 let mut from = Mailbox::new(&address);
348 if let Some(name) = &email.from_name {
349 from = from.with_name(name.clone());
350 }
351 let domain_auth = match &email.sender_policy {
352 Some(policy) => {
353 let sender = address.rsplit('@').next().unwrap_or_default().to_string();
354 let lookup = SystemTxtLookup::new().map_err(config)?;
355 Some((
356 Arc::new(lookup) as Arc<dyn adk_drivers::email::TxtLookup>,
357 SenderPolicy::new(sender, &policy.dkim_selector, &policy.spf_mechanism),
358 ))
359 }
360 None => None,
361 };
362 options.email = Some(EmailOptions { driver: Arc::new(driver), from, domain_auth });
363 set.push(format!("email as {address}"));
364 }
365
366 if let Some(upkeep) = read_json::<UpkeepConfig>(&paths.root().join("upkeep.json"))? {
367 match (&upkeep.lockfile, &upkeep.advisories) {
368 (Some(lockfile), Some(advisories)) => {
369 options.advisories = Some((
370 paths.root().join(lockfile),
371 Arc::new(crate::upkeep::AdvisoryDatabase::new(paths.root().join(advisories))),
372 ));
373 set.push(format!(
374 "advisories from {} against {}",
375 advisories.display(),
376 lockfile.display()
377 ));
378 }
379 (None, None) => {}
380 _ => {
381 return Err(config(
382 "upkeep.json: name both the `lockfile` and the `advisories` database",
383 ));
384 }
385 }
386 if upkeep.certificate {
387 let origin = url::Url::parse(&format!("https://{}", domain()?)).map_err(config)?;
388 let only =
389 std::collections::BTreeSet::from([adk_site::migrate::http::origin_of(&origin)]);
390 let http = adk_site::migrate::http::HttpClient::builder()
391 .egress(adk_site::migrate::http::EgressScope::Only(only))
392 .build()
393 .map_err(config)?;
394 options.certificate =
395 Some(Arc::new(crate::upkeep::OriginCertificate::new(Arc::new(http), origin)));
396 set.push("the origin's certificate".to_string());
397 }
398 }
399
400 if let Some(wallet) = read_json::<WalletConfig>(&paths.root().join("wallet.json"))? {
401 wallet.policy.validate()?;
402 let id = domain()?.replace('.', "-");
403 let currency = wallet.policy.currency.clone();
404 let mut builder =
405 Wallet::builder(id, wallet.policy.clone(), Arc::new(NoStoredValue::new(¤cy)));
406 for provider in &wallet.billing {
407 let dir = paths.data().join("wallet").join(provider);
408 builder = builder.rail(Arc::new(ProviderBillingRail::new(Arc::new(
409 FileBillingAccount::new(provider.clone(), dir),
410 ))));
411 }
412 std::fs::create_dir_all(paths.data()).map_err(config)?;
413 let pool = sqlx::SqlitePool::connect(&paths.database("wallet")).await.map_err(config)?;
414 let store = adk_payments::wallet::SqliteWalletStore::new(pool);
415 store.migrate().await?;
416 let mut builder = builder.store(Arc::new(store));
417 if !options.owner.is_empty() {
418 builder = builder.owner(SubjectRef::human(options.owner.clone()));
419 }
420 options.wallet = Some(builder.build()?);
421 set.push(format!("the wallet, billed through {}", wallet.billing.join(", ")));
422 }
423
424 let claim =
425 domain().ok().map(|domain| paths.data().join("claims").join(format!("{domain}.json")));
426 if options.probe.is_none() && claim.is_some_and(|claim| claim.exists()) {
427 options.probe = Some(ProbeOptions::system());
428 set.push("the Guardian's probe of the claimed domain".to_string());
429 }
430 Ok(set)
431}
432
433type SecretRef = String;
435
436#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(rename_all = "camelCase", deny_unknown_fields)]
457pub struct ChannelsConfig {
458 #[serde(default, skip_serializing_if = "Option::is_none")]
460 pub telegram: Option<TelegramChannel>,
461 #[serde(default, skip_serializing_if = "Option::is_none")]
463 pub whatsapp: Option<WhatsAppChannel>,
464 #[serde(default, skip_serializing_if = "Option::is_none")]
466 pub slack: Option<SlackChannel>,
467 #[serde(default, skip_serializing_if = "Option::is_none")]
469 pub discord: Option<DiscordChannel>,
470 #[serde(default, skip_serializing_if = "Option::is_none")]
472 pub matrix: Option<MatrixChannel>,
473}
474
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
477#[serde(rename_all = "camelCase", deny_unknown_fields)]
478pub struct TelegramChannel {
479 pub token: SecretRef,
481}
482
483#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
485#[serde(rename_all = "camelCase", deny_unknown_fields)]
486pub struct WhatsAppChannel {
487 pub phone_number_id: String,
489 pub access_token: SecretRef,
491 pub app_secret: SecretRef,
493 pub verify_token: SecretRef,
495 #[serde(default, skip_serializing_if = "Option::is_none")]
497 pub template: Option<WhatsAppTemplate>,
498}
499
500#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
502#[serde(rename_all = "camelCase", deny_unknown_fields)]
503pub struct WhatsAppTemplate {
504 pub name: String,
506 pub language: String,
508}
509
510#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
512#[serde(rename_all = "camelCase", deny_unknown_fields)]
513pub struct SlackChannel {
514 pub app_token: SecretRef,
516 pub bot_token: SecretRef,
518}
519
520#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
522#[serde(rename_all = "camelCase", deny_unknown_fields)]
523pub struct DiscordChannel {
524 pub token: SecretRef,
526}
527
528#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
530#[serde(rename_all = "camelCase", deny_unknown_fields)]
531pub struct MatrixChannel {
532 pub homeserver: String,
534 pub access_token: SecretRef,
536}
537
538#[derive(Clone, Default)]
541pub struct ChatConfig {
542 pub telegram: Option<adk_core::CredentialSecret>,
544 pub whatsapp: Option<WhatsAppSecrets>,
546 pub slack: Option<(adk_core::CredentialSecret, adk_core::CredentialSecret)>,
548 pub discord: Option<adk_core::CredentialSecret>,
550 pub matrix: Option<(String, adk_core::CredentialSecret)>,
552}
553
554#[derive(Clone, Debug)]
556pub struct WhatsAppSecrets {
557 pub phone_number_id: String,
559 pub access_token: adk_core::CredentialSecret,
561 pub app_secret: adk_core::CredentialSecret,
563 pub verify_token: adk_core::CredentialSecret,
565 pub template: Option<(String, String)>,
567}
568
569impl std::fmt::Debug for ChatConfig {
570 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
571 f.debug_struct("ChatConfig").field("platforms", &self.platforms()).finish_non_exhaustive()
572 }
573}
574
575impl ChatConfig {
576 pub fn platforms(&self) -> Vec<&'static str> {
578 [
579 ("Telegram", self.telegram.is_some()),
580 ("WhatsApp", self.whatsapp.is_some()),
581 ("Slack", self.slack.is_some()),
582 ("Discord", self.discord.is_some()),
583 ("Matrix", self.matrix.is_some()),
584 ]
585 .into_iter()
586 .filter_map(|(name, set)| set.then_some(name))
587 .collect()
588 }
589}
590
591pub fn chat(paths: &ProjectPaths) -> Result<Option<ChatConfig>> {
598 const FILE: &str = "channels.json";
599 let Some(channels) = read_json::<ChannelsConfig>(&paths.root().join(FILE))? else {
600 return Ok(None);
601 };
602 let secret = |source: &str| secret_in(paths, FILE, source);
603 let whatsapp = match &channels.whatsapp {
604 Some(w) => Some(WhatsAppSecrets {
605 phone_number_id: w.phone_number_id.clone(),
606 access_token: secret(&w.access_token)?,
607 app_secret: secret(&w.app_secret)?,
608 verify_token: secret(&w.verify_token)?,
609 template: w.template.as_ref().map(|t| (t.name.clone(), t.language.clone())),
610 }),
611 None => None,
612 };
613 Ok(Some(ChatConfig {
614 telegram: channels.telegram.as_ref().map(|t| secret(&t.token)).transpose()?,
615 whatsapp,
616 slack: match &channels.slack {
617 Some(s) => Some((secret(&s.app_token)?, secret(&s.bot_token)?)),
618 None => None,
619 },
620 discord: channels.discord.as_ref().map(|d| secret(&d.token)).transpose()?,
621 matrix: match &channels.matrix {
622 Some(m) => Some((m.homeserver.clone(), secret(&m.access_token)?)),
623 None => None,
624 },
625 }))
626}