pitboard-core 0.4.0

The engine behind pitboard: parking and restoring Claude Code and Codex logins. Serves pitboard's own front ends.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! Names pitboard is about to write a login into, written down before the login is.
//!
//! The switch got this right and nothing else did. `enroll --sign-in` and the renewal that
//! runs inside every `pitboard status` both claimed a name, wrote a login into it, and only
//! then recorded it, with cleanup that runs when a step returns an error and never when a
//! run is killed. Killed in that window, the machine keeps a live refresh token that no
//! entry in `state.json` names: never renewed, never offered, not removed by
//! `pitboard uninstall`, and on macOS not listable by any tool the user has, because
//! `security find-generic-password` takes no wildcard.
//!
//! So every name is written here first and resolved by the next command. This is an index,
//! not a vault: it holds names, never a token.

use crate::context::Context;
use crate::error::{Error, Result};
use crate::state::State;
use crate::{atomic, home, park, store};
use std::path::PathBuf;

fn path(ctx: &Context) -> PathBuf {
    home::dir(ctx).join("pending")
}

fn read(ctx: &Context) -> Vec<String> {
    std::fs::read_to_string(path(ctx))
        .unwrap_or_default()
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty())
        .map(str::to_owned)
        .collect()
}

fn store_list(ctx: &Context, names: &[String]) -> Result<()> {
    let path = path(ctx);
    if names.is_empty() {
        // Nothing outstanding: leave no file rather than an empty one, so the ordinary
        // state of a machine is the absence of this.
        match std::fs::remove_file(&path) {
            Ok(()) => return Ok(()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(source) => return Err(Error::HomeUnwritable { path, source }),
        }
    }
    let mut body = names.join("\n");
    body.push('\n');
    atomic::write(&path, body.as_bytes(), atomic::Perms::Secret)
        .map_err(|source| Error::HomeUnwritable { path, source })
}

/// Write a name down before anything is written into it. A name here that never receives a
/// login costs one line and is dropped by the next sweep.
pub fn reserve(ctx: &Context, service: &str) -> Result<()> {
    home::ensure(ctx).map_err(|source| Error::HomeUnwritable {
        path: home::dir(ctx),
        source,
    })?;
    let mut names = read(ctx);
    if !names.iter().any(|n| n == service) {
        names.push(service.to_string());
    }
    store_list(ctx, &names)
}

/// What resolving unnamed logins did.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Reclaimed {
    /// Given back to the account whose name they carry: (label, service).
    pub given_back: Vec<(String, String)>,
    /// Listed for deletion. Only ever a name this pitboard wrote down itself and nothing
    /// recorded, which is the one case where being sure is possible.
    pub deleted: Vec<String>,
    /// Found in the store, belonging to no account here and never written down here.
    /// Reported and not touched: the store is shared by the whole machine and pitboard's
    /// records are not, so an item pitboard cannot account for may be another pitboard's.
    pub strangers: Vec<String>,
    /// Left exactly as they are, because the store could not be read.
    pub unreadable: Vec<String>,
}

impl Reclaimed {
    pub fn found(&self) -> usize {
        self.given_back.len() + self.deleted.len()
    }

    pub fn is_empty(&self) -> bool {
        self.given_back.is_empty()
            && self.deleted.is_empty()
            && self.strangers.is_empty()
            && self.unreadable.is_empty()
    }
}

/// Resolve every name pitboard wrote down and nothing refers to any more.
///
/// Runs in every `settle`, after the journal has had its say, so a switch's own park is
/// already accounted for by then. It reads pitboard's own list rather than asking the
/// store, because it is on the path of every change and a keychain dump is not free.
pub fn sweep(ctx: &Context, state: &mut State) -> Result<Reclaimed> {
    let ours = read(ctx);
    resolve(ctx, state, ours.clone(), &ours)
}

/// The same, asking the store what is actually there rather than trusting pitboard's list.
/// This is what finds a login whose name was lost with the list, or written by a version
/// that had no list. `pitboard repair` runs it; nothing else does, because on macOS it
/// dumps the keychain.
pub fn reclaim(ctx: &Context, state: &mut State) -> Result<Reclaimed> {
    let ours = read(ctx);
    let Some(stored) = store::vault_list(ctx)? else {
        // A store that cannot be enumerated: pitboard's own list is all there is.
        return resolve(ctx, state, ours.clone(), &ours);
    };
    let mut names = stored;
    for listed in &ours {
        if !names.contains(listed) {
            names.push(listed.clone());
        }
    }
    resolve(ctx, state, names, &ours)
}

