pitboard-core 0.5.2

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
//! A machine to run changes against: two accounts of one tool, stores in memory, services
//! that answer from a script, and a clock that stands still.
//!
//! Shared by the tests that kill a change partway ([`super::crash`]), the tests that make
//! one refuse ([`super::refusals`]), the tests of what a sign-in enrols ([`super::enroll`]),
//! and the tests of what a change refused over its name still settles ([`crate::service`]),
//! because all of them need the same starting shape:
//! one account signed in, one parked and ready, and the tool's own files where the engine
//! expects them. There is one for each tool, and the invariants in [`hold`] are asked of
//! every one of them through the provider boundary, because what must be true after a
//! crash is a fact about parking a login and not about any one tool's.

use super::*;
use crate::api::Owner;
use crate::api::scripted::ScriptedApi;
use crate::provider::ProviderId;
use crate::provider::claude::paths as claude;

use crate::state::Account;
use crate::store::memory::MemoryHost;
use crate::time::{Clock, FixedClock};
use serde_json::json;
use std::collections::HashSet;
use std::sync::Arc;

pub(crate) const NOW: i64 = 1_760_000_000;

/// Every place a change can be killed, named the way the code names it.
pub(crate) const POINTS: [&str; 6] = [
    "switch.journal_written",
    "switch.park_stored",
    "switch.park_recorded",
    "switch.installed",
    "switch.recorded",
    "switch.config_updated",
];

pub(crate) struct Machine {
    pub(crate) ctx: Context,
    pub(crate) mem: Arc<MemoryHost>,
    pub(crate) api: Arc<ScriptedApi>,
    root: PathBuf,
    /// The keychain item Claude Code's login is in, on a Claude Code machine.
    pub(crate) service: String,
    /// Which tool's accounts this machine holds.
    pub(crate) which: ProviderId,
}

impl Machine {
    /// Where the tool's own files are, for a test that needs to change one.
    pub(crate) fn ctx_home(&self) -> PathBuf {
        self.root.clone()
    }

    /// The live login, read the way the tool reads it.
    pub(crate) fn live(&self) -> Option<Value> {
        crate::provider::of(self.which)
            .read_live(&self.ctx)
            .ok()
            .flatten()
            .map(|credential| credential.raw)
    }

    /// Replace the live login, the way the tool itself would write it.
    pub(crate) fn sign_in(&self, document: &Value) {
        let live = crate::provider::of(self.which)
            .live(&self.ctx)
            .expect("a store to write to");
        store::write_raw(&live.chain, &live.service, &document.to_string())
            .expect("the live login is written");
    }

    pub(crate) fn key(&self, label: &str) -> Key {
        Key::new(self.which, label)
    }

    /// From now on the live login's store misbehaves this way: the keychain item for Claude
    /// Code, the `auth.json` file for Codex.
    pub(crate) fn fault_live(&self, fault: crate::store::memory::Fault) {
        let (store, service) = self.live_store();
        store.fault(&service, fault);
    }

    /// The store the live login is in, and its name there, for a test that has to fault it
    /// from inside a change.
    pub(crate) fn live_store(&self) -> (Arc<crate::store::memory::MemoryStore>, String) {
        let live = crate::provider::of(self.which)
            .live(&self.ctx)
            .expect("a live store");
        let store = match self.which {
            ProviderId::Claude => Arc::clone(self.mem.live()),
            ProviderId::Codex => self
                .mem
                .file_at(crate::provider::codex::paths::auth_file(&self.ctx)),
        };
        (store, live.service)
    }
}

