pitboard-core 0.21.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
//! Where Codex CLI keeps things (`codex_login_location`); which store, [`super::layers`].

use super::layers;
use crate::context::{Context, Environment};
use crate::host::Os;
use std::path::{Path, PathBuf};

/// The file Codex keeps its login in, inside [`home`].
pub(crate) const AUTH_FILE: &str = "auth.json";

// Unset on Windows, in `FOLDERID_Profile` wherever `USERPROFILE` points (`codex_windows_home`).
pub(crate) fn home(ctx: &Context) -> PathBuf {
    match ctx.codex_home() {
        Some(dir) if !dir.is_empty() => match ctx.os {
            Os::MacOs | Os::Linux => PathBuf::from(dir),
            Os::Windows => std::fs::canonicalize(dir)
                .map_or_else(|_| PathBuf::from(dir), crate::host::without_verbatim_prefix),
        },
        _ => ctx.profile.as_deref().unwrap_or(ctx.home()).join(".codex"),
    }
}

// Codex does not start where `CODEX_HOME` names no folder. Asked on Windows alone until
// macOS and Linux refuse it too, which would be a change in what they accept.
pub(crate) fn missing_home(ctx: &Context) -> Option<PathBuf> {
    let dir = ctx.codex_home().filter(|dir| !dir.is_empty())?;
    (ctx.os == Os::Windows && !Path::new(dir).is_dir()).then(|| PathBuf::from(dir))
}

pub(crate) fn auth_file(ctx: &Context) -> PathBuf {
    home(ctx).join(AUTH_FILE)
}

// `codex_install_places` and `codex_windows_install_places`. Never the copy inside the ChatGPT
// app, which OpenAI documents no use of (`codex_runs_inside_the_chatgpt_app`).
pub(crate) fn install_places(env: &Environment) -> Vec<PathBuf> {
    let standalone = match env.os() {
        Os::MacOs | Os::Linux => Some(env.home().join(".local").join("bin")),
        // install.ps1 takes one that is only white space for unset.
        Os::Windows => env
            .named_folder("CODEX_INSTALL_DIR")
            .filter(|dir| !dir.to_string_lossy().trim().is_empty())
            .or_else(|| {
                let mut dir = env.named_folder("LOCALAPPDATA")?;
                dir.extend(["Programs", "OpenAI", "Codex", "bin"]);
                Some(dir)
            }),
    };
    standalone
        .into_iter()
        .chain(env.os().package_bins(env))
        .collect()
}

// What npm's `codex.js` starts, with what it sets (`codex_windows_install_places`).
pub(crate) fn npm_native(script: &Path) -> Option<(PathBuf, crate::provider::Launched)> {
    let named = |path: &Path, name: &str| {
        path.file_name()
            .is_some_and(|its| its.eq_ignore_ascii_case(name))
    };
    let bin = script.parent().filter(|bin| named(bin, "bin"))?;
    let package = bin.parent().filter(|package| named(package, "codex"))?;
    package.parent().filter(|scope| named(scope, "@openai"))?;
    if !named(script, "codex.js") {
        return None;
    }
    let program = NPM_TARGETS.iter().find_map(|(target, platform)| {
        let vendor = bin
            .ancestors()
            .filter(|dir| !named(dir, "node_modules"))
            .map(|dir| dir.join("node_modules").join("@openai").join(platform))
            .find(|found| found.join("package.json").is_file())
            .unwrap_or_else(|| package.to_path_buf())
            .join("vendor");
        let program = vendor.join(target).join("bin").join("codex.exe");
        crate::host::proc::can_run(&program).then_some(program)
    })?;
    let root = std::fs::canonicalize(package).map_or_else(
        |_| package.to_path_buf(),
        crate::host::without_verbatim_prefix,
    );
    let mut set: crate::provider::Launched = vec![
        ("CODEX_MANAGED_PACKAGE_ROOT", Some(root.into_os_string())),
        ("CODEX_MANAGED_BY_NPM", Some("1".into())),
    ];
    set.extend(
        [
            "CODEX_MANAGED_BY_BUN",
            "CODEX_MANAGED_BY_PNPM",
            "CODEX_MANAGED_BY_VITE_PLUS",
        ]
        .map(|other| (other, None)),
    );
    Some((program, set))
}

// npm installs the one its `node` runs on; an x64 `node` runs on an ARM64 PC too.
const NPM_TARGETS: [(&str, &str); 2] = if cfg!(target_arch = "aarch64") {
    [
        ("aarch64-pc-windows-msvc", "codex-win32-arm64"),
        ("x86_64-pc-windows-msvc", "codex-win32-x64"),
    ]
} else {
    [
        ("x86_64-pc-windows-msvc", "codex-win32-x64"),
        ("aarch64-pc-windows-msvc", "codex-win32-arm64"),
    ]
};

