1use crate::{
2 config::{self, Config},
3 encrypted,
4 runtime::{self, Identity},
5};
6use anyhow::{Context, Result, ensure};
7use base64::{Engine, engine::general_purpose::STANDARD};
8use gent_crypto::VerifiedState;
9use gent_protocol::*;
10use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
11use serde_json::{Value, json};
12use sha2::{Digest, Sha256};
13use std::{
14 collections::{BTreeMap, BTreeSet},
15 path::{Path, PathBuf},
16 sync::Arc,
17 time::{SystemTime, UNIX_EPOCH},
18};
19use tokio::sync::Notify;
20mod activity;
21mod administration;
22mod agents;
23mod babysitter;
24mod configuration;
25mod message_dates;
26mod notifications;
27mod ordinary_babysitter;
28mod stats_sync;
29mod usage;
30mod wire;
31pub(crate) use configuration::pending::schema as pending_configuration_schema;
32pub(crate) use configuration::routing::schema as configuration_routing_schema;
33mod dashboards;
34pub use dashboards::grant_verifier;
35mod diagnostics;
36pub mod direct;
37pub(crate) mod directory;
38mod directory_sync;
39mod files;
40pub(crate) mod handoff;
41mod history;
42pub(crate) mod hosted;
43pub mod invitations;
44mod mesh;
45mod network;
46pub mod node_invites;
47mod pairing;
48pub(crate) mod peer_configuration;
49mod permissions;
50mod presence;
51mod recovered;
52mod relay;
53pub(crate) mod removals;
54mod requests;
55#[cfg(test)]
56mod storage_tests;
57mod synchronization;
58mod wake;
59pub use wake::wake_binding_tag;
60mod work;
61
62pub fn now() -> i64 {
63 SystemTime::now()
64 .duration_since(UNIX_EPOCH)
65 .expect("clock before epoch")
66 .as_secs()
67 .try_into()
68 .expect("clock overflow")
69}
70fn hash(value: &str) -> String {
71 format!("{:x}", Sha256::digest(value.as_bytes()))
72}
73fn require_pro(home: &Path, cfg: &Config, feature: &str) -> Result<()> {
74 ensure!(
75 crate::entitlements::paid(home, cfg),
76 "{feature} requires an active Gent Pro plan for this cluster. See https://gent.link/pricing"
77 );
78 Ok(())
79}
80const UNAVAILABLE: &str = "recipient or message unavailable";
81
82pub struct Store {
83 db: Connection,
84 direct_certs: direct::CertificateCache,
85 pub(crate) board_transport: std::sync::Weak<crate::sync::direct::Direct>,
86 home: PathBuf,
87 config: Config,
88 identity: Identity,
89 owner_hash: String,
90 stats_cache: Option<stats_sync::Ranking>,
91 stats_poll: Option<stats_sync::Poll>,
92 pub(crate) sync_wakeup: Arc<Notify>,
93 pub(crate) sync_health: Arc<crate::sync::health::Health>,
94}
95impl Store {
96 pub(crate) fn local_node_id(&self) -> &str {
97 self.identity.node.id()
98 }
99 pub fn require_provisioning_owner(&self) -> Result<()> {
102 self.identity.signing_owner(&self.db)?;
103 self.require_provisioning_member()
104 }
105
106 pub fn require_provisioning_member(&self) -> Result<()> {
107 let state = self.identity.state(&self.db)?;
108 ensure!(
109 state
110 .state()
111 .nodes
112 .get(self.identity.node.id())
113 .is_some_and(|n| n.signing_key == self.identity.node.public_key()),
114 "this node is no longer enrolled in the cluster"
115 );
116 Ok(())
119 }
120 pub fn require_provisioning_joined(&self) -> Result<()> {
121 ensure!(
122 !self
123 .identity
124 .is_current_owner(&self.identity.state(&self.db)?),
125 "the existing owner cannot be replaced by a joined identity"
126 );
127 self.require_provisioning_member()
128 }
129
130 pub fn require_service_setup_role(&self, originally_owner: bool) -> Result<()> {
134 let state = self.identity.state(&self.db)?;
135 if state.owner_epoch() > 0 || state.state().peer.is_some() {
136 self.require_provisioning_member()
137 } else if originally_owner {
138 self.require_provisioning_owner()
139 } else {
140 self.require_provisioning_joined()
141 }
142 }
143
144 pub fn open(home: &Path) -> Result<Self> {
145 let config = config::load_for_runtime(home)?;
146 ensure!(
147 config.hosted_parent()?.is_none(),
148 "this web node is served by its native host daemon"
149 );
150 let replacement = crate::pairing::replacement::check_intent(home, &config, None)?;
151 let owner_hash = hash(&config::read_private(&home.join("owner.key"))?);
152 ensure!(
153 home.join("state.sqlite3").exists() || !home.join(runtime::KEY_FILE).exists(),
154 "authority database is missing; restore this node's state"
155 );
156 let mut db = encrypted::open_database(home, "state.sqlite3")?;
157 db.busy_timeout(std::time::Duration::from_secs(5))?;
158 db.execute_batch("PRAGMA foreign_keys=ON;
159 CREATE TABLE IF NOT EXISTS agents (id TEXT PRIMARY KEY, credential_hash TEXT UNIQUE NOT NULL, node_id TEXT NOT NULL, name TEXT NOT NULL, provider TEXT NOT NULL, last_seen INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);
160 CREATE TABLE IF NOT EXISTS exchanges (id TEXT PRIMARY KEY, a TEXT NOT NULL REFERENCES agents(id), b TEXT NOT NULL REFERENCES agents(id), expires_at INTEGER NOT NULL, count INTEGER NOT NULL);
161 CREATE TABLE IF NOT EXISTS messages (id TEXT PRIMARY KEY, sender TEXT NOT NULL REFERENCES agents(id), recipient TEXT NOT NULL REFERENCES agents(id), request_id TEXT NOT NULL, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, acknowledged INTEGER NOT NULL DEFAULT 0, UNIQUE(sender,request_id));
162 CREATE INDEX IF NOT EXISTS messages_inbox ON messages(recipient,acknowledged);
163 CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY,value TEXT NOT NULL);
164 CREATE TABLE IF NOT EXISTS stream_relay_upload (
165 group_id BLOB PRIMARY KEY REFERENCES streams(group_id) ON DELETE CASCADE,
166 next_sequence INTEGER NOT NULL CHECK(next_sequence >= 0)
167 );")?;
168 network::schema(&db)?;
169 configuration::schema(&db)?;
170 peer_configuration::schema(&db)?;
171 mesh::schema(&db)?;
172 relay::schema(&db)?;
173 files::schema(&mut db)?;
174 requests::schema(&db, now())?;
175 history::schema(&db)?;
176 recovered::schema(&db)?;
177 work::schema(&db)?;
178 wake::schema(&db)?;
179 presence::schema(&db)?;
180 directory::schema(&db)?;
181 activity::schema(&db)?;
182 wire::schema(&db)?;
183 dashboards::schema(&db)?;
184 babysitter::schema(&db)?;
185 ordinary_babysitter::schema(&db)?;
186 notifications::schema(&db)?;
187 hosted::schema(&db)?;
188 directory_sync::schema(&db)?;
189 direct::schema(&db)?;
190 db.execute("UPDATE hosted_checkpoints SET lease_until=0", [])?;
191 let previous: Option<String> = db
192 .query_row("SELECT value FROM metadata WHERE key='cluster'", [], |r| {
193 r.get(0)
194 })
195 .optional()?;
196 if let Some(previous) = previous {
197 ensure!(
198 previous == config.cluster.id,
199 "database belongs to another cluster"
200 );
201 } else {
202 db.execute(
203 "INSERT INTO metadata VALUES ('cluster',?1)",
204 [&config.cluster.id],
205 )?;
206 }
207 let previous_node: Option<String> = db
208 .query_row("SELECT value FROM metadata WHERE key='node'", [], |r| {
209 r.get(0)
210 })
211 .optional()?;
212 if let Some(previous_node) = previous_node {
213 ensure!(
214 previous_node == config.node.id,
215 "database belongs to another node"
216 );
217 } else {
218 db.execute("INSERT INTO metadata VALUES ('node',?1)", [&config.node.id])?;
219 }
220 let tx = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
221 let identity = Identity::load_or_create(home, &config, &tx, now() as u64)?;
222 peer_configuration::check_state(&tx, &identity.state(&tx)?)?;
223 directory::backfill_names(&tx, &identity.state(&tx)?)?;
224 message_dates::migrate(&tx, identity.node.id())?;
225 usage::migrate(&tx, identity.node.id(), now())?;
226 stats_sync::schema(&tx)?;
227 configuration::pending::recover(&tx, identity.node.id())?;
228 if let Some(record) = replacement {
229 record.verify_node(&identity.node)?;
230 let target = record.replaces;
231 let state = identity.state(&tx)?;
232 ensure!(
233 !state.state().nodes.contains_key(&target.id)
234 && state.state().retired_nodes.contains(&target.id)
235 && state.state().retired_keys.contains(&target.signing_key),
236 "replacement record does not match signed retirement"
237 );
238 }
239 if !identity.is_current_owner(&identity.state(&tx)?) {
240 tx.execute("DELETE FROM authority_join_pins", [])?;
243 }
244 tx.commit()?;
245 let mut store = Self {
246 direct_certs: Default::default(),
247 db,
248 home: home.into(),
249 config,
250 owner_hash,
251 identity,
252 sync_wakeup: Arc::new(Notify::new()),
253 sync_health: Arc::default(),
254 board_transport: Default::default(),
255 stats_cache: None,
256 stats_poll: None,
257 };
258 let _ = store.project_config();
260 Ok(store)
261 }
262
263 pub fn handle(&mut self, request: Request) -> Response {
264 match self.execute(request) {
265 Ok(value) => Response::Ok(value),
266 Err(error) => Response::Error(error.to_string()),
267 }
268 }
269
270 fn require_owner_credential(&self, credential: &str) -> Result<()> {
271 ensure!(hash(credential) == self.owner_hash, "unauthorized");
272 Ok(())
273 }
274
275 fn execute(&mut self, request: Request) -> Result<Value> {
276 if let Request::Agent {
277 credential,
278 action: AgentOp::FileExport { file_id },
279 } = &request
280 {
281 for step in [
284 files::ExportStep::Reserve,
285 files::ExportStep::Write,
286 files::ExportStep::Publish,
287 ] {
288 let value = self.execute_step(
289 Request::Agent {
290 credential: credential.clone(),
291 action: AgentOp::FileExport {
292 file_id: file_id.clone(),
293 },
294 },
295 step,
296 )?;
297 if !value.is_null() {
298 return Ok(value);
299 }
300 }
301 anyhow::bail!("export did not finish");
302 }
303 self.execute_step(request, files::ExportStep::Reserve)
304 }
305
306 fn execute_step(&mut self, request: Request, export_step: files::ExportStep) -> Result<Value> {
307 if let Request::Owner { credential, .. } = &request {
308 self.require_owner_credential(credential)?;
309 if matches!(
310 &request,
311 Request::Owner {
312 action: OwnerOp::Stats,
313 ..
314 }
315 ) {
316 return self.stats_snapshot(None);
317 }
318 }
319 if let Request::Owner {
320 action:
321 OwnerOp::RestoreWebNode {
322 node_id,
323 home,
324 checkpoint,
325 epoch,
326 },
327 ..
328 } = &request
329 {
330 return self.restore_web_node(node_id, home, checkpoint, *epoch);
331 }
332 if let Request::Owner {
333 action: OwnerOp::PrepareHostedNode { node_id, home },
334 ..
335 } = &request
336 {
337 return self.prepare_hosted_node(node_id, home);
338 }
339 if let Request::Owner {
340 credential,
341 action: OwnerOp::PreparePeerConfiguration,
342 } = &request
343 {
344 return Ok(serde_json::to_value(
345 self.prepare_configuration_log(credential)?,
346 )?);
347 }
348 if matches!(
349 &request,
350 Request::Owner {
351 action: OwnerOp::Diagnose,
352 ..
353 }
354 ) {
355 return self.diagnose();
356 }
357 if let Request::Owner {
358 action: OwnerOp::Pair { cluster_id, action },
359 ..
360 } = request
361 {
362 return self.pair(&cluster_id, action);
363 }
364 if let Request::Owner {
365 credential,
366 action: OwnerOp::Invitation { action },
367 } = request
368 {
369 return self.manage_invitation(&credential, action);
370 }
371 if let Request::Owner {
372 credential,
373 action: OwnerOp::OwnerTransfer { action },
374 } = request
375 {
376 return self.owner_transfer(&credential, action);
377 }
378 let projection_pending = runtime::projection_pending(&self.db)?;
382 let local_only = matches!(
383 &request,
384 Request::Agent {
385 action: AgentOp::WakePending
386 | AgentOp::BabysitterClaim { .. }
387 | AgentOp::BabysitterChatProbe { .. }
388 | AgentOp::BabysitterChatClaim { .. }
389 | AgentOp::BabysitterChatCheck { .. }
390 | AgentOp::BabysitterChatSubmitted { .. }
391 | AgentOp::BabysitterCheck { .. }
392 | AgentOp::BabysitterSubmitted { .. },
393 ..
394 } | Request::Owner {
395 action: OwnerOp::NotificationPut { .. }
396 | OwnerOp::NotificationSent { .. }
397 | OwnerOp::BabysitterVerifiedBlockedClaim { .. },
398 ..
399 }
400 );
401 let read_only = (matches!(
402 &request,
403 Request::Owner {
404 action: OwnerOp::Status
405 | OwnerOp::Agents
406 | OwnerOp::Nodes
407 | OwnerOp::Dashboards { .. }
408 | OwnerOp::NotificationPending { .. }
409 | OwnerOp::WebCheckpoint { .. }
410 | OwnerOp::WebDeliveryDemand { .. }
411 | OwnerOp::NodeRemovals { .. }
412 | OwnerOp::WakePendingAgents { .. }
413 | OwnerOp::WakeDirectTurnEvidence { .. },
414 ..
415 }
416 ) || matches!(
417 &request,
418 Request::HostedStatus { .. }
419 | Request::Agent {
420 action: AgentOp::BabysitterChatProbe { .. },
421 ..
422 }
423 )) && !projection_pending;
424 let tx = self.db.transaction_with_behavior(if read_only {
425 TransactionBehavior::Deferred
426 } else {
427 TransactionBehavior::Immediate
428 })?;
429 let timestamp = if read_only {
430 requests::diagnostic_clock(&tx, now())?
431 } else {
432 requests::clock(&tx, now())?
433 };
434 let state = self.identity.state(&tx)?;
435 let mut config = self.config.clone();
436 config.policy = state.state().policy.clone();
437 config.cluster.name.clone_from(&state.state().name);
438 if let Some(node) = state.state().nodes.get(self.identity.node.id()) {
439 config.node.name.clone_from(&node.name);
440 }
441 config.applied_revision = Some(state.checkpoint().revision);
442 let mut session = StoreSession {
443 db: &tx,
444 home: &self.home,
445 config,
446 identity: &self.identity,
447 state,
448 timestamp,
449 };
450 let owner_request = matches!(&request, Request::Owner { .. });
451 let refresh_nodes = matches!(
452 &request,
453 Request::Owner {
454 action: OwnerOp::RefreshNodes,
455 ..
456 }
457 );
458 let status_request = matches!(
459 &request,
460 Request::Owner {
461 action: OwnerOp::Status,
462 ..
463 }
464 );
465 let mut value = match request {
466 Request::Owner { action, .. } => session.owner(action, &self.sync_health)?,
467 Request::DashboardDelegate {
468 agent,
469 secret,
470 action,
471 } => session.dashboard_delegate(&agent.to_string(), &secret, action)?,
472 Request::Agent { credential, action } => {
473 session.state.authorize_node(
474 self.identity.node.id(),
475 &self.identity.node.public_key(),
476 timestamp as u64,
477 )?;
478 session.agent(self.identity.node.id(), &credential, action, export_step)?
479 }
480 Request::HostedAgent {
481 node_id,
482 gateway_credential,
483 credential,
484 action,
485 epoch,
486 } => {
487 session.check_hosted(&node_id, &gateway_credential)?;
488 hosted::check_epoch(&tx, &node_id, epoch)?;
489 session.require_web_lease(&node_id)?;
490 session.dirty_web(&node_id, &action)?;
491 ensure!(
492 !matches!(
493 action,
494 AgentOp::FilePaths
495 | AgentOp::FileImport { .. }
496 | AgentOp::FileExport { .. }
497 ),
498 "local filesystem tools are unavailable to hosted chats"
499 );
500 let value = session.agent(&node_id, &credential, action, export_step)?;
501 if epoch.is_some() {
502 hosted::check_epoch(&tx, &node_id, epoch)?;
503 }
504 value
505 }
506 Request::HostedStatus {
507 node_id,
508 gateway_credential,
509 } => {
510 session.check_hosted(&node_id, &gateway_credential)?;
511 session.hosted_status(&node_id)?
512 }
513 };
514 tx.commit()?;
515 if refresh_nodes
516 && value.as_array().is_some_and(|nodes| {
517 nodes
518 .iter()
519 .any(|n| n["presence"]["probe_started_at"].is_i64())
520 })
521 && self
522 .sync_health
523 .connected
524 .load(std::sync::atomic::Ordering::SeqCst)
525 {
526 self.sync_health.verify_watch.notify_one();
527 }
528 if status_request {
529 value["sync"] = self.synchronization_status()?;
530 }
531 if read_only || (local_only && !projection_pending) {
532 return Ok(value);
533 }
534 self.sync_wakeup.notify_one();
536 let projected = self.project_config();
539 if owner_request
540 && (value.get("applied") == Some(&Value::Bool(true))
541 || value.get("config_saved").is_some())
542 {
543 value["config_saved"] = json!(projected.is_ok());
544 if let Err(error) = projected {
545 value["config_error"] = json!(error.to_string());
546 }
547 }
548 Ok(value)
549 }
550
551 fn project_config(&mut self) -> Result<()> {
552 let tx = self
553 .db
554 .transaction_with_behavior(TransactionBehavior::Immediate)?;
555 runtime::project(&self.home, &tx, &self.identity)?;
556 tx.commit()?;
557 Ok(())
558 }
559
560 pub fn maintain(&mut self) -> Result<()> {
563 self.clean_invitations()?;
565 self.clean_files()?;
566 self.clean_history()?;
567 self.clean_wake()?;
568 {
569 let tx = self
570 .db
571 .transaction_with_behavior(TransactionBehavior::Immediate)?;
572 configuration::pending::recover(&tx, self.identity.node.id())?;
573 encrypted::ordered::storage::clean(&tx, false)?;
574 tx.commit()?;
575 }
576 let timestamp = now() as u64;
577 let tx = self
578 .db
579 .transaction_with_behavior(TransactionBehavior::Immediate)?;
580 let state = self.identity.state(&tx)?;
581 ensure!(
582 state
583 .state()
584 .nodes
585 .get(self.identity.node.id())
586 .is_some_and(|n| n.signing_key == self.identity.node.public_key()),
587 "local node is no longer enrolled"
588 );
589 crate::file_objects::Objects::new(&tx, timestamp)?.reap()?;
590 let renew = !self.identity.legacy_signing_fenced()
591 && self.identity.legacy_service_checked
592 && self.identity.is_current_owner(&state)
593 && !handoff::frozen(&tx, &state)?
594 && state.state().expires_at.saturating_sub(timestamp) <= 6 * 60 * 60;
595 if renew {
596 let update = state.renew(&*self.identity.signing_owner(&tx)?, timestamp)?;
597 self.identity.apply(&tx, update)?;
598 }
599 tx.commit()?;
600 if renew {
601 self.sync_wakeup.notify_one();
602 }
603 self.project_config()?;
604 self.reconcile_configuration()
605 }
606
607 pub fn install_joined(
610 home: &Path,
611 node: &gent_crypto::NodeIdentity,
612 state: &VerifiedState,
613 ) -> Result<()> {
614 runtime::install_joined(home, node, state)
615 }
616
617 pub(crate) fn relay_settings(&self) -> Option<(config::RelayConfig, PathBuf)> {
618 self.config
619 .relay
620 .clone()
621 .map(|relay| (relay, self.home.clone()))
622 }
623 pub(crate) fn sync_streams(&self) -> Result<Vec<crate::sync::Stream>> {
624 if self.identity.state(&self.db)?.state().peer.is_some() {
625 return self.data_streams();
626 }
627 let mut streams: Vec<_> =
628 encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?
629 .configuration_streams(now() as u64)?
630 .into_iter()
631 .map(|s| crate::sync::Stream {
632 group: s.group,
633 outgoing: s.outgoing,
634 configuration: true,
635 })
636 .collect();
637 streams.extend(self.data_streams()?);
638 Ok(streams)
639 }
640 pub(crate) fn sync_pending_groups(
641 &self,
642 streams: &[crate::sync::Stream],
643 ) -> Result<crate::sync::MailboxWork> {
644 let mut work = crate::sync::MailboxWork::default();
645 let mut pending = self.db.prepare(
646 "SELECT s.group_id,s.head>=COALESCE(u.next_sequence,0)
647 FROM streams s LEFT JOIN stream_relay_upload u USING(group_id)
648 LEFT JOIN stream_confirmed c USING(group_id)
649 WHERE s.writer=?1 AND s.head>COALESCE(c.sequence,-1)",
650 )?;
651 let mut rows = pending.query([self.identity.node.id()])?;
652 while let Some(row) = rows.next()? {
653 let group: Vec<u8> = row.get(0)?;
654 work.unconfirmed.insert(group.clone());
655 if row.get::<_, bool>(1)? {
656 work.ready.insert(group);
657 }
658 }
659 let local = self
660 .db
661 .prepare(
662 "SELECT group_id FROM owner_deliveries WHERE next<parts
663 UNION SELECT s.group_id FROM streams s JOIN stream_pending p
664 ON p.group_id=s.group_id AND p.sequence=s.head+1",
665 )?
666 .query_map([], |r| r.get(0))?
667 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()?;
668 work.ready.extend(local);
669 self.add_ready_network_groups(&mut work.ready)?;
670
671 let writers: BTreeSet<_> = streams
675 .iter()
676 .filter(|s| s.configuration && s.outgoing)
677 .map(|s| s.group.as_slice())
678 .collect();
679 if writers.is_empty() {
680 return Ok(work);
681 }
682 let state = self.identity.state(&self.db)?;
683 let mut query = self.db.prepare(
684 "SELECT c.group_id,c.grant,h.revision FROM configuration_streams c
685 JOIN streams s USING(group_id) JOIN authority_history h ON h.revision=c.revision+1
686 WHERE s.writer=?1",
687 )?;
688 let mut rows = query.query([self.identity.node.id()])?;
689 while let Some(row) = rows.next()? {
690 let group: Vec<u8> = row.get(0)?;
691 if !writers.contains(group.as_slice()) {
692 continue;
693 }
694 let grant = gent_crypto::SignedConfigurationGrant::decode(&row.get::<_, Vec<u8>>(1)?)?;
695 let limit = encrypted::ordered::configuration::publication_limit(&grant, &state);
696 let revision: u64 = row.get(2)?;
697 if limit.is_none_or(|last| revision <= last) {
698 work.ready.insert(group);
699 }
700 }
701 Ok(work)
702 }
703
704 pub(crate) fn relay_upload_start(
707 &self,
708 group: &[u8],
709 relay_next: u64,
710 confirmed_next: u64,
711 ) -> Result<u64> {
712 let (local_next, uploaded): (u64, u64) = self.db.query_row(
713 "SELECT s.head+1,COALESCE(u.next_sequence,0) FROM streams s
714 LEFT JOIN stream_relay_upload u USING(group_id) WHERE s.group_id=?1 AND s.writer=?2",
715 params![group, self.identity.node.id()],
716 |r| Ok((r.get(0)?, r.get(1)?)),
717 )?;
718 ensure!(
719 relay_next <= local_next,
720 "relay position exceeds local history"
721 );
722 if relay_next < uploaded {
723 self.record_relay_upload(group, relay_next)?;
724 }
725 Ok(uploaded.min(relay_next).max(confirmed_next))
726 }
727
728 pub(crate) fn record_relay_upload(&self, group: &[u8], next: u64) -> Result<()> {
729 self.db.execute(
730 "INSERT INTO stream_relay_upload(group_id,next_sequence) VALUES(?1,?2)
731 ON CONFLICT(group_id) DO UPDATE SET next_sequence=excluded.next_sequence",
732 params![group, next],
733 )?;
734 Ok(())
735 }
736 pub(crate) fn sync_prepare(&self, group: &[u8]) -> Result<()> {
737 let mut endpoint =
738 encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
739 let timestamp = now() as u64;
740 if endpoint
741 .prepare_configuration(group, None, timestamp)?
742 .is_none()
743 {
744 endpoint.prepare_owner_handoff(group, timestamp)?;
745 }
746 Ok(())
747 }
748
749 pub(crate) fn transport_receipt(
750 &self,
751 group: &[u8],
752 configuration: bool,
753 ) -> Result<gent_crypto::stream::Receipt> {
754 if !configuration {
755 self.data_peer(&self.db, group, false)?;
756 }
757 encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?
758 .receipt(group, now() as u64)
759 }
760
761 pub(crate) fn transport_confirm(
762 &self,
763 group: &[u8],
764 configuration: bool,
765 receipt: Option<&gent_crypto::stream::Receipt>,
766 ) -> Result<Option<gent_crypto::stream::Receipt>> {
767 Ok(self
768 .transport_confirmation(group, configuration, receipt)?
769 .0)
770 }
771
772 pub(crate) fn transport_confirmation(
774 &self,
775 group: &[u8],
776 configuration: bool,
777 receipt: Option<&gent_crypto::stream::Receipt>,
778 ) -> Result<(Option<gent_crypto::stream::Receipt>, bool)> {
779 let mut endpoint =
780 encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
781 let reader = if configuration {
782 endpoint.configuration_reader(group)?
783 } else {
784 self.data_peer(&self.db, group, true)?
785 };
786 if let Some(receipt) = receipt {
787 ensure!(
788 receipt.group() == group,
789 "checkpoint belongs to another stream"
790 );
791 return endpoint
792 .confirm_and_get(receipt, &reader, now() as u64)
793 .map(|(receipt, advanced)| (Some(receipt), advanced));
794 }
795 Ok((endpoint.confirmed_receipt(group, now() as u64)?, false))
796 }
797 pub(crate) fn sync_outgoing(
798 &self,
799 group: &[u8],
800 next: u64,
801 ) -> Result<Option<gent_crypto::stream::Packet>> {
802 let mut endpoint =
803 encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
804 let timestamp = now() as u64;
805 let status = endpoint.configuration_status(group, timestamp)?;
806 ensure!(next <= status.next, "relay position exceeds local history");
807 Ok(endpoint
808 .configuration_outbox(group, next.checked_sub(1), 1, timestamp)?
809 .pop())
810 }
811 pub(crate) fn sync_next(&mut self, group: &[u8]) -> Result<u64> {
812 let mut endpoint =
813 encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
814 let timestamp = now() as u64;
815 let pending = endpoint.drain_configuration(group, 1, timestamp)?;
818 let next = endpoint
819 .configuration_status(group, timestamp)
820 .map(|status| status.next);
821 drop(endpoint);
822 if !pending.is_empty() {
823 self.project_config()?;
824 self.reconcile_configuration()?;
825 self.sync_wakeup.notify_one();
826 }
827 next
828 }
829 pub(crate) fn sync_receive(&mut self, packet: &gent_crypto::stream::Packet) -> Result<()> {
830 let mut endpoint =
831 encrypted::ordered::OrderedEndpoint::open_runtime(&self.home, &self.identity.node)?;
832 let timestamp = now() as u64;
833 endpoint.stage_configuration(packet, timestamp)?;
834 endpoint.drain_configuration(packet.group(), 1, timestamp)?;
835 self.sync_wakeup.notify_one();
836 self.project_config()?;
837 self.reconcile_configuration()
838 }
839}
840
841struct StoreSession<'a> {
842 db: &'a Connection,
843 home: &'a Path,
844 config: Config,
845 identity: &'a Identity,
846 state: VerifiedState,
847 timestamp: i64,
848}
849
850#[derive(Default)]
851struct SendContext {
852 parent: Option<Message>,
853 relay: Option<RelayMessage>,
854 file_ids: Vec<String>,
855}
856
857fn message_fingerprint(
858 recipient: &str,
859 text: &str,
860 files: &[FilePart],
861 reply_to: &Option<String>,
862 relay: &Option<RelayMessage>,
863 file_ids: &[String],
864) -> Result<String> {
865 let mut value = json!({"recipient":recipient,"text":text,"files":files,"reply_to":reply_to});
866 if let Some(relay) = relay {
868 value["relay"] = json!(relay);
869 }
870 if !file_ids.is_empty() {
871 value["file_ids"] = json!(file_ids);
872 }
873 Ok(hash(&serde_json::to_string(&value)?))
874}
875impl StoreSession<'_> {
876 fn decode_agent(row: &rusqlite::Row<'_>) -> rusqlite::Result<Agent> {
877 Ok(Agent {
878 id: row.get(0)?,
879 node_id: row.get(1)?,
880 name: row.get(2)?,
881 provider: row.get(3)?,
882 last_seen: row.get(4)?,
883 revoked: row.get(5)?,
884 })
885 }
886 fn get_agent(&self, id: &str) -> Result<Agent> {
887 let mut agent = self
888 .db
889 .query_row(
890 "SELECT id,node_id,name,provider,last_seen,revoked FROM agents WHERE id=?1",
891 [id],
892 Self::decode_agent,
893 )
894 .optional()?
895 .context(UNAVAILABLE)?;
896 agent.revoked |= !self.state.state().nodes.contains_key(&agent.node_id);
897 Ok(agent)
898 }
899 fn all_agents(&self) -> Result<Vec<Agent>> {
900 let mut agents = self
901 .db
902 .prepare("SELECT id,node_id,name,provider,last_seen,revoked FROM agents ORDER BY id")?
903 .query_map([], Self::decode_agent)?
904 .collect::<Result<Vec<_>, _>>()?;
905 for agent in &mut agents {
906 agent.revoked |= !self.state.state().nodes.contains_key(&agent.node_id);
907 }
908 Ok(agents)
909 }
910 fn owner(&mut self, action: OwnerOp, health: &crate::sync::health::Health) -> Result<Value> {
911 match action {
912 OwnerOp::WebDeliveryDemand { node_id } => self.web_delivery_demand(&node_id),
913 OwnerOp::WebDeliveryChecked {
914 node_id,
915 message_id,
916 } => {
917 let cleared = self.db.execute(
918 "DELETE FROM web_delivery_demand WHERE node=?1 AND message=?2",
919 params![node_id, message_id],
920 )?;
921 Ok(json!({"cleared":cleared==1}))
922 }
923 OwnerOp::WebAdmission { node_id, body_hash } => self.web_admission(&node_id, body_hash),
924 OwnerOp::WebCheckpoint { node_id } => self.web_checkpoint(&node_id),
925 OwnerOp::WebLease { node_id, seconds } => self.web_lease(&node_id, seconds),
926 OwnerOp::WebGrant {
927 node_id,
928 epoch,
929 expires_at,
930 } => self.web_grant(&node_id, epoch, expires_at),
931 OwnerOp::WebCommit {
932 node_id,
933 revision,
934 epoch,
935 } => self.web_commit(&node_id, revision, epoch),
936 OwnerOp::RestoreWebNode { .. } => unreachable!("handled before session"),
937 OwnerOp::NodeInvite {
938 request_id,
939 name,
940 can_configure,
941 activate,
942 } => self.request_node_invite(&request_id, &name, can_configure, activate),
943 OwnerOp::AgentRecover {
944 directory,
945 manifest_sha256,
946 source_agent,
947 agent_credential,
948 name,
949 provider,
950 } => {
951 let registered = self.agent(
952 self.identity.node.id(),
953 &agent_credential,
954 AgentOp::Register {
955 name: name.clone(),
956 provider: provider.clone(),
957 },
958 files::ExportStep::Reserve,
959 )?;
960 let id = registered["agent"]["id"]
961 .as_str()
962 .context("missing recovered chat identity")?;
963 let agent = self.get_agent(id)?;
964 ensure!(
965 agent.name == name && agent.provider == provider,
966 "recovery registration arguments changed"
967 );
968 let history = self.recovered_import(
969 Path::new(&directory),
970 &manifest_sha256,
971 &source_agent,
972 id,
973 None,
974 )?;
975 Ok(
976 json!({"agent":agent,"history":history,"source_agent":source_agent,
977 "scope":"fresh local registration with assigned history; old credentials, peer permissions and pending work are not restored"}),
978 )
979 }
980 OwnerOp::HistoryImports => self.recovered_imports(None),
981 OwnerOp::HistoryImport {
982 directory,
983 manifest_sha256,
984 source_agent,
985 target_agent,
986 restore_revision,
987 } => self.recovered_import(
988 Path::new(&directory),
989 &manifest_sha256,
990 &source_agent,
991 &target_agent,
992 restore_revision,
993 ),
994 OwnerOp::HistoryRemove {
995 import_id,
996 expected_revision,
997 } => self.recovered_remove(&import_id, expected_revision),
998 OwnerOp::Pair { .. }
999 | OwnerOp::Invitation { .. }
1000 | OwnerOp::Diagnose
1001 | OwnerOp::PreparePeerConfiguration => {
1002 anyhow::bail!("pairing must use its owner-authenticated entry point")
1003 }
1004 OwnerOp::Stats | OwnerOp::RefreshStats => {
1005 anyhow::bail!("statistics require the owner statistics entry point")
1006 }
1007 OwnerOp::Status => Ok(
1008 json!({"process_id":std::process::id(),"node":self.config.node,"cluster":self.config.cluster,"transport":"local_unix_socket","remote_ready":self.remote_ready()?,
1009 "release_channel":self.state.state().release_channel,
1010 "can_set_release_channel":self.identity.is_current_owner(&self.state) || self.identity.has_configuration_grant(&self.state),
1011 "authority":{"mode":if self.state.state().peer.is_some(){"peers"}else{"legacy"},"sequence":self.state.checkpoint().revision,"revision":self.state.checkpoint().revision,"expires_at":self.state.state().expires_at,"fresh":self.state.require_fresh(self.timestamp as u64).is_ok()},"config_saved":!runtime::projection_pending(self.db)?}),
1012 ),
1013 OwnerOp::Groups { name } => match name {
1014 Some(name) => Ok(
1015 json!({"name":name,"members":self.config.policy.groups.get(&name).context("unknown group")?}),
1016 ),
1017 None => Ok(json!(self.config.policy.groups)),
1018 },
1019 OwnerOp::GroupAdmins => Ok(
1020 json!({"grants":self.config.policy.group_admin_grants,"retired":self.state.state().retired_admin_grants}),
1021 ),
1022 OwnerOp::GroupAdminHistory {
1023 administrator,
1024 before,
1025 } => self.administration_history(administrator.as_deref(), before, true),
1026 OwnerOp::NotificationPending { scope } => self.pending_notices(&scope),
1027 OwnerOp::NotificationPut { notice, scope } => self.enqueue_notice(¬ice, scope),
1028 OwnerOp::NotificationSent { id } => {
1029 self.db
1030 .execute("DELETE FROM account_outbox WHERE id=?1", [id.to_string()])?;
1031 Ok(json!({}))
1032 }
1033 OwnerOp::DashboardRemoteHtml { .. } => {
1034 anyhow::bail!("remote board view requires live transport")
1035 }
1036 OwnerOp::DashboardGrant { agent, action } => {
1037 self.authorize_dashboard_grant_admin(self.identity.node.id())?;
1038 self.dashboard_grant(&agent.to_string(), action)
1039 }
1040 OwnerOp::Dashboards { after } => self.dashboards(after.as_deref()),
1041 OwnerOp::DashboardClick {
1042 agent,
1043 revision,
1044 widget,
1045 request_id,
1046 } => self.dashboard_action(&agent, revision, Some(&widget), &request_id),
1047 OwnerOp::DashboardRefresh {
1048 agent,
1049 revision,
1050 request_id,
1051 } => self.dashboard_action(&agent, revision, None, &request_id),
1052 OwnerOp::PermissionRules => Ok(json!({"rules":self.state.state().policy.rules,
1053 "groups":self.state.state().policy.groups.keys().collect::<Vec<_>>()})),
1054 OwnerOp::PermissionExplain { actor, peer } => self.permission_explain(&actor, &peer),
1055 OwnerOp::PermissionAdmins => {
1056 Ok(json!({"grants":self.state.state().policy.admin_grants,
1057 "retired":self.state.state().retired_admin_grants,"revision":self.state.checkpoint().revision}))
1058 }
1059 OwnerOp::PermissionAdminHistory {
1060 administrator,
1061 before,
1062 } => self.permission_admin_history(administrator.as_deref(), before),
1063 OwnerOp::Nodes => self.nodes(health),
1064 OwnerOp::RefreshNodes => self.refresh_nodes(health),
1065 OwnerOp::Agents => Ok(serde_json::to_value(self.directory(None)?)?),
1066 OwnerOp::Resolve {
1067 name,
1068 node,
1069 provider,
1070 } => self.resolve_agent(None, &name, node.as_deref(), provider.as_deref()),
1071 OwnerOp::NativeMessageDates => self.local_native_message_dates(),
1072 OwnerOp::ObserveActivity {
1073 agent_id,
1074 last_activity_at,
1075 last_native_message_at,
1076 } => self.observe_activity(&agent_id, last_activity_at, last_native_message_at),
1077 OwnerOp::ClearRetiredAgents { dry_run } => self.clear_retired_agents(dry_run),
1078 OwnerOp::Agent { agent_id } => self.agent_details(&agent_id),
1079 OwnerOp::RenameAgent {
1080 agent_id,
1081 name,
1082 expected_generation,
1083 } => {
1084 self.rename_agent(&agent_id, &name, expected_generation)?;
1085 self.agent_details(&agent_id)
1086 }
1087 OwnerOp::FilesStatus => self.files_status(),
1088 OwnerOp::FilesClean { dry_run } => self.files_clean(dry_run),
1089 OwnerOp::HistoryStatus => self.history_status(),
1090 OwnerOp::OwnerHandoffStatus => handoff::status(self.db, &self.state),
1091 OwnerOp::OwnerTransfer { .. } => {
1092 anyhow::bail!("owner transfer requires the authenticated store entry point")
1093 }
1094 OwnerOp::RecoveryChallenge => Ok(serde_json::to_value(
1095 gent_crypto::recovery::RecoveryBaseline::new(&self.state, self.timestamp as u64)?,
1096 )?),
1097 OwnerOp::RecoveryObserve { challenge } => {
1098 let challenge =
1099 gent_crypto::recovery::RecoveryChallenge::decode(challenge.as_bytes())?;
1100 Ok(serde_json::to_value(self.identity.node.observe_recovery(
1101 &self.state,
1102 &challenge,
1103 self.timestamp as u64,
1104 )?)?)
1105 }
1106 OwnerOp::WorkList { after_message_id } => self.work_list(after_message_id.as_deref()),
1107 OwnerOp::WakeList { after_message_id } => self.wake_list(after_message_id.as_deref()),
1108 OwnerOp::WakeStatus => wake::retention::status(self.db, self.timestamp),
1109 OwnerOp::WakePendingAgents { after } => self.wake_pending_agents(after.as_deref()),
1110 OwnerOp::WakeDirectTurnEvidence {
1111 completed_relay,
1112 agent_credential,
1113 thread_id,
1114 turn,
1115 } => {
1116 let who = self.native_supervisor_agent(&agent_credential, thread_id)?;
1117 self.direct_turn_evidence(&who, thread_id, turn, completed_relay)
1118 }
1119 OwnerOp::BabysitterVerifiedBlockedClaim {
1120 agent_credential,
1121 thread_id,
1122 goal,
1123 turn,
1124 failed_at,
1125 reason,
1126 } => {
1127 let who = self.native_supervisor_agent(&agent_credential, thread_id)?;
1128 self.babysitter_claim(
1129 &who,
1130 &goal,
1131 turn,
1132 failed_at,
1133 reason,
1134 babysitter::Window::VerifiedBlocked,
1135 )
1136 }
1137 OwnerOp::WakeClean { dry_run } => {
1138 wake::retention::clean(self.db, self.timestamp, dry_run)
1139 }
1140 OwnerOp::WakeShow { message_id } => self.wake_show(&message_id),
1141 OwnerOp::WorkShow { message_id } => self.work_show(&message_id),
1142 OwnerOp::WorkReconcile {
1143 message_id,
1144 expect_revision,
1145 resolution,
1146 note,
1147 } => self.work_reconcile(&message_id, expect_revision, resolution, ¬e),
1148 OwnerOp::HistoryClean { dry_run } => self.history_clean(dry_run),
1149 OwnerOp::TransportStatus => encrypted::ordered::storage::status(self.db),
1150 OwnerOp::TransportClean { dry_run } => {
1151 encrypted::ordered::storage::clean(self.db, dry_run)
1152 }
1153 OwnerOp::Providers => {
1154 let mut providers = BTreeMap::<String, Vec<Agent>>::new();
1155 for agent in self.all_agents()? {
1156 if !agent.revoked {
1157 providers
1158 .entry(agent.provider.clone())
1159 .or_default()
1160 .push(agent);
1161 }
1162 }
1163 Ok(json!(providers))
1164 }
1165 OwnerOp::RelayGrants => Ok(json!({"grants":self.state.state().policy.relay_grants,
1166 "retired":self.state.state().retired_relay_grants,"revision":self.state.checkpoint().revision})),
1167 OwnerOp::RelayAttachments => self.relay_attachments(),
1168 OwnerOp::Configure { request_id, edit } => self.submit_configuration(&request_id, edit),
1169 OwnerOp::ConfigurationRequests { request_id } => match request_id {
1170 Some(id) => self.configuration_status(&id),
1171 None => self.configuration_requests(),
1172 },
1173 OwnerOp::DelegateConfiguration { node_id, allow } => {
1174 if self.state.state().peer.is_some() {
1175 return self.submit_configuration(
1176 &uuid::Uuid::new_v4().to_string(),
1177 ConfigurationEdit::DelegateNode { node_id, allow },
1178 );
1179 }
1180 let update = self.state.delegate_configuration(
1181 &*self.identity.signing_owner(self.db)?,
1182 &node_id,
1183 allow,
1184 self.timestamp as u64,
1185 )?;
1186 self.state = self.identity.apply(self.db, update)?;
1187 Ok(
1188 json!({"applied":true,"revision":self.state.checkpoint().revision,"node_id":node_id,"can_configure":allow}),
1189 )
1190 }
1191 OwnerOp::RemoveNode { node_id } => self.remove_node(&node_id),
1192 OwnerOp::NodeRemovals {
1193 after,
1194 pending_only,
1195 } => self.node_removals(after.as_deref(), pending_only),
1196 OwnerOp::ConfirmNodeRemoval { node_id, revision } => {
1197 self.confirm_node_removal(&node_id, revision)
1198 }
1199 OwnerOp::SetPolicy { policy } => {
1200 let disk = config::load_for_runtime(self.home)?;
1201 ensure!(
1202 disk.node.id == self.config.node.id
1203 && disk.cluster.id == self.config.cluster.id,
1204 "cannot change active identities while daemon runs"
1205 );
1206 self.submit_configuration(
1207 &uuid::Uuid::new_v4().to_string(),
1208 ConfigurationEdit::Replace {
1209 cluster_name: disk.cluster.name,
1210 node_name: disk.node.name,
1211 policy,
1212 },
1213 )
1214 }
1215 OwnerOp::Renew => self
1216 .submit_configuration(&uuid::Uuid::new_v4().to_string(), ConfigurationEdit::Renew),
1217 OwnerOp::RenameNode { name } => self.submit_configuration(
1218 &uuid::Uuid::new_v4().to_string(),
1219 ConfigurationEdit::RenameNode { name },
1220 ),
1221 OwnerOp::PrepareHostedNode { .. } => unreachable!("handled before session"),
1222 OwnerOp::Revoke { agent_id } => self.request_unregister(&agent_id),
1223 }
1224 }
1225
1226 fn native_supervisor_agent(&self, credential: &str, thread: uuid::Uuid) -> Result<Agent> {
1227 ensure!(!thread.is_nil(), "invalid native thread");
1228 let node = self.identity.node.id();
1229 self.state.authorize_node(
1230 node,
1231 &self.identity.node.public_key(),
1232 self.timestamp as u64,
1233 )?;
1234 self.registered_agent(node, &hash(credential))
1235 }
1236
1237 fn registered_agent(&self, node: &str, digest: &str) -> Result<Agent> {
1238 let who = self.db.query_row(
1239 "SELECT id,node_id,name,provider,last_seen,revoked FROM agents WHERE credential_hash=?1",
1240 [digest],
1241 Self::decode_agent,
1242 ).optional()?.context("register this connection first")?;
1243 ensure!(!who.revoked, "registration revoked");
1244 ensure!(
1245 who.node_id == node && self.local_node(node),
1246 "credential belongs to another node"
1247 );
1248 Ok(who)
1249 }
1250
1251 fn agent(
1252 &mut self,
1253 node: &str,
1254 credential: &str,
1255 action: AgentOp,
1256 export_step: files::ExportStep,
1257 ) -> Result<Value> {
1258 ensure!(
1259 credential.len() == 64 && credential.bytes().all(|b| b.is_ascii_hexdigit()),
1260 "invalid registration credential"
1261 );
1262 let digest = hash(credential);
1263 if let AgentOp::Register { name, provider } = &action {
1264 config::label(name)?;
1265 config::label(provider)?;
1266 if !self.db.query_row(
1267 "SELECT EXISTS(SELECT 1 FROM agents WHERE credential_hash=?1)",
1268 [&digest],
1269 |r| r.get::<_, bool>(0),
1270 )? {
1271 let nonce = uuid::Uuid::new_v4();
1272 let agent = gent_crypto::agent_id(node, nonce)?;
1273 self.db.execute("INSERT INTO agents(id,credential_hash,node_id,name,provider,last_seen) VALUES (?1,?2,?3,?4,?5,?6)",params![agent,digest,node,name,provider,self.timestamp])?;
1274 self.db.execute("INSERT INTO network_origins(agent,nonce,legacy,generation) VALUES(?1,?2,NULL,1)",params![agent,nonce.to_string()])?;
1275 self.announce(&agent)?;
1276 }
1277 }
1278 let who = self.registered_agent(node, &digest)?;
1279 if !matches!(
1280 &action,
1281 AgentOp::BabysitterClaim { .. }
1282 | AgentOp::BabysitterChatProbe { .. }
1283 | AgentOp::BabysitterChatClaim { .. }
1284 | AgentOp::BabysitterChatCheck { .. }
1285 | AgentOp::BabysitterChatSubmitted { .. }
1286 | AgentOp::BabysitterCheck { .. }
1287 | AgentOp::BabysitterSubmitted { .. }
1288 | AgentOp::WakePending
1289 | AgentOp::WakeClaim { .. }
1290 | AgentOp::WakeCheck { .. }
1291 | AgentOp::WakeSubmitted { .. }
1292 | AgentOp::WakeDirectClaim { .. }
1293 | AgentOp::WakeDirectPending { .. }
1294 | AgentOp::WakeDirectRead { .. }
1295 | AgentOp::WakeDirectObserve { .. }
1296 | AgentOp::WakeDirectComplete { .. }
1297 ) {
1298 self.db.execute(
1299 "UPDATE agents SET last_seen=?1 WHERE id=?2",
1300 params![self.timestamp, who.id],
1301 )?;
1302 }
1303 match action {
1304 AgentOp::Register { .. } | AgentOp::Identity => self.agent_identity(&who.id),
1305 AgentOp::Rename {
1306 name,
1307 expected_generation,
1308 } => {
1309 self.rename_agent(&who.id, &name, expected_generation)?;
1310 self.agent_identity(&who.id)
1311 }
1312 AgentOp::Babysit { enabled } => self.babysit(&who, enabled),
1313 AgentOp::BabysitterClaim {
1314 goal,
1315 turn,
1316 failed_at,
1317 reason,
1318 } => self.babysitter_claim(
1319 &who,
1320 &goal,
1321 turn,
1322 failed_at,
1323 reason,
1324 babysitter::Window::Routine,
1325 ),
1326 AgentOp::BabysitterCheck { attempt } => {
1327 Ok(json!({"eligible":self.babysitter_check(&who,attempt)?}))
1328 }
1329 AgentOp::BabysitterSubmitted { attempt, scope } => {
1330 self.babysitter_submitted(&who, attempt, scope)
1331 }
1332 AgentOp::BabysitterChatProbe {
1333 turn,
1334 operator,
1335 failed_at,
1336 } => Ok(
1337 json!({"inspect":self.babysitter_chat_probe(&who, turn, operator, failed_at)?,
1338 "direct_handoff":true}),
1339 ),
1340 AgentOp::BabysitterChatClaim {
1341 turn,
1342 failed_at,
1343 reason,
1344 origin,
1345 } => self.babysitter_chat_claim(&who, turn, failed_at, reason, origin),
1346 AgentOp::BabysitterChatCheck { attempt } => self.babysitter_chat_check(&who, attempt),
1347 AgentOp::BabysitterChatSubmitted { attempt } => {
1348 self.babysitter_chat_submitted(&who, attempt)
1349 }
1350 AgentOp::DashboardGet => self.dashboard_get(&who),
1351 op @ (AgentOp::DashboardPublish { .. }
1352 | AgentOp::DashboardDefine { .. }
1353 | AgentOp::DashboardAttachHtml { .. }
1354 | AgentOp::DashboardUpdate { .. }
1355 | AgentOp::DashboardDelete { .. }) => self.dashboard_mutate(&who, op),
1356 AgentOp::Agents => self.visible_agents(&who),
1357 AgentOp::Resolve {
1358 name,
1359 node,
1360 provider,
1361 } => self.resolve_agent(Some(&who), &name, node.as_deref(), provider.as_deref()),
1362 AgentOp::HistoryImports => self.recovered_imports(Some(&who)),
1363 AgentOp::HistoryMessages { import_id, after } => {
1364 self.recovered_messages(&who, &import_id, after)
1365 }
1366 AgentOp::HistoryFileRead {
1367 import_id,
1368 message_id,
1369 file_index,
1370 chunk_index,
1371 } => self.recovered_file_read(&who, &import_id, &message_id, file_index, chunk_index),
1372 AgentOp::HistoryFileView {
1373 import_id,
1374 message_id,
1375 file_index,
1376 } => self.recovered_file_view(&who, &import_id, &message_id, file_index),
1377 AgentOp::PermissionCheck { peer } => self.permission_check(&who, &peer),
1378 AgentOp::PermissionAdminCheck { actor, peer } => {
1379 self.permission_admin_check(&who, &actor, &peer)
1380 }
1381 AgentOp::PermissionPreview { changes } => self.permission_preview(&who, &changes),
1382 AgentOp::PermissionApply {
1383 request_id,
1384 changes,
1385 } => self.permission_apply(&who, &request_id, changes),
1386 AgentOp::PermissionRequest { request_id } => self.permission_request(&who, &request_id),
1387 AgentOp::PermissionRuleScopes => self.permission_rule_scopes(&who),
1388 AgentOp::GroupAdminScopes => self.group_admin_scopes(&who),
1389 AgentOp::GroupMembers { group } => self.group_members(&who, &group),
1390 AgentOp::GroupPreview { changes } => self.group_preview(&who, &changes),
1391 AgentOp::GroupApply {
1392 request_id,
1393 changes,
1394 } => self.group_apply(&who, &request_id, changes),
1395 AgentOp::GroupRequest { request_id } => self.permission_request(&who, &request_id),
1396 AgentOp::PermissionRulePreview { changes } => {
1397 self.permission_rule_preview(&who, &changes)
1398 }
1399 AgentOp::PermissionRuleApply {
1400 request_id,
1401 changes,
1402 } => self.permission_rule_apply(&who, &request_id, changes),
1403 AgentOp::RequestIds { count } => self.request_ids(count),
1404 AgentOp::WorkStatus { message_id } => self.work_status(&who, &message_id),
1405 AgentOp::WakeDirectClaim {
1406 message_id,
1407 attempt_id,
1408 target,
1409 } => self.wake_direct_claim(&who, &message_id, &attempt_id, target),
1410 AgentOp::WakeDirectPending { target } => self.wake_direct_pending(&who, &target),
1411 AgentOp::WakeDirectRead {
1412 message_id,
1413 attempt_id,
1414 target,
1415 } => self.wake_direct_read(&who, &message_id, &attempt_id, &target),
1416 AgentOp::WakeDirectObserve {
1417 message_id,
1418 attempt_id,
1419 target,
1420 turn_id,
1421 } => self.wake_direct_observe(&who, &message_id, &attempt_id, &target, &turn_id),
1422 AgentOp::WakeDirectComplete {
1423 message_id,
1424 attempt_id,
1425 target,
1426 turn_id,
1427 text,
1428 } => {
1429 self.wake_direct_complete(&who, &message_id, &attempt_id, &target, (&turn_id, text))
1430 }
1431 AgentOp::WakePending => self.wake_pending(&who),
1432 AgentOp::WakeClaim {
1433 message_id,
1434 attempt_id,
1435 target,
1436 } => self.wake_claim(&who, &message_id, &attempt_id, target),
1437 AgentOp::WakeCheck {
1438 message_id,
1439 attempt_id,
1440 target,
1441 } => self.wake_check(&who, &message_id, &attempt_id, &target),
1442 AgentOp::WakeSubmitted {
1443 message_id,
1444 attempt_id,
1445 submission_id,
1446 } => self.wake_submitted(&who, &message_id, &attempt_id, &submission_id),
1447 AgentOp::WorkBegin {
1448 message_id,
1449 expect_revision,
1450 description,
1451 } => self.work_begin(&who, &message_id, expect_revision, &description),
1452 AgentOp::WorkComplete {
1453 message_id,
1454 expect_revision,
1455 note,
1456 } => self.work_complete(&who, &message_id, expect_revision, ¬e),
1457 AgentOp::FilePaths => self.file_paths(&who),
1458 AgentOp::FileImport {
1459 request_id,
1460 name,
1461 media_type,
1462 } => self.file_import(&who, &request_id, &name, &media_type),
1463 AgentOp::FileStatus { file_id } => self.file_status(&who, &file_id),
1464 AgentOp::FileReceiveStatus { file } => self.file_receive_status(&who, &file),
1465 AgentOp::FileReceive {
1466 file,
1467 byte_length,
1468 sha256,
1469 } => {
1470 ensure!(
1471 byte_length <= gent_protocol::file_objects::MAX_FILE_BYTES as u64,
1472 "file exceeds 32 MiB"
1473 );
1474 ensure!(
1475 sha256.len() == 64
1476 && sha256
1477 .bytes()
1478 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)),
1479 "invalid file digest"
1480 );
1481 let status = self.file_receive_status(&who, &file)?;
1482 ensure!(
1483 status["state"] != "ready"
1484 || (status["file"]["byte_length"] == byte_length
1485 && status["file"]["sha256"] == sha256),
1486 "request_id already used with different content"
1487 );
1488 Ok(status)
1489 }
1490 AgentOp::FileReceiveData { file, bytes } => self.file_receive(&who, &file, &bytes),
1491 AgentOp::FileRead {
1492 file_id,
1493 chunk_index,
1494 } => self.file_read(&who, &file_id, chunk_index),
1495 AgentOp::FileView { file_id } => self.file_view(&who, &file_id),
1496 AgentOp::FileExport { file_id } => self.file_export(&who, &file_id, export_step),
1497 AgentOp::RelayAttach { target, request_id } => {
1498 self.relay_attach(&who, &target, &request_id)
1499 }
1500 AgentOp::RelayStatus { attachment_id } => self.relay_status(&who, attachment_id),
1501 AgentOp::RelayDetach { attachment_id } => self.relay_detach(&who, &attachment_id),
1502 AgentOp::RelaySend {
1503 attachment_id,
1504 request_id,
1505 text,
1506 files,
1507 file_ids,
1508 } => self.relay_send(&who, &attachment_id, &request_id, (text, files, file_ids)),
1509 AgentOp::RelayTurnStatus {
1510 turn_id,
1511 after_message_id,
1512 } => self.relay_turn_status(&who, &turn_id, after_message_id.as_deref()),
1513 AgentOp::RelayNext => self.relay_next(&who),
1514 AgentOp::RelayTurns { after_turn_id } => {
1515 self.relay_turns(&who, after_turn_id.as_deref())
1516 }
1517 AgentOp::RelayRespond {
1518 turn_id,
1519 request_id,
1520 text,
1521 files,
1522 file_ids,
1523 outcome,
1524 } => self.relay_respond(
1525 &who,
1526 &turn_id,
1527 &request_id,
1528 (text, files, file_ids),
1529 outcome,
1530 ),
1531 AgentOp::RelayCancel {
1532 turn_id,
1533 request_id,
1534 } => self.relay_cancel(&who, &turn_id, &request_id),
1535 AgentOp::Send {
1536 recipient,
1537 request_id,
1538 text,
1539 files,
1540 file_ids,
1541 } => self.send(
1542 &who,
1543 &recipient,
1544 &request_id,
1545 text,
1546 files,
1547 SendContext {
1548 file_ids,
1549 ..Default::default()
1550 },
1551 ),
1552 AgentOp::RequestReply {
1553 recipient,
1554 request_id,
1555 text,
1556 files,
1557 file_ids,
1558 } => self.request_reply(&who, &recipient, &request_id, (text, files, file_ids)),
1559 AgentOp::Reply {
1560 message_id,
1561 request_id,
1562 text,
1563 files,
1564 file_ids,
1565 } => {
1566 let parent = self.message(&message_id)?;
1567 ensure!(parent.recipient == who.id, UNAVAILABLE);
1568 if parent.relay.as_ref().is_some_and(|r| {
1569 r.kind == RelayMessageKind::Request && r.attachment_id == r.turn_id
1570 }) {
1571 return self.relay_respond(
1572 &who,
1573 &message_id,
1574 &request_id,
1575 (text, files, file_ids),
1576 RelayResponseKind::Complete,
1577 );
1578 }
1579 ensure!(parent.relay.is_none(), "use relay_respond for a relay turn");
1580 self.send(
1581 &who,
1582 &parent.sender.clone(),
1583 &request_id,
1584 text,
1585 files,
1586 SendContext {
1587 parent: Some(parent),
1588 relay: None,
1589 file_ids,
1590 },
1591 )
1592 }
1593 AgentOp::Inbox => {
1594 let mut statement=self.db.prepare("SELECT payload,acknowledged FROM messages WHERE recipient=?1 AND acknowledged=0 ORDER BY rowid")?;
1595 let rows = statement.query_map([&who.id], |r| {
1596 Ok((r.get::<_, String>(0)?, r.get::<_, bool>(1)?))
1597 })?;
1598 let mut inbox = Vec::new();
1599 let mut bytes = 0;
1600 for row in rows {
1601 let (payload, acknowledged) = row?;
1602 let mut message: Message = serde_json::from_str(&payload)?;
1603 message.acknowledged = acknowledged;
1604 if self.deliverable(&message)? && self.relay_inbox_visible(&message)? {
1605 if inbox.len() >= 50 || bytes + payload.len() > MAX_FRAME_BYTES / 2 {
1606 break;
1607 }
1608 bytes += payload.len();
1609 self.wake_observe(&who, &message.id)?;
1610 inbox.push(message);
1611 }
1612 }
1613 Ok(json!(inbox))
1614 }
1615 AgentOp::Ack { message_id } => self.acknowledge(&who, &message_id),
1616 AgentOp::MessageStatus { message_id } => {
1617 let message = self.message(&message_id)?;
1618 ensure!(
1619 message.sender == who.id || message.recipient == who.id,
1620 UNAVAILABLE
1621 );
1622 let state = if message.expires_at <= self.timestamp {
1623 "expired"
1624 } else if !self.deliverable(&message)?
1625 || self.db.query_row(
1626 "SELECT EXISTS(SELECT 1 FROM network_rejections WHERE message=?1)",
1627 [&message.id],
1628 |r| r.get::<_, bool>(0),
1629 )?
1630 {
1631 "revoked"
1632 } else if message.acknowledged {
1633 "delivered"
1634 } else {
1635 "queued"
1636 };
1637 Ok(json!({"message_id":message.id,"state":state}))
1638 }
1639 }
1640 }
1641
1642 fn acknowledge(&self, who: &Agent, message_id: &str) -> Result<Value> {
1643 let message = self.message(message_id)?;
1644 ensure!(
1645 message.recipient == who.id && self.deliverable(&message)?,
1646 UNAVAILABLE
1647 );
1648 let changed = self.db.execute(
1649 "UPDATE messages SET acknowledged=1 WHERE id=?1 AND acknowledged=0",
1650 [message_id],
1651 )?;
1652 let sender = self.get_agent(&message.sender)?;
1653 if changed == 1 {
1654 self.web_state_changed(&sender.node_id)?;
1655 }
1656 if !self.local_node(&sender.node_id) {
1657 self.receipt(
1658 self.state.transport_host(&sender.node_id)?,
1659 message_id,
1660 true,
1661 message.expires_at,
1662 )?;
1663 }
1664 Ok(json!({"acknowledged":true}))
1665 }
1666
1667 fn message(&self, message_id: &str) -> Result<Message> {
1668 let (payload, ack): (String, bool) = self
1669 .db
1670 .query_row(
1671 "SELECT payload,acknowledged FROM messages WHERE id=?1",
1672 [message_id],
1673 |r| Ok((r.get(0)?, r.get(1)?)),
1674 )
1675 .optional()?
1676 .context(UNAVAILABLE)?;
1677 let mut message: Message = serde_json::from_str(&payload)?;
1678 message.acknowledged = ack;
1679 Ok(message)
1680 }
1681 fn deliverable(&self, message: &Message) -> Result<bool> {
1682 if !self.web_message_ready(message)? {
1683 return Ok(false);
1684 }
1685 if message.expires_at <= self.timestamp {
1686 return Ok(false);
1687 }
1688 let a = self.get_agent(&message.sender)?;
1689 let b = self.get_agent(&message.recipient)?;
1690 if !self.relay_authorized(message)? {
1691 return Ok(false);
1692 }
1693 Ok(if message.reply_to.is_some() {
1694 self.config.policy.can_reply(&a, &b)
1695 } else {
1696 self.config.policy.can_open(&a, &b)
1697 })
1698 }
1699
1700 fn send(
1701 &mut self,
1702 sender: &Agent,
1703 recipient_id: &str,
1704 request_id: &str,
1705 text: String,
1706 files: Vec<FilePart>,
1707 context: SendContext,
1708 ) -> Result<Value> {
1709 uuid::Uuid::parse_str(request_id)
1710 .context("request_id must be a UUID; reuse it only when retrying the same message")?;
1711 let SendContext {
1712 parent,
1713 relay,
1714 file_ids,
1715 } = context;
1716 network::validate_contents(&text, &files, file_ids.len())?;
1717 ensure!(
1718 file_ids
1719 .iter()
1720 .collect::<std::collections::BTreeSet<_>>()
1721 .len()
1722 == file_ids.len(),
1723 "duplicate file ID"
1724 );
1725 let reply_to = parent.as_ref().map(|p| p.id.clone());
1726 let fingerprint =
1727 message_fingerprint(recipient_id, &text, &files, &reply_to, &relay, &file_ids)?;
1728 let existing: Option<(String, String)> = self
1729 .db
1730 .query_row(
1731 "SELECT id,fingerprint FROM messages WHERE sender=?1 AND request_id=?2",
1732 params![sender.id, request_id],
1733 |r| Ok((r.get(0)?, r.get(1)?)),
1734 )
1735 .optional()?;
1736 if let Some((message_id, previous)) = existing {
1737 ensure!(
1738 previous == fingerprint,
1739 "request_id already used with different content"
1740 );
1741 return Ok(json!({"message_id":message_id,"duplicate":true}));
1742 }
1743 requests::admit(request_id, self.timestamp)?;
1744 let recipient = self.get_agent(recipient_id)?;
1745 ensure!(sender.id != recipient.id, UNAVAILABLE);
1746 let remote = !self.local_node(&recipient.node_id);
1747 let message_id = crate::messages::message_id(&sender.id, request_id)?;
1748 let timestamp = self.timestamp;
1749 let (exchange_id, expires_at) = if let Some(parent) = parent {
1750 ensure!(
1751 self.config.policy.can_reply(sender, &recipient),
1752 UNAVAILABLE
1753 );
1754 let (a, b, expiry, count): (String, String, i64, u32) = self.db.query_row(
1755 "SELECT a,b,expires_at,count FROM exchanges WHERE id=?1",
1756 [&parent.exchange_id],
1757 |r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
1758 )?;
1759 ensure!(
1760 (a == sender.id && b == recipient.id) || (b == sender.id && a == recipient.id),
1761 UNAVAILABLE
1762 );
1763 ensure!(expiry > timestamp, "exchange expired");
1764 ensure!(
1765 count < MAX_EXCHANGE_MESSAGES,
1766 "exchange reply limit reached"
1767 );
1768 (parent.exchange_id, expiry)
1769 } else {
1770 ensure!(self.config.policy.can_open(sender, &recipient), UNAVAILABLE);
1771 let mut expiry = timestamp + EXCHANGE_TTL_SECONDS;
1772 if let Some(grant_id) = relay.as_ref().and_then(|relay| relay.grant_id.as_ref()) {
1773 let grant = self
1774 .config
1775 .policy
1776 .relay_grants
1777 .get(grant_id)
1778 .context(UNAVAILABLE)?;
1779 expiry = expiry.min(grant.expires_at as i64);
1780 }
1781 (message_id.clone(), expiry)
1782 };
1783 if remote {
1784 let sent: u32 = self.db.query_row(
1785 "SELECT COUNT(*) FROM messages WHERE json_extract(payload,'$.exchange_id')=?1 AND sender=?2",
1786 params![exchange_id, sender.id],
1787 |r| r.get(0),
1788 )?;
1789 ensure!(
1790 sent < MAX_EXCHANGE_MESSAGES / 2,
1791 "remote exchange sender limit reached (16 messages)"
1792 );
1793 }
1794 let attachments = self.seal_attachments(sender, &file_ids, expires_at)?;
1795 let message = Message {
1796 id: message_id,
1797 exchange_id: exchange_id.clone(),
1798 sender: sender.id.clone(),
1799 recipient: recipient.id.clone(),
1800 text,
1801 files,
1802 attachments: attachments
1803 .iter()
1804 .map(|f| f.grant.descriptor().clone())
1805 .collect(),
1806 reply_to,
1807 created_at: timestamp,
1808 expires_at,
1809 acknowledged: false,
1810 relay,
1811 };
1812 self.validate_relay_message(&message)?;
1813 self.validate_local_relay(&message)?;
1814 let tx = self.db;
1815 if message.reply_to.is_none() {
1816 tx.execute(
1817 "INSERT INTO exchanges VALUES (?1,?2,?3,?4,0)",
1818 params![exchange_id, sender.id, recipient.id, expires_at],
1819 )?;
1820 }
1821 ensure!(
1822 tx.execute(
1823 "UPDATE exchanges SET count=count+1 WHERE id=?1 AND count<?2",
1824 params![exchange_id, MAX_EXCHANGE_MESSAGES]
1825 )? == 1,
1826 "exchange reply limit reached"
1827 );
1828 let payload = serde_json::to_string(&message)?;
1829 history::message_capacity(tx, payload.len())?;
1830 tx.execute("INSERT INTO messages(id,sender,recipient,request_id,fingerprint,payload) VALUES (?1,?2,?3,?4,?5,?6)",params![message.id,message.sender,message.recipient,request_id,fingerprint,payload])?;
1831 self.bind_attachments(&message, &attachments)?;
1832 self.record_relay_message(&message)?;
1833 self.web_state_changed(&recipient.node_id)?;
1834 if !self.gate_web_message(&message)? {
1835 usage::record_send(tx, &sender.name, &message)?;
1836 }
1837 self.save_activity(&sender.id, message.created_at)?;
1838 self.record_gent_message(&sender.id, message.created_at)?;
1839 if !remote {
1840 self.record_gent_message(&recipient.id, message.created_at)?;
1841 }
1842 if remote {
1843 self.record_web_demand(&recipient.node_id, &message.id)?;
1844 self.queue_message(
1845 self.state.transport_host(&recipient.node_id)?,
1846 request_id,
1847 &message,
1848 )?;
1849 }
1850 Ok(json!({"message_id":message.id,"exchange_id":exchange_id,"duplicate":false}))
1851 }
1852}