gent-daemon 0.1.6

Local daemon, storage and synchronization for Gent chat clusters.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
use anyhow::{Context, Result, bail, ensure};
use gent_protocol::Policy;
use serde::{Deserialize, Serialize};
use std::{
    collections::BTreeMap,
    fs,
    io::Write,
    os::unix::fs::PermissionsExt,
    path::{Path, PathBuf},
};

mod host_recovery;
pub use host_recovery::{HostRecovery, MAX_RECOVERY_AGENTS, RecoveryAgent, RecoveryHost};
mod ordinary_babysitter;
pub use ordinary_babysitter::{ordinary_babysitter_enabled, set_ordinary_babysitter_enabled};
mod discovery;
mod transport;
pub use discovery::Discovery;
pub use transport::{Direct, Transport};
mod hosted;
pub use hosted::HostedParent;

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Updates {
    pub enabled: bool,
}
impl Default for Updates {
    fn default() -> Self {
        Self { enabled: true }
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NodeConfig {
    pub id: String,
    pub name: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ClusterConfig {
    pub id: String,
    pub name: String,
    pub local_only: bool,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Config {
    pub version: u32,
    /// Last signed revision projected to this file; edits require config apply.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub applied_revision: Option<u64>,
    pub node: NodeConfig,
    pub cluster: ClusterConfig,
    /// Node-local transport settings are never replicated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub relay: Option<RelayConfig>,
    /// Account routing metadata, local to this node and never replicated.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub service: Option<ServiceConfig>,
    #[serde(default)]
    pub policy: Policy,
    #[serde(flatten)]
    pub extra: BTreeMap<String, toml::Value>,
}

/// Machine-local selection only. These records never enter signed authority.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Contexts {
    pub version: u32,
    pub active_cluster: String,
    pub profiles: BTreeMap<String, ContextProfile>,
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ContextProfile {
    pub home: PathBuf,
    pub node_id: String,
}

/// Local account-session reference. It grants no cluster signing authority.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AccountSource {
    pub version: u32,
    pub home: PathBuf,
    pub cluster_id: String,
    pub node_id: String,
    pub service: ServiceConfig,
}
impl AccountSource {
    pub fn validate(&self) -> Result<()> {
        ensure!(
            self.version == 1 && self.home.is_absolute(),
            "invalid account-session source"
        );
        ensure!(
            !self
                .home
                .to_str()
                .context("account source path must be UTF-8")?
                .chars()
                .any(char::is_control),
            "invalid account source path"
        );
        for id in [&self.cluster_id, &self.node_id] {
            ensure!(
                uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == *id),
                "invalid account source identity"
            );
        }
        self.service.validate()
    }
}

impl Contexts {
    pub const LIMIT: usize = 128;
    pub fn validate(&self) -> Result<()> {
        ensure!(
            self.version == 1 && !self.profiles.is_empty() && self.profiles.len() <= Self::LIMIT,
            "invalid cluster profile registry"
        );
        ensure!(
            self.profiles.contains_key(&self.active_cluster),
            "active cluster is missing from the profile registry"
        );
        let mut homes = std::collections::BTreeSet::new();
        for (cluster, profile) in &self.profiles {
            for id in [cluster, &profile.node_id] {
                ensure!(
                    uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == *id),
                    "invalid cluster profile identity"
                );
            }
            let text = profile
                .home
                .to_str()
                .context("profile path must be UTF-8")?;
            ensure!(
                profile.home.is_absolute()
                    && !text.chars().any(char::is_control)
                    && homes.insert(profile.home.clone()),
                "cluster profiles require distinct absolute directories"
            );
        }
        Ok(())
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServiceConfig {
    pub origin: String,
    pub account_id: String,
}
impl ServiceConfig {
    pub fn validate(&self) -> Result<()> {
        RelayConfig {
            endpoint: self.origin.clone(),
            credential_file: "unused".into(),
        }
        .validate()?;
        let id = uuid::Uuid::parse_str(&self.account_id).context("invalid service account")?;
        ensure!(
            !id.is_nil() && id.to_string() == self.account_id,
            "invalid service account"
        );
        Ok(())
    }
}

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RelayConfig {
    pub endpoint: String,
    pub credential_file: PathBuf,
}
impl RelayConfig {
    pub fn validate(&self) -> Result<reqwest::Url> {
        let url = reqwest::Url::parse(&self.endpoint)?;
        ensure!(
            url.username().is_empty()
                && url.password().is_none()
                && url.query().is_none()
                && url.fragment().is_none()
                && url.path() == "/",
            "relay endpoint must be an origin without credentials, path, query, or fragment"
        );
        let loopback = matches!(url.host_str(), Some("127.0.0.1" | "[::1]" | "localhost"));
        ensure!(
            url.scheme() == "https" || (url.scheme() == "http" && loopback),
            "relay requires HTTPS except on loopback"
        );
        ensure!(
            !self.credential_file.as_os_str().is_empty(),
            "relay credential file is required"
        );
        Ok(url)
    }
}

pub fn secret() -> String {
    format!(
        "{}{}",
        uuid::Uuid::new_v4().simple(),
        uuid::Uuid::new_v4().simple()
    )
}

pub fn private_dir(path: &Path) -> Result<()> {
    if let Ok(metadata) = fs::symlink_metadata(path) {
        ensure!(
            metadata.is_dir() && !metadata.file_type().is_symlink(),
            "state directory must be a real directory, not a symlink"
        );
        ensure!(
            metadata.permissions().mode() & 0o077 == 0,
            "state directory must be private (mode 0700); choose a dedicated directory"
        );
        return Ok(());
    }
    use std::os::unix::fs::DirBuilderExt;
    fs::DirBuilder::new()
        .recursive(true)
        .mode(0o700)
        .create(path)?;
    Ok(())
}

pub fn write_private(path: &Path, bytes: &[u8]) -> Result<()> {
    let parent = path.parent().context("missing parent directory")?;
    private_dir(parent)?;
    let mut file = tempfile::NamedTempFile::new_in(parent)?;
    file.as_file()
        .set_permissions(fs::Permissions::from_mode(0o600))?;
    file.write_all(bytes)?;
    file.as_file().sync_all()?;
    file.persist(path).map_err(|e| e.error)?;
    fs::File::open(parent)?.sync_all()?;
    Ok(())
}

pub fn read_private(path: &Path) -> Result<String> {
    read_credential(path, false)
}

/// Relay transport accepts a service-issued node credential or the local proof
/// token. Owner RPC and chat binding readers retain their separate format.
pub fn read_relay_credential(path: &Path) -> Result<String> {
    read_credential(path, true)
}

fn read_credential(path: &Path, relay: bool) -> Result<String> {
    let metadata = fs::symlink_metadata(path).context("credential file is unavailable")?;
    ensure!(
        metadata.is_file() && !metadata.file_type().is_symlink(),
        "credential must be a regular file"
    );
    ensure!(
        metadata.permissions().mode() & 0o077 == 0,
        "credential file must not be accessible to other users"
    );
    let value = fs::read_to_string(path)?;
    ensure!(
        (value.trim().len() == 64 && value.trim().bytes().all(|b| b.is_ascii_hexdigit()))
            || (relay && gent_protocol::service::transport_created_at(value.trim()).is_some()),
        "invalid credential file"
    );
    Ok(value.trim().into())
}

pub fn binding(path: &Path) -> Result<String> {
    if path.exists() {
        return read_private(path);
    }
    let parent = path.parent().context("missing binding directory")?;
    private_dir(parent)?;
    let value = secret();
    // create_new makes concurrent initialization fail rather than changing a live identity.
    use std::os::unix::fs::OpenOptionsExt;
    let mut file = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .mode(0o600)
        .open(path)?;
    file.write_all(value.as_bytes())?;
    file.sync_all()?;
    Ok(value)
}

pub fn path(home: &Path) -> PathBuf {
    home.join("config.toml")
}
pub fn load(home: &Path) -> Result<Config> {
    let config = load_for_runtime(home)?;
    config.validate()?;
    Ok(config)
}
/// Read local identity/settings while allowing an unapplied shared-policy edit.
/// Existing runtime authority comes from the verified database, not this file.
pub(crate) fn load_for_runtime(home: &Path) -> Result<Config> {
    crate::recovery::ensure_active(home)?;
    let config: Config = toml::from_str(
        &fs::read_to_string(path(home))
            .context("no Gent configuration; run gent cluster new <name> --local")?,
    )?;
    config.validate_local()?;
    Ok(config)
}
pub fn save(home: &Path, config: &Config) -> Result<()> {
    crate::recovery::ensure_active(home)?;
    config.validate()?;
    private_dir(home)?;
    let _lock = configuration_lock(home)?;
    let mut next = config.clone();
    // A daemon may have loaded its projection before a concurrent switch.
    // Preserve the latest local registry inside the shared filesystem lock.
    if path(home).exists() {
        let previous = load_for_runtime(home)?;
        if let Some(contexts) = previous.contexts()? {
            ensure!(
                previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
                "cannot replace the identity of a registered cluster profile"
            );
            next.set_contexts(contexts)?;
        }
        if let Some(source) = previous.account_source()? {
            ensure!(
                previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
                "cannot replace the identity of a managed account profile"
            );
            next.set_account_source(source)?;
        }
        if let Some(id) = previous.profile_setup()? {
            ensure!(
                previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
                "cannot replace the identity of a profile setup registry"
            );
            next.set_profile_setup(id)?;
        }
        if let Some(id) = previous.gateway_registry()? {
            ensure!(
                previous.cluster.id == next.cluster.id && previous.node.id == next.node.id,
                "cannot replace the identity of a gateway node"
            );
            next.set_gateway_registry(id)?;
        }
        if let Some(recovery) = previous.host_recovery()? {
            next.set_host_recovery(recovery)?;
        }
        if previous.portable_web()? {
            next.enable_portable_web()?;
        }
        // Update preferences are node-local and direct TOML edits take effect
        // without config apply. Never replace them with a stale projection.
        for name in ["updates", "discovery", "transport"] {
            match previous.extra.get(name) {
                Some(value) => {
                    next.extra.insert(name.into(), value.clone());
                }
                None => {
                    next.extra.remove(name);
                }
            }
        }
    }
    next.validate()?;
    write_private(&path(home), toml::to_string_pretty(&next)?.as_bytes())
}

/// Serialize local settings edits with daemon projections. The closure reads
/// the latest file under the same lock used by save, so two edits cannot merge
/// stale copies of the registry. This does not change signed cluster policy.
pub fn edit_local<T>(home: &Path, edit: impl FnOnce(&mut Config) -> Result<T>) -> Result<T> {
    crate::recovery::ensure_active(home)?;
    let _lock = configuration_lock(home)?;
    let mut config = load_for_runtime(home)?;
    let result = edit(&mut config)?;
    config.validate_local()?;
    write_private(&path(home), toml::to_string_pretty(&config)?.as_bytes())?;
    Ok(result)
}

fn configuration_lock(home: &Path) -> Result<fs::File> {
    let until = std::time::Instant::now() + std::time::Duration::from_secs(3);
    loop {
        match state_lock(home, "config.lock") {
            Ok(lock) => return Ok(lock),
            Err(error)
                if error.chain().any(|cause| {
                    cause
                        .downcast_ref::<std::io::Error>()
                        .is_some_and(|e| e.kind() == std::io::ErrorKind::WouldBlock)
                }) =>
            {
                ensure!(
                    std::time::Instant::now() < until,
                    "configuration is busy; retry the command"
                );
                std::thread::sleep(std::time::Duration::from_millis(10));
            }
            Err(error) => return Err(error),
        }
    }
}
impl Config {
    pub fn updates(&self) -> Result<Updates> {
        self.extra
            .get("updates")
            .cloned()
            .map(|v| v.try_into().context("invalid update settings"))
            .transpose()
            .map(|v| v.unwrap_or_default())
    }

    pub fn set_updates(&mut self, updates: Updates) -> Result<()> {
        self.extra
            .insert("updates".into(), toml::Value::try_from(updates)?);
        Ok(())
    }
    pub fn gateway_registry(&self) -> Result<Option<String>> {
        self.extra
            .get("gateway_registry")
            .map(|value| {
                let id = value.as_str().context("invalid gateway registry pin")?;
                ensure!(
                    uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == id),
                    "invalid gateway registry pin"
                );
                Ok(id.to_string())
            })
            .transpose()
    }
    pub fn set_gateway_registry(&mut self, id: String) -> Result<()> {
        ensure!(
            self.gateway_registry()?
                .is_none_or(|previous| previous == id),
            "gateway registry changed"
        );
        self.extra
            .insert("gateway_registry".into(), toml::Value::String(id));
        self.update_local_version()
    }
    pub fn profile_setup(&self) -> Result<Option<String>> {
        self.extra
            .get("profile_setup")
            .map(|value| {
                let id = value
                    .as_str()
                    .context("invalid profile setup registry pin")?;
                ensure!(
                    uuid::Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == id),
                    "invalid profile setup registry pin"
                );
                Ok(id.to_string())
            })
            .transpose()
    }
    pub fn set_profile_setup(&mut self, id: String) -> Result<()> {
        ensure!(
            self.profile_setup()?.is_none_or(|previous| previous == id),
            "profile setup registry changed"
        );
        self.extra
            .insert("profile_setup".into(), toml::Value::String(id));
        self.update_local_version()?;
        self.profile_setup()?;
        Ok(())
    }
    pub fn account_source(&self) -> Result<Option<AccountSource>> {
        self.extra
            .get("account_source")
            .cloned()
            .map(|value| -> Result<AccountSource> {
                let source: AccountSource =
                    value.try_into().context("invalid account-session source")?;
                source.validate()?;
                if let Some(pin) = &self.service {
                    ensure!(
                        pin.account_id == source.service.account_id
                            && reqwest::Url::parse(&pin.origin)?
                                == reqwest::Url::parse(&source.service.origin)?,
                        "account source does not match this profile's service"
                    );
                }
                Ok(source)
            })
            .transpose()
    }
    pub fn set_account_source(&mut self, source: AccountSource) -> Result<()> {
        source.validate()?;
        self.extra
            .insert("account_source".into(), toml::Value::try_from(source)?);
        self.update_local_version()?;
        self.account_source()?;
        Ok(())
    }
    pub fn contexts(&self) -> Result<Option<Contexts>> {
        self.extra
            .get("contexts")
            .cloned()
            .map(|value| -> Result<Contexts> {
                let contexts: Contexts = value
                    .try_into()
                    .context("invalid cluster profile registry")?;
                contexts.validate()?;
                let own = contexts
                    .profiles
                    .get(&self.cluster.id)
                    .context("original cluster profile is missing")?;
                ensure!(
                    own.node_id == self.node.id,
                    "original node does not match its profile"
                );
                Ok(contexts)
            })
            .transpose()
    }
    pub fn set_contexts(&mut self, contexts: Contexts) -> Result<()> {
        contexts.validate()?;
        self.extra
            .insert("contexts".into(), toml::Value::try_from(contexts)?);
        self.update_local_version()?;
        self.contexts()?;
        Ok(())
    }
    fn local_features(&self) -> Result<Vec<String>> {
        let mut features = Vec::new();
        if self.account_source()?.is_some() {
            features.push("account_source".into());
        }
        if self.contexts()?.is_some() {
            features.push("contexts".into());
        }
        if self.gateway_registry()?.is_some() {
            features.push("gateway_registry".into());
        }
        if self.profile_setup()?.is_some() {
            features.push("profile_setup".into());
        }
        if self.host_recovery()?.is_some() {
            features.push("host_recovery".into());
        }
        if self.hosted_parent()?.is_some() {
            features.push("hosted_parent".into());
        }
        if self.portable_web()? {
            features.push("portable_web".into());
        }
        Ok(features)
    }
    pub fn portable_web(&self) -> Result<bool> {
        match self.extra.get("portable_web") {
            None => Ok(false),
            Some(toml::Value::Boolean(true)) => Ok(true),
            _ => anyhow::bail!("invalid portable web metadata"),
        }
    }
    pub fn enable_portable_web(&mut self) -> Result<()> {
        self.extra
            .insert("portable_web".into(), toml::Value::Boolean(true));
        self.update_local_version()
    }
    fn update_local_version(&mut self) -> Result<()> {
        let features = self.local_features()?;
        if self.account_source()?.is_some()
            || self.profile_setup()?.is_some()
            || self.gateway_registry()?.is_some()
            || self.host_recovery()?.is_some()
            || self.hosted_parent()?.is_some()
            || self.portable_web()?
        {
            self.version = 3;
            self.extra
                .insert("local_features".into(), toml::Value::try_from(features)?);
        } else {
            self.version = if self.contexts()?.is_some() { 2 } else { 1 };
            self.extra.remove("local_features");
        }
        Ok(())
    }
    pub fn validate(&self) -> Result<()> {
        self.validate_local()?;
        label(&self.node.name)?;
        label(&self.cluster.name)?;
        gent_crypto::validate_policy(&self.policy)?;
        Ok(())
    }
    /// Check routing and identity without rejecting an unapplied shared-policy
    /// edit. Live policy authority comes from the verified daemon database.
    pub fn validate_local(&self) -> Result<()> {
        self.updates()?;
        self.discovery()?;
        self.transport()?;
        ensure!(
            matches!(self.version, 1..=3),
            "unsupported configuration version"
        );
        let features = self.local_features()?;
        let required: Option<Vec<String>> = self
            .extra
            .get("local_features")
            .cloned()
            .map(|value| {
                value
                    .try_into()
                    .context("invalid local metadata requirements")
            })
            .transpose()?;
        ensure!(
            match self.version {
                1 => features.is_empty() && required.is_none(),
                2 => features == ["contexts"] && required.is_none(),
                3 => required.as_ref() == Some(&features) && !features.is_empty(),
                _ => false,
            },
            "configuration version or required local metadata does not match its fields"
        );
        ensure!(
            self.cluster.local_only || self.relay.is_some(),
            "a service cluster requires a configured relay"
        );
        for value in [&self.node.id, &self.cluster.id] {
            let parsed =
                uuid::Uuid::parse_str(value).context("invalid node or cluster identity")?;
            ensure!(
                !parsed.is_nil() && parsed.to_string() == *value,
                "identity must be a canonical nonzero UUID"
            );
        }
        if let Some(relay) = &self.relay {
            relay.validate()?;
        }
        if let Some(service) = &self.service {
            service.validate()?;
            ensure!(
                !self.cluster.local_only && self.relay.is_some(),
                "service metadata requires service transport"
            );
        }
        Ok(())
    }
}
pub fn label(value: &str) -> Result<()> {
    ensure!(
        !value.trim().is_empty() && value.len() <= 128 && !value.chars().any(char::is_control),
        "label must contain 1-128 bytes without control characters"
    );
    Ok(())
}
pub fn initialize(home: &Path, name: &str) -> Result<Config> {
    crate::recovery::ensure_active(home)?;
    label(name)?;
    private_dir(home)?;
    if path(home).exists() {
        bail!("already configured; existing identity has been preserved");
    }
    ensure!(
        !pending_join(home)?.exists(),
        "a node join is pending; rerun gent cluster join to preserve its identity"
    );
    let config = fresh(name)?;
    binding(&home.join("owner.key"))?;
    save(home, &config)?;
    Ok(config)
}

/// Allocate identities without publishing state. Hosted setup journals this
/// configuration before any filesystem or service operation can be retried.
pub fn fresh(name: &str) -> Result<Config> {
    label(name)?;
    Ok(Config {
        version: 1,
        applied_revision: None,
        node: NodeConfig {
            id: uuid::Uuid::new_v4().to_string(),
            name: std::env::var("HOSTNAME")
                .ok()
                .filter(|s| label(s).is_ok())
                .unwrap_or_else(|| "my-node".into()),
        },
        cluster: ClusterConfig {
            id: uuid::Uuid::new_v4().to_string(),
            name: name.into(),
            local_only: true,
        },
        relay: None,
        service: None,
        policy: Policy::cluster_default(),
        extra: BTreeMap::new(),
    })
}

pub fn pending_join(home: &Path) -> Result<PathBuf> {
    let mut name = home
        .file_name()
        .context("missing node directory name")?
        .to_os_string();
    name.push(".joining");
    Ok(home.with_file_name(name))
}

/// Persistent lock files stay in the final home across installation. Never
/// rename or remove them: that could split writers between different inodes.
pub fn state_lock(home: &Path, name: &str) -> Result<fs::File> {
    use fs2::FileExt;
    use std::os::unix::fs::{MetadataExt, OpenOptionsExt};
    let path = home.join(name);
    if let Ok(meta) = fs::symlink_metadata(&path) {
        ensure!(
            meta.is_file()
                && !meta.file_type().is_symlink()
                && meta.nlink() == 1
                && meta.permissions().mode() & 0o077 == 0,
            "state lock must be a private regular file"
        );
    }
    let lock = fs::OpenOptions::new()
        .create(true)
        .truncate(false)
        .read(true)
        .write(true)
        .mode(0o600)
        .open(path)?;
    lock.try_lock_exclusive()
        .context("node is busy; stop its daemon or wait for the other setup command")?;
    Ok(lock)
}