/// Which store this machine's Codex is configured to keep its login in.
///
/// The shipped default is `file`, and it is a packaged default rather than a line in
/// anybody's `config.toml`, so an absent setting means `file` and not "unknown".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Backend {
    File,
    Keyring,
    /// `auto`: the keyring, falling back to the file.
    Either,
    /// In memory for the life of one process. Nothing Pitboard can park.
    Ephemeral,
    /// `[features] secret_auth_storage` with a keyring store: an encrypted file whose key
    /// is in the keychain.
    Secrets,
    /// A layer Codex reads is there and cannot be read as Codex reads it, which stops Codex
    /// from starting, so nobody can tell. Refused like a store Pitboard does not handle.
    Unknown,
}

/// The person's own `config.toml`, in Codex's home.
pub(crate) fn config_file(ctx: &Context) -> PathBuf {
    home(ctx).join("config.toml")
}

// Where this machine's Codex keeps its login, from every layer it reads outside a project.
pub(crate) fn store(ctx: &Context) -> layers::Store {
    layers::of(ctx, &config_file(ctx))
}

pub(crate) fn restrictions(ctx: &Context) -> layers::Restrictions {
    layers::restrictions_of(ctx, &config_file(ctx))
}

/// Where a sign-in Pitboard runs keeps the login it signs in to: its private home holds no
/// `config.toml`, and its command line names the file store ([`layers::FILE_STORE`]), so
/// only what an administrator set over that moves it.
pub(crate) fn sign_in_store(ctx: &Context) -> layers::Store {
    layers::of_a_sign_in(ctx, &config_file(ctx))
}

// Never by running it, and no further than two folders up: names before any file is opened.
pub(crate) fn installed_version(program: &Path) -> Option<String> {
    use crate::host::program::{looks_like_a_version, npm_shim_target, version_where};
    let program = npm_shim_target(program).unwrap_or_else(|| program.to_path_buf());
    let resolved = std::fs::canonicalize(program).ok()?;
    let near: Vec<&Path> = resolved.ancestors().skip(1).take(2).collect();
    near.iter()
        .find_map(|dir| {
            dir.file_name()
                .and_then(|n| n.to_str())
                .and_then(|name| name.split('-').next())
                .filter(|leading| looks_like_a_version(leading))
                .map(str::to_owned)
        })
        .or_else(|| {
            near.iter().find_map(|dir| {
                version_where(&dir.join("package.json"), "name", "@openai/codex")
                    .or_else(|| version_where(&dir.join("codex-package.json"), "variant", "codex"))
            })
        })
}

#[cfg(test)]
#[allow(
    clippy::disallowed_methods,
    reason = "a test sets up its scratch files as a person or a tool would"
)]
mod tests {
    use super::*;

    fn backend(ctx: &Context) -> Backend {
        store(ctx).backend
    }

    // `secret_auth_storage` is on by default on Windows alone, which makes either of Codex's
    // keyring stores its encrypted file.
    fn keyring_or(alone: Backend) -> Backend {
        match crate::host::OS {
            Os::MacOs | Os::Linux => alone,
            Os::Windows => Backend::Secrets,
        }
    }

    fn at(dir: &Path, config: &str) -> Context {
        std::fs::create_dir_all(dir).expect("a scratch codex home");
        std::fs::write(dir.join("config.toml"), config).expect("a config");
        Context::for_unit_test().with_codex_home(dir.to_string_lossy().into())
    }

    // Codex 0.162.1's find_codex_home_from_env: a set `CODEX_HOME` must be a folder and is
    // canonicalised, and unset it is `.codex` in `FOLDERID_Profile`, which dirs 6.0.0 reads.
    #[test]
    fn codex_finds_its_home_on_windows_as_codex_does() {
        use crate::context::Environment;
        use crate::host::Os;
        let scratch = tempfile::tempdir().expect("a scratch folder");
        let profile = scratch.path().join("profile");
        std::fs::create_dir_all(profile.join("codex")).expect("a scratch codex home");
        std::fs::write(profile.join("file"), "").expect("a file");
        let named = |path: PathBuf| path.to_string_lossy().into_owned();
        let read = |os: Os, codex: Option<PathBuf>| {
            let pairs = [
                ("USERPROFILE", named(profile.clone())),
                ("HOME", named(profile.clone())),
            ]
            .into_iter()
            .chain(codex.map(|dir| ("CODEX_HOME", named(dir))));
            Context::read(&Environment::on(os, pairs), "cli")
        };

        let handed = Context::new(profile.clone());
        assert_eq!(home(&handed), profile.join(".codex"), "a handed home's");
        let unset = read(Os::Windows, None);
        assert_eq!(
            home(&unset),
            profile.join(".codex"),
            "no profile is looked up in a test"
        );
        let elsewhere = profile.join("Profile");
        assert_eq!(
            home(&unset.with_profile(elsewhere.clone())),
            elsewhere.join(".codex"),
            "not the home, where the profile is elsewhere"
        );
        let given = read(Os::Windows, Some(profile.join(".").join("codex")));
        let canonical = std::fs::canonicalize(profile.join("codex")).expect("there");
        assert_eq!(
            home(&given),
            crate::host::without_verbatim_prefix(canonical)
        );
        assert_eq!(missing_home(&given), None);
        for nothing in [profile.join("never-made"), profile.join("file")] {
            assert_eq!(
                missing_home(&read(Os::Windows, Some(nothing.clone()))),
                Some(nothing)
            );
        }
        for os in [Os::MacOs, Os::Linux] {
            let missing = profile.join("never-made");
            let ctx = read(os, Some(missing.clone()));
            assert_eq!((home(&ctx), missing_home(&ctx)), (missing, None), "{os:?}");
        }
    }