/// `ours` is the list of names this pitboard wrote down before creating them. It is what
/// separates an item that may be deleted from one that may only be reported.
///
/// The asymmetry matters more than anything else here. On macOS the keychain belongs to the
/// whole login session while pitboard's records belong to one `PITBOARD_HOME`, so an item
/// this pitboard cannot account for is not evidence of an orphan: it may be another
/// pitboard's parked login, and deleting it would end that account's session for someone
/// who never ran this command. Giving a login back is additive and safe to do on a guess;
/// deleting one is not, and is done only where being sure is possible. Where the vault is
/// shared that way, a login given back that this pitboard did not write down is recorded
/// as such, so letting it go later never deletes it either: only using it does.
fn resolve(
    ctx: &Context,
    state: &mut State,
    names: Vec<String>,
    ours: &[String],
) -> Result<Reclaimed> {
    let mut keep = Vec::new();
    let mut out = Reclaimed::default();
    for service in names {
        if state.names(&service) {
            continue;
        }
        let written_here = ours.contains(&service);
        match store::vault_read(ctx, &service) {
            // Claimed but never written to. Nothing was ever there.
            Ok(None) => {}
            // Cannot tell. Try again next time rather than guess.
            Err(_) => {
                out.unreadable.push(service.clone());
                if written_here {
                    keep.push(service);
                }
            }
            Ok(Some(raw)) => match adopt(ctx, state, &service, &raw, written_here) {
                Some(label) => out.given_back.push((label, service)),
                None if written_here => {
                    // This pitboard wrote this name down, wrote a login into it, and
                    // nothing here recorded it. That is an orphan and nothing else can be.
                    release(ctx, state, &service);
                    out.deleted.push(service);
                }
                None => out.strangers.push(service),
            },
        }
    }
    if keep != ours {
        store_list(ctx, &keep)?;
    }
    if !out.given_back.is_empty() || !out.deleted.is_empty() {
        crate::state::save(ctx, state)?;
    }
    Ok(out)
}

/// Give an orphan back to the account whose name it carries, where that account is enrolled
/// and holds nothing, or holds an older copy this one replaces.
///
/// The second case is what a renewal leaves when it is killed after writing the fresh login
/// and before recording it: the service has already spent the older copy's refresh token,
/// so the account holds a dead login and the orphan is its only live one. Keeping the older
/// and deleting the newer, which is what happened, lost the login. Only a name this pitboard
/// wrote down itself is trusted that far; a stranger replaces nothing. The older copy is
/// released rather than discarded, because an enrolment killed at the same point leaves the
/// same shape with an older copy nothing spent, and an older copy `repair` gave back may be
/// another pitboard's.
///
/// Anything else is refused: an account that already holds a newer park has a login
/// pitboard renews, and a second copy of one refresh chain is the state that ends a login
/// for both holders.
fn adopt(
    ctx: &Context,
    state: &mut State,
    service: &str,
    raw: &str,
    written_here: bool,
) -> Option<String> {
    let (uuid, at_millis) = park::parts_of(service)?;
    let oauth = serde_json::from_str::<serde_json::Value>(raw).ok()?;
    let account = state.owner_of_park(&uuid)?;
    let key = account.key();
    let park = park::describe(key.provider, service, at_millis / 1000, &oauth);
    if park.refresh_fingerprint.is_empty() || !park.restorable_at(ctx.now()) {
        return None;
    }
    let replaces_an_older_copy = |held: &crate::state::Park| {
        written_here
            && held.refresh_fingerprint != park.refresh_fingerprint
            && park.parked_at >= held.parked_at
    };
    if account
        .parked
        .as_ref()
        .is_some_and(|held| !replaces_an_older_copy(held))
    {
        return None;
    }
    // A copy of the login signed in now is not something to give back, for a tool whose
    // park may never be a copy.
    if park::is_live_twin(ctx, key.provider, &oauth) {
        return None;
    }
    // A vault of files lives inside this home, so whatever is in it is this pitboard's
    // whether or not it was written down, and is deleted like any other once let go.
    if written_here || !store::vault_is_shared(ctx) {
        state.park(&key, park);
    } else {
        state.park_foreign(&key, park);
    }
    let label = key.typed();
    crate::audit::record(ctx, "reclaim", &label, "ok");
    Some(label)
}

/// List it for deletion the way every other unwanted park is listed, so a delete that fails
/// is retried rather than forgotten.
fn release(ctx: &Context, state: &mut State, service: &str) {
    debug_assert!(park::is_park_name(service), "only pitboard's own names");
    state.release(service);
    crate::audit::record(ctx, "reclaim", service, "discarded");
}

/// Forget everything listed, without touching the vault. Only `uninstall` does this, once
/// it has deleted what the names refer to.
pub fn clear(ctx: &Context) {
    let _ = std::fs::remove_file(path(ctx));
}

/// Every name still outstanding, for `doctor` to report.
pub fn outstanding(ctx: &Context) -> Vec<String> {
    read(ctx)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::provider::ProviderId;
    use crate::store::memory::MemoryHost;
    use crate::time::{Clock, FixedClock};
    use serde_json::json;
    use std::sync::Arc;

    const NOW: i64 = 1_760_000_000;

    fn work() -> crate::state::Key {
        crate::state::Key::new(ProviderId::Claude, "work")
    }

    fn machine(name: &str) -> (Context, Arc<MemoryHost>, PathBuf) {
        let root = std::env::temp_dir().join(format!(
            "pitboard-pending-{name}-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = std::fs::remove_dir_all(&root);
        let mem = MemoryHost::new();
        let ctx = Context::new(root.clone())
            .with_pitboard_home(root.clone())
            .with_memory_stores(Arc::clone(&mem))
            .with_clock(Arc::new(FixedClock::at(NOW)) as Arc<dyn Clock>);
        home::ensure(&ctx).expect("a home");
        (ctx, mem, root)
    }

    fn oauth(refresh: &str) -> serde_json::Value {
        json!({
            "refreshToken": refresh,
            "accessToken": "a",
            "expiresAt": (NOW + 3600) * 1000,
            "refreshTokenExpiresAt": (NOW + 30 * 86_400) * 1000
        })
    }

    fn account(label: &str, uuid: &str) -> crate::state::Account {
        crate::state::Account {
            last_used_at: None,
            label: label.into(),
            account_uuid: uuid.into(),
            email: format!("{uuid}@example.com"),
            detail: crate::state::Detail::Claude {
                organization_uuid: "org".into(),
                oauth_account: json!({}),
            },
            parked: None,
        }
    }

    #[test]
    fn a_name_claimed_but_never_written_to_is_simply_dropped() {
        let (ctx, _mem, root) = machine("never-written");
        reserve(&ctx, "pitboard-park-acc-1760000000000").expect("reserved");
        let mut state = State::default();

        assert_eq!(sweep(&ctx, &mut state).expect("swept").found(), 0);
        assert!(outstanding(&ctx).is_empty());
        let _ = std::fs::remove_dir_all(root);
    }

    #[test]
    fn an_orphan_goes_back_to_the_account_whose_name_it_carries() {
        let (ctx, mem, root) = machine("adopt");
        let service = "pitboard-park-acc-1760000000000";
        reserve(&ctx, service).expect("reserved");
        mem.vault().plant(service, &oauth("r").to_string());

        let mut state = State::default();
        state.accounts.push(account("work", "acc"));
        assert_eq!(sweep(&ctx, &mut state).expect("swept").found(), 1);

        let park = state
            .get(&crate::state::Key::new(
                crate::provider::ProviderId::Claude,
                "work",
            ))
            .expect("account")
            .parked
            .clone()
            .expect("the orphan was taken back");
        assert_eq!(park.service, service);
        assert_eq!(
            park.parked_at, 1_760_000_000,
            "when it was parked is in its own name"
        );
        assert!(state.foreign.is_empty(), "this pitboard wrote it");
        assert!(outstanding(&ctx).is_empty());
        let _ = std::fs::remove_dir_all(root);
    }

    /// The account a name was written for, holding `held`, with `orphan` in the vault under
    /// a name this pitboard wrote down and nothing recorded.
    fn holding(
        name: &str,
        held: (&str, &str, i64),
        orphan: (&str, &str),
    ) -> (Context, State, PathBuf) {
        let (ctx, mem, root) = machine(name);
        mem.vault().plant(held.0, &oauth(held.1).to_string());
        mem.vault().plant(orphan.0, &oauth(orphan.1).to_string());
        reserve(&ctx, orphan.0).expect("reserved");
        let mut state = State::default();
        state.accounts.push(account("work", "acc"));
        state.park(
            &work(),
            park::describe(ProviderId::Claude, held.0, held.2, &oauth(held.1)),
        );
        (ctx, state, root)
    }

    fn parked(state: &State) -> Option<String> {
        state
            .get(&work())
            .and_then(|a| a.parked.as_ref())
            .map(|p| p.service.clone())
    }

    /// Two copies of one refresh chain is the state that ends a login for both holders, so
    /// the copy nothing names loses.
    #[test]
    fn a_second_copy_of_the_chain_an_account_holds_is_deleted() {
        let held = "pitboard-park-acc-1750000000000";
        let orphan = "pitboard-park-acc-1760000000000";
        let (ctx, mut state, root) = holding("same-chain", (held, "r", NOW), (orphan, "r"));

        assert_eq!(sweep(&ctx, &mut state).expect("swept").found(), 1);
        assert_eq!(parked(&state).as_deref(), Some(held));
        assert!(state.discarded.iter().any(|s| s == orphan));
        assert!(outstanding(&ctx).is_empty());
        let _ = std::fs::remove_dir_all(root);
    }

    /// An orphan older than what the account holds is left over from before it, and the
    /// recorded copy is the one pitboard renews.
    #[test]
    fn an_older_copy_than_the_one_an_account_holds_is_deleted() {
        let held = "pitboard-park-acc-1760000000000";
        let orphan = "pitboard-park-acc-1750000000000";
        let (ctx, mut state, root) = holding("older", (held, "held", NOW), (orphan, "orphan"));

        assert_eq!(sweep(&ctx, &mut state).expect("swept").found(), 1);
        assert_eq!(parked(&state).as_deref(), Some(held));
        assert!(state.discarded.iter().any(|s| s == orphan));
        let _ = std::fs::remove_dir_all(root);
    }

    /// A newer copy this pitboard wrote and never recorded is what a renewal killed between
    /// writing and recording leaves. The service spent the older copy's chain when it
    /// answered, so the newer one is the account's only working login and replaces it.
    #[test]
    fn a_newer_copy_written_here_replaces_the_one_an_account_holds() {
        let held = "pitboard-park-acc-1750000000000";
        let orphan = "pitboard-park-acc-1760000000000";
        let (ctx, mut state, root) =
            holding("newer", (held, "spent", 1_750_000_000), (orphan, "fresh"));

        let reclaimed = sweep(&ctx, &mut state).expect("swept");
        assert_eq!(reclaimed.given_back.len(), 1);
        assert_eq!(parked(&state).as_deref(), Some(orphan));
        assert!(
            state.discarded.iter().any(|s| s == held),
            "the spent copy goes"
        );
        let _ = std::fs::remove_dir_all(root);
    }

    /// A store that could not answer says nothing about what is in it.
    #[test]
    fn an_item_that_cannot_be_read_stays_listed_rather_than_being_guessed_at() {
        let (ctx, mem, root) = machine("unreadable");
        let service = "pitboard-park-acc-1760000000000";
        reserve(&ctx, service).expect("reserved");
        mem.vault().plant(service, &oauth("r").to_string());
        mem.vault().fault(
            service,
            crate::store::memory::Fault::Unreadable("the keychain is locked".into()),
        );

        let mut state = State::default();
        assert_eq!(sweep(&ctx, &mut state).expect("swept").found(), 0);
        assert_eq!(outstanding(&ctx), vec![service.to_string()]);
        assert!(state.discarded.is_empty(), "nothing is deleted on a guess");
        let _ = std::fs::remove_dir_all(root);
    }

    /// The case the list alone cannot answer: a login in the vault that pitboard never
    /// wrote a name down for, because the home was lost, or because it was parked by a
    /// version that kept no list. Only asking the store finds it.
    #[test]
    fn asking_the_store_finds_a_login_the_list_never_knew_about() {
        let (ctx, mem, root) = machine("reclaim");
        let service = "pitboard-park-acc-1760000000000";
        mem.vault().plant(service, &oauth("r").to_string());
        assert!(
            outstanding(&ctx).is_empty(),
            "nothing was ever written down"
        );

        let mut state = State::default();
        state.accounts.push(account("work", "acc"));

        // The cheap sweep cannot see it, because it only reads pitboard's own list.
        assert_eq!(sweep(&ctx, &mut state).expect("swept").found(), 0);
        assert!(state.get(&work()).expect("account").parked.is_none());

        let reclaimed = reclaim(&ctx, &mut state).expect("reclaimed");
        assert_eq!(reclaimed.given_back.len(), 1);
        assert_eq!(reclaimed.given_back[0].0, "work");
        assert_eq!(
            state
                .get(&crate::state::Key::new(
                    crate::provider::ProviderId::Claude,
                    "work"
                ))
                .expect("account")
                .parked
                .as_ref()
                .map(|p| p.service.as_str()),
            Some(service)
        );
        assert_eq!(
            state.foreign,
            vec![service.to_string()],
            "nothing says this pitboard wrote it, so it may be another's"
        );
        let _ = std::fs::remove_dir_all(root);
    }

    /// A login for an account this machine has never heard of. Keeping it would be keeping
    /// a credential nothing can ever use, renew or name.
    /// The rule that matters most here. A keychain belongs to a login session; pitboard's
    /// records belong to one PITBOARD_HOME. So a parked login this pitboard cannot account
    /// for is not evidence of an orphan, it is evidence of another pitboard, and deleting
    /// it would end that account's session for somebody who never ran this command.
    #[test]
    fn a_login_this_pitboard_never_wrote_down_is_reported_and_not_touched() {
        let (ctx, mem, root) = machine("stranger");
        let service = "pitboard-park-stranger-1760000000000";
        mem.vault().plant(service, &oauth("r").to_string());

        let mut state = State::default();
        let reclaimed = reclaim(&ctx, &mut state).expect("reclaimed");

        assert!(reclaimed.given_back.is_empty());
        assert!(
            reclaimed.deleted.is_empty(),
            "nothing may be deleted on a guess"
        );
        assert_eq!(reclaimed.strangers, vec![service.to_string()]);
        assert!(state.discarded.is_empty());
        assert_eq!(
            mem.vault().peek(service).as_deref(),
            Some(oauth("r").to_string().as_str()),
            "it is still there"
        );
        let _ = std::fs::remove_dir_all(root);
    }

    /// The one case where being sure is possible: this pitboard wrote the name down, wrote
    /// a login into it, and nothing here recorded it.
    #[test]
    fn a_login_this_pitboard_wrote_down_and_nothing_wants_is_deleted() {
        let (ctx, mem, root) = machine("our-orphan");
        let service = "pitboard-park-stranger-1760000000000";
        mem.vault().plant(service, &oauth("r").to_string());
        reserve(&ctx, service).expect("written down first");

        let mut state = State::default();
        let reclaimed = reclaim(&ctx, &mut state).expect("reclaimed");

        assert_eq!(reclaimed.deleted, vec![service.to_string()]);
        assert!(reclaimed.strangers.is_empty());
        assert!(state.discarded.iter().any(|s| s == service));
        let _ = std::fs::remove_dir_all(root);
    }

    #[test]
    fn a_name_the_state_already_carries_is_not_swept_at_all() {
        let (ctx, mem, root) = machine("already-named");
        let service = "pitboard-park-acc-1760000000000";
        reserve(&ctx, service).expect("reserved");
        mem.vault().plant(service, &oauth("r").to_string());

        let mut state = State::default();
        state.accounts.push(account("work", "acc"));
        state.park(
            &work(),
            park::describe(ProviderId::Claude, service, NOW, &oauth("r")),
        );

        assert_eq!(sweep(&ctx, &mut state).expect("swept").found(), 0);
        assert!(outstanding(&ctx).is_empty());
        assert!(state.discarded.is_empty());
        let _ = std::fs::remove_dir_all(root);
    }
}