1use std::collections::BTreeMap;
21use std::path::{Component, Path, PathBuf};
22
23use adk_core::{AdkError, Result};
24use adk_site::feed::FeedMapping;
25use adk_site::host::SiteHost;
26use adk_site::release::{PreviousRelease, manifest_digest, manifest_path};
27use awp_types::{FeedBounds, ReleaseManifest};
28use base64::Engine as _;
29use base64::engine::general_purpose::URL_SAFE_NO_PAD;
30use bytes::Bytes;
31use serde::{Deserialize, Serialize};
32use zeroize::Zeroizing;
33
34use crate::edge::handlers::Slot;
35
36fn io(path: &Path, error: impl std::fmt::Display) -> AdkError {
37 AdkError::config(format!("{}: {error}", path.display()))
38}
39
40#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct ProjectPaths {
53 root: PathBuf,
54}
55
56impl ProjectPaths {
57 pub fn new(root: impl Into<PathBuf>) -> Self {
59 Self { root: root.into() }
60 }
61
62 pub fn root(&self) -> &Path {
64 &self.root
65 }
66
67 pub fn data(&self) -> PathBuf {
69 self.root.join("data")
70 }
71
72 pub fn key_file(&self, name: &str) -> PathBuf {
74 self.data().join("keys").join(format!("{name}.jwk"))
75 }
76
77 pub fn host_dir(&self) -> PathBuf {
79 self.data().join("host")
80 }
81
82 pub fn work(&self) -> PathBuf {
84 self.data().join("work")
85 }
86
87 pub fn history(&self) -> PathBuf {
89 self.data().join("history")
90 }
91
92 pub fn journal(&self) -> PathBuf {
94 self.data().join("updates")
95 }
96
97 pub fn experiments(&self) -> PathBuf {
99 self.data().join("experiments")
100 }
101
102 pub fn database(&self, name: &str) -> String {
104 format!("sqlite://{}?mode=rwc", self.data().join(format!("{name}.db")).display())
105 }
106
107 pub fn kernel_database(&self) -> String {
124 let listed = self.root.parent().and_then(|agency| {
125 let text = std::fs::read_to_string(agency.join("agency.toml")).ok()?;
126 let file: super::serve::AgencyFile = toml::from_str(&text).ok()?;
127 let name = self.root.file_name()?;
128 file.sites
129 .iter()
130 .any(|site| site.dir.as_os_str() == name || agency.join(&site.dir) == self.root)
131 .then(|| ProjectPaths::new(agency))
132 });
133 listed.map_or_else(|| self.database("kernel"), |agency| agency.database("kernel"))
134 }
135
136 pub fn well_known(&self) -> PathBuf {
138 self.root.join("well-known")
139 }
140
141 pub fn static_dir(&self) -> PathBuf {
143 self.root.join("static")
144 }
145}
146
147pub struct KeyFile {
150 pub kid: String,
152 seed: Zeroizing<[u8; 32]>,
153}
154
155impl std::fmt::Debug for KeyFile {
156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
157 f.debug_struct("KeyFile").field("kid", &self.kid).finish_non_exhaustive()
158 }
159}
160
161impl KeyFile {
162 pub fn load_or_create(path: &Path, kid: &str) -> Result<Self> {
168 if path.exists() {
169 return Self::read(path);
170 }
171 let mut seed = Zeroizing::new([0u8; 32]);
172 getrandom::fill(seed.as_mut()).map_err(|e| io(path, e))?;
173 let key = Self { kid: kid.to_string(), seed };
174 key.write_new(path)?;
175 Ok(key)
176 }
177
178 pub fn read(path: &Path) -> Result<Self> {
184 #[derive(Deserialize)]
185 struct Jwk {
186 kty: String,
187 crv: String,
188 kid: Option<String>,
189 d: Option<String>,
190 }
191 let text = Zeroizing::new(std::fs::read_to_string(path).map_err(|e| io(path, e))?);
192 let jwk: Jwk = serde_json::from_str(&text)
193 .map_err(|_| io(path, "not a JSON Web Key; a key file is an Ed25519 private JWK"))?;
194 if jwk.kty != "OKP" || jwk.crv != "Ed25519" {
195 return Err(io(path, "not an Ed25519 key (kty OKP, crv Ed25519)"));
196 }
197 let d = Zeroizing::new(jwk.d.unwrap_or_default());
198 let bytes = Zeroizing::new(
199 URL_SAFE_NO_PAD.decode(d.as_bytes()).map_err(|_| io(path, "`d` is not base64url"))?,
200 );
201 let seed: [u8; 32] = bytes
202 .as_slice()
203 .try_into()
204 .map_err(|_| io(path, "`d` is not a 32-byte Ed25519 seed"))?;
205 let kid = jwk.kid.filter(|kid| !kid.is_empty()).ok_or_else(|| io(path, "no `kid`"))?;
206 Ok(Self { kid, seed: Zeroizing::new(seed) })
207 }
208
209 pub fn seed(&self) -> [u8; 32] {
211 *self.seed
212 }
213
214 fn write_new(&self, path: &Path) -> Result<()> {
215 use std::io::Write as _;
216 let key = adk_auth::web_bot_auth::Ed25519SigningKey::from_seed(*self.seed)
217 .map_err(|e| io(path, e))?;
218 let text = Zeroizing::new(format!(
219 "{{\"kty\":\"OKP\",\"crv\":\"Ed25519\",\"kid\":{},\"x\":\"{}\",\"d\":\"{}\"}}\n",
220 serde_json::Value::String(self.kid.clone()),
221 URL_SAFE_NO_PAD.encode(key.public_key()),
222 Zeroizing::new(URL_SAFE_NO_PAD.encode(self.seed.as_ref())).as_str()
223 ));
224 if let Some(parent) = path.parent() {
225 std::fs::create_dir_all(parent).map_err(|e| io(parent, e))?;
226 }
227 let mut options = std::fs::OpenOptions::new();
228 options.write(true).create_new(true);
229 #[cfg(unix)]
230 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
231 let mut file = options.open(path).map_err(|e| io(path, e))?;
232 file.write_all(text.as_bytes()).map_err(|e| io(path, e))
233 }
234}
235
236pub fn documents(paths: &ProjectPaths) -> Result<BTreeMap<String, Bytes>> {
244 let mut documents = BTreeMap::new();
245 collect(&paths.well_known(), ".well-known", &mut documents)?;
246 collect(&paths.static_dir(), "", &mut documents)?;
247 documents.remove(awp_types::v2::contract::CHARTER_PATH.trim_start_matches('/'));
248 Ok(documents)
249}
250
251fn collect(dir: &Path, prefix: &str, documents: &mut BTreeMap<String, Bytes>) -> Result<()> {
252 if !dir.is_dir() {
253 return Ok(());
254 }
255 let mut stack = vec![dir.to_path_buf()];
256 while let Some(current) = stack.pop() {
257 for entry in std::fs::read_dir(¤t).map_err(|e| io(¤t, e))? {
258 let path = entry.map_err(|e| io(¤t, e))?.path();
259 if path.is_dir() {
260 stack.push(path);
261 continue;
262 }
263 let relative = path.strip_prefix(dir).unwrap_or(&path);
264 if !relative.components().all(|c| matches!(c, Component::Normal(_))) {
265 continue;
266 }
267 let relative = relative.to_string_lossy().replace('\\', "/");
268 let key = if prefix.is_empty() { relative } else { format!("{prefix}/{relative}") };
269 let bytes = std::fs::read(&path).map_err(|e| io(&path, e))?;
270 documents.insert(key, Bytes::from(bytes));
271 }
272 }
273 Ok(())
274}
275
276pub async fn previous_release(host: &dyn SiteHost, size: u64) -> Result<Option<PreviousRelease>> {
283 if size == 0 {
284 return Ok(None);
285 }
286 let fetch = |seq: u64| async move {
287 let bytes = host
288 .fetch(&manifest_path(seq))
289 .await
290 .map_err(|e| AdkError::config(e.to_string()))?
291 .ok_or_else(|| {
292 AdkError::config(format!(
293 "the site log holds release {seq} but the host does not serve its manifest"
294 ))
295 })?;
296 serde_json::from_slice::<ReleaseManifest>(&bytes)
297 .map_err(|e| AdkError::config(format!("release {seq}'s manifest: {e}")))
298 };
299 let latest = fetch(size).await?;
300 let mut chain = vec![latest.clone()];
301 while let Some(base) = chain.last().and_then(|manifest| manifest.base) {
302 if chain.len() > 10_000 {
303 return Err(AdkError::config("the delta chain does not end in a snapshot"));
304 }
305 chain.push(fetch(base).await?);
306 }
307 let mut files = BTreeMap::new();
308 for manifest in chain.iter().rev() {
309 files = manifest.apply_to(&files);
310 }
311 let snapshot = chain.last().map_or((latest.seq, latest.created_at), |m| (m.seq, m.created_at));
312 let (digest, _) = manifest_digest(&latest).map_err(|e| AdkError::config(e.to_string()))?;
313 Ok(Some(PreviousRelease { manifest: latest, digest, files, last_snapshot: snapshot }))
314}
315
316pub(crate) fn read_json<T: serde::de::DeserializeOwned>(path: &Path) -> Result<Option<T>> {
317 match std::fs::read(path) {
318 Ok(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| io(path, e)),
319 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
320 Err(error) => Err(io(path, error)),
321 }
322}
323
324#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
326pub struct ConfiguredFeed {
327 pub mapping: FeedMapping,
329 pub bounds: FeedBounds,
331}
332
333pub fn feeds(paths: &ProjectPaths) -> Result<Vec<ConfiguredFeed>> {
339 Ok(read_json(&paths.root().join("feeds.json"))?.unwrap_or_default())
340}
341
342pub fn slots(paths: &ProjectPaths) -> Result<Option<Vec<Slot>>> {
348 read_json(&paths.root().join("calendar.json"))
349}
350
351#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366#[serde(rename_all = "camelCase", deny_unknown_fields)]
367pub struct CalDavConfig {
368 pub slots: String,
370 #[serde(default, skip_serializing_if = "Option::is_none")]
372 pub bookings: Option<String>,
373 #[serde(default, skip_serializing_if = "Option::is_none")]
375 pub username: Option<String>,
376 #[serde(default, skip_serializing_if = "Option::is_none")]
378 pub password: Option<String>,
379 #[serde(default, skip_serializing_if = "Option::is_none")]
381 pub token: Option<String>,
382 #[serde(default, skip_serializing_if = "Option::is_none")]
384 pub price: Option<u64>,
385 #[serde(default, skip_serializing_if = "Option::is_none")]
387 pub time_zone: Option<String>,
388}
389
390pub(crate) fn secret_in(
393 paths: &ProjectPaths,
394 file: &str,
395 source: &str,
396) -> Result<adk_core::CredentialSecret> {
397 let text = if let Some(var) = source.strip_prefix("env:") {
398 std::env::var(var)
399 .map_err(|_| AdkError::config(format!("{file}: the environment holds no `{var}`")))?
400 } else if let Some(path) = source.strip_prefix("file:") {
401 let path = paths.root().join(path);
402 std::fs::read_to_string(&path).map_err(|e| io(&path, e))?
403 } else {
404 return Err(AdkError::config(format!(
405 "{file}: write each secret as `env:VAR` or `file:PATH`, never in the file itself"
406 )));
407 };
408 Ok(adk_core::CredentialSecret::new(text.trim()))
409}
410
411fn secret_reference(paths: &ProjectPaths, source: &str) -> Result<adk_core::CredentialSecret> {
412 secret_in(paths, "caldav.json", source)
413}
414
415pub fn caldav(paths: &ProjectPaths) -> Result<Option<crate::edge::caldav::CalDavCalendar>> {
422 use crate::edge::caldav::{CalDavAuth, CalDavCalendar};
423
424 let Some(config) = read_json::<CalDavConfig>(&paths.root().join("caldav.json"))? else {
425 return Ok(None);
426 };
427 let auth = match (&config.username, &config.password, &config.token) {
428 (Some(username), Some(password), None) => CalDavAuth::Basic {
429 username: username.clone(),
430 password: secret_reference(paths, password)?,
431 },
432 (None, None, Some(token)) => CalDavAuth::Bearer(secret_reference(paths, token)?),
433 (None, None, None) => CalDavAuth::None,
434 _ => {
435 return Err(AdkError::config(
436 "caldav.json: sign in with `username` and `password`, or with `token`",
437 ));
438 }
439 };
440 let mut calendar = CalDavCalendar::new(&config.slots, auth)?;
441 if let Some(bookings) = &config.bookings {
442 calendar = calendar.with_bookings(bookings)?;
443 }
444 if let Some(price) = config.price {
445 calendar = calendar.with_price(price);
446 }
447 if let Some(zone) = &config.time_zone {
448 let zone = zone.parse::<chrono_tz::Tz>().map_err(|_| {
449 AdkError::config(format!("caldav.json: `{zone}` is not an IANA time zone"))
450 })?;
451 calendar = calendar.with_time_zone(zone);
452 }
453 Ok(Some(calendar))
454}
455
456#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
459#[serde(rename_all = "camelCase")]
460pub struct PaymentLink {
461 pub rail: String,
463 pub instructions: String,
465 #[serde(default, skip_serializing_if = "Option::is_none")]
467 pub url: Option<String>,
468}
469
470pub fn payment_links(paths: &ProjectPaths) -> Result<Option<Vec<PaymentLink>>> {
476 read_json(&paths.root().join("payments.json"))
477}
478
479pub fn approval_thresholds(paths: &ProjectPaths) -> Result<crate::packs::ApprovalThresholds> {
488 let thresholds: crate::packs::ApprovalThresholds =
489 read_json(&paths.root().join("approvals.json"))?.unwrap_or_default();
490 thresholds.validate()?;
491 Ok(thresholds)
492}