    /// The shipped default is a packaged one rather than a line anybody wrote, so an absent
    /// setting means the file and not "cannot tell".
    #[test]
    fn no_setting_means_the_file() {
        let scratch = tempfile::tempdir().expect("a scratch folder");
        let dir = scratch.path().join("dir");
        let ctx = at(&dir, "model = \"gpt-5\"\n");
        assert_eq!(backend(&ctx), Backend::File);
        assert_eq!(auth_file(&ctx), home(&ctx).join("auth.json"));
        assert_eq!(
            std::fs::canonicalize(home(&ctx)).ok(),
            std::fs::canonicalize(&dir).ok()
        );
    }

    /// Each store is read from the person's own `config.toml` as TOML. A value that is not a
    /// store Codex has stops Codex from starting, so it is no longer taken for the file.
    #[test]
    fn each_store_is_recognised() {
        let scratch = tempfile::tempdir().expect("a scratch folder");
        let dir = scratch.path().join("dir");
        for (written, expected) in [
            (
                "cli_auth_credentials_store = \"keyring\"",
                keyring_or(Backend::Keyring),
            ),
            (
                "cli_auth_credentials_store=\"auto\"",
                keyring_or(Backend::Either),
            ),
            (
                "  cli_auth_credentials_store = 'ephemeral'",
                Backend::Ephemeral,
            ),
            ("cli_auth_credentials_store = \"file\"", Backend::File),
            (
                "cli_auth_credentials_store = \"nonsense\"",
                Backend::Unknown,
            ),
            ("cli_auth_credentials_store = keyring", Backend::Unknown),
        ] {
            let ctx = at(&dir, written);
            assert_eq!(backend(&ctx), expected, "{written}");
        }
    }

    /// A trailing comment is not part of the value. Read as part of it, a keyring store
    /// looked like the default file, and Pitboard would read a file Codex had deleted.
    #[test]
    fn a_comment_after_the_value_is_not_the_value() {
        let scratch = tempfile::tempdir().expect("a scratch folder");
        let dir = scratch.path().join("dir");
        let ctx = at(
            &dir,
            "cli_auth_credentials_store = \"keyring\"  # on this mac\n",
        );
        assert_eq!(backend(&ctx), keyring_or(Backend::Keyring));
    }

    /// A key of the same name inside another table is not the setting.
    #[test]
    fn only_the_top_level_key_is_the_setting() {
        let scratch = tempfile::tempdir().expect("a scratch folder");
        let dir = scratch.path().join("dir");
        for (config, expected, why) in [
            (
                "[profiles.work]\ncli_auth_credentials_store = \"keyring\"\n",
                Backend::File,
                "a key inside another table is not the setting",
            ),
            (
                "cli_auth_credentials_store = \"keyring\"\n\
                 [features]\nsecret_auth_storage = true\n",
                Backend::Secrets,
                "an encrypted file whose key is in the keychain is a store of its own",
            ),
            (
                "[features]\nsecret_auth_storage = true\n",
                Backend::File,
                "the feature only changes a keyring store",
            ),
        ] {
            assert_eq!(backend(&at(&dir, config)), expected, "{why}");
        }
    }

