Skip to main content

gent_daemon/
pairing.rs

1//! Node bootstrap over a separately authenticated private channel (currently SSH).
2//! No relay is allowed to supply these snapshots, requests, or grants in plaintext.
3use crate::{
4    config,
5    encrypted::ordered::{OrderedEndpoint, configuration::ConfigurationInvitation},
6    store::{Store, now},
7};
8use anyhow::{Context, Result, ensure};
9use base64::{Engine as _, engine::general_purpose::STANDARD};
10use fs2::FileExt;
11use gent_crypto::{
12    Checkpoint, NodeIdentity, ReplacedNode, SignedConfigurationGrant, SignedState, TrustAnchor,
13    VerifiedState, stream::Packet,
14};
15use gent_protocol::{MAX_FRAME_BYTES, PairingOp};
16use serde::{Deserialize, Serialize};
17use serde_json::{Value, json};
18use std::{
19    fs,
20    future::Future,
21    io::Read,
22    os::unix::fs::{OpenOptionsExt, PermissionsExt},
23    path::{Path, PathBuf},
24};
25use uuid::Uuid;
26use zeroize::{Zeroize, Zeroizing};
27mod publication;
28pub(crate) mod replacement;
29pub use replacement::installed_replacement;
30
31#[derive(Serialize, Deserialize)]
32#[serde(deny_unknown_fields)]
33pub struct RelayAccess {
34    pub endpoint: String,
35    pub credential: String,
36}
37impl Drop for RelayAccess {
38    fn drop(&mut self) {
39        self.credential.zeroize();
40    }
41}
42
43#[derive(Serialize, Deserialize)]
44#[serde(deny_unknown_fields)]
45pub struct Snapshot {
46    pub anchor: TrustAnchor,
47    pub checkpoint: Checkpoint,
48    pub state: String,
49    pub writer: String,
50    pub relay: Option<RelayAccess>,
51    #[serde(default, skip_serializing_if = "Option::is_none")]
52    pub service: Option<ServiceRelay>,
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub configuration: Option<gent_protocol::configuration_log::Commit>,
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub configuration_decisions: Option<String>,
57}
58
59#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
60#[serde(deny_unknown_fields)]
61pub struct ServiceRelay {
62    pub account: config::ServiceConfig,
63    pub relay_endpoint: String,
64}
65impl Snapshot {
66    fn verify(&self, cluster: &str) -> Result<VerifiedState> {
67        ensure!(self.anchor.cluster_id == cluster, "wrong pairing cluster");
68        ensure!(
69            self.relay.is_none() || self.service.is_none(),
70            "ambiguous pairing transport"
71        );
72        if let Some(service) = &self.service {
73            service.account.validate()?;
74            config::RelayConfig {
75                endpoint: service.relay_endpoint.clone(),
76                credential_file: "relay.key".into(),
77            }
78            .validate()?;
79        }
80        let state = VerifiedState::restore(
81            self.anchor.clone(),
82            self.checkpoint.clone(),
83            SignedState::decode(&STANDARD.decode(&self.state)?)?,
84        )?;
85        state.require_fresh(now() as u64)?;
86        ensure!(
87            state.state().nodes.contains_key(&self.writer),
88            "pairing writer is not enrolled"
89        );
90        Ok(state)
91    }
92}
93
94#[derive(Serialize, Deserialize)]
95#[serde(deny_unknown_fields)]
96pub struct Invitation {
97    pub packet: String,
98    pub grant: String,
99}
100impl Invitation {
101    pub(crate) fn encode(invitation: &ConfigurationInvitation) -> Result<Self> {
102        Ok(Self {
103            packet: STANDARD.encode(invitation.packet.encode()?),
104            grant: STANDARD.encode(invitation.grant.encode()?),
105        })
106    }
107    fn decode(&self) -> Result<ConfigurationInvitation> {
108        Ok(ConfigurationInvitation {
109            packet: Packet::decode(&STANDARD.decode(&self.packet)?)?,
110            grant: SignedConfigurationGrant::decode(&STANDARD.decode(&self.grant)?)?,
111        })
112    }
113}
114
115/// Implementations must authenticate the owner endpoint independently of Gent's
116/// relay and protect the entire channel, including bootstrap metadata and tokens.
117pub trait Peer {
118    /// Invitation channels prove this persisted identity before requesting any
119    /// snapshot. SSH peers already authenticate through the owner's login.
120    fn prepare_node(
121        &mut self,
122        _node: &NodeIdentity,
123        _name: &str,
124    ) -> impl Future<Output = Result<()>> {
125        async { Ok(()) }
126    }
127    fn call(&mut self, action: PairingOp) -> impl Future<Output = Result<Value>>;
128    /// Called with the committed node while setup and daemon locks are held.
129    /// A receipt failure must not invalidate an already-published installation.
130    fn published(&mut self, _node: &NodeIdentity, _name: &str) -> impl Future<Output = Result<()>> {
131        async { Ok(()) }
132    }
133    fn prepare_service(&mut self, _service: &ServiceRelay) -> impl Future<Output = Result<()>> {
134        async { anyhow::bail!("this pairing client does not support service enrollment") }
135    }
136    fn provision_service(
137        &mut self,
138        _runtime: &Path,
139        _home: &Path,
140        _service: &ServiceRelay,
141    ) -> impl Future<Output = Result<()>> {
142        async { anyhow::bail!("this pairing client does not support service enrollment") }
143    }
144}
145
146pub struct Options<'a> {
147    pub cluster: &'a str,
148    pub name: &'a str,
149    /// Override when the owner's loopback development relay has a different route here.
150    pub relay_endpoint: Option<&'a str>,
151    /// Explicit owner-authorized replacement of a lost joined node.
152    pub replace_node: Option<&'a str>,
153}
154
155#[derive(Serialize, Deserialize)]
156#[serde(deny_unknown_fields)]
157struct Seed {
158    version: u8,
159    cluster: String,
160    name: String,
161    node: String,
162    package_request: Uuid,
163    stream_request: Uuid,
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    replace_node: Option<String>,
166    #[serde(default, skip_serializing_if = "Option::is_none")]
167    replacement: Option<ReplacedNode>,
168}
169struct Pending {
170    dir: PathBuf,
171    runtime: PathBuf,
172    seed: Seed,
173    node: NodeIdentity,
174    _lock: fs::File,
175}
176impl Pending {
177    fn open(home: &Path, options: &Options<'_>) -> Result<Self> {
178        config::label(options.name)?;
179        if let Some(id) = options.replace_node {
180            ensure!(
181                Uuid::parse_str(id).is_ok_and(|u| !u.is_nil() && u.to_string() == id),
182                "replacement node must be a canonical UUID"
183            );
184        }
185        ensure!(
186            Uuid::parse_str(options.cluster)?.to_string() == options.cluster,
187            "cluster ID must be a canonical UUID"
188        );
189        config::private_dir(home)?;
190        let dir = config::pending_join(home)?;
191        publication::check_home(home, &dir)?;
192        config::private_dir(&dir)?;
193        let lock_path = dir.join("lock");
194        if fs::symlink_metadata(&lock_path).is_ok() {
195            read_private_bytes(&lock_path, 0)?;
196        }
197        let lock = fs::OpenOptions::new()
198            .create(true)
199            .truncate(false)
200            .read(true)
201            .write(true)
202            .mode(0o600)
203            .open(&lock_path)?;
204        lock.try_lock_exclusive()
205            .context("another node join is running")?;
206        let key = dir.join("join.key");
207        let (node, seed) = if key.exists() {
208            let bytes = read_private_bytes(&key, 8192)?;
209            ensure!(
210                bytes.len() > 40 && &bytes[..8] == b"GENTJOIN",
211                "invalid pending identity"
212            );
213            let seed: Seed = serde_json::from_slice(&bytes[40..])?;
214            ensure!(
215                seed.version == 1
216                    && seed.cluster == options.cluster
217                    && seed.name == options.name
218                    && seed.replace_node.as_deref() == options.replace_node,
219                "pending join belongs to another cluster, node name or replacement target"
220            );
221            let node = NodeIdentity::from_secret_bytes(&seed.node, bytes[8..40].try_into()?)?;
222            (node, seed)
223        } else {
224            ensure!(
225                fs::read_dir(&dir)?
226                    .all(|entry| entry.is_ok_and(|entry| entry.file_name() == "lock")),
227                "pending pairing identity is missing; restore its state"
228            );
229            let node = NodeIdentity::generate()?;
230            let seed = Seed {
231                version: 1,
232                cluster: options.cluster.into(),
233                name: options.name.into(),
234                node: node.id().into(),
235                package_request: Uuid::new_v4(),
236                stream_request: Uuid::new_v4(),
237                replace_node: options.replace_node.map(str::to_owned),
238                replacement: None,
239            };
240            (node, seed)
241        };
242        let pending = Self {
243            runtime: dir.join("node"),
244            dir,
245            node,
246            seed,
247            _lock: lock,
248        };
249        pending.save_seed()?;
250        Ok(pending)
251    }
252    fn save_seed(&self) -> Result<()> {
253        let mut bytes = Zeroizing::new(Vec::from(b"GENTJOIN".as_slice()));
254        bytes.extend_from_slice(self.node.expose_secret().as_ref());
255        serde_json::to_writer(&mut *bytes, &self.seed)?;
256        config::write_private(&self.dir.join("join.key"), &bytes)
257    }
258    fn pin(&self, state: &VerifiedState) -> Result<()> {
259        let path = self.dir.join("anchor.json");
260        if path.exists() {
261            let anchor: TrustAnchor = serde_json::from_slice(&read_private_bytes(&path, 8192)?)?;
262            ensure!(
263                &anchor == state.anchor(),
264                "pairing authority changed; refusing replacement"
265            );
266        } else {
267            ensure!(
268                !config::path(&self.runtime).exists(),
269                "pending pairing authority pin is missing"
270            );
271            config::write_private(&path, &serde_json::to_vec(state.anchor())?)?;
272        }
273        Ok(())
274    }
275    fn reset_stream(&mut self) -> Result<()> {
276        // A grant that expired before first receipt cannot bootstrap a stream.
277        // Preserve node identity and request a fresh package/stream, never reuse a key.
278        self.seed.package_request = Uuid::new_v4();
279        self.seed.stream_request = Uuid::new_v4();
280        self.save_seed()?;
281        Ok(())
282    }
283
284    fn pin_service(&self, service: &Option<ServiceRelay>) -> Result<()> {
285        let path = self.dir.join("service-pin.json");
286        if path.exists() {
287            let previous: Option<ServiceRelay> =
288                serde_json::from_slice(&read_private_bytes(&path, 8192)?)?;
289            ensure!(
290                previous == *service,
291                "pairing service changed; restore the original service settings"
292            );
293        } else {
294            // A pre-service pending join must not be converted mid-bootstrap.
295            ensure!(
296                service.is_none() || !config::path(&self.runtime).exists(),
297                "pending join has no service pin"
298            );
299            config::write_private(&path, &serde_json::to_vec(service)?)?;
300        }
301        Ok(())
302    }
303}
304
305fn read_private_bytes(path: &Path, limit: usize) -> Result<Zeroizing<Vec<u8>>> {
306    let meta = fs::symlink_metadata(path)?;
307    ensure!(
308        meta.is_file() && !meta.file_type().is_symlink() && meta.permissions().mode() & 0o077 == 0,
309        "pairing state must be a private regular file"
310    );
311    let mut bytes = Zeroizing::new(Vec::new());
312    fs::File::open(path)?
313        .take(limit as u64 + 1)
314        .read_to_end(&mut bytes)?;
315    ensure!(bytes.len() <= limit, "pairing state is too large");
316    Ok(bytes)
317}
318
319async fn catch_up(
320    home: &Path,
321    endpoint: &mut OrderedEndpoint<'_>,
322    peer: &mut impl Peer,
323    target: Option<&Checkpoint>,
324) -> Result<()> {
325    #[derive(Deserialize)]
326    #[serde(deny_unknown_fields)]
327    struct History {
328        record: Option<String>,
329        #[serde(default)]
330        commit: Option<gent_protocol::configuration_log::Commit>,
331    }
332    // One bounded record per request; checkpoints survive interruptions.
333    for _ in 0..4096 {
334        let state = endpoint.authority_state()?;
335        if let Some(target) = target {
336            ensure!(
337                state.checkpoint().revision <= target.revision,
338                "configuration grant precedes local state"
339            );
340            if state.checkpoint().revision == target.revision {
341                ensure!(state.checkpoint() == target, "pairing history fork");
342                return Ok(());
343            }
344        }
345        let value = peer
346            .call(PairingOp::History {
347                revision: state.checkpoint().revision,
348                digest: state.checkpoint().state_hash,
349            })
350            .await?;
351        let history: History = serde_json::from_value(value)?;
352        if let Some(commit) = history.commit {
353            ensure!(history.record.is_none(), "ambiguous pairing history");
354            Store::open(home)?.accept_configuration_commit(&commit)?;
355            continue;
356        }
357        let Some(record) = history.record else {
358            ensure!(target.is_none(), "missing pairing history");
359            return Ok(());
360        };
361        endpoint.apply_authority(&[SignedState::decode(&STANDARD.decode(record)?)?])?;
362    }
363    anyhow::bail!("pairing history still catching up; rerun the join command")
364}
365
366/// Join using a protected owner channel. Files stay in a sibling staging
367/// directory until membership, identity, and the configuration stream are ready.
368pub async fn join(home: &Path, options: Options<'_>, peer: &mut impl Peer) -> Result<Value> {
369    crate::recovery::ensure_active(home)?;
370    if let Some(endpoint) = options.relay_endpoint {
371        config::RelayConfig {
372            endpoint: endpoint.into(),
373            credential_file: "relay.key".into(),
374        }
375        .validate()?;
376    }
377    let home = std::path::absolute(home)?;
378    config::private_dir(&home)?;
379    let home = fs::canonicalize(home)?;
380    let _service_lock = config::state_lock(&home, "service.lock")?;
381    let _daemon_lock = config::state_lock(&home, "daemon.lock")?;
382    if config::path(&home).exists() {
383        let config = config::load(&home)?;
384        replacement::check_intent(&home, &config, options.replace_node)?;
385        ensure!(
386            config.cluster.id == options.cluster,
387            "node already belongs to another cluster"
388        );
389        // Loading the runtime verifies that the identity and checkpoint still exist.
390        let store = Store::open(&home)?;
391        let local_node = store.pairing_node()?;
392        if store.needs_data_pairing()? {
393            let node = store.pairing_node()?;
394            drop(store);
395            peer.prepare_node(&node, &config.node.name).await?;
396            let snapshot: Snapshot = serde_json::from_value(peer.call(PairingOp::Snapshot).await?)?;
397            let state = snapshot.verify(options.cluster)?;
398            let mut endpoint = OrderedEndpoint::open_runtime(&home, &node)?;
399            ensure!(
400                endpoint.authority_state()?.anchor() == state.anchor(),
401                "pairing authority changed"
402            );
403            catch_up(&home, &mut endpoint, peer, None).await?;
404            drop(endpoint);
405            connect_data(&home, &node, &snapshot.writer, peer).await?;
406        }
407        if let Some(account) = &config.service {
408            let service = ServiceRelay {
409                account: account.clone(),
410                relay_endpoint: config
411                    .relay
412                    .as_ref()
413                    .context("missing service relay")?
414                    .endpoint
415                    .clone(),
416            };
417            ensure!(
418                options.relay_endpoint.is_none(),
419                "service relay overrides are not supported"
420            );
421            peer.prepare_service(&service).await?;
422            peer.provision_service(&home, &home, &service).await?;
423        }
424        cleanup_published(&home, &local_node);
425        peer.published(&local_node, &config.node.name).await?;
426        return Ok(
427            json!({"joined":true,"already_joined":true,"node":config.node,"cluster":config.cluster}),
428        );
429    }
430    let mut pending = Pending::open(&home, &options)?;
431    if publication::started(&pending.dir) {
432        let staged = config::load(&pending.runtime)?;
433        let service = staged
434            .service
435            .as_ref()
436            .map(|account| -> Result<_> {
437                Ok(ServiceRelay {
438                    account: account.clone(),
439                    relay_endpoint: staged
440                        .relay
441                        .as_ref()
442                        .context("missing staged relay")?
443                        .endpoint
444                        .clone(),
445                })
446            })
447            .transpose()?;
448        pending.pin_service(&service)?;
449        if let Some(service) = &service {
450            ensure!(
451                options.relay_endpoint.is_none(),
452                "service relay overrides are not supported"
453            );
454            peer.prepare_service(service).await?;
455        }
456        let config = publication::publish(&home, &pending)?;
457        let _ = fs::remove_dir_all(&pending.dir);
458        if let Some(service) = &service {
459            peer.provision_service(&home, &home, service).await?;
460        }
461        peer.published(&pending.node, &config.node.name).await?;
462        return Ok(
463            json!({"joined":true,"node":config.node,"cluster":config.cluster,"configuration_relay":true,"next":"gent daemon install"}),
464        );
465    }
466    peer.prepare_node(&pending.node, options.name).await?;
467    let snapshot: Snapshot = serde_json::from_value(peer.call(PairingOp::Snapshot).await?)?;
468    let mut state = snapshot.verify(options.cluster)?;
469    pending.pin(&state)?;
470    pending.pin_replacement(&state, &snapshot.writer)?;
471    pending.pin_service(&snapshot.service)?;
472    if let Some(service) = &snapshot.service {
473        ensure!(
474            options.relay_endpoint.is_none(),
475            "service relay overrides are not supported"
476        );
477        peer.prepare_service(service).await?;
478    }
479    ensure!(
480        snapshot.relay.is_some() || snapshot.service.is_some(),
481        "owner has no configuration relay; configure [relay] and restart its daemon before joining"
482    );
483    let request = match &pending.seed.replacement {
484        Some(target) => pending.node.request_replacement(
485            state.anchor(),
486            state.checkpoint(),
487            options.name,
488            target.clone(),
489            now() as u64,
490        )?,
491        None => pending.node.request_enrollment(
492            state.anchor(),
493            state.checkpoint(),
494            options.name,
495            now() as u64,
496        )?,
497    };
498    let action = PairingOp::Enroll {
499        request: STANDARD.encode(request.encode()?),
500    };
501    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(120);
502    let enrolled: Snapshot = loop {
503        let value = peer.call(action.clone()).await?;
504        if value["state"] != "pending" {
505            break serde_json::from_value(value)?;
506        }
507        ensure!(
508            tokio::time::Instant::now() < deadline,
509            "configuration enrollment is still pending; retry the same join code"
510        );
511        tokio::time::sleep(std::time::Duration::from_secs(2)).await;
512    };
513    state = enrolled.verify(options.cluster)?;
514    pending.pin(&state)?;
515    pending.pin_service(&enrolled.service)?;
516    state.authorize_node(pending.node.id(), &pending.node.public_key(), now() as u64)?;
517    if let Some(target) = &pending.seed.replacement {
518        ensure!(
519            !state.state().nodes.contains_key(&target.id)
520                && state.state().retired_nodes.contains(&target.id)
521                && state.state().retired_keys.contains(&target.signing_key),
522            "owner did not retire the replacement target"
523        );
524    }
525    // Both snapshots arrive through an independently authenticated owner channel. This is
526    // bootstrap authority only; an installed runtime advances through history.
527    if !config::path(&pending.runtime).exists() {
528        crate::runtime::install_joined_checkpoint(
529            &pending.runtime,
530            &pending.node,
531            &state,
532            enrolled.configuration.as_ref(),
533            &if enrolled.configuration.is_some() {
534                STANDARD.decode(
535                    enrolled
536                        .configuration_decisions
537                        .as_ref()
538                        .context("configuration retry history is missing from enrollment")?,
539                )?
540            } else {
541                b"[]".to_vec()
542            },
543        )?;
544    }
545    pending.save_replacement()?;
546    let mut endpoint = OrderedEndpoint::open_runtime(&pending.runtime, &pending.node)?;
547    ensure!(
548        endpoint.authority_state()?.anchor() == state.anchor(),
549        "installed pairing authority differs"
550    );
551    for attempt in 0..if state.state().peer.is_some() { 0 } else { 3 } {
552        let invite_path = pending
553            .dir
554            .join(format!("invitation-{}.json", pending.seed.stream_request));
555        let invitation = if invite_path.exists() {
556            serde_json::from_slice::<Invitation>(&read_private_bytes(
557                &invite_path,
558                MAX_FRAME_BYTES,
559            )?)?
560            .decode()?
561        } else {
562            let package_path = pending
563                .dir
564                .join(format!("package-{}", pending.seed.package_request));
565            let package = if package_path.exists() {
566                read_private_bytes(&package_path, 24 * 1024)?.to_vec()
567            } else {
568                catch_up(&pending.runtime, &mut endpoint, peer, None).await?;
569                let package = endpoint.key_package(pending.seed.package_request, now() as u64)?;
570                config::write_private(&package_path, &package)?;
571                package
572            };
573            let value = peer
574                .call(PairingOp::Configuration {
575                    request_id: pending.seed.stream_request.to_string(),
576                    peer: pending.node.id().into(),
577                    key_package: STANDARD.encode(package),
578                })
579                .await?;
580            let wire: Invitation = serde_json::from_value(value)?;
581            let invitation = wire.decode()?;
582            config::write_private(&invite_path, &serde_json::to_vec(&wire)?)?;
583            invitation
584        };
585        invitation.grant.verify(state.anchor())?;
586        ensure!(
587            invitation.grant.grant.writer == enrolled.writer,
588            "unexpected configuration writer"
589        );
590        if endpoint
591            .configuration_streams(now() as u64)?
592            .iter()
593            .any(|s| s.group == invitation.packet.group())
594        {
595            catch_up(&pending.runtime, &mut endpoint, peer, None).await?;
596            endpoint.join_configuration(&invitation, now() as u64)?;
597            break;
598        }
599        let current = endpoint.authority_state()?;
600        if current.checkpoint().revision <= invitation.grant.grant.base.revision {
601            catch_up(
602                &pending.runtime,
603                &mut endpoint,
604                peer,
605                Some(&invitation.grant.grant.base),
606            )
607            .await?;
608            if endpoint
609                .authority_state()?
610                .require_fresh(now() as u64)
611                .is_ok()
612            {
613                endpoint.join_configuration(&invitation, now() as u64)?;
614                break;
615            }
616        }
617        ensure!(attempt < 2, "pairing grant expired; rerun the join command");
618        // Drop the endpoint's borrow while updating the pending request IDs.
619        drop(endpoint);
620        pending.reset_stream()?;
621        endpoint = OrderedEndpoint::open_runtime(&pending.runtime, &pending.node)?;
622    }
623    catch_up(&pending.runtime, &mut endpoint, peer, None).await?;
624    drop(endpoint);
625    connect_data(&pending.runtime, &pending.node, &enrolled.writer, peer).await?;
626    drop(Store::open(&pending.runtime)?); // Project the latest verified policy.
627    let mut config = config::load(&pending.runtime)?;
628    if let Some(service) = &enrolled.service {
629        peer.provision_service(&pending.runtime, &home, service)
630            .await?;
631        config = config::load(&pending.runtime)?;
632    } else {
633        let relay = enrolled
634            .relay
635            .as_ref()
636            .context("owner removed its configuration relay during pairing")?;
637        let settings = config::RelayConfig {
638            endpoint: options.relay_endpoint.unwrap_or(&relay.endpoint).into(),
639            credential_file: "relay.key".into(),
640        };
641        settings.validate()?;
642        ensure!(
643            relay.credential.len() == 64 && relay.credential.bytes().all(|c| c.is_ascii_hexdigit()),
644            "invalid development relay credential"
645        );
646        config::write_private(
647            &pending.runtime.join("relay.key"),
648            relay.credential.as_bytes(),
649        )?;
650        config.relay = Some(settings);
651    }
652    config::save(&pending.runtime, &config)?;
653    let config = publication::publish(&home, &pending)?;
654    peer.published(&pending.node, &config.node.name).await?;
655    let result = json!({"joined":true,"node":config.node,"cluster":config.cluster,"configuration_relay":config.relay.is_some(),"next":["gent","--home",home,"daemon","run"]});
656    // Cleanup failure does not turn a committed installation into a failed join.
657    let _ = fs::remove_dir_all(&pending.dir);
658    Ok(result)
659}
660
661fn cleanup_published(home: &Path, node: &NodeIdentity) {
662    let Ok(dir) = config::pending_join(home) else {
663        return;
664    };
665    if !publication::started(&dir) {
666        return;
667    }
668    let Ok(bytes) = read_private_bytes(&dir.join("join.key"), 8192) else {
669        return;
670    };
671    if bytes.len() > 40 && &bytes[..8] == b"GENTJOIN" && bytes[8..40] == *node.expose_secret() {
672        // This node is already committed and verified. A crash after publishing
673        // config.toml may have left its private staging copies behind.
674        let _ = fs::remove_dir_all(dir);
675    }
676}
677
678/// Establish independent writer streams in both directions through the same
679/// authenticated channel as enrollment. Request IDs persist before any network call.
680async fn connect_data(
681    home: &Path,
682    node: &NodeIdentity,
683    writer: &str,
684    peer: &mut impl Peer,
685) -> Result<()> {
686    #[derive(Serialize, Deserialize)]
687    #[serde(deny_unknown_fields)]
688    struct PendingData {
689        request: Uuid,
690        peer: String,
691    }
692    #[derive(Deserialize)]
693    #[serde(deny_unknown_fields)]
694    struct DataInvitation {
695        packet: String,
696        key_package: String,
697        legacy: Vec<gent_crypto::SignedLegacyAgentBinding>,
698    }
699    let path = home.join(format!("data-pairing-{writer}.json"));
700    let saved = if path.exists() {
701        serde_json::from_slice::<PendingData>(&read_private_bytes(&path, 4096)?)?
702    } else {
703        let saved = PendingData {
704            request: Uuid::new_v4(),
705            peer: writer.into(),
706        };
707        config::write_private(&path, &serde_json::to_vec(&saved)?)?;
708        saved
709    };
710    ensure!(
711        saved.peer == writer && !saved.request.is_nil(),
712        "invalid saved data pairing"
713    );
714    let mut endpoint = OrderedEndpoint::open_runtime(home, node)?;
715    let package = endpoint.key_package(saved.request, now() as u64)?;
716    let store = Store::open(home)?;
717    let legacy_agents = store.legacy_registrations()?;
718    drop(store);
719    let invitation: DataInvitation = serde_json::from_value(
720        peer.call(PairingOp::Data {
721            request_id: saved.request.to_string(),
722            peer: node.id().into(),
723            key_package: STANDARD.encode(package),
724            legacy_agents,
725        })
726        .await?,
727    )?;
728    catch_up(home, &mut endpoint, peer, None).await?;
729    let incoming = Packet::decode(&STANDARD.decode(invitation.packet)?)?;
730    endpoint.join(&incoming, writer, &[node.id(), writer], now() as u64)?;
731    let reverse_id =
732        gent_crypto::scoped_id(b"gent/pair-return-stream/v1\0", &[saved.request.as_bytes()]);
733    let outgoing = endpoint.create(
734        reverse_id,
735        &[(writer, &STANDARD.decode(invitation.key_package)?)],
736        now() as u64,
737    )?;
738    let response = peer
739        .call(PairingOp::AcceptData {
740            peer: node.id().into(),
741            packet: STANDARD.encode(outgoing.encode()?),
742            outgoing_group: STANDARD.encode(incoming.group()),
743        })
744        .await?;
745    ensure!(
746        response.get("connected") == Some(&Value::Bool(true)),
747        "invalid data pairing response"
748    );
749    drop(endpoint);
750    Store::open(home)?.install_data_link(
751        writer,
752        outgoing.group(),
753        incoming.group(),
754        &invitation.legacy,
755    )?;
756    Ok(())
757}