1pub mod account_key;
13pub mod agent_changes;
14pub mod agent_set;
15pub mod aws_import;
16pub mod aws_import_batch;
17pub mod backed;
18pub mod capture;
19pub mod changes;
20pub mod card;
21pub mod card_fill;
22pub mod card_target;
23pub mod expiry;
24pub mod files;
25pub mod generate;
26pub mod github_secret;
27pub mod history;
28pub mod import;
29pub mod inspect;
30pub mod kdbx_export;
31pub mod kdbx_names;
32pub mod kinds;
33pub mod linked;
34pub mod pace;
35pub mod proposals;
36pub mod plain_export;
37pub mod requests;
38pub mod endpoint_key;
39pub mod route_key;
40pub mod scrub;
41pub mod seal;
42pub mod setting_key;
43pub mod shares;
44pub mod signins;
45pub mod signups;
46pub mod slots;
47pub mod source_link;
48pub mod sync_activity;
49pub mod sync_adapter;
50pub mod sync_capture;
51mod sync_capture_kinds;
52pub mod sync_grant;
53pub mod sync_links;
54pub mod sync_merge;
55pub mod sync_record;
56pub mod sync_seal;
57pub mod sync_store;
58pub mod sync_take;
59mod sync_take_grants;
60pub mod transfer;
61pub mod uses;
62pub mod vaults;
63pub mod versions;
64pub mod wordlist;
65
66use std::collections::BTreeMap;
67
68use agentmux_common::time::now_ms;
69use serde::{Deserialize, Serialize};
70
71use crate::backend::storage::store::Store;
72use crate::backend::storage::vault::{VaultActivityRow, VaultRow, PERSONAL_VAULT};
73use kinds::VaultSection;
74use seal::Parts;
75
76pub const PERSON: &str = "you";
78
79const MAX_LABEL: usize = 200;
80const MAX_FIELD: usize = 4096;
81const MAX_PART: usize = 1024 * 1024;
83const MAX_TAGS: usize = 50;
84const MAX_ID: usize = 48;
85
86#[derive(Debug, Clone, Serialize, ts_rs::TS)]
89#[ts(export, export_to = "../../../frontend/types/rpc/")]
90pub struct VaultEntryInfo {
91 pub id: String,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
95 #[ts(optional)]
96 pub link_id: Option<String>,
97 pub kind: String,
98 pub section: VaultSection,
99 pub label: String,
100 pub vault_id: String,
102 pub fields: BTreeMap<String, String>,
103 pub tags: Vec<String>,
104 pub parts_set: Vec<String>,
106 pub grants: Vec<String>,
108 pub tail: String,
109 pub versions: u32,
111 #[serde(skip_serializing_if = "Option::is_none")]
114 #[ts(optional)]
115 pub source_checked: Option<source_link::VaultSourceCheck>,
116 #[serde(skip_serializing_if = "Option::is_none")]
118 #[ts(optional)]
119 pub copies_checked: Option<Vec<linked::VaultCopyCheck>>,
120 #[ts(type = "number")]
121 pub created_at: i64,
122 #[ts(type = "number")]
123 pub updated_at: i64,
124 #[ts(type = "number")]
125 pub last_used_at: i64,
126}
127
128#[derive(Debug, Clone, Serialize, PartialEq)]
132pub struct VaultAgentEntry {
133 pub id: String,
134 pub link_id: String,
136 pub label: String,
137 pub kind: String,
138 pub section: VaultSection,
139 pub vault: String,
141 #[serde(skip_serializing_if = "Option::is_none")]
142 pub expires: Option<String>,
143 #[serde(skip_serializing_if = "Option::is_none")]
145 pub source: Option<source_link::AgentLink>,
146 #[serde(skip_serializing_if = "std::ops::Not::not")]
148 pub shared_with_you: bool,
149}
150
151#[derive(Debug, Clone, Serialize, ts_rs::TS)]
152#[ts(export, export_to = "../../../frontend/types/rpc/")]
153pub struct VaultActivity {
154 #[ts(type = "number")]
155 pub at: i64,
156 pub entry_id: String,
157 pub entry_label: String,
158 pub actor: String,
159 pub action: String,
160 pub target: String,
161 pub outcome: String,
162 #[ts(type = "number")]
164 pub seq: i64,
165 #[ts(type = "number")]
167 pub version: i64,
168 pub actor_kind: String,
170 pub host: String,
172 pub reason: String,
174 pub refs: Vec<String>,
176 pub is_use: bool,
178}
179
180impl From<VaultActivityRow> for VaultActivity {
181 fn from(r: VaultActivityRow) -> Self {
182 VaultActivity {
183 is_use: crate::backend::storage::vault::VALUE_USES.contains(&r.action.as_str()),
184 refs: history::refs_of(&r.refs),
185 at: r.at,
186 entry_id: r.entry_id,
187 entry_label: r.entry_label,
188 actor: r.actor,
189 action: r.action,
190 target: r.target,
191 outcome: r.outcome,
192 seq: r.seq,
193 version: r.version,
194 actor_kind: r.actor_kind,
195 host: r.host,
196 reason: r.reason,
197 }
198 }
199}
200
201#[derive(Deserialize)]
203pub struct NewEntry {
204 pub kind: String,
205 pub label: String,
206 #[serde(default)]
207 pub fields: BTreeMap<String, String>,
208 #[serde(default)]
209 pub tags: Vec<String>,
210 #[serde(default)]
211 pub parts: Parts,
212}
213
214#[derive(Deserialize)]
217pub struct EntryChange {
218 pub id: String,
219 pub label: String,
220 #[serde(default)]
221 pub fields: BTreeMap<String, String>,
222 #[serde(default)]
223 pub tags: Vec<String>,
224 #[serde(default)]
225 pub parts: Parts,
226 #[serde(default)]
227 pub clear: Vec<String>,
228}
229
230fn validate(kind: &kinds::Kind, label: &str, fields: &BTreeMap<String, String>, tags: &[String], parts: &Parts) -> Result<(), String> {
231 if label.trim().is_empty() {
232 return Err("an entry needs a label".into());
233 }
234 if label.chars().count() > MAX_LABEL {
235 return Err(format!("a label is at most {MAX_LABEL} characters"));
236 }
237 for (k, v) in fields {
238 if !kind.fields.contains(&k.as_str()) && !source_link::is_field(k) && !linked::is_field(k) && !shares::is_field(kind.name, k) {
239 return Err(format!("a {} entry has no field {k:?}", kind.name));
240 }
241 if v.len() > MAX_FIELD {
242 return Err(format!("{k} is longer than {MAX_FIELD} bytes"));
243 }
244 if k == expiry::FIELD {
245 expiry::parse(v)?;
246 }
247 if k == signins::PROFILE && !signins::is_profile(v) {
248 return Err(format!("{v:?} isn't a browser profile: personal or profile:<id>"));
249 }
250 if k == shares::SHARED && v.split(',').any(|w| w.trim() != shares::EVERY_AGENT && !shares::is_uid(w.trim())) {
251 return Err("shared lists agents by their permanent uid, or *".into());
252 }
253 if k == signins::PROXY && v != "yes" {
254 return Err("proxy is \"yes\" for a proxy's sign-in, or left out".into());
255 }
256 }
257 source_link::validate(fields)?;
258 linked::validate(fields, !parts.0.is_empty())?;
259 if tags.len() > MAX_TAGS || tags.iter().any(|t| t.chars().count() > MAX_LABEL) {
260 return Err(format!("at most {MAX_TAGS} tags, each at most {MAX_LABEL} characters"));
261 }
262 for (k, v) in &parts.0 {
263 if !kind.parts.contains(&k.as_str()) {
264 return Err(format!("a {} entry has no part {k:?}", kind.name));
265 }
266 if v.len() > MAX_PART {
267 return Err(format!("{k} is longer than 1 MiB"));
268 }
269 }
270 Ok(())
271}
272
273fn trimmed(fields: BTreeMap<String, String>) -> BTreeMap<String, String> {
275 fields.into_iter().map(|(k, v)| (k, v.trim().to_string())).filter(|(_, v)| !v.is_empty()).collect()
276}
277
278fn drop_empty(parts: &mut Parts) {
279 parts.0.retain(|_, v| !v.is_empty());
280}
281
282fn keep_one_default(store: &Store, kind: &str, vault_id: &str, id: &str, fields: &BTreeMap<String, String>) -> Result<(), String> {
286 if kind != card::KIND || fields.get(card::DEFAULT).map(String::as_str) != Some("yes") {
287 return Ok(());
288 }
289 let rows = store.vault_list().map_err(|e| format!("couldn't list the cards: {e}"))?;
290 let mut failed = Vec::new();
291 for row in rows.into_iter().filter(|r| r.id != id && r.kind == card::KIND && r.vault_id == vault_id) {
292 let mut other: BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
293 if other.remove(card::DEFAULT).is_none() {
294 continue;
295 }
296 let cleared = serde_json::to_string(&other).map_err(|e| e.to_string()).and_then(|json| store.vault_set_fields(&row.id, &json).map_err(|e| e.to_string()));
297 if let Err(e) = cleared {
298 failed.push(format!("{}: {e}", row.id));
299 }
300 }
301 if failed.is_empty() {
302 Ok(())
303 } else {
304 Err(format!("couldn't clear the default flag of {}", failed.join("; ")))
305 }
306}
307
308pub(crate) fn resettle_card(store: &Store, id: &str) -> Result<(), String> {
311 let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
312 if row.kind != card::KIND {
313 return Ok(());
314 }
315 let key = seal::key(false)?;
316 let mut parts = seal::open(&key, &row.id, &row.sealed)?;
317 let before: BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
318 let mut fields = before.clone();
319 card::settle(card::KIND, &mut fields, &mut parts)?;
320 if fields != before {
321 let json = serde_json::to_string(&fields).map_err(|e| e.to_string())?;
322 store.vault_set_fields(&row.id, &json).map_err(|e| e.to_string())?;
323 }
324 Ok(())
325}
326
327fn part_of(kind: &str, parts: &Parts, part: &str) -> Option<String> {
329 if kind == card::KIND {
330 card::part_value(parts, part)
331 } else {
332 parts.get(part).map(str::to_string)
333 }
334}
335
336fn new_id(store: &Store, kind: &str, label: &str) -> Result<String, String> {
340 new_id_besides(store, kind, label, &[])
341}
342
343fn new_id_besides(store: &Store, kind: &str, label: &str, taken: &[String]) -> Result<String, String> {
346 let mut slug = String::new();
347 for c in format!("{kind}-{label}").chars().flat_map(char::to_lowercase) {
348 if c.is_ascii_alphanumeric() {
349 slug.push(c);
350 } else if !slug.ends_with('-') {
351 slug.push('-');
352 }
353 }
354 let mut base: String = slug.trim_matches('-').chars().take(MAX_ID).collect();
355 base = base.trim_end_matches('-').to_string();
356 for n in 1..1000 {
357 let id = if n == 1 { base.clone() } else { format!("{base}-{n}") };
358 if !taken.contains(&id) && store.vault_get(&id).map_err(|e| e.to_string())?.is_none() {
359 return Ok(id);
360 }
361 }
362 Err("too many entries with that label".into())
363}
364
365const USES: &[&str] = &["filled a web form", signins::SIGNED_IN, "ran a command", "revealed", "copied", route_key::USED];
367
368pub fn record(store: &Store, entry_id: &str, entry_label: &str, actor: &str, action: &str, target: &str, outcome: &str) {
370 let row = VaultActivityRow {
371 entry_id: entry_id.into(),
372 entry_label: entry_label.into(),
373 actor: actor.into(),
374 action: action.into(),
375 target: target.into(),
376 outcome: outcome.into(),
377 ..Default::default()
378 };
379 record_row(store, row);
380}
381
382pub struct Line<'a> {
384 pub entry_id: &'a str,
385 pub label: &'a str,
386 pub actor: &'a str,
387 pub action: &'a str,
388 pub target: &'a str,
389 pub outcome: &'a str,
390 pub reason: &'a str,
391}
392
393pub fn record_line(store: &Store, l: Line<'_>) {
395 record_row(
396 store,
397 VaultActivityRow {
398 entry_id: l.entry_id.into(),
399 entry_label: l.label.into(),
400 actor: l.actor.into(),
401 action: l.action.into(),
402 target: l.target.into(),
403 outcome: l.outcome.into(),
404 reason: l.reason.into(),
405 ..Default::default()
406 },
407 );
408}
409
410pub fn record_row(store: &Store, mut row: VaultActivityRow) {
412 if USES.contains(&row.action.as_str()) && !row.entry_id.is_empty() {
413 if let Ok(Some(entry)) = store.vault_get(&row.entry_id) {
414 if expiry::expired(&entry, expiry::today()) {
415 row.target = if row.target.is_empty() { "(expired)".into() } else { format!("{} (expired)", row.target) };
416 }
417 }
418 }
419 row.at = now_ms();
420 history::append(store, row);
421}
422
423pub fn create(store: &Store, entry: NewEntry) -> Result<String, String> {
425 insert(store, entry, PERSON, "created", "")
426}
427
428pub fn create_in(store: &Store, entry: NewEntry, vault_id: &str) -> Result<String, String> {
430 insert_in(store, entry, PERSON, "created", "", vault_id)
431}
432
433fn insert(store: &Store, entry: NewEntry, actor: &str, action: &str, target: &str) -> Result<String, String> {
435 insert_in(store, entry, actor, action, target, PERSONAL_VAULT)
436}
437
438fn insert_in(store: &Store, entry: NewEntry, actor: &str, action: &str, target: &str, vault_id: &str) -> Result<String, String> {
440 insert_in_why(store, entry, actor, action, target, vault_id, "")
441}
442
443fn insert_in_why(store: &Store, entry: NewEntry, actor: &str, action: &str, target: &str, vault_id: &str, reason: &str) -> Result<String, String> {
445 let (id, label) = insert_unrecorded(store, entry, vault_id)?;
446 record_line(store, Line { entry_id: &id, label: &label, actor, action, target, outcome: "done", reason });
447 Ok(id)
448}
449
450fn insert_unrecorded(store: &Store, entry: NewEntry, vault_id: &str) -> Result<(String, String), String> {
452 insert_unrecorded_bound(store, entry, vault_id, None)
453}
454
455fn insert_unrecorded_bound(store: &Store, mut entry: NewEntry, vault_id: &str, link_id: Option<&str>) -> Result<(String, String), String> {
456 store.vault_info(vault_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no Vault {vault_id}"))?;
457 let kind = kinds::kind(&entry.kind).ok_or_else(|| format!("unknown kind {:?}", entry.kind))?;
458 drop_empty(&mut entry.parts);
459 let mut fields = trimmed(std::mem::take(&mut entry.fields));
460 if fields.contains_key(shares::SHARED) {
461 return Err("a login is shared with an agent after it is saved (the Share button on its card), never when it is made".into());
462 }
463 signins::normalize_site(kind.name, &mut fields);
464 signins::settle_profile(kind.name, &mut fields);
465 card::settle(kind.name, &mut fields, &mut entry.parts)?;
466 validate(kind, &entry.label, &fields, &entry.tags, &entry.parts)?;
467 if !linked::is_linked(&fields) && entry.parts.get(kind.parts[0]).is_none() {
469 return Err(format!("a {} entry needs its {}", kind.name, kind.parts[0]));
470 }
471 let key = seal::key(store.vault_count().map_err(|e| e.to_string())? == 0)?;
472 let label = entry.label.trim().to_string();
473 let id = new_id(store, kind.name, &label)?;
474 let now = now_ms();
475 let row = VaultRow {
476 id: id.clone(),
477 kind: kind.name.into(),
478 label: label.clone(),
479 fields: serde_json::to_string(&fields).map_err(|e| e.to_string())?,
480 tags: serde_json::to_string(&entry.tags).map_err(|e| e.to_string())?,
481 sealed: seal::seal(&key, &id, &entry.parts)?,
482 created_at: now,
483 updated_at: now,
484 last_used_at: 0,
485 vault_id: vault_id.to_string(),
486 };
487 store.vault_insert_bound(&row, link_id).map_err(|e| e.to_string())?;
488 if let Err(e) = keep_one_default(store, kind.name, vault_id, &id, &fields) {
489 tracing::warn!(entry = %id, error = %e, "vault: the new default card is saved, but another card still has the default flag");
490 }
491 Ok((id, label))
492}
493
494pub const GENERATED_KINDS: &[(&str, &str)] = &[("api-key", "value"), ("login", "password"), ("note", "text")];
497
498#[derive(Debug, Deserialize)]
500pub struct GenerateRequest {
501 pub kind: String,
502 pub label: String,
503 #[serde(default)]
504 pub why: String,
505 #[serde(default)]
507 pub reason: Option<String>,
508 #[serde(default)]
510 pub fields: BTreeMap<String, String>,
511 #[serde(default)]
512 pub rules: generate::RulesRequest,
513 #[serde(default)]
516 pub expires: Option<String>,
517 #[serde(default)]
519 pub vault: Option<String>,
520}
521
522#[derive(Debug, Serialize, PartialEq)]
524pub struct Generated {
525 pub id: String,
526 pub label: String,
527 pub kind: String,
528 pub made: String,
530}
531
532pub fn generate_entry(store: &Store, req: GenerateRequest, actor: &str) -> Result<Generated, String> {
536 generate_entry_in(store, req, actor, None)
537}
538
539pub fn generate_entry_in(store: &Store, req: GenerateRequest, actor: &str, own_profile: Option<&str>) -> Result<Generated, String> {
544 let reason = history::require_reason(req.reason.as_deref().filter(|r| !r.trim().is_empty()).or(Some(req.why.as_str())))?;
545 let Some((kind, part)) = GENERATED_KINDS.iter().find(|(k, _)| *k == req.kind) else {
546 let names: Vec<&str> = GENERATED_KINDS.iter().map(|(k, _)| *k).collect();
547 return Err(format!("generate makes {} entries, not {:?}: an ID number or a card is the person's, so ask for it with request", names.join(", "), req.kind));
548 };
549 if let Some(name) = [shares::SHARED, signins::PROFILE].into_iter().find(|f| req.fields.contains_key(*f)) {
550 return Err(inspect::person_only_refusal(name));
551 }
552 if let Some(site) = req.fields.get(signins::SITE).filter(|s| !s.trim().is_empty()) {
553 inspect::agent_origin(site)?;
554 }
555 let signin_profile = match (*kind == "login" && req.fields.get(signins::SITE).is_some_and(|s| !s.trim().is_empty()), own_profile) {
556 (false, _) => None,
557 (true, Some(profile)) => Some(profile.to_string()),
558 (true, None) => return Err("a login for a site is made for your own browser profile, and this call doesn't name one: sign in to AgentMux as the agent, or leave the site out".into()),
559 };
560 let rules = generate::rules(&req.rules)?;
561 let value = generate::generate(&rules)?;
562 let mut parts = Parts::default();
563 parts.0.insert(part.to_string(), value.to_string());
564 let target = generate::describe(&rules);
565 let mut fields = req.fields;
566 if let Some(profile) = &signin_profile {
567 fields.insert(signins::PROFILE.to_string(), profile.clone());
568 }
569 if let Some(date) = req.expires.filter(|d| !d.trim().is_empty()) {
570 fields.insert(expiry::FIELD.to_string(), date);
571 }
572 let entry = NewEntry { kind: kind.to_string(), label: req.label, fields, tags: Vec::new(), parts };
573 let label = entry.label.trim().to_string();
574 let vault_id = match req.vault.as_deref().map(str::trim).filter(|v| !v.is_empty()) {
575 Some(which) => vaults::resolve(store, which, Some(Some(actor)))?.id,
576 None => match &signin_profile {
577 Some(profile) => {
579 let kept = signins::vault_for(store, profile)?;
580 if vaults::entry_row_usable(store, &kept, Some(actor))? {
581 kept
582 } else {
583 vaults::default_for(store, Some(actor))?
584 }
585 }
586 None => vaults::default_for(store, Some(actor))?,
587 },
588 };
589 let id = insert_in_why(store, entry, actor, "generated", &target, &vault_id, &reason)?;
590 if signin_profile.is_some() {
591 agent_set::mark_site(store, &id, actor);
593 }
594 Ok(Generated { id, label, kind: kind.to_string(), made: generate::describe(&rules) })
595}
596
597pub fn update(store: &Store, mut change: EntryChange) -> Result<(), String> {
599 let row = store.vault_get(&change.id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {}", change.id))?;
600 let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {} has an unknown kind", row.id))?;
601 drop_empty(&mut change.parts);
602 let mut fields = trimmed(std::mem::take(&mut change.fields));
603 signins::normalize_site(kind.name, &mut fields);
604 signins::settle_profile(kind.name, &mut fields);
605 let old_fields: BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
606 match old_fields.get(shares::SHARED) {
609 Some(v) => fields.insert(shares::SHARED.to_string(), v.clone()),
610 None => fields.remove(shares::SHARED),
611 };
612 validate(kind, &change.label, &fields, &change.tags, &change.parts)?;
613 if linked::mark(&fields) != linked::mark(&old_fields) {
614 return Err(linked::SET_WHEN_MADE.into());
615 }
616 if change.clear.iter().any(|p| p == kind.parts[0]) {
617 return Err(format!("a {} entry needs its {}", kind.name, kind.parts[0]));
618 }
619 let key = seal::key(false)?;
620 let mut parts = seal::open(&key, &row.id, &row.sealed)?;
621 for p in &change.clear {
622 if let Some(mut v) = parts.0.remove(p) {
623 zeroize::Zeroize::zeroize(&mut v);
624 }
625 }
626 let replaced = change.parts.0.contains_key(kind.parts[0]);
628 let kept = replaced.then(|| versions::of(&row, PERSON, "replaced"));
629 if replaced {
630 versions::prune(store);
631 }
632 let (was, was_fields) = (row.sealed.clone(), row.fields.clone());
633 for (k, v) in std::mem::take(&mut change.parts.0) {
634 if let Some(mut old) = parts.0.insert(k, v) {
635 zeroize::Zeroize::zeroize(&mut old);
636 }
637 }
638 card::settle(kind.name, &mut fields, &mut parts)?;
639 let label = change.label.trim().to_string();
640 let target = match (old_fields.get(expiry::FIELD), fields.get(expiry::FIELD)) {
641 (old, Some(new)) if old != Some(new) => format!("expires {new}"),
642 (Some(_), None) => "no expiry date".to_string(),
643 _ => String::new(),
644 };
645 let changed = VaultRow {
646 label: label.clone(),
647 fields: serde_json::to_string(&fields).map_err(|e| e.to_string())?,
648 tags: serde_json::to_string(&change.tags).map_err(|e| e.to_string())?,
649 sealed: seal::seal(&key, &row.id, &parts)?,
650 updated_at: now_ms(),
651 ..row
652 };
653 if !store.vault_update_kept(&changed, &was, &was_fields, kept.as_ref()).map_err(|e| e.to_string())? {
656 return Err(format!("{label} changed while you were editing it, so nothing was saved: open it again"));
657 }
658 if let Err(e) = keep_one_default(store, kind.name, &changed.vault_id, &changed.id, &fields) {
659 tracing::warn!(entry = %changed.id, error = %e, "vault: the new default card is saved, but another card still has the default flag");
660 }
661 record(store, &changed.id, &label, PERSON, if replaced { "replaced" } else { "changed" }, &target, "done");
662 Ok(())
663}
664
665pub fn reveal(store: &Store, id: &str, part: &str, action: &str) -> Result<zeroize::Zeroizing<String>, String> {
671 if action != "revealed" && action != "copied" {
672 return Err(format!("unknown use {action:?}"));
673 }
674 let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
675 let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {id} has an unknown kind"))?;
676 if !kind.parts.contains(&part) {
677 return Err(format!("a {} entry has no part {part:?}", kind.name));
678 }
679 let value = if linked::is_backed_row(&row) {
680 backed_part(&row, part)?
682 } else {
683 let key = seal::key(false)?;
684 let parts = seal::open(&key, &row.id, &row.sealed)?;
685 let value = parts.get(part).ok_or_else(|| format!("{} has no {part} saved", row.label))?;
686 zeroize::Zeroizing::new(value.to_string())
687 };
688 if action == "revealed" {
689 store.vault_touch(&row.id, now_ms()).map_err(|e| e.to_string())?;
690 record(store, &row.id, &row.label, PERSON, action, part, "done");
691 }
692 Ok(value)
693}
694
695pub fn record_copy(store: &Store, id: &str, part: &str, done: bool) -> Result<(), String> {
698 let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
699 if !kinds::kind(&row.kind).is_some_and(|k| k.parts.contains(&part)) {
700 return Err(format!("{} has no part {part:?}", row.label));
701 }
702 if done {
703 store.vault_touch(&row.id, now_ms()).map_err(|e| e.to_string())?;
704 }
705 record(store, &row.id, &row.label, PERSON, "copied", part, if done { "done" } else { "failed" });
706 Ok(())
707}
708
709#[derive(Clone)]
712pub struct FillTarget {
713 pub id: String,
715 pub kind: &'static str,
717 pub typed: bool,
719 pub kind_info: &'static kinds::Kind,
721 pub label: String,
722 pub part: &'static str,
723 pub slot: Option<&'static str>,
724 pub what: String,
725 pub created_at: i64,
729 pub version: Option<&'static str>,
732}
733
734fn usable_entry(store: &Store, id: &str, agent: Option<&str>) -> Result<VaultRow, String> {
737 let none = || format!("no Vault entry {id:?}: Vault's list action shows the entries");
738 let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(none)?;
739 if !vaults::entry_row_usable(store, &row.vault_id, agent)? {
740 return Err(none());
741 }
742 if let Some(no_value) = linked::no_value(&row) {
743 return Err(no_value);
744 }
745 Ok(row)
746}
747
748pub fn fill_target(store: &Store, vault: &str, agent: Option<&str>) -> Result<FillTarget, String> {
750 let (id, part) = slots::split(vault);
751 let row = usable_entry(store, id, agent)?;
752 let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {id} has an unknown kind"))?;
753 let part = slots::fillable_part(kind, part)?;
754 let slot = slots::slot(kind, part);
755 let what = slots::what(kind, part);
756 Ok(FillTarget { id: row.id, kind: kind.name, typed: false, kind_info: kind, label: row.label, part, slot, what, created_at: row.created_at, version: None })
757}
758
759pub fn request_target(kind: &str, label: &str) -> Result<FillTarget, String> {
761 let kind = kinds::kind(kind).ok_or_else(|| format!("unknown kind {kind:?}"))?;
762 let label = label.trim();
763 if label.is_empty() || label.chars().count() > MAX_LABEL {
764 return Err("request_value needs a label saying what the value is, e.g. \"Alex's SSN\"".into());
765 }
766 let part = slots::fillable_part(kind, None)?;
767 Ok(FillTarget { id: String::new(), kind: kind.name, typed: true, kind_info: kind, label: label.to_string(), part, slot: slots::slot(kind, part), what: slots::what(kind, part), created_at: 0, version: None })
768}
769
770pub fn command_target(store: &Store, vault: &str, agent: Option<&str>) -> Result<FillTarget, String> {
775 let (vault, version) = match vault.trim().split_once('@') {
777 Some((id, rest)) => {
778 let (which, part) = rest.split_once('.').map(|(w, p)| (w, Some(p))).unwrap_or((rest, None));
779 let which = match which {
780 "previous" => "previous",
781 "pending" => "pending",
782 other => return Err(format!("{id}@{other}: a command can name {id}@previous (the value the last change replaced), not @{other}")),
783 };
784 (part.map(|p| format!("{id}.{p}")).unwrap_or_else(|| id.to_string()), Some(which))
785 }
786 None => (vault.to_string(), None),
787 };
788 let mut target = command_target_now(store, &vault, agent)?;
789 target.version = version;
790 if let Some(v) = version {
791 target.what = format!("{} ({v} value)", target.what);
792 }
793 Ok(target)
794}
795
796fn command_target_now(store: &Store, vault: &str, agent: Option<&str>) -> Result<FillTarget, String> {
797 let (id, part) = slots::split(vault);
798 let row = usable_entry(store, id, agent)?;
799 let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {id} has an unknown kind"))?;
800 let part = match part {
801 None => kind.parts[0],
802 Some(p) => *kind.parts.iter().find(|x| **x == p).ok_or_else(|| format!("{} has no part {p:?}; its parts are {}", row.label, kind.parts.join(", ")))?,
803 };
804 Ok(FillTarget { id: row.id, kind: kind.name, typed: false, kind_info: kind, label: row.label, part, slot: None, what: slots::what(kind, part), created_at: row.created_at, version: None })
805}
806
807pub fn value_for_fill(store: &Store, id: &str, created_at: i64, part: &str) -> Result<zeroize::Zeroizing<String>, String> {
810 let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
811 if row.created_at != created_at {
812 return Err(format!("{} was replaced while the person was deciding: nothing was typed", row.label));
813 }
814 if linked::is_backed_row(&row) {
815 return backed_part(&row, part);
816 }
817 let key = seal::key(false)?;
818 let parts = seal::open(&key, &row.id, &row.sealed)?;
819 let value = part_of(&row.kind, &parts, part).ok_or_else(|| format!("{} has no {part} saved", row.label))?;
820 Ok(zeroize::Zeroizing::new(value))
821}
822
823fn backed_part(row: &VaultRow, part: &str) -> Result<zeroize::Zeroizing<String>, String> {
825 let main = kinds::kind(&row.kind).map(|k| k.parts[0]);
826 if main != Some(part) {
827 return Err(format!("{} has no {part} saved", row.label));
828 }
829 backed::value_of(row)
830}
831
832pub fn value_for_command(store: &Store, t: &FillTarget) -> Result<zeroize::Zeroizing<String>, String> {
835 let Some(which) = t.version else { return value_for_fill(store, &t.id, t.created_at, t.part) };
836 let row = store.vault_get(&t.id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {}", t.id))?;
837 if row.created_at != t.created_at {
838 return Err(format!("{} was replaced while the person was deciding: nothing was run", row.label));
839 }
840 if linked::is_backed_row(&row) {
841 return Err(backed::no_versions(&row, which));
842 }
843 let (_, sealed) = versions::sealed_version(store, &row, which)?;
844 let key = seal::key(false)?;
845 let parts = seal::open(&key, &row.id, &sealed)?;
846 let value = part_of(&row.kind, &parts, t.part).ok_or_else(|| format!("{}'s {which} value has no {}", row.label, t.part))?;
847 Ok(zeroize::Zeroizing::new(value))
848}
849
850pub fn delete(store: &Store, id: &str) -> Result<(), String> {
851 let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
852 store.vault_delete(id).map_err(|e| e.to_string())?;
853 requests::requests().forget_entry(id);
855 record(store, id, &row.label, PERSON, "deleted", "", "done");
856 Ok(())
857}
858
859pub const LINK_ID_PREFIX: &str = "e_";
861
862fn new_link_id() -> String {
864 let hex = uuid::Uuid::new_v4().simple().to_string();
865 format!("{LINK_ID_PREFIX}{}", &hex[..16])
866}
867
868pub fn link_ids(store: &Store, ids: &[&str]) -> Result<std::collections::HashMap<String, String>, String> {
870 let mut known = store.vault_link_ids().map_err(|e| e.to_string())?;
871 for id in ids {
872 if known.contains_key(*id) {
873 continue;
874 }
875 for _ in 0..8 {
876 if let Some(link) = store.vault_link_id_assign(id, &new_link_id()).map_err(|e| e.to_string())? {
877 known.insert(id.to_string(), link);
878 break;
879 }
880 }
881 }
882 Ok(known)
883}
884
885pub fn entry_of_link(store: &Store, link_id: &str) -> Result<Option<String>, String> {
887 store.vault_entry_of_link(link_id).map_err(|e| e.to_string())
888}
889
890pub fn list_for_pane(store: &Store) -> Result<(Vec<VaultEntryInfo>, Option<String>), String> {
893 let rows = store.vault_list().map_err(|e| e.to_string())?;
894 let mut grants = store.vault_grants().map_err(|e| e.to_string())?;
895 versions::prune(store);
896 let counts = store.vault_version_counts().map_err(|e| e.to_string())?;
897 let mut links = link_ids(store, &rows.iter().map(|r| r.id.as_str()).collect::<Vec<_>>())?;
898 let key = if rows.is_empty() { Ok(None) } else { seal::key(false).map(Some) };
899 let mut problem = key.as_ref().err().cloned();
900 let mut out = Vec::with_capacity(rows.len());
901 for row in rows {
902 let Some(kind) = kinds::kind(&row.kind) else { continue };
903 let (parts_set, tail) = match &key {
904 Ok(Some(key)) => match seal::open(key, &row.id, &row.sealed) {
905 Ok(parts) => (parts.0.keys().cloned().collect(), parts.get(kind.parts[0]).map(|v| kinds::tail(kind, v)).unwrap_or_default()),
906 Err(e) => {
907 problem.get_or_insert(e);
908 (Vec::new(), String::new())
909 }
910 },
911 _ => (Vec::new(), String::new()),
912 };
913 let source_checked = source_link::Link::of_row(&row).and_then(|link| source_link::last_check(store, &row, &link));
914 let copies_checked = Some(linked::copy_checks(store, &row)).filter(|copies| !copies.is_empty());
915 out.push(VaultEntryInfo {
916 source_checked,
917 copies_checked,
918 fields: serde_json::from_str(&row.fields).unwrap_or_default(),
919 tags: serde_json::from_str(&row.tags).unwrap_or_default(),
920 section: kind.section,
921 grants: grants.remove(&row.id).unwrap_or_default(),
922 versions: counts.get(&row.id).filter(|(created, _)| *created == row.created_at).map(|(_, n)| *n).unwrap_or(0),
923 link_id: links.remove(&row.id),
924 id: row.id,
925 kind: row.kind,
926 label: row.label,
927 vault_id: row.vault_id,
928 parts_set,
929 tail,
930 created_at: row.created_at,
931 updated_at: row.updated_at,
932 last_used_at: row.last_used_at,
933 });
934 }
935 Ok((out, problem))
936}
937
938pub fn list_for_agent(store: &Store, agent: Option<&str>) -> Result<Vec<VaultAgentEntry>, String> {
941 list_for_agent_as(store, agent, None)
942}
943
944pub fn list_for_agent_as(store: &Store, agent: Option<&str>, uid: Option<&str>) -> Result<Vec<VaultAgentEntry>, String> {
946 let vaults = store.vaults().map_err(|e| e.to_string())?;
947 let rows = store.vault_list().map_err(|e| e.to_string())?;
948 let mut links = link_ids(store, &rows.iter().map(|r| r.id.as_str()).collect::<Vec<_>>())?;
949 Ok(rows
950 .into_iter()
951 .filter_map(|r| {
952 let vault = vaults.iter().find(|v| v.id == r.vault_id);
953 if !vault.is_none_or(|v| vaults::may_use(v, agent)) {
954 return None;
955 }
956 let section = kinds::kind(&r.kind)?.section;
957 let expires = expiry::of(&r).map(|d| d.to_string());
958 let vault = vault.map(|v| v.name.clone()).unwrap_or_default();
959 let source = source_link::for_agent(store, &r);
960 let shared_with_you = uid.is_some_and(|u| shares::names(&signins::fields_of(&r), u));
961 let link_id = links.remove(&r.id).unwrap_or_default();
962 Some(VaultAgentEntry { id: r.id, link_id, label: r.label, kind: r.kind, section, vault, expires, source, shared_with_you })
963 })
964 .collect())
965}
966
967pub fn activity(store: &Store, limit: i64) -> Result<Vec<VaultActivity>, String> {
968 Ok(store
969 .vault_activity_list(limit.clamp(1, 1000))
970 .map_err(|e| e.to_string())?
971 .into_iter()
972 .map(VaultActivity::from)
973 .collect())
974}
975
976#[cfg(test)]
977mod agent_changes_tests;
978#[cfg(test)]
979mod agent_place_tests;
980#[cfg(test)]
981mod card_scan_tests;
982#[cfg(test)]
983mod history_tests;
984#[cfg(test)]
985mod tests;
986#[cfg(test)]
987mod transfer_tests;