impl Drop for Machine {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

pub(crate) fn oauth(refresh: &str, expires_in_days: i64) -> Value {
    json!({
        "accessToken": format!("access-{refresh}"),
        "refreshToken": refresh,
        "expiresAt": (NOW + 3600) * 1000,
        "refreshTokenExpiresAt": (NOW + expires_in_days * 86_400) * 1000,
        "scopes": ["user:profile", "user:inference"],
    })
}

pub(crate) fn document(refresh: &str) -> Value {
    json!({
        "claudeAiOauth": oauth(refresh, 30),
        "organizationUuid": "org-of-the-outgoing-account",
        "mcpOAuth": {"some-server": {"token": "unrelated"}},
    })
}

pub(crate) fn owner(uuid: &str) -> Owner {
    Owner {
        account_uuid: uuid.into(),
        email: format!("{uuid}@example.com"),
        organization_uuid: format!("org-{uuid}"),
    }
}

/// Two accounts: `here` is signed in, `there` is parked and ready. The shape every switch
/// starts from.
pub(crate) fn machine(name: &str) -> Machine {
    let root = std::env::temp_dir().join(format!(
        "pitboard-crash-{name}-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).expect("a scratch home");

    let mem = MemoryHost::new();
    let api = ScriptedApi::new();
    let ctx = Context::new(root.clone())
        .with_pitboard_home(root.join(".pitboard"))
        .with_memory_stores(Arc::clone(&mem))
        .with_scripted_api(Arc::clone(&api))
        .with_clock(Arc::new(FixedClock::at(NOW)) as Arc<dyn Clock>);

    // Claude Code's own files: the live credential, and the config a switch rewrites.
    let service = claude::live_service(&ctx);
    mem.live()
        .plant(&service, &document("here-refresh").to_string());
    std::fs::write(
        root.join(".claude.json"),
        json!({
            "oauthAccount": {
                "accountUuid": "here",
                "emailAddress": "here@example.com",
                "organizationUuid": "org-here",
            },
            "cachedArtifactRoster": {"org": "org-here"},
            "numStartups": 7,
        })
        .to_string(),
    )
    .expect("a config file");

    api.owned_by("access-here-refresh", owner("here"));
    api.owned_by("access-there-refresh", owner("there"));

    // `there` holds a parked login, written the way a switch would have written it.
    std::fs::create_dir_all(root.join(".pitboard")).expect("a pitboard home");
    let parked_service = park::reserve(&ctx, "there").expect("a free name");
    let parked = park::store_at(
        &ctx,
        crate::provider::ProviderId::Claude,
        &parked_service,
        &oauth("there-refresh", 30),
    )
    .expect("parked");

    let mut state = State::default();
    state.accounts.push(account("here", "here", None));
    state.accounts.push(account("there", "there", Some(parked)));
    state.set_active(ProviderId::Claude, Some("here".into()));
    state::save(&ctx, &state).expect("saved");

    Machine {
        ctx,
        mem,
        api,
        root,
        service,
        which: ProviderId::Claude,
    }
}

/// Where OpenAI puts its own claims in a standard token.
const OPENAI: &str = "https://api.openai.com/auth";

/// A Codex login as `codex login` writes one, for the account `who`.
///
/// The access token is unique to the refresh token so every login has its own, which is
/// what the scripted usage answers are keyed by.
pub(crate) fn codex_login(who: &str, refresh: &str) -> Value {
    json!({
        "auth_mode": "chatgpt",
        "OPENAI_API_KEY": null,
        "tokens": {
            "id_token": crate::provider::jwt::unsigned(&json!({
                "email": format!("{who}@example.com"),
                "exp": NOW + 3600,
                OPENAI: {
                    "chatgpt_account_id": who,
                    "chatgpt_user_id": format!("user-{who}"),
                    "chatgpt_plan_type": "pro",
                },
            })),
            "access_token": codex_access(refresh),
            "refresh_token": refresh,
            "account_id": who,
        },
        "last_refresh": "2025-10-09T08:00:00Z",
    })
}

/// The identity Codex's own claims give the account `who`: the ChatGPT account with the
/// person inside it.
pub(crate) fn codex_id(who: &str) -> String {
    format!("{who}_user-{who}")
}

/// The access token [`codex_login`] carries for this refresh token.
pub(crate) fn codex_access(refresh: &str) -> String {
    crate::provider::jwt::unsigned(&json!({"exp": NOW + 10 * 86_400, "for": refresh}))
}

pub(crate) fn codex_account(label: &str, uuid: &str, parked: Option<Park>) -> Account {
    Account {
        last_used_at: None,
        label: label.into(),
        account_uuid: uuid.into(),
        email: format!("{uuid}@example.com"),
        parked,
        detail: crate::state::Detail::Codex {
            workspace_id: None,
            plan: Some("pro".into()),
        },
    }
}

/// The same shape for Codex: `here` is signed in, `there` is parked and ready, and OpenAI
/// answers for both.
pub(crate) fn codex_machine(name: &str) -> Machine {
    let root = std::env::temp_dir().join(format!(
        "pitboard-crash-codex-{name}-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(root.join(".codex")).expect("a scratch codex home");

    let mem = MemoryHost::new();
    let api = ScriptedApi::new();
    let ctx = Context::new(root.clone())
        .with_pitboard_home(root.join(".pitboard"))
        .with_codex_home(root.join(".codex").to_string_lossy().into_owned())
        .with_memory_stores(Arc::clone(&mem))
        .with_scripted_api(Arc::clone(&api))
        .with_clock(Arc::new(FixedClock::at(NOW)) as Arc<dyn Clock>);
    let machine = Machine {
        ctx,
        mem,
        api,
        root,
        service: String::new(),
        which: ProviderId::Codex,
    };
    machine.sign_in(&codex_login("here", "here-refresh"));
    for refresh in ["here-refresh", "there-refresh"] {
        machine.api.using(
            &codex_access(refresh),
            crate::usage::Snapshot {
                windows: Vec::new(),
                observed_at: Some(NOW),
                account_uuid: None,
                source: crate::usage::Source::Live,
            },
        );
    }

    std::fs::create_dir_all(machine.root.join(".pitboard")).expect("a pitboard home");
    let parked_service = park::reserve(&machine.ctx, &codex_id("there")).expect("a free name");
    let parked = park::store_at(
        &machine.ctx,
        ProviderId::Codex,
        &parked_service,
        &codex_login("there", "there-refresh"),
    )
    .expect("parked");

    let mut state = State::default();
    state
        .accounts
        .push(codex_account("here", &codex_id("here"), None));
    state
        .accounts
        .push(codex_account("there", &codex_id("there"), Some(parked)));
    state.set_active(ProviderId::Codex, Some("here".into()));
    state::save(&machine.ctx, &state).expect("saved");
    machine
}

/// A login of the account `who` as this machine's tool writes one, with the service taught
/// whose it is where the tool has to ask.
pub(crate) fn login_of(m: &Machine, who: &str, refresh: &str) -> Value {
    match m.which {
        ProviderId::Claude => {
            m.api.owned_by(&format!("access-{refresh}"), owner(who));
            document(refresh)
        }
        ProviderId::Codex => codex_login(who, refresh),
    }
}

/// A sign-in the tool finished as `who`, left where a finished one leaves its login.
pub(crate) fn signed_in(m: &Machine, who: &str, refresh: &str) -> enroll::SignIn {
    enroll::planted(&m.ctx, m.which, login_of(m, who, refresh)).expect("a sign-in")
}

/// The service answers a renewal of the login on `refresh` with one on `renewed`.
pub(crate) fn renews(m: &Machine, refresh: &str, renewed: &str) {
    match m.which {
        ProviderId::Claude => {
            m.api.renews(
                refresh,
                crate::api::Renewed {
                    access_token: format!("access-{renewed}"),
                    refresh_token: Some(renewed.into()),
                    expires_in: 3600,
                    refresh_token_expires_in: Some(30 * 86_400),
                    scopes: None,
                    at: None,
                },
            );
        }
        ProviderId::Codex => {
            m.api.codex_renews(
                refresh,
                crate::provider::codex::api::Fresh {
                    id_token: None,
                    access_token: Some(codex_access(renewed)),
                    refresh_token: Some(renewed.into()),
                    at: Some(NOW),
                },
            );
        }
    }
}

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

/// Everything that must be true after a killed change has been recovered, whatever the
/// change was and wherever it died.
pub(crate) fn hold(m: &Machine, after: &str) {
    let state = state::load(&m.ctx)
        .unwrap_or_else(|e| panic!("{after}: the state file must still parse, got {e}"));

    // Nothing in the vault that the state does not name. An item nobody names holds a live
    // refresh token that no command will ever renew or delete, and on macOS nothing can
    // even list it.
    let named: HashSet<&str> = state
        .accounts
        .iter()
        .filter_map(|a| a.parked.as_ref())
        .map(|p| p.service.as_str())
        .chain(state.discarded.iter().map(String::as_str))
        .collect();
    for service in m.mem.vault().services() {
        assert!(
            named.contains(service.as_str()),
            "{after}: {service} holds a login nothing on this machine names"
        );
    }

    // One refresh token, one place. A token in two places is a token one holder will rotate
    // past, which ends the login for the other; for a tool whose sign-out revokes what it
    // finds, it is a token the person's own next sign-out kills in both.
    let tool = crate::provider::of(m.which);
    let mut seen: HashSet<String> = HashSet::new();
    let mut fingerprints = Vec::new();
    for service in m.mem.vault().services() {
        let raw = m.mem.vault().peek(&service).expect("just listed");
        let value: Value = serde_json::from_str(&raw).expect("a park is JSON");
        fingerprints.push((service, tool.fingerprint(&value)));
    }
    let live = m.live();
    if let Some(document) = &live {
        fingerprints.push(("the live slot".into(), tool.fingerprint(document)));
    }
    for (place, fingerprint) in fingerprints {
        assert!(
            seen.insert(fingerprint.clone()),
            "{after}: the login in {place} is also somewhere else"
        );
    }

    // Every account can still be got back to. Signed in, or holding a login that can be
    // restored, or holding nothing and saying so, but never holding one that has expired.
    let live_uuid = live
        .and_then(|document| {
            tool.identify(&m.ctx, &crate::provider::Credential::new(m.which, document))
                .ok()
        })
        .map(|found| found.account_id);
    for a in &state.accounts {
        if Some(&a.account_uuid) == live_uuid.as_ref() {
            continue;
        }
        if let Some(park) = &a.parked {
            assert!(
                park.restorable_at(NOW),
                "{after}: {} holds a login that can no longer be restored",
                a.label
            );
            assert!(
                m.mem.vault().peek(&park.service).is_some(),
                "{after}: {} names a park that is not in the vault",
                a.label
            );
        }
    }
}

/// Recovery, run the way the next command runs it.
pub(crate) fn recover(m: &Machine) -> Result<()> {
    settle(&m.ctx, None).map(|_| ())
}