    /// What this machine's folder of Codex's configuration says is read as well as the
    /// person's own file, where Pitboard read only the person's.
    #[test]
    fn the_system_layers_are_read_as_well_as_the_persons_own() {
        let scratch = tempfile::tempdir().expect("a scratch folder");
        let dir = scratch.path().join("dir");
        let host = crate::host::memory::MemoryHost::new();
        let ctx = at(&dir, "model = \"gpt-5\"\n").with_memory_stores(host.clone());
        let system = |name| layers::system_file(&ctx, name);
        host.administers(
            system("config.toml"),
            "cli_auth_credentials_store = \"keyring\"\n",
        );
        assert_eq!(backend(&ctx), keyring_or(Backend::Keyring));
        std::fs::write(
            dir.join("config.toml"),
            "cli_auth_credentials_store = \"file\"\n",
        )
        .expect("a config");
        assert_eq!(backend(&ctx), Backend::File);
        host.administers(
            system("requirements.toml"),
            "cli_auth_credentials_store = \"keyring\"\n",
        );
        assert_eq!(backend(&ctx), keyring_or(Backend::Keyring));
        assert_eq!(
            sign_in_store(&ctx).backend,
            keyring_or(Backend::Keyring),
            "a requirement pins a sign-in's store too"
        );
    }

    /// Each way Codex is installed, laid out in a scratch directory, and a shim that names
    /// nothing. Only the two directories above the program are looked at, names first, so a
    /// standalone install is named without opening any file inside it.
    #[test]
    fn a_version_is_read_out_of_each_way_codex_is_installed() {
        use crate::host::fs::testing;

        let scratch = tempfile::tempdir().expect("a scratch home");
        let root = scratch.path().to_path_buf();
        let place = |at: &str| {
            let path = root.join(at);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, "").unwrap();
            path
        };

        let standalone =
            place("codex/packages/standalone/releases/0.154.0-aarch64-apple-darwin/bin/codex");
        // A package.json beside it that would say otherwise, to show it is never opened.
        std::fs::write(
            standalone.with_file_name("package.json"),
            r#"{"name": "@openai/codex", "version": "9.9.9"}"#,
        )
        .unwrap();
        let link = root.join("bin/codex");
        std::fs::create_dir_all(link.parent().unwrap()).unwrap();
        testing::link(&standalone, &link).expect("a link");
        assert_eq!(installed_version(&link).as_deref(), Some("0.154.0"));

        let cask = place("Caskroom/codex/0.153.2/codex-aarch64-apple-darwin");
        assert_eq!(installed_version(&cask).as_deref(), Some("0.153.2"));

        let npm = place("lib/node_modules/@openai/codex/bin/codex.js");
        std::fs::write(
            root.join("lib/node_modules/@openai/codex/package.json"),
            r#"{"name": "@openai/codex", "version": "0.150.1"}"#,
        )
        .unwrap();
        assert_eq!(installed_version(&npm).as_deref(), Some("0.150.1"));

        // Three levels up is too far: nothing further than two directories is read.
        let shim = place("volta/bin/volta-shim");
        std::fs::write(
            root.join("package.json"),
            r#"{"name": "@openai/codex", "version": "1.2.3"}"#,
        )
        .unwrap();
        assert_eq!(installed_version(&shim), None);
    }

    // `codex.exe` has no version resource in 0.162.1.
    #[test]
    fn a_version_is_read_where_codex_is_installed_on_windows() {
        let scratch = tempfile::tempdir().expect("a scratch home");
        let root = scratch.path().to_path_buf();
        let place = |at: &str| {
            let path = root.join(at);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, "").unwrap();
            path
        };
        let layout = |version: &str, variant: &str| {
            format!(
                r#"{{"layoutVersion": 1, "version": "{version}", "target": "x86_64-pc-windows-msvc", "variant": "{variant}", "entrypoint": "bin/codex.exe"}}"#
            )
        };

        let vendored = place("codex-win32-x64/vendor/x86_64-pc-windows-msvc/bin/codex.exe");
        let package = root.join("codex-win32-x64/vendor/x86_64-pc-windows-msvc/codex-package.json");
        std::fs::write(&package, layout("0.162.1", "codex")).unwrap();
        assert_eq!(installed_version(&vendored).as_deref(), Some("0.162.1"));
        std::fs::write(&package, layout("0.162.1", "something-else")).unwrap();
        assert_eq!(
            installed_version(&vendored),
            None,
            "only Codex's own package"
        );

        place("npm/node_modules/@openai/codex/bin/codex.js");
        std::fs::write(
            root.join("npm/node_modules/@openai/codex/package.json"),
            r#"{"name": "@openai/codex", "version": "0.161.0"}"#,
        )
        .unwrap();
        let shim = root.join("npm/codex.cmd");
        std::fs::write(
            &shim,
            "@ECHO off\r\nIF EXIST \"%dp0%\\node.exe\" (\r\n  SET \"_prog=%dp0%\\node.exe\"\r\n)\r\n\
             \"%_prog%\"  \"%dp0%\\node_modules\\@openai\\codex\\bin\\codex.js\" %*\r\n",
        )
        .unwrap();
        assert_eq!(installed_version(&shim).as_deref(), Some("0.161.0"));
    }
}