Skip to main content

pitboard_core/
lib.rs

1//! The engine behind Pitboard: parking and restoring a person's own Claude Code, Codex and
2//! Claude Desktop logins, and reading what each Claude Code and Codex account has left. It
3//! serves Pitboard's own front ends, the command line and the native apps, which reach it
4//! through [`service::Pitboard`] with an explicit [`context::Context`].
5//!
6//! # What is supported
7//!
8//! This crate is published because the `pitboard` binary depends on it, not because it was
9//! designed for other programs to build on. The supported interface is [`service::Pitboard`],
10//! [`context::Context`], and the types those two return. Everything else public is what the
11//! front ends in this repository use, and may change in any release.
12//!
13//! What a version promises, for the part that is supported: a code is a name, and names are
14//! kept. Adding an error, warning or check code is not a breaking change, which is why every
15//! enum a caller reads codes out of is `#[non_exhaustive]` and every such caller needs a
16//! fallback arm. Renaming or removing a code is a breaking change: a new minor version of
17//! this crate, whose version is its own, apart from Pitboard's.
18//! A report a caller reads, such as what `uninstall` returns, may likewise say more in a
19//! later release, so those structs are `#[non_exhaustive]` too.
20//!
21//! What is deliberately not reachable: nothing outside this crate may write Pitboard's index.
22//! Every change goes through [`switch`], which records what it is about to do first.
23
24#![warn(clippy::print_stdout, clippy::print_stderr)]
25
26// Pitboard for Windows is being built, and reaches people only once the command line, the
27// app, their installers and their docs are done. Until then a Windows build of a release
28// compiles and refuses everything at run time (`release`). It compiles only for the two
29// targets its builds are made and tested on: an x64 or ARM64 PC with the MSVC toolchain.
30// A 32-bit, GNU, UWP or Arm64EC build is another program nobody has run.
31#[cfg(all(
32    windows,
33    not(all(
34        target_vendor = "pc",
35        target_env = "msvc",
36        any(target_arch = "x86_64", target_arch = "aarch64")
37    ))
38))]
39compile_error!(
40    "Pitboard for Windows is built for x86_64-pc-windows-msvc and aarch64-pc-windows-msvc \
41     alone, the targets it is built and tested on."
42);
43
44#[cfg(not(any(target_os = "macos", target_os = "linux", windows)))]
45compile_error!(
46    "Pitboard runs on macOS, Linux and Windows. Another system needs a host of its own in \
47     `host/`, saying where its stores, processes and scheduler are."
48);
49
50pub(crate) mod api;
51pub mod app;
52pub mod assumptions;
53pub mod audit;
54pub mod context;
55// The Claude Desktop the tests play, reached as `testing::desktop`.
56#[cfg(any(test, feature = "test-support"))]
57#[doc(hidden)]
58#[allow(
59    clippy::disallowed_methods,
60    reason = "it leaves Claude Desktop's files as Claude does"
61)]
62pub mod desktop_testing;
63pub mod doctor;
64pub mod duty;
65pub mod error;
66pub(crate) mod in_use;
67pub mod label;
68pub mod provider;
69pub mod redact;
70pub mod release;
71pub mod schedule;
72// The Secret Service the tests start on Linux, reached as `testing::SecretService`.
73// windows: the Secret Service is Linux's own
74#[cfg(all(target_os = "linux", any(test, feature = "test-support")))]
75#[doc(hidden)]
76#[allow(
77    clippy::disallowed_methods,
78    reason = "it writes the bus's config and the daemons' logs in a test's own folder"
79)]
80pub mod secret_service_testing;
81pub mod service;
82pub(crate) mod settings;
83pub mod state;
84pub mod status;
85pub mod statusline;
86pub mod switch;
87pub mod time;
88pub mod usage;
89pub(crate) mod warning;
90pub mod watch_service;
91pub mod words;
92
93pub(crate) mod atomic;
94pub(crate) mod fault;
95#[cfg(test)]
96mod helper;
97pub mod holder;
98pub(crate) mod home;
99pub mod host;
100pub(crate) mod lock;
101pub(crate) mod park;
102pub(crate) mod pending;
103pub(crate) mod permit;
104pub(crate) mod proxy;
105pub(crate) mod sessions;
106/// The program the tests start in place of a tool, reached as `testing::stand_in`. Its own
107/// tests run with the core's.
108#[cfg(any(test, feature = "test-support"))]
109#[doc(hidden)]
110#[allow(
111    clippy::print_stdout,
112    clippy::print_stderr,
113    reason = "it prints what the program it plays would"
114)]
115pub mod stand_in;
116pub(crate) mod store;
117
118/// What the integration tests reach into: they plant and inspect parked logins in the real
119/// store, and must never touch the credential slot this machine's Claude Code reads.
120#[cfg(feature = "test-support")]
121#[doc(hidden)]
122pub mod testing {
123    pub use crate::api::scripted::{Answer, Asked, ScriptedApi, Trouble};
124    pub use crate::context::ScratchMachine;
125    pub use crate::desktop_testing as desktop;
126    pub use crate::doctor::example::{
127        healthy_linux as doctor_on_a_healthy_linux, healthy_mac as doctor_on_a_healthy_mac,
128        healthy_pc as doctor_on_a_healthy_pc,
129    };
130    pub use crate::duty::warm::run::{Ran, Started, WarmScript};
131    /// What a test or a fixture does to a file's access, or to make a link, which only this
132    /// system's face says how to do: the integration tests and the apps' fixtures do it here,
133    /// as the core's own tests do.
134    pub use crate::host::fs::testing as fs;
135    pub use crate::host::memory::MemoryHost;
136    pub use crate::provider::claude::api::Renewed;
137    pub use crate::provider::claude::paths::live_service;
138    pub use crate::provider::claude::slot::{LIVE_SERVICE, dir_hash, service_for_dir};
139    pub use crate::provider::jwt::unsigned as unsigned_token;
140    #[cfg(target_os = "linux")]
141    pub use crate::secret_service_testing::SecretService;
142    /// The program the integration tests, the model's tests and the fixtures' tests start in
143    /// place of `claude`, `codex` and every other program they run, on every system.
144    pub use crate::stand_in;
145    pub use crate::store::memory::{Fault, MemoryStore};
146    pub use crate::store::vault_read;
147    pub use crate::switch::enroll::{ScriptedSignIn, SignInScript};
148    pub use crate::time::{Clock, FixedClock};
149
150    /// The launcher a job starts `program` through on this system, which a test or a fixture
151    /// puts beside it for the job to be installed.
152    pub fn launcher(program: &std::path::Path) -> Option<std::path::PathBuf> {
153        crate::host::OS.launcher(program)
154    }
155
156    /// Every variable Pitboard reads from its environment, by name, which a test withholds
157    /// from every command it runs unless it means to pass one on.
158    pub fn variables() -> impl Iterator<Item = &'static str> {
159        crate::context::variables()
160    }
161
162    pub fn codex_login(
163        account: &str,
164        email: &str,
165        access: &str,
166        refresh: &str,
167    ) -> serde_json::Value {
168        crate::provider::codex::login_for_a_test(account, email, access, refresh)
169    }
170
171    /// Every kind of process `which`'s tool names as holding its login, on every system, as a
172    /// switch finds them: an app among them is named by its own system's `holder::AppId`.
173    pub fn holders(which: crate::provider::ProviderId) -> &'static [crate::holder::Holder] {
174        use crate::provider::{Adoption, LoginKind};
175        match crate::provider::of(which) {
176            LoginKind::Document(tool) => match tool.adoption(None) {
177                Adoption::RestartRequired { holders, .. } => holders,
178                _ => &[],
179            },
180            LoginKind::Folder(app) => std::slice::from_ref(app.holder()),
181        }
182    }
183
184    pub fn park_unread(label: &str, path: &std::path::Path, why: &str) -> crate::error::Error {
185        crate::store::folder::unread(label, path, why)
186    }
187
188    // The one guard every test's folder is refused by.
189    pub fn lies_in(path: &std::path::Path, place: &std::path::Path) -> bool {
190        crate::host::lies_in(path, place)
191    }
192
193    pub fn real_login_places(
194        started_in: &crate::context::Context,
195    ) -> Result<Vec<std::path::PathBuf>, String> {
196        crate::host::real_login_places(Some(started_in))
197    }
198
199    /// Parks `contents` under `service` in this context's vault, as a change does, once the
200    /// gate every change passes has let it: a test that runs as root is refused here too.
201    pub fn vault_write(
202        ctx: &crate::context::Context,
203        service: &str,
204        contents: &str,
205    ) -> crate::error::Result<()> {
206        let permit = crate::permit::gate(ctx)?;
207        Ok(crate::store::vault_write(ctx, permit, service, contents)?)
208    }
209
210    pub fn may_be_running(pid: u32) -> bool {
211        crate::host::proc::may_be_running(pid)
212    }
213
214    // The build of the Windows this runs on, as the floor reads it.
215    #[cfg(windows)]
216    pub fn windows_build() -> Option<u32> {
217        crate::host::user::version().map(|(_, _, build)| build)
218    }
219
220    // Every process's id, its parent's and its program's name, from one snapshot.
221    #[cfg(windows)]
222    pub fn processes() -> std::io::Result<Vec<(u32, u32, String)>> {
223        crate::host::proc::snapshot()
224    }
225
226    // A program's version resource, read as Claude Code's is (W17).
227    #[cfg(windows)]
228    pub mod version_resource {
229        use std::path::Path;
230
231        pub fn file_version(program: &Path) -> Option<[u16; 4]> {
232            crate::host::proc::file_version(program)
233        }
234
235        pub fn product_version(program: &Path) -> Option<[u16; 4]> {
236            crate::host::proc::product_version(program)
237        }
238
239        pub fn string(program: &Path, name: &str) -> Option<String> {
240            crate::host::proc::version_string(program, name)
241        }
242    }
243
244    /// Claude Code's login in Credential Manager as Pitboard writes, reads and deletes it, under
245    /// a test's own service, and each item as Windows keeps it, its blob by length alone.
246    #[cfg(windows)]
247    pub mod credman {
248        use crate::context::Context;
249        use crate::store::RawStore;
250
251        pub struct Item {
252            pub kind: u32,
253            pub persist: u32,
254            pub user: String,
255            pub comment: Option<String>,
256            pub attributes: u32,
257            pub bytes: usize,
258        }
259
260        fn refused(target: &str) -> std::io::Result<()> {
261            match crate::provider::names::refusal(target, &[]) {
262                Some(why) => Err(std::io::Error::other(why)),
263                None => Ok(()),
264            }
265        }
266
267        pub fn item(target: &str) -> std::io::Result<Option<Item>> {
268            refused(target)?;
269            Ok(
270                crate::host::windows_credman::item(target)?.map(|held| Item {
271                    kind: held.kind,
272                    persist: held.persist,
273                    user: held.user,
274                    comment: held.comment,
275                    attributes: held.attributes,
276                    bytes: held.blob.len(),
277                }),
278            )
279        }
280
281        // As `Bun.secrets.set` writes one (docs/facts/windows-runners.md).
282        pub fn write_as_bun(target: &str, user: &str, value: &str) -> std::io::Result<()> {
283            refused(target)?;
284            crate::host::windows_credman::write(target, user, value.as_bytes())
285        }
286
287        fn store(ctx: &Context) -> crate::provider::claude::credman::Store {
288            crate::provider::claude::credman::Store::of(ctx)
289        }
290
291        pub fn write(ctx: &Context, service: &str, contents: &str) -> crate::error::Result<()> {
292            let permit = crate::permit::gate(ctx)?;
293            Ok(store(ctx).write(permit, service, contents)?)
294        }
295
296        pub fn read(ctx: &Context, service: &str) -> crate::error::Result<Option<String>> {
297            Ok(store(ctx).read(service)?)
298        }
299
300        // Every piece too, as Claude Code deletes its login.
301        pub fn discard(ctx: &Context, service: &str) -> crate::error::Result<()> {
302            let permit = crate::permit::gate(ctx)?;
303            Ok(store(ctx).delete(permit, service)?)
304        }
305
306        // A test's cleanup: every item under `service`, each by name.
307        pub fn sweep(ctx: &Context, service: &str) -> Result<(), String> {
308            crate::provider::claude::credman::swept(ctx, service)
309        }
310    }
311
312    /// Deletes what is parked under `service`, once the gate has let it.
313    pub fn vault_delete(ctx: &crate::context::Context, service: &str) -> crate::error::Result<()> {
314        let permit = crate::permit::gate(ctx)?;
315        Ok(crate::store::vault_delete(ctx, permit, service)?)
316    }
317
318    /// A sign-in to `which`'s tool that finished with `document`, the login the tool would
319    /// have stored, as JSON, and never ran the tool: what enrolling a second account by
320    /// signing in privately needs, in a test that may run no tool. Made once the gate has let
321    /// it, as every sign-in is.
322    pub fn signed_in(
323        ctx: &crate::context::Context,
324        which: crate::provider::ProviderId,
325        document: &str,
326    ) -> crate::error::Result<crate::switch::SignIn> {
327        use crate::provider::LoginKind;
328        let document = serde_json::from_str(document).expect("a login a test wrote as JSON");
329        match crate::provider::of(which) {
330            LoginKind::Document(tool) => {
331                crate::switch::planted(ctx, crate::permit::gate(ctx)?, tool, document)
332            }
333            LoginKind::Folder(_) => Err(crate::error::Error::Usage(
334                "a Claude Desktop sign-in is played by testing::desktop".into(),
335            )),
336        }
337    }
338}