Skip to main content

gent_daemon/store/
invitations.rs

1//! Owner-local admission journal. Service approval never substitutes for this
2//! state. The only peer-facing entry points accept authenticated Noise traffic.
3use super::*;
4
5pub(super) fn validate_queued_enrollment(
6    db: &Connection,
7    state: &VerifiedState,
8    identity: &Identity,
9    id: &str,
10    request: &gent_crypto::SignedEnrollment,
11    can_configure: bool,
12    timestamp: u64,
13) -> Result<()> {
14    let row = record(db, id)?;
15    row.offer.verify_current(state, timestamp)?;
16    let claim = row.claim.as_ref().context("invitation claim is missing")?;
17    ensure!(
18        row.phase == "claimed"
19            && row.offer.offer.issuer_id == identity.node.id()
20            && row.offer.offer.issuer_key == identity.node.public_key()
21            && row.offer.offer.can_configure == can_configure
22            && row.offer.offer.replaces == request.request.replaces
23            && claim.id == request.request.node_id
24            && claim.key == request.request.member.signing_key
25            && claim.name == request.request.member.name,
26        "enrollment invitation is no longer authorized"
27    );
28    if matches!(&row.offer.offer.purpose, Purpose::NamedNode { .. }) {
29        ensure!(
30            state
31                .state()
32                .nodes
33                .iter()
34                .all(|(id, n)| id == &claim.id || n.name != claim.name),
35            "node name is already enrolled"
36        );
37    }
38    Ok(())
39}
40use gent_crypto::invitation::{
41    ClaimedNode, Options, OwnerInvitation, Purpose, ServiceBinding, SignedOffer,
42    channel::{Channel, Hello, PendingClaim},
43};
44use serde::{Deserialize, Serialize};
45use uuid::Uuid;
46use zeroize::Zeroizing;
47mod dispatch;
48mod replacement;
49#[cfg(test)]
50mod tests;
51
52const MAX_INVITATIONS: u64 = 128;
53const MAX_ATTEMPTS: u64 = 64;
54const MAX_OPERATIONS: u64 = 32_768;
55const MAX_INVITATION_OPERATIONS: u64 = 8192;
56const MAX_GRANTS: u64 = 4;
57
58pub(crate) fn schema(db: &Connection, previous: i64) -> Result<()> {
59    super::node_invites::schema(db)?;
60    if previous >= 14 {
61        for table in ["invitations", "invitation_operations", "invitation_clock"] {
62            let exists: bool = db.query_row(
63                "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name=?1)",
64                [table],
65                |r| r.get(0),
66            )?;
67            ensure!(
68                exists,
69                "invitation journal is missing; restore this node's state"
70            );
71        }
72        ensure!(
73            db.query_row(
74                "SELECT COUNT(*) FROM invitation_clock WHERE singleton=1",
75                [],
76                |r| r.get::<_, u64>(0)
77            )? == 1,
78            "invitation clock is missing; restore this node's state"
79        );
80    } else {
81        db.execute_batch("CREATE TABLE IF NOT EXISTS invitation_clock(singleton INTEGER PRIMARY KEY CHECK(singleton=1),floor INTEGER NOT NULL);
82        INSERT OR IGNORE INTO invitation_clock VALUES(1,0);
83        CREATE TABLE IF NOT EXISTS invitations(
84          id TEXT PRIMARY KEY,create_request TEXT UNIQUE NOT NULL,intent BLOB NOT NULL CHECK(length(intent)=32),
85          offer BLOB NOT NULL CHECK(length(offer)<=8192),secret BLOB CHECK(length(secret)<=16384),
86          phase TEXT NOT NULL CHECK(phase IN ('draft','issued','claimed','complete','revoked')),
87          expires INTEGER NOT NULL,claim BLOB CHECK(length(claim)<=1024),history_floor INTEGER,
88          attempts INTEGER NOT NULL DEFAULT 0 CHECK(attempts BETWEEN 0 AND 64));
89        CREATE INDEX IF NOT EXISTS invitations_expiry ON invitations(expires);
90        CREATE TABLE IF NOT EXISTS invitation_operations(
91          invitation TEXT NOT NULL REFERENCES invitations(id) ON DELETE CASCADE,id TEXT NOT NULL,
92          fingerprint BLOB NOT NULL CHECK(length(fingerprint)=32),kind TEXT NOT NULL,
93          done INTEGER NOT NULL DEFAULT 0 CHECK(done IN (0,1)),group_id BLOB CHECK(length(group_id)<=256),
94          PRIMARY KEY(invitation,id));
95        CREATE INDEX IF NOT EXISTS invitation_operation_kind ON invitation_operations(invitation,kind);")?;
96    }
97    if previous >= 15 {
98        ensure!(db.query_row(
99            "SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='invitation_attempts')",
100            [], |r| r.get::<_, bool>(0)
101        )?, "invitation attempt journal is missing; restore this node's state");
102    } else {
103        // Version 14 did not retain attempt IDs. It cannot safely distinguish
104        // old handshakes after an upgrade. Keep membership/keys, but close used
105        // offers; partial joins can use an explicit continuation invitation.
106        db.execute_batch("DELETE FROM invitation_operations WHERE invitation IN (SELECT id FROM invitations WHERE attempts>0);
107            UPDATE invitations SET phase='revoked',secret=NULL WHERE attempts>0;
108            CREATE TABLE IF NOT EXISTS invitation_attempts(
109              invitation TEXT NOT NULL REFERENCES invitations(id) ON DELETE CASCADE,
110              id TEXT NOT NULL CHECK(length(id)=36),PRIMARY KEY(invitation,id));")?;
111    }
112    Ok(())
113}
114
115struct Record {
116    offer: SignedOffer,
117    secret: Option<Zeroizing<Vec<u8>>>,
118    phase: String,
119    claim: Option<ClaimedNode>,
120    history_floor: Option<u64>,
121    attempts: u64,
122}
123type RecordRow = (
124    Vec<u8>,
125    Option<Vec<u8>>,
126    String,
127    Option<Vec<u8>>,
128    Option<u64>,
129    u64,
130    u64,
131);
132fn record(db: &Connection, id: &str) -> Result<Record> {
133    let (offer, secret, phase, claim, history_floor, attempts, expires): RecordRow = db.query_row("SELECT offer,secret,phase,claim,history_floor,attempts,expires FROM invitations WHERE id=?1", [id], |r| {
134        Ok((r.get(0)?,r.get(1)?,r.get(2)?,r.get(3)?,r.get(4)?,r.get(5)?,r.get(6)?))
135    }).optional()?.context("invitation unavailable")?;
136    let secret = secret.map(Zeroizing::new);
137    let offer = SignedOffer::decode(&offer)?;
138    ensure!(
139        offer.offer.id == id && expires == offer.offer.expires_at && attempts <= MAX_ATTEMPTS,
140        "invalid invitation journal binding"
141    );
142    let claim = claim
143        .map(|bytes| -> Result<ClaimedNode> {
144            ensure!(bytes.len() <= 1024, "invalid saved invitation claim");
145            serde_json::from_slice(&bytes).context("invalid saved invitation claim")
146        })
147        .transpose()?;
148    ensure!(
149        match phase.as_str() {
150            "draft" | "issued" => claim.is_none() && history_floor.is_none(),
151            "claimed" => claim.is_some(),
152            "complete" => claim.is_some() && history_floor.is_some(),
153            "revoked" => secret.is_none(),
154            _ => false,
155        },
156        "invalid invitation journal phase"
157    );
158    Ok(Record {
159        offer,
160        secret,
161        phase,
162        claim,
163        history_floor,
164        attempts,
165    })
166}
167
168/// Clock advancement commits independently of a rejected operation. Observing
169/// expiry and then rolling the clock back must not reactivate its credential.
170fn observe(db: &Connection, wall: u64) -> Result<u64> {
171    ensure!(wall > 0 && wall < (1 << 53), "invalid invitation clock");
172    db.execute(
173        "UPDATE invitation_clock SET floor=?1 WHERE singleton=1 AND floor<?1",
174        [wall],
175    )?;
176    let floor: u64 = db.query_row(
177        "SELECT floor FROM invitation_clock WHERE singleton=1",
178        [],
179        |r| r.get(0),
180    )?;
181    // Explicit child deletion also works when an OrderedEndpoint connection has
182    // SQLite foreign-key enforcement disabled. Both deletions commit together.
183    let tx = db.unchecked_transaction()?;
184    tx.execute("DELETE FROM invitation_operations WHERE invitation IN (SELECT id FROM invitations WHERE expires<=?1)", [floor])?;
185    tx.execute("DELETE FROM invitation_attempts WHERE invitation IN (SELECT id FROM invitations WHERE expires<=?1)", [floor])?;
186    tx.execute("DELETE FROM invitations WHERE expires<=?1", [floor])?;
187    tx.commit()?;
188    Ok(floor)
189}
190
191pub struct PendingSession {
192    pending: PendingClaim,
193}
194pub struct Session {
195    channel: Channel,
196}
197
198/// A bounded encrypted request, distinct from owner RPC. UUIDv4 operation IDs
199/// are scoped to this invitation; retries must preserve their complete input.
200#[derive(Clone, Serialize, Deserialize)]
201#[serde(deny_unknown_fields)]
202pub struct Invocation {
203    pub id: String,
204    pub action: Action,
205}
206#[derive(Clone, Serialize, Deserialize)]
207#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
208pub enum Action {
209    Pair { action: PairingOp },
210    Finish,
211}
212impl Invocation {
213    pub fn encode(&self) -> Result<Zeroizing<Vec<u8>>> {
214        let bytes = Zeroizing::new(serde_jcs::to_vec(self)?);
215        ensure!(
216            bytes.len() <= MAX_FRAME_BYTES,
217            "invitation request too large"
218        );
219        Ok(bytes)
220    }
221    fn decode(bytes: &[u8]) -> Result<Self> {
222        ensure!(
223            bytes.len() <= MAX_FRAME_BYTES,
224            "invitation request too large"
225        );
226        let value: Self = serde_json::from_slice(bytes)
227            .map_err(|_| anyhow::anyhow!("invalid invitation request"))?;
228        ensure!(
229            *value.encode()? == bytes,
230            "invitation request must use canonical JSON"
231        );
232        canonical_v4(&value.id)?;
233        Ok(value)
234    }
235}
236fn canonical_v4(value: &str) -> Result<Uuid> {
237    let id = Uuid::parse_str(value).context("invalid invitation operation ID")?;
238    ensure!(
239        id.get_version_num() == 4
240            && id.get_variant() == uuid::Variant::RFC4122
241            && id.to_string() == value,
242        "invitation operation ID must be UUIDv4"
243    );
244    Ok(id)
245}
246
247impl Store {
248    pub(super) fn manage_invitation(
249        &mut self,
250        credential: &str,
251        action: InvitationOp,
252    ) -> Result<Value> {
253        self.invitation_owner(credential)?;
254        match action {
255            InvitationOp::Create {
256                request_id,
257                can_configure,
258                continuation,
259                replace_node,
260            } => {
261                let bytes = self.create_invitation_with_replacement(
262                    credential,
263                    &request_id,
264                    can_configure,
265                    continuation.as_deref(),
266                    replace_node.as_deref(),
267                )?;
268                Ok(json!({"private_invitation": STANDARD.encode(bytes.as_slice())}))
269            }
270            InvitationOp::Activate { id } => {
271                self.activate_invitation(credential, &id)?;
272                Ok(json!({"id":id,"active":true}))
273            }
274            InvitationOp::Revoke { id } => {
275                self.revoke_invitation(credential, &id)?;
276                Ok(json!({"id":id,"revoked":true}))
277            }
278            InvitationOp::List => {
279                let _lock = config::state_lock(&self.home, "invitation.lock")?;
280                observe(&self.db, now() as u64)?;
281                let mut query = self
282                    .db
283                    .prepare("SELECT id FROM invitations ORDER BY id LIMIT 129")?;
284                let ids = query
285                    .query_map([], |r| r.get::<_, String>(0))?
286                    .collect::<rusqlite::Result<Vec<_>>>()?;
287                ensure!(
288                    ids.len() <= MAX_INVITATIONS as usize,
289                    "invalid invitation journal size"
290                );
291                let records = ids.iter().map(|id| {
292                    let row = record(&self.db, id)?;
293                    let mut value = json!({"id":id,"phase":row.phase,"expires_at":row.offer.offer.expires_at,
294                        "can_configure":row.offer.offer.can_configure,"node":row.claim});
295                    if let Some(target) = &row.offer.offer.replaces {
296                        value["replaces"] = json!(target);
297                    }
298                    Ok(value)
299                }).collect::<Result<Vec<_>>>()?;
300                Ok(json!({"invitations":records}))
301            }
302        }
303    }
304
305    /// Local scheduling metadata only. No private offer material leaves Store.
306    /// This rechecks current native authority even when service access survives.
307    pub(crate) fn invitation_jobs(&mut self) -> Result<Vec<SignedOffer>> {
308        self.process_node_invites()?;
309        if self.config.service.is_none()
310            || !self
311                .identity
312                .can_administer(&self.identity.state(&self.db)?)
313        {
314            return Ok(Vec::new());
315        }
316        if !self
317            .db
318            .query_row("SELECT EXISTS(SELECT 1 FROM invitations)", [], |r| {
319                r.get::<_, bool>(0)
320            })?
321        {
322            return Ok(Vec::new());
323        }
324        let _lock = config::state_lock(&self.home, "invitation.lock")?;
325        let timestamp = observe(&self.db, now() as u64)?;
326        let ids = self.db.prepare(
327            "SELECT id FROM invitations WHERE phase IN ('issued','claimed','complete') ORDER BY id LIMIT 129"
328        )?.query_map([], |r| r.get::<_, String>(0))?.collect::<rusqlite::Result<Vec<_>>>()?;
329        ensure!(
330            ids.len() <= MAX_INVITATIONS as usize,
331            "invalid invitation journal size"
332        );
333        let mut offers = Vec::new();
334        for id in ids {
335            let row = record(&self.db, &id)?;
336            if self.invitation_authority(&row, timestamp).is_ok() {
337                offers.push(row.offer);
338            }
339        }
340        Ok(offers)
341    }
342
343    pub(crate) fn invitation_bearer(&self) -> Result<Zeroizing<String>> {
344        let settings = self
345            .config
346            .relay
347            .as_ref()
348            .context("invitation relay unavailable")?;
349        Ok(Zeroizing::new(config::read_relay_credential(
350            &self.home.join(&settings.credential_file),
351        )?))
352    }
353
354    /// Recheck before sending a cached response, including a completed Finish.
355    /// Revocation cannot retract bytes already released to a network request.
356    pub(crate) fn invitation_live(&mut self, offer: &SignedOffer) -> Result<()> {
357        let _lock = config::state_lock(&self.home, "invitation.lock")?;
358        let timestamp = observe(&self.db, now() as u64)?;
359        let row = record(&self.db, &offer.offer.id)?;
360        self.invitation_authority(&row, timestamp)?;
361        ensure!(
362            row.offer == *offer && matches!(row.phase.as_str(), "issued" | "claimed" | "complete"),
363            "invitation unavailable"
364        );
365        Ok(())
366    }
367
368    pub(crate) fn invitation_claim_receipt(
369        &mut self,
370        session: &mut Session,
371    ) -> Result<Vec<Vec<u8>>> {
372        self.invitation_live(session.channel.offer())?;
373        session
374            .channel
375            .seal(crate::invitation_transport::CLAIM_RECEIPT, now() as u64)
376    }
377
378    fn invitation_owner(&self, credential: &str) -> Result<()> {
379        ensure!(hash(credential) == self.owner_hash, "unauthorized");
380        self.identity.require_administrator(&self.db)?;
381        Ok(())
382    }
383    fn invitation_service(&self) -> Result<ServiceBinding> {
384        let account = self
385            .config
386            .service
387            .as_ref()
388            .context("invitation enrollment requires service setup")?;
389        ensure!(
390            !self.config.cluster.local_only,
391            "invitation enrollment requires a service cluster"
392        );
393        let relay = self
394            .config
395            .relay
396            .as_ref()
397            .context("invitation enrollment requires a service relay")?;
398        // Config origins historically include a trailing slash. Sign the
399        // canonical origins, then compare the same representation on every use.
400        let service = ServiceBinding {
401            account_id: account.account_id.clone(),
402            account_origin: account.origin.trim_end_matches('/').into(),
403            relay_origin: relay.endpoint.trim_end_matches('/').into(),
404        };
405        service.validate()?;
406        Ok(service)
407    }
408    fn invitation_authority(&self, record: &Record, timestamp: u64) -> Result<VerifiedState> {
409        self.identity.require_administrator(&self.db)?;
410        let state = self.identity.state(&self.db)?;
411        record.offer.verify_current(&state, timestamp)?;
412        // Continue an exact enrolled identity, including a lost Finish reply.
413        // A draft or claim for a new identity still needs a current paid lease.
414        if record.offer.offer.purpose.continuation().is_none()
415            && !record.claim.as_ref().is_some_and(|node| {
416                state
417                    .state()
418                    .nodes
419                    .get(&node.id)
420                    .is_some_and(|m| m.signing_key == node.key)
421            })
422        {
423            require_pro(&self.home, &self.config, "Inviting another node")?;
424        }
425        ensure!(
426            record.offer.offer.issuer_id == self.identity.node.id()
427                && record.offer.offer.issuer_key == self.identity.node.public_key()
428                && record.offer.offer.service == self.invitation_service()?,
429            "invitation owner or service changed"
430        );
431        state.authorize_node(
432            self.identity.node.id(),
433            &self.identity.node.public_key(),
434            timestamp,
435        )?;
436        ensure!(record.phase != "revoked", "invitation revoked");
437        self.invitation_replacement(record, &state, timestamp)?;
438        if let Some(node) = &record.claim {
439            ensure!(
440                !state.state().retired_nodes.contains(&node.id)
441                    && !state.state().retired_keys.contains(&node.key),
442                "invitation node was retired"
443            );
444            if let Some(member) = state.state().nodes.get(&node.id) {
445                ensure!(
446                    member.signing_key == node.key
447                        && member.name == node.name
448                        && member.can_configure == record.offer.offer.can_configure,
449                    "invitation node identity or privileges changed"
450                );
451            } else {
452                ensure!(
453                    record.history_floor.is_none()
454                        && record.offer.offer.purpose.continuation().is_none()
455                        && matches!(
456                            record.offer.offer.purpose,
457                            Purpose::NewNode | Purpose::NamedNode { .. }
458                        ),
459                    "invitation node is no longer enrolled"
460                );
461            }
462        }
463        Ok(state)
464    }
465
466    /// Owner-only local API. The returned bytes are for protected transfer,
467    /// never an MCP response or a public account-service request.
468    pub fn create_invitation(
469        &mut self,
470        credential: &str,
471        request: &str,
472        can_configure: bool,
473        continuation: Option<&str>,
474    ) -> Result<Zeroizing<Vec<u8>>> {
475        self.create_invitation_with_replacement(
476            credential,
477            request,
478            can_configure,
479            continuation,
480            None,
481        )
482    }
483
484    pub fn create_invitation_with_replacement(
485        &mut self,
486        credential: &str,
487        request: &str,
488        can_configure: bool,
489        continuation: Option<&str>,
490        replace_node: Option<&str>,
491    ) -> Result<Zeroizing<Vec<u8>>> {
492        self.invitation_owner(credential)?;
493        self.maintain()?;
494        self.create_invitation_at(
495            request,
496            can_configure,
497            continuation,
498            replace_node,
499            None,
500            now() as u64,
501        )
502    }
503    pub(super) fn create_invitation_at(
504        &mut self,
505        request: &str,
506        can_configure: bool,
507        continuation: Option<&str>,
508        replace_node: Option<&str>,
509        name: Option<(&str, &str)>,
510        wall: u64,
511    ) -> Result<Zeroizing<Vec<u8>>> {
512        let _lock = config::state_lock(&self.home, "invitation.lock")?;
513        let timestamp = observe(&self.db, wall)?;
514        let service = self.invitation_service()?;
515        ensure!(
516            continuation.is_none() || replace_node.is_none(),
517            "choose replacement or continuation, not both"
518        );
519        // Preserve the original ordinary-invitation retry fingerprint.
520        ensure!(
521            name.is_none() || (continuation.is_none() && replace_node.is_none()),
522            "named invitations must enroll a new node"
523        );
524        let intent: [u8; 32] = Sha256::digest(match (replace_node, name) {
525            (_, Some(name)) => serde_jcs::to_vec(&("named", can_configure, name, &service))?,
526            (None, None) => serde_jcs::to_vec(&(can_configure, continuation, &service))?,
527            (Some(target), None) => {
528                serde_jcs::to_vec(&(can_configure, continuation, &service, target))?
529            }
530        })
531        .into();
532        let previous: Option<(String, Vec<u8>)> = self
533            .db
534            .query_row(
535                "SELECT id,intent FROM invitations WHERE create_request=?1",
536                [request],
537                |r| Ok((r.get(0)?, r.get(1)?)),
538            )
539            .optional()?;
540        if let Some((id, saved)) = previous {
541            ensure!(
542                saved == intent,
543                "invitation creation request already used with different options"
544            );
545            let row = record(&self.db, &id)?;
546            self.invitation_authority(&row, timestamp)?;
547            let private = row.secret.context("invitation secret unavailable")?;
548            return OwnerInvitation::decode(&private)?.invitation().encode();
549        }
550        let issued =
551            requests::issued(request).context("invitation creation request must be UUIDv7")? as u64;
552        ensure!(
553            issued <= timestamp && timestamp - issued < gent_crypto::invitation::OFFER_LIFETIME,
554            "invitation creation request expired or is from the future"
555        );
556        let state = self.identity.state(&self.db)?;
557        let purpose = match (continuation, name) {
558            (None, Some((name, inviter))) => {
559                let mut matching = state
560                    .state()
561                    .nodes
562                    .iter()
563                    .filter(|(_, member)| member.name == name);
564                let existing = matching.next();
565                ensure!(
566                    matching.next().is_none(),
567                    "multiple nodes have this name; use an explicit node ID invitation"
568                );
569                let continuation = existing.map(|(id, member)| ClaimedNode {
570                    id: id.clone(),
571                    key: member.signing_key,
572                    name: member.name.clone(),
573                });
574                Purpose::NamedNode {
575                    name: name.into(),
576                    inviter: inviter.into(),
577                    continuation,
578                }
579            }
580            (None, None) => Purpose::NewNode,
581            (Some(id), _) => {
582                let member = state
583                    .state()
584                    .nodes
585                    .get(id)
586                    .context("continuation node unavailable")?;
587                Purpose::Continue {
588                    node: ClaimedNode {
589                        id: id.into(),
590                        key: member.signing_key,
591                        name: member.name.clone(),
592                    },
593                }
594            }
595        };
596        if purpose.continuation().is_none() {
597            require_pro(&self.home, &self.config, "Inviting another node")?;
598        }
599        let (replaces, can_configure) = match (&purpose, replace_node) {
600            (Purpose::NewNode, Some(id)) => {
601                ensure!(
602                    id != self.identity.node.id(),
603                    "cannot replace the signing owner through an invitation"
604                );
605                let member = state
606                    .state()
607                    .nodes
608                    .get(id)
609                    .context("replacement target is unavailable")?;
610                (
611                    Some(gent_crypto::ReplacedNode {
612                        id: id.into(),
613                        signing_key: member.signing_key,
614                    }),
615                    can_configure && member.can_configure,
616                )
617            }
618            (Purpose::Continue { node }, None) => (
619                removals::replacement_target(&self.db, &state, &node.id, &node.key)?,
620                can_configure,
621            ),
622            (Purpose::NewNode | Purpose::NamedNode { .. }, None) => (None, can_configure),
623            _ => unreachable!("exclusive replacement and continuation checked"),
624        };
625        let tx = self.db.unchecked_transaction()?;
626        ensure!(
627            tx.query_row("SELECT COUNT(*) FROM invitations", [], |r| r
628                .get::<_, u64>(0))?
629                < MAX_INVITATIONS,
630            "invitation capacity reached; wait for existing offers to expire"
631        );
632        let options = Options {
633            service,
634            purpose,
635            can_configure,
636            replaces,
637        };
638        let owner = if state.state().peer.is_some() {
639            OwnerInvitation::issue_peer(&state, &self.identity.node, options, timestamp)?
640        } else {
641            OwnerInvitation::issue(
642                &*self.identity.signing_owner(&self.db)?,
643                &state,
644                &self.identity.node,
645                options,
646                timestamp,
647            )?
648        };
649        let offer = owner.invitation().offer();
650        let private = owner.encode()?;
651        tx.execute("INSERT INTO invitations(id,create_request,intent,offer,secret,phase,expires) VALUES(?1,?2,?3,?4,?5,'draft',?6)", params![offer.offer.id,request,intent.as_slice(),offer.encode()?,private.as_slice(),offer.offer.expires_at])?;
652        tx.commit()?;
653        owner.invitation().encode()
654    }
655
656    /// Called after the account service confirms the exact persisted draft.
657    /// The activation itself does not make an account or cryptographic member.
658    pub fn activate_invitation(&mut self, credential: &str, id: &str) -> Result<()> {
659        self.invitation_owner(credential)?;
660        let _lock = config::state_lock(&self.home, "invitation.lock")?;
661        let timestamp = observe(&self.db, now() as u64)?;
662        let row = record(&self.db, id)?;
663        self.invitation_authority(&row, timestamp)?;
664        self.db.execute(
665            "UPDATE invitations SET phase='issued' WHERE id=?1 AND phase='draft'",
666            [id],
667        )?;
668        Ok(())
669    }
670    pub fn revoke_invitation(&mut self, credential: &str, id: &str) -> Result<()> {
671        self.invitation_owner(credential)?;
672        let issued =
673            gent_protocol::service::invitations::issued_at(id).context("invalid invitation ID")?;
674        let _lock = config::state_lock(&self.home, "invitation.lock")?;
675        let timestamp = observe(&self.db, now() as u64)?;
676        let tx = self.db.unchecked_transaction()?;
677        let changed = tx.execute(
678            "UPDATE invitations SET phase='revoked',secret=NULL WHERE id=?1",
679            [id],
680        )?;
681        ensure!(
682            changed == 1 || timestamp >= issued + gent_crypto::invitation::OFFER_LIFETIME,
683            "invitation unavailable"
684        );
685        tx.execute(
686            "DELETE FROM invitation_operations WHERE invitation=?1",
687            [id],
688        )?;
689        tx.commit()?;
690        Ok(())
691    }
692
693    pub fn begin_invitation(
694        &mut self,
695        id: &str,
696        hello: &Hello,
697    ) -> Result<(PendingSession, Vec<u8>)> {
698        let _lock = config::state_lock(&self.home, "invitation.lock")?;
699        let timestamp = observe(&self.db, now() as u64)?;
700        let row = record(&self.db, id)?;
701        self.invitation_authority(&row, timestamp)?;
702        canonical_v4(&hello.attempt)?;
703        ensure!(
704            !self.invitation_attempt_seen(id, &hello.attempt)?,
705            "invitation attempt already admitted; use a fresh handshake"
706        );
707        ensure!(
708            row.phase != "draft" && row.attempts < MAX_ATTEMPTS,
709            "invitation unavailable or attempt budget exhausted"
710        );
711        let private = row.secret.context("invitation secret unavailable")?;
712        let owner = OwnerInvitation::decode(&private)?;
713        ensure!(
714            owner.invitation().offer() == &row.offer,
715            "invitation private record changed"
716        );
717        let (pending, reply) = owner.respond(hello, timestamp)?;
718        let tx = self.db.unchecked_transaction()?;
719        tx.execute(
720            "INSERT INTO invitation_attempts(invitation,id) VALUES(?1,?2)",
721            params![id, hello.attempt],
722        )?;
723        tx.execute(
724            "UPDATE invitations SET attempts=attempts+1 WHERE id=?1",
725            [id],
726        )?;
727        tx.commit()?;
728        Ok((PendingSession { pending }, reply))
729    }
730
731    /// Scheduling hint only. Admission rechecks under the invitation lock and
732    /// commits the ID before releasing a handshake response. A lost in-memory
733    /// session must never be reconstructed from an already admitted Hello.
734    pub fn invitation_attempt_seen(&self, id: &str, attempt: &str) -> Result<bool> {
735        canonical_v4(attempt)?;
736        Ok(self.db.query_row(
737            "SELECT EXISTS(SELECT 1 FROM invitation_attempts WHERE invitation=?1 AND id=?2)",
738            params![id, attempt],
739            |r| r.get(0),
740        )?)
741    }
742    pub fn accept_invitation(
743        &mut self,
744        pending: PendingSession,
745        frames: &[Vec<u8>],
746    ) -> Result<Session> {
747        let _lock = config::state_lock(&self.home, "invitation.lock")?;
748        let timestamp = observe(&self.db, now() as u64)?;
749        let channel = pending.pending.accept(frames, timestamp, |offer, node| {
750            self.claim_invitation(offer, node, timestamp)
751        })?;
752        Ok(Session { channel })
753    }
754    fn claim_invitation(
755        &mut self,
756        offer: &SignedOffer,
757        node: &ClaimedNode,
758        timestamp: u64,
759    ) -> Result<()> {
760        if let Purpose::NamedNode { name, .. } = &offer.offer.purpose {
761            ensure!(
762                &node.name == name,
763                "invitation requires its assigned node name"
764            );
765        }
766        let row = record(&self.db, &offer.offer.id)?;
767        let state = self.invitation_authority(&row, timestamp)?;
768        ensure!(
769            &row.offer == offer && row.phase != "draft",
770            "invitation claim changed"
771        );
772        if let Some(saved) = &row.claim {
773            ensure!(saved == node, "invitation already claimed by another node");
774            return Ok(());
775        }
776        ensure!(row.phase == "issued", "invitation is not claimable");
777        let floor = match offer.offer.purpose.continuation() {
778            None => {
779                if matches!(&offer.offer.purpose, Purpose::NamedNode { .. }) {
780                    ensure!(
781                        !state
782                            .state()
783                            .nodes
784                            .values()
785                            .any(|member| member.name == node.name),
786                        "this node name is already enrolled; run gent node add with the same name for a continuation code"
787                    );
788                }
789                ensure!(
790                    !state.state().nodes.contains_key(&node.id)
791                        && !state.state().retired_nodes.contains(&node.id)
792                        && !state.state().retired_keys.contains(&node.key)
793                        && !state
794                            .state()
795                            .nodes
796                            .values()
797                            .any(|n| n.signing_key == node.key),
798                    "node already enrolled or retired; use an explicit continuation"
799                );
800                None
801            }
802            Some(expected) => {
803                ensure!(node == expected, "continuation identity changed");
804                state.authorize_node(&node.id, &node.key, timestamp)?;
805                let member = &state.state().nodes[&node.id];
806                ensure!(
807                    member.name == node.name && member.can_configure == offer.offer.can_configure,
808                    "continuation privileges changed"
809                );
810                Some(
811                    self.db
812                        .query_row("SELECT MIN(revision) FROM authority_history", [], |r| {
813                            r.get::<_, u64>(0)
814                        })?,
815                )
816            }
817        };
818        let tx = self.db.unchecked_transaction()?;
819        let changed = tx.execute("UPDATE invitations SET phase='claimed',claim=?2,history_floor=?3 WHERE id=?1 AND phase='issued' AND claim IS NULL", params![offer.offer.id,serde_jcs::to_vec(node)?,floor])?;
820        ensure!(changed == 1, "invitation claim raced another writer");
821        tx.commit()?;
822        Ok(())
823    }
824
825    pub fn invitation_call(
826        &mut self,
827        session: &mut Session,
828        frames: &[Vec<u8>],
829    ) -> Result<Vec<Vec<u8>>> {
830        let timestamp = now() as u64;
831        let bytes = session.channel.open(frames, timestamp)?;
832        let response = match Invocation::decode(&bytes)
833            .and_then(|request| self.dispatch_invitation(&session.channel, request, timestamp))
834        {
835            Ok(value) => Response::Ok(value),
836            Err(error) => Response::Error(error.to_string().chars().take(1024).collect()),
837        };
838        let bytes = Zeroizing::new(serde_json::to_vec(&response)?);
839        session.channel.seal(&bytes, now() as u64)
840    }
841
842    /// Startup/periodic maintenance also retires expired secrets and retry rows.
843    pub(super) fn clean_invitations(&mut self) -> Result<()> {
844        let any: bool = self
845            .db
846            .query_row("SELECT EXISTS(SELECT 1 FROM invitations)", [], |r| r.get(0))?;
847        if any {
848            let _lock = config::state_lock(&self.home, "invitation.lock")?;
849            observe(&self.db, now() as u64)?;
850        }
851        Ok(())
852    }
853}