pitboard-core 0.14.0

The engine behind Pitboard: switches Claude Code, Codex and Claude Desktop between accounts by parking and restoring their logins. Its API 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
//! Parked logins `repair` gave back that this Pitboard never wrote.
//!
//! On macOS every `PITBOARD_HOME` shares the login keychain, so a park this home never wrote
//! down may be another Pitboard's. Giving one back to the account whose name it carries is
//! additive and safe; what was not safe was what followed. Once given back it was this
//! home's to delete, so the next switch away from its account, a forget or an uninstall
//! deleted another Pitboard's parked login. Now only using one deletes it. Every case runs
//! for both tools, because who wrote a park is a fact about the store and not about a tool.
//! Off macOS the vault is a directory inside the home, which no other Pitboard parks in, so
//! there a park `repair` finds is this Pitboard's own.

use super::harness::{
    Machine, NOW, Tool, account, codex_access, codex_account, codex_id, codex_login, codex_machine,
    machine, oauth, owner, renews,
};
use super::*;
use crate::api::scripted::Trouble;
use crate::service::Permit;
use serde_json::json;

type Make = fn(&str) -> Machine;

const MACHINES: [Make; 2] = [machine, codex_machine];

/// The account id this machine's tool gives `who`.
fn id(m: &Machine, who: &str) -> String {
    match Tool::of(m.which) {
        Tool::Claude => who.to_string(),
        Tool::Codex => codex_id(who),
    }
}

/// `who`'s account, enrolled the way this machine's tool enrols one.
fn enrolled(m: &Machine, who: &str, parked: Option<Park>) -> Account {
    match Tool::of(m.which) {
        Tool::Claude => account(who, who, parked),
        Tool::Codex => codex_account(who, who, parked),
    }
}

/// A login of `who`'s on a refresh chain of its own, as this machine's tool parks one, and
/// a service that answers for it.
fn login(m: &Machine, who: &str, refresh: &str) -> Value {
    match Tool::of(m.which) {
        Tool::Claude => {
            m.api.owned_by(&format!("access-{refresh}"), owner(who));
            oauth(refresh, 30)
        }
        Tool::Codex => {
            m.api.using(
                &codex_access(refresh),
                crate::usage::Snapshot {
                    windows: Vec::new(),
                    observed_at: Some(NOW),
                    answered_at: Some(NOW),
                    lists_every_limit: false,
                    source: crate::usage::Source::Live,
                },
            );
            codex_login(who, refresh)
        }
    }
}

/// The same, with its access token lapsed, so the next renewal is due.
fn lapsed(m: &Machine, who: &str, refresh: &str) -> Value {
    let mut document = login(m, who, refresh);
    match Tool::of(m.which) {
        Tool::Claude => document["expiresAt"] = json!((NOW - 60) * 1000),
        Tool::Codex => {
            document["tokens"]["access_token"] = json!(provider::jwt::unsigned(
                &json!({"exp": NOW - 60, "for": refresh})
            ));
        }
    }
    document
}

/// `away` is enrolled, not signed in, and holds nothing: its park is gone, the way a
/// refused one goes.
fn enrol_away(m: &Machine) {
    let mut state = state::load(&m.ctx).expect("state");
    state.upsert(enrolled(m, "away", None));
    state::save(&m.ctx, Permit::for_a_test(), &state).expect("saved");
}

/// Another Pitboard on the same machine, with a home of its own and the same keychain,
/// parks a login of `who`'s and records it, the way its own switch would have.
fn parked_elsewhere(m: &Machine, who: &str, document: &Value) -> (Context, Park) {
    let other = m
        .ctx
        .clone()
        .with_pitboard_home(m.ctx_home().join(".pitboard-elsewhere"));
    let service = park::reserve(&other, Permit::for_a_test(), &id(m, who)).expect("a free name");
    let parked = park::store_at(
        &other,
        Permit::for_a_test(),
        provider::document(m.which),
        &service,
        document,
    )
    .expect("parked");
    let mut theirs = State::default();
    theirs.accounts.push(enrolled(m, who, Some(parked.clone())));
    state::save(&other, Permit::for_a_test(), &theirs).expect("saved");
    (other, parked)
}

fn repair_here(m: &Machine) -> Reclaimed {
    repair(
        settle(&m.ctx, Permit::for_a_test(), None)
            .expect("nothing to recover")
            .0,
    )
    .expect("repaired")
    .0
}

