Skip to main content

adk_website/deploy/
config.rs

1//! A served site's settings from its project's configuration files (spec 3.5 §7.13, §7.14,
2//! §7.17, §7.20): what the `adk-website` binary and `adk-rust website new` read into
3//! [`SiteOptions`] with [`configure`].
4//!
5//! | File | Sets | Holds |
6//! |---|---|---|
7//! | `email.json` | [`SiteOptions::email`] | The site's mailbox over IMAP and SMTP ([`EmailConfig`]): the Inbox reads it, nurture and the outbox send from it |
8//! | `upkeep.json` | [`SiteOptions::advisories`], [`SiteOptions::certificate`] | The edge's `Cargo.lock` with a RustSec advisory database checkout, and whether the origin's certificate is read ([`UpkeepConfig`]) |
9//! | `wallet.json` | [`SiteOptions::wallet`] | The owner's wallet policy and the providers that bill the owner's own accounts ([`WalletConfig`]) |
10//! | `channels.json` | Read by [`chat`] for a host that builds the adapters into [`SiteOptions::chat`] | The chat platforms the site talks on ([`ChannelsConfig`]): Telegram, WhatsApp, Slack, Discord and Matrix (spec 3.5 §10 X12) |
11//! | `data/claims/{domain}.json` | [`SiteOptions::probe`] | The owner's domain claim, which `adk-rust site migrate` keeps; the Guardian proves it again with the system's resolver on every probe |
12//!
13//! Secrets are `env:VAR` or `file:PATH`, a path relative to the project, never the secret
14//! itself (A-I19). A file that is absent leaves its options as they were.
15
16use 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/// How a mail server connection is secured.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "snake_case")]
40pub enum MailSecurityConfig {
41    /// TLS from the start, as on ports 465 and 993.
42    Tls,
43    /// Upgraded with STARTTLS, as on port 587.
44    Starttls,
45    /// No TLS: loopback servers only.
46    Plain,
47}
48
49/// One mail server.
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "camelCase", deny_unknown_fields)]
52pub struct MailServerConfig {
53    /// The host name, which TLS verifies.
54    pub host: String,
55    /// The port.
56    pub port: u16,
57    /// How the connection is secured.
58    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/// The sender policy SPF, DKIM and DMARC are checked against before bulk sends.
73#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
74#[serde(rename_all = "camelCase", deny_unknown_fields)]
75pub struct SenderPolicyConfig {
76    /// The DKIM selector the sending service signs with.
77    pub dkim_selector: String,
78    /// The SPF mechanism that authorises the sending service, such as
79    /// `include:_spf.mail.example`.
80    pub spf_mechanism: String,
81}
82
83/// The site's email in `email.json` (spec 3.5 §7.13).
84///
85/// ```json
86/// {
87///   "imap": { "host": "imap.mail.example", "port": 993, "security": "tls" },
88///   "smtp": { "host": "smtp.mail.example", "port": 587, "security": "starttls" },
89///   "username": "hello@juniper.example",
90///   "password": "env:JUNIPER_MAIL_PASSWORD",
91///   "fromName": "Juniper Bakery",
92///   "senderPolicy": { "dkimSelector": "mail", "spfMechanism": "include:_spf.mail.example" }
93/// }
94/// ```
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
96#[serde(rename_all = "camelCase", deny_unknown_fields)]
97pub struct EmailConfig {
98    /// Where the inbox is read.
99    pub imap: MailServerConfig,
100    /// Where mail is sent.
101    pub smtp: MailServerConfig,
102    /// The account.
103    pub username: String,
104    /// Its password, as `env:VAR` or `file:PATH`.
105    pub password: String,
106    /// The address the site sends from; the account's when not set.
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub from: Option<String>,
109    /// The display name it sends as.
110    #[serde(default, skip_serializing_if = "Option::is_none")]
111    pub from_name: Option<String>,
112    /// The mailbox read; `INBOX` when not set.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub mailbox: Option<String>,
115    /// The sender policy bulk sends wait for, checked through the system's resolver.
116    #[serde(default, skip_serializing_if = "Option::is_none")]
117    pub sender_policy: Option<SenderPolicyConfig>,
118}
119
120/// The hosting job's sources in `upkeep.json` (spec 3.5 §7.20, S10).
121///
122/// ```json
123/// { "lockfile": "Cargo.lock", "advisories": "/var/lib/advisory-db", "certificate": true }
124/// ```
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase", deny_unknown_fields)]
127pub struct UpkeepConfig {
128    /// The edge's `Cargo.lock`, relative to the project.
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    pub lockfile: Option<PathBuf>,
131    /// A checkout of the RustSec advisory database (`github.com/rustsec/advisory-db`),
132    /// relative to the project.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub advisories: Option<PathBuf>,
135    /// Whether the certificate the site's origin presents is read for renewal proposals.
136    #[serde(default)]
137    pub certificate: bool,
138}
139
140/// The owner's wallet in `wallet.json` (spec 3.5 §7.14).
141///
142/// The policy's mandates name their rails; each provider in `billing` is a
143/// `provider_billing:{provider}` rail that bills the owner's own account at that provider:
144/// the wallet authorises each charge within its mandate and cap and records it in
145/// `data/wallet/{provider}/charges.jsonl`, and reconciliation reads the provider's invoice
146/// lines the owner exports to `data/wallet/{provider}/invoice.jsonl`. The wallet holds no
147/// funds of its own here: a payment on a wallet-funded rail is refused.
148///
149/// ```json
150/// {
151///   "policy": {
152///     "currency": "KES",
153///     "period": "month",
154///     "categories": {
155///       "hosting": { "capPerPeriod": 300000, "maxPerPayment": 300000,
156///                    "payees": [{ "id": "hostco" }], "rail": "provider_billing:hostco" }
157///     },
158///     "anomaly": { "multiple": 3.0, "trailingDays": 30, "minHistoryDays": 7, "minAmount": 0 },
159///     "reconciliation": "monthly"
160///   },
161///   "billing": ["hostco"]
162/// }
163/// ```
164#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase", deny_unknown_fields)]
166pub struct WalletConfig {
167    /// The owner's policy: mandates per category, caps, payees and rails.
168    pub policy: WalletPolicy,
169    /// The providers that bill the owner's own accounts.
170    #[serde(default)]
171    pub billing: Vec<String>,
172}
173
174/// A provider account that bills the owner directly, kept in files (spec 3.5 §7.14): each
175/// charge the wallet allowed is appended to `charges.jsonl`, and the provider's invoice is
176/// the `invoice.jsonl` the owner exports from the provider.
177#[derive(Debug, Clone)]
178pub struct FileBillingAccount {
179    provider: String,
180    dir: PathBuf,
181}
182
183impl FileBillingAccount {
184    /// The account at `provider`, its files in `dir`.
185    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/// The funding of a wallet whose rails all bill the owner's accounts: it holds nothing, so a
243/// payment on a wallet-funded rail is refused until the owner gives the wallet a provider.
244#[derive(Debug, Clone)]
245pub struct NoStoredValue {
246    currency: String,
247}
248
249impl NoStoredValue {
250    /// No funds in `currency`.
251    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
300/// Sets `options` from the configuration files in `paths` (spec 3.5 §7.17): the email, the
301/// upkeep sources, the wallet and the Guardian's probe. Returns what it set, in words, for
302/// the person starting the site.
303///
304/// # Example
305///
306/// ```rust
307/// use adk_website::deploy::{ProjectPaths, SiteOptions, config::configure};
308///
309/// # #[tokio::main(flavor = "current_thread")]
310/// # async fn main() -> adk_core::Result<()> {
311/// let dir = tempfile::tempdir().unwrap();
312/// std::fs::write(dir.path().join("upkeep.json"), r#"{ "lockfile": "Cargo.lock", "advisories": "advisory-db" }"#).unwrap();
313/// let mut options = SiteOptions::default();
314/// let set = configure(&ProjectPaths::new(dir.path()), &mut options).await?;
315/// assert!(options.advisories.is_some());
316/// assert_eq!(set, ["advisories from advisory-db against Cargo.lock"]);
317/// # Ok(())
318/// # }
319/// ```
320///
321/// # Errors
322///
323/// A file that does not parse, a secret written in a file or not found, a mail server or
324/// policy the drivers refuse, or a project without a `site.toml` when the certificate, the
325/// wallet or the probe needs its domain.
326pub 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(&currency)));
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
433/// One secret: `env:VAR` or `file:PATH`, never the secret itself (A-I19).
434type SecretRef = String;
435
436/// The chat platforms a served site talks on, from `channels.json` (spec 3.5 §10 X12). Every
437/// platform is optional; secrets are references.
438///
439/// # Example
440///
441/// ```rust
442/// use adk_website::deploy::config::ChannelsConfig;
443///
444/// let config: ChannelsConfig = serde_json::from_value(serde_json::json!({
445///     "whatsapp": {
446///         "phoneNumberId": "1001",
447///         "accessToken": "env:WHATSAPP_ACCESS_TOKEN",
448///         "appSecret": "env:WHATSAPP_APP_SECRET",
449///         "verifyToken": "env:WHATSAPP_VERIFY_TOKEN"
450///     },
451///     "telegram": { "token": "env:TELEGRAM_BOT_TOKEN" }
452/// })).unwrap();
453/// assert!(config.whatsapp.is_some() && config.slack.is_none());
454/// ```
455#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(rename_all = "camelCase", deny_unknown_fields)]
457pub struct ChannelsConfig {
458    /// A Telegram bot.
459    #[serde(default, skip_serializing_if = "Option::is_none")]
460    pub telegram: Option<TelegramChannel>,
461    /// A WhatsApp Business number on the Cloud API.
462    #[serde(default, skip_serializing_if = "Option::is_none")]
463    pub whatsapp: Option<WhatsAppChannel>,
464    /// A Slack app in Socket Mode.
465    #[serde(default, skip_serializing_if = "Option::is_none")]
466    pub slack: Option<SlackChannel>,
467    /// A Discord bot.
468    #[serde(default, skip_serializing_if = "Option::is_none")]
469    pub discord: Option<DiscordChannel>,
470    /// A Matrix account.
471    #[serde(default, skip_serializing_if = "Option::is_none")]
472    pub matrix: Option<MatrixChannel>,
473}
474
475/// A Telegram bot in `channels.json`.
476#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
477#[serde(rename_all = "camelCase", deny_unknown_fields)]
478pub struct TelegramChannel {
479    /// The bot token's reference.
480    pub token: SecretRef,
481}
482
483/// A WhatsApp Business number in `channels.json`.
484#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
485#[serde(rename_all = "camelCase", deny_unknown_fields)]
486pub struct WhatsAppChannel {
487    /// The business phone number's id, from the app's WhatsApp settings.
488    pub phone_number_id: String,
489    /// The access token's reference.
490    pub access_token: SecretRef,
491    /// The app secret's reference, which signs every webhook body.
492    pub app_secret: SecretRef,
493    /// The webhook's verify token's reference.
494    pub verify_token: SecretRef,
495    /// An approved template with no variables, sent outside the 24-hour window.
496    #[serde(default, skip_serializing_if = "Option::is_none")]
497    pub template: Option<WhatsAppTemplate>,
498}
499
500/// An approved WhatsApp template.
501#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
502#[serde(rename_all = "camelCase", deny_unknown_fields)]
503pub struct WhatsAppTemplate {
504    /// Its name.
505    pub name: String,
506    /// Its language, such as `en_US`.
507    pub language: String,
508}
509
510/// A Slack app in `channels.json`.
511#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
512#[serde(rename_all = "camelCase", deny_unknown_fields)]
513pub struct SlackChannel {
514    /// The app-level token's reference (`connections:write`).
515    pub app_token: SecretRef,
516    /// The bot token's reference.
517    pub bot_token: SecretRef,
518}
519
520/// A Discord bot in `channels.json`.
521#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
522#[serde(rename_all = "camelCase", deny_unknown_fields)]
523pub struct DiscordChannel {
524    /// The bot token's reference.
525    pub token: SecretRef,
526}
527
528/// A Matrix account in `channels.json`.
529#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
530#[serde(rename_all = "camelCase", deny_unknown_fields)]
531pub struct MatrixChannel {
532    /// The homeserver's address.
533    pub homeserver: String,
534    /// The access token's reference.
535    pub access_token: SecretRef,
536}
537
538/// The chat platforms of `channels.json` with their secrets read (spec 3.5 §10 X12), for a
539/// host that builds the adapters. Its `Debug` shows no secret.
540#[derive(Clone, Default)]
541pub struct ChatConfig {
542    /// Telegram's bot token.
543    pub telegram: Option<adk_core::CredentialSecret>,
544    /// WhatsApp's number id, access token, app secret, verify token and template.
545    pub whatsapp: Option<WhatsAppSecrets>,
546    /// Slack's app-level and bot tokens.
547    pub slack: Option<(adk_core::CredentialSecret, adk_core::CredentialSecret)>,
548    /// Discord's bot token.
549    pub discord: Option<adk_core::CredentialSecret>,
550    /// Matrix's homeserver and access token.
551    pub matrix: Option<(String, adk_core::CredentialSecret)>,
552}
553
554/// WhatsApp's settings with their secrets read.
555#[derive(Clone, Debug)]
556pub struct WhatsAppSecrets {
557    /// The business phone number's id.
558    pub phone_number_id: String,
559    /// The access token.
560    pub access_token: adk_core::CredentialSecret,
561    /// The app secret.
562    pub app_secret: adk_core::CredentialSecret,
563    /// The verify token.
564    pub verify_token: adk_core::CredentialSecret,
565    /// The approved template, as name and language.
566    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    /// The platforms set, as people read them.
577    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
591/// The chat platforms of the project's `channels.json`, their secrets read from the
592/// environment or the project's files (spec 3.5 §10 X12, A-I19); `None` without the file.
593///
594/// # Errors
595///
596/// A file that does not parse, or a secret that cannot be read.
597pub 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}