use super::logins::SeatSeen;
use super::{Login, SeatLogin, SeatState, VaultTx, read_seat};
use crate::claude::credentials::{LoginMeta, Secret};
use crate::claude::seats::{Seat, SeatId};
use crate::core::harness::Harness;
use crate::core::ids::LoginId;
const REFRESH_LIFETIME_DAYS: i64 = 30;
impl VaultTx<'_> {
pub(super) fn observe(&mut self, seat: &Seat, s: &SeatLogin) -> SeatState {
let Some(sec) = &s.secret else {
self.index.seats.remove(&seat.id);
return SeatState::default();
};
let meta = sec.meta();
let fp = meta.fingerprint.clone();
let profile_at = s.account.as_ref().and_then(|a| a.profile_fetched_at);
let account = s.account.as_ref().map(|a| a.id().to_string());
let prev = self.index.seats.get(&seat.id).cloned();
let named = meta.account.is_some() && meta.account == account;
let unverified_since = match &prev {
_ if matches!(seat.harness, Harness::Agy | Harness::Codex) || named => None,
None => {
let issued = meta
.refresh_expires_at
.map(|t| t - chrono::Duration::days(REFRESH_LIFETIME_DAYS));
let copied_in = match (s.written_at, meta.access_expires_at, profile_at) {
(Some(w), Some(exp), Some(p))
if w > p && exp + chrono::Duration::minutes(5) < w =>
{
Some(w)
}
_ => None,
};
match (issued, profile_at) {
(Some(i), Some(p)) if i > p + chrono::Duration::minutes(10) => Some(i),
_ => copied_in,
}
}
Some(p) if p.fingerprint != fp => {
let known = self.index.logins.iter().any(|l| {
l.is_in(&seat.id)
&& l.meta.fingerprint == fp
&& l.account_uuid.is_some()
&& l.account_uuid == account
});
if profile_at > p.profile_at || known {
None
} else {
Some(self.now)
}
}
Some(p) => p.unverified_since.filter(|_| profile_at <= p.profile_at),
};
let followed = self
.index
.logins
.iter()
.any(|l| l.is_in(&seat.id) && l.meta.fingerprint == fp);
let switched_at = prev
.as_ref()
.filter(|p| p.fingerprint == fp || followed)
.and_then(|p| p.switched_at);
let seen = SeatSeen {
label: seat.label.clone(),
fingerprint: fp.clone(),
account_uuid: account.clone(),
profile_at: if unverified_since.is_some() {
prev.as_ref().and_then(|p| p.profile_at).or(profile_at)
} else {
profile_at
},
unverified_since,
switched_at,
};
if prev.as_ref() != Some(&seen) {
self.index.seats.insert(seat.id.clone(), seen);
}
let saved_as = self
.index
.logins
.iter()
.find(|l| l.harness == seat.harness && l.meta.fingerprint == fp)
.map(|l| l.label.clone());
SeatState {
fingerprint: Some(fp),
account_uuid: if unverified_since.is_some() {
None
} else {
account
},
unverified_since,
switched_at,
saved_as,
}
}
pub fn seat_states(
&mut self,
seats: &[Seat],
) -> anyhow::Result<std::collections::BTreeMap<SeatId, SeatState>> {
self.index.adopt_seats(seats);
let mut out = std::collections::BTreeMap::new();
for seat in seats {
match read_seat(seat) {
Ok(s) => {
self.sync_seat(seat, &s);
out.insert(seat.id.clone(), self.observe(seat, &s));
}
Err(e) => crate::diag::log("vault", &format!("seat {}: {e:#}", seat.label)),
}
}
Ok(out)
}
pub fn sync(&mut self, seats: &[Seat]) -> anyhow::Result<()> {
self.index.adopt_seats(seats);
for seat in seats {
match read_seat(seat) {
Ok(s) => self.sync_seat(seat, &s),
Err(e) => crate::diag::log("vault", &format!("seat {}: {e:#}", seat.label)),
}
}
Ok(())
}
pub(super) fn sync_seat(&mut self, seat: &Seat, s: &SeatLogin) {
let mounted = self
.index
.logins
.iter()
.find(|l| l.is_in(&seat.id))
.cloned();
let Some(sec) = &s.secret else {
if let Some(l) = mounted.and_then(|m| self.index.find_mut(&m.id)) {
l.mounted.retain(|m| *m != seat.id);
}
return;
};
let meta = sec.meta();
let saved = self
.index
.logins
.iter()
.find(|l| l.harness == seat.harness && l.meta.fingerprint == meta.fingerprint)
.map(|l| (l.id.clone(), l.label.clone()));
match &mounted {
Some(m) if m.meta.fingerprint == meta.fingerprint => {
self.keep_current(&m.id, sec);
return;
}
Some(m) if saved.is_none() && is_rotation(m, &self.saved_meta(m), &meta, s) => {
self.keep_current(&m.id, sec);
self.adopt_profile(&m.id, s);
self.journal(&format!(
"seat={}: the refresh token of '{}' was rotated; the saved login follows it",
seat.label, m.label
));
return;
}
Some(m) => {
if let Some(l) = self.index.find_mut(&m.id) {
l.mounted.retain(|x| *x != seat.id);
}
self.journal(&format!(
"seat={} has a new login; '{}' kept unchanged",
seat.label, m.label
));
}
None => {}
}
if saved.is_none()
&& let Some((id, label)) = self.orphan_of(seat, &meta, s)
{
self.mount(&id, &seat.id);
self.keep_current(&id, sec);
self.adopt_profile(&id, s);
self.journal(&format!(
"seat={}: the refresh token of '{label}' was rotated while no seat held it; \
the saved login follows it",
seat.label
));
return;
}
if let Some((id, label)) = saved {
self.mount(&id, &seat.id);
self.keep_current(&id, sec);
self.journal(&format!(
"seat={} holds '{label}': recorded as mounted there",
seat.label
));
}
}
fn saved_meta(&self, l: &Login) -> LoginMeta {
self.secret(&l.id)
.map(|x| x.meta())
.unwrap_or_else(|| l.meta.clone())
}
fn orphan_of(&self, seat: &Seat, new: &LoginMeta, s: &SeatLogin) -> Option<(LoginId, String)> {
if seat.harness != Harness::Claude {
return None;
}
let new_exp = new.refresh_expires_at?;
let mut found = self.index.logins.iter().filter(|l| {
if l.harness != seat.harness || !l.mounted.is_empty() || l.mounted_label.is_some() {
return false;
}
let old = self.saved_meta(l);
old.refresh_expires_at
.is_some_and(|e| (e - new_exp).abs() <= expiry_slack())
&& is_rotation(l, &old, new, s)
});
let l = found.next()?;
found
.next()
.is_none()
.then(|| (l.id.clone(), l.label.clone()))
}
fn adopt_profile(&mut self, id: &LoginId, s: &SeatLogin) {
let Some(sec) = &s.secret else { return };
let named = sec.meta().account;
let Some(a) = s
.account
.as_ref()
.filter(|a| named.is_some() && named.as_deref() == Some(a.id().as_str()))
else {
return;
};
if let Some(l) = self.index.find_mut(id)
&& l.account_uuid.is_none()
{
l.account_uuid = named;
l.email = a.email.clone().or(l.email.take());
l.plan = a.effective_tier().or(l.plan.take());
if l.oauth_account.is_none() {
l.oauth_account = s.oauth_account.clone();
}
l.updated_at = self.now;
}
}
fn keep_current(&mut self, id: &LoginId, sec: &Secret) {
let saved = self.secret(id);
if saved.as_ref() == Some(sec) {
return;
}
let newer = match saved.map(|x| x.meta()) {
None => true,
Some(old) => {
let new = sec.meta();
old.fingerprint != new.fingerprint
|| match (old.access_expires_at, new.access_expires_at) {
(Some(a), Some(b)) => b > a,
(None, _) | (Some(_), None) => true,
}
}
};
if newer {
self.set_secret(id, sec);
if let Some(l) = self.index.find_mut(id) {
l.meta = sec.meta();
l.updated_at = self.now;
}
}
}
}
const FRESH_ACCESS_MINUTES: i64 = 30;
fn expiry_slack() -> chrono::Duration {
chrono::Duration::minutes(5)
}
fn is_rotation(mounted: &Login, old: &LoginMeta, new: &LoginMeta, s: &SeatLogin) -> bool {
let same_account = if let (Some(a), Some(b)) = (&old.account, &new.account) {
a == b
} else {
let new_account = new
.account
.clone()
.or_else(|| s.account.as_ref().map(|a| a.id().to_string()));
let old_account = mounted.account_uuid.clone().or_else(|| old.account.clone());
old_account.is_some() && new_account == old_account
};
let same = |a: &Option<String>, b: &Option<String>| a.is_none() || b.is_none() || a == b;
let same_plan = same(&old.subscription_type, &new.subscription_type)
&& same(&old.rate_limit_tier, &new.rate_limit_tier);
let fresh = s
.written_at
.zip(new.access_expires_at)
.is_some_and(|(w, exp)| exp > w + chrono::Duration::minutes(FRESH_ACCESS_MINUTES));
let not_shorter = old
.refresh_expires_at
.zip(new.refresh_expires_at)
.is_none_or(|(old, new)| new + expiry_slack() >= old);
let forward = old
.access_expires_at
.zip(new.access_expires_at)
.is_none_or(|(old, new)| new >= old);
same_account && same_plan && fresh && not_shorter && forward
}