/// The whole of what went wrong. Another Pitboard has `here` parked; this one has `here`
/// signed in and so holds nothing for it; `repair` gives the other's park to `here`; and
/// the next switch away parks the live login in its place. That park was never used here,
/// so it is still where the other Pitboard left it, and still loads there.
#[test]
#[cfg_attr(
    windows,
    ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
)]
fn a_park_repair_gave_back_outlives_a_switch_away_from_its_account() {
    for make in MACHINES {
        let m = make("foreign-replaced");
        let theirs = login(&m, "here", "here-elsewhere");
        let (other, recorded) = parked_elsewhere(&m, "here", &theirs);

        let reclaimed = repair_here(&m);
        assert_eq!(
            reclaimed.given_back,
            vec![(m.key("here").typed(), recorded.service.clone())]
        );
        let state = state::load(&m.ctx).expect("state");
        assert_eq!(state.foreign, vec![recorded.service.clone()]);

        let settled = settle(&m.ctx, Permit::for_a_test(), None)
            .expect("nothing to recover")
            .0;
        switch(settled, &m.key("there")).expect("switched");

        let state = state::load(&m.ctx).expect("state");
        let parked = state.get(&m.key("here")).unwrap().parked.clone();
        assert_ne!(
            parked.expect("the live login was parked").service,
            recorded.service
        );
        assert!(state.foreign.is_empty(), "nothing here holds it now");
        assert!(
            !state
                .discarded
                .iter()
                .any(|d| d.service == recorded.service)
        );
        assert_eq!(
            park::load(
                &other,
                provider::document(m.which),
                &m.key("here"),
                &recorded
            )
            .expect("the other Pitboard's park"),
            theirs,
            "{:?}",
            m.which
        );
    }
}

/// Dropping the account that holds one does not delete it either.
#[test]
#[cfg_attr(windows, ignore = "W21: switching Codex on Windows")]
fn forgetting_its_account_leaves_a_park_repair_gave_back() {
    for make in MACHINES {
        let m = make("foreign-forgotten");
        enrol_away(&m);
        let (_, recorded) = parked_elsewhere(&m, "away", &login(&m, "away", "away-elsewhere"));
        assert_eq!(repair_here(&m).given_back.len(), 1);

        let settled = settle(&m.ctx, Permit::for_a_test(), Some(m.which))
            .expect("nothing to recover")
            .0;
        forget(settled, &m.key("away")).expect("forgotten");

        let state = state::load(&m.ctx).expect("state");
        assert!(state.foreign.is_empty());
        assert!(
            !state
                .discarded
                .iter()
                .any(|d| d.service == recorded.service)
        );
        assert!(
            m.mem.vault().peek(&recorded.service).is_some(),
            "{:?}: it is still where the other Pitboard left it",
            m.which
        );
    }
}

/// Uninstalling deletes what this Pitboard wrote and leaves the rest, and says how many it
/// left, because somebody told their logins were removed would otherwise not look for them.
#[test]
#[cfg_attr(windows, ignore = "W21: switching Codex on Windows")]
fn uninstalling_leaves_a_park_repair_gave_back_and_says_so() {
    for make in MACHINES {
        let m = make("foreign-uninstalled");
        enrol_away(&m);
        let (_, recorded) = parked_elsewhere(&m, "away", &login(&m, "away", "away-elsewhere"));
        assert_eq!(repair_here(&m).given_back.len(), 1);

        let removed = uninstall(
            settle(&m.ctx, Permit::for_a_test(), None)
                .expect("nothing to recover")
                .0,
        )
        .expect("uninstalled");

        assert_eq!(removed.parks, 1, "`there`'s, which this Pitboard wrote");
        assert_eq!(removed.left, 1);
        assert_eq!(removed.pending, 0);
        assert!(
            removed.home_removed,
            "a login left for another Pitboard does not keep this one's home"
        );
        assert_eq!(
            m.mem.vault().services(),
            vec![recorded.service.clone()],
            "{:?}",
            m.which
        );
    }
}

/// Installed, it has been used, whoever wrote it. For Codex a parked copy of the login now
/// signed in must not stay beside it, and for Claude Code the park is the live login from
/// now on, so it goes the way every installed park goes.
#[test]
#[cfg_attr(
    windows,
    ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
)]
fn a_park_repair_gave_back_is_deleted_once_a_switch_installs_it() {
    for make in MACHINES {
        let m = make("foreign-installed");
        enrol_away(&m);
        let theirs = login(&m, "away", "away-elsewhere");
        let (_, recorded) = parked_elsewhere(&m, "away", &theirs);
        assert_eq!(repair_here(&m).given_back.len(), 1);

        let settled = settle(&m.ctx, Permit::for_a_test(), None)
            .expect("nothing to recover")
            .0;
        switch(settled, &m.key("away")).expect("switched");

        let tool = provider::document(m.which);
        assert_eq!(
            tool.fingerprint(&m.live().expect("a live login")),
            tool.fingerprint(&theirs)
        );
        let state = state::load(&m.ctx).expect("state");
        assert!(state.foreign.is_empty());
        assert!(
            m.mem.vault().peek(&recorded.service).is_none(),
            "{:?}: used here, so deleted here",
            m.which
        );
    }
}

/// A renewal spends the refresh token it presents, so the copy it renewed is used up
/// whoever wrote it, and what it writes is this Pitboard's own.
#[test]
#[cfg_attr(windows, ignore = "W21: switching Codex on Windows")]
fn a_park_repair_gave_back_is_deleted_once_a_renewal_spends_it() {
    for make in MACHINES {
        let m = make("foreign-renewed");
        enrol_away(&m);
        let (_, recorded) = parked_elsewhere(&m, "away", &lapsed(&m, "away", "away-elsewhere"));
        renews(&m, "away-elsewhere", "away-renewed");
        assert_eq!(repair_here(&m).given_back.len(), 1);

        let renewed = renew_due(&m.ctx, Permit::for_a_test(), Due::ToBeAsked);

        assert_eq!(renewed.len(), 1);
        assert_eq!(renewed[0].1.code(), "renewed", "{:?}", m.which);
        let state = state::load(&m.ctx).expect("state");
        let fresh = state.get(&m.key("away")).unwrap().parked.clone();
        assert_ne!(fresh.expect("renewed").service, recorded.service);
        assert!(state.foreign.is_empty(), "what the renewal wrote is ours");
        assert!(
            m.mem.vault().peek(&recorded.service).is_none(),
            "{:?}: spent here, so deleted here",
            m.which
        );
    }
}

/// Killed after the service answered and before the answer was recorded, a renewal leaves
/// the fresh copy for the next change to give back in place of the one it spent. That one
/// was saved as used before the answer was written, so giving the fresh one back deletes it
/// rather than letting it go for a Pitboard that would present a spent token.
#[test]
#[cfg_attr(windows, ignore = "W21: switching Codex on Windows")]
fn a_park_repair_gave_back_is_deleted_once_a_killed_renewal_spends_it() {
    for make in MACHINES {
        let m = make("foreign-renewal-killed");
        enrol_away(&m);
        let (_, recorded) = parked_elsewhere(&m, "away", &lapsed(&m, "away", "away-elsewhere"));
        renews(&m, "away-elsewhere", "away-renewed");
        assert_eq!(repair_here(&m).given_back.len(), 1);

        let died = fault::killing("renew.park_stored", || {
            renew_due(&m.ctx, Permit::for_a_test(), Due::ToBeAsked)
        });
        assert_eq!(died.unwrap_err(), "renew.park_stored", "{:?}", m.which);
        settle(&m.ctx, Permit::for_a_test(), None)
            .expect("the next change gives the fresh copy back");

        let state = state::load(&m.ctx).expect("state");
        assert_eq!(
            state
                .get(&m.key("away"))
                .and_then(|a| a.parked.as_ref())
                .map(|p| p.login.clone()),
            Some(store::fingerprint("away-renewed")),
            "{:?}",
            m.which
        );
        assert!(state.foreign.is_empty());
        assert!(
            m.mem.vault().peek(&recorded.service).is_none(),
            "{:?}: spent here, so deleted here",
            m.which
        );
        harness::hold(&m, &format!("{:?}, after a killed renewal", m.which));
    }
}

/// Refused is not spent: presenting it took nothing from it. The Pitboard that wrote it is
/// refused the same way and drops it itself.
#[test]
#[cfg_attr(windows, ignore = "W21: switching Codex on Windows")]
fn a_park_repair_gave_back_that_the_service_refuses_is_let_go_and_left() {
    for make in MACHINES {
        let m = make("foreign-refused");
        enrol_away(&m);
        let (_, recorded) = parked_elsewhere(&m, "away", &lapsed(&m, "away", "away-elsewhere"));
        match Tool::of(m.which) {
            Tool::Claude => m.api.renew_trouble("away-elsewhere", Trouble::InvalidGrant),
            Tool::Codex => m
                .api
                .codex_renew_trouble("away-elsewhere", Trouble::InvalidGrant),
        };
        assert_eq!(repair_here(&m).given_back.len(), 1);

        let renewed = renew_due(&m.ctx, Permit::for_a_test(), Due::ToBeAsked);

        assert_eq!(renewed[0].1.code(), "parked_login_refused");
        let state = state::load(&m.ctx).expect("state");
        assert!(state.get(&m.key("away")).unwrap().parked.is_none());
        assert!(state.foreign.is_empty());
        assert!(
            m.mem.vault().peek(&recorded.service).is_some(),
            "{:?}",
            m.which
        );
    }
}

/// What this Pitboard wrote down itself is its own, however it was found again. Written
/// down, written to, and killed before anything recorded it, it is given back like the
/// other Pitboard's, and the same switch away deletes it as it always did.
#[test]
#[cfg_attr(
    windows,
    ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
)]
fn a_park_this_pitboard_wrote_down_and_lost_is_still_deleted_when_replaced() {
    for make in MACHINES {
        let m = make("ours-replaced");
        let service =
            park::reserve(&m.ctx, Permit::for_a_test(), &id(&m, "here")).expect("a free name");
        park::store_at(
            &m.ctx,
            Permit::for_a_test(),
            provider::document(m.which),
            &service,
            &login(&m, "here", "here-lost"),
        )
        .expect("parked");

        let settled = settle(&m.ctx, Permit::for_a_test(), None)
            .expect("the sweep gives it back")
            .0;
        let state = state::load(&m.ctx).expect("state");
        assert_eq!(
            state
                .get(&m.key("here"))
                .and_then(|a| a.parked.as_ref())
                .map(|p| p.service.as_str()),
            Some(service.as_str())
        );
        assert!(state.foreign.is_empty(), "this Pitboard wrote it down");

        switch(settled, &m.key("there")).expect("switched");

        assert!(
            m.mem.vault().peek(&service).is_none(),
            "{:?}: its own, so deleted",
            m.which
        );
    }
}

/// A park written into this vault and then lost from this home's records, as a state file
/// restored from a backup leaves it. Only its account names it.
fn lost(m: &Machine, who: &str, document: &Value) -> Park {
    let service = park::service_name(&id(m, who), (NOW - 60) * 1000);
    park::store_at(
        &m.ctx,
        Permit::for_a_test(),
        provider::document(m.which),
        &service,
        document,
    )
    .expect("parked")
}

/// Off macOS the vault is a directory inside Pitboard's own, which no other Pitboard parks
/// in. A park `repair` finds there is this Pitboard's even when nothing here wrote its name
/// down, so it is deleted like any other once it is let go, and `uninstall` leaves nothing
/// behind and does not say it did.
#[test]
#[cfg_attr(
    windows,
    ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
)]
fn a_park_found_in_a_vault_of_this_homes_own_is_this_pitboards() {
    for make in MACHINES {
        let m = make("found-replaced");
        m.mem.vault_of_its_own();
        let found = lost(&m, "here", &login(&m, "here", "here-lost"));
        assert_eq!(repair_here(&m).given_back.len(), 1);
        assert!(state::load(&m.ctx).expect("state").foreign.is_empty());

        let settled = settle(&m.ctx, Permit::for_a_test(), None)
            .expect("nothing to recover")
            .0;
        switch(settled, &m.key("there")).expect("switched");
        assert!(
            m.mem.vault().peek(&found.service).is_none(),
            "{:?}: replaced, and this Pitboard's, so deleted",
            m.which
        );
        harness::hold(&m, &format!("{:?}, after the switch away", m.which));

        let m = make("found-uninstalled");
        m.mem.vault_of_its_own();
        enrol_away(&m);
        lost(&m, "away", &login(&m, "away", "away-lost"));
        assert_eq!(repair_here(&m).given_back.len(), 1);

        let removed = uninstall(
            settle(&m.ctx, Permit::for_a_test(), None)
                .expect("nothing to recover")
                .0,
        )
        .expect("uninstalled");
        assert_eq!(
            removed.parks, 2,
            "{:?}: `there`'s and the one found",
            m.which
        );
        assert_eq!(removed.left, 0, "{:?}", m.which);
        assert!(m.mem.vault().services().is_empty(), "{:?}", m.which);
    }
}