diff --git a/Cargo.lock b/Cargo.lock index aaf2be6..c66cd1d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -654,7 +654,7 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jaynshare" -version = "2.3.2" +version = "2.3.3" dependencies = [ "base64", "bytes", diff --git a/Cargo.toml b/Cargo.toml index 7cf87cc..8e72336 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "jaynshare" -version = "2.3.2" +version = "2.3.3" edition = "2024" rust-version = "1.95" publish = false diff --git a/README.md b/README.md index 062ad8e..5e651c8 100644 --- a/README.md +++ b/README.md @@ -26,9 +26,10 @@ Website

-jaynshare is a self-hosted proxy for Claude Code and Codex. -Just replace `claude` by `jaynshare claude` (or `codex` by `jaynshare codex`) -and you can draw from your friends' subscriptions when yours is rate limited. +jaynshare is a self-hosted proxy for Claude Code, Codex and Claude Desktop on macOS. +Just replace `claude` by `jaynshare claude` (or `codex` by `jaynshare codex`, +or open Claude Desktop with `jaynshare desktop`) and you can draw from your +friends' subscriptions when yours is rate limited. PS : It also works if you pool several accounts of your own. > [!WARNING] @@ -57,15 +58,21 @@ Before having to set up a server, you can spin up one on your own Mac easily using this (it downloads the latest release, runs it, joins a client and offers to add your accounts). -It needs `python3`, and Claude Code or Codex installed. +It needs `python3`, and Claude Code, Codex or Claude Desktop installed. ```sh curl -fsSLO https://github.com/jaynlabs/jaynshare/releases/latest/download/quickstart.sh bash quickstart.sh #sets up everything bash quickstart.sh claude #launches claude bash quickstart.sh codex #launches codex +bash quickstart.sh desktop #launches Claude Desktop +bash quickstart.sh down #stops the server ``` +`desktop` uses your real Claude Desktop: it asks to trust the quickstart's CA +in your keychain, then points Desktop at the quickstart until `down`. +`bash quickstart.sh client trust-ca remove` removes the CA. + ## Demo

@@ -93,6 +100,7 @@ a product of Anthropic. - OAuth subscription and API-key accounts - Account picker at launch - Claude Code status line naming the serving account +- Claude Desktop on macOS, with account switching from its terminal - One-line join for macOS and Windows from a single-use invite - Anthropic and OpenAI accounts added by their owners when joining - Private-network listeners only, TLS pinned to the server's own identity, and @@ -106,7 +114,8 @@ a product of Anthropic. - A Linux server with systemd - A private network between the engineers and the server, such as a tailnet (but I'm sure you can make it work with other clever solutions) -- Claude Code or Codex already installed on each engineer's machine +- Claude Code, Codex or Claude Desktop (macOS) already installed on each + engineer's machine ## Quick start @@ -174,17 +183,18 @@ a shell alias so that `claude` itself goes through the pool. `jaynshare codex` does the same for Codex over the pool's ChatGPT accounts, added with `jaynshare account login --provider codex`. Codex still needs your -own `codex login`; the pool replaces it on every request. +own `codex login`; the pool replaces it on every request. On macOS, Codex's +own updater also works through the pool. -### Claude Desktop Chat on macOS +### Claude Desktop on macOS On an enrolled Mac, install Claude Desktop in `/Applications` or `~/Applications` and quit the app fully, then start the connection from a terminal. When the pool's CA is missing from macOS trust, the command shows its fingerprint and asks `Install CA globally (needed for Claude Desktop) [y/N]`. Answer `y` to install it in your login keychain and continue; Enter or `n` -cancels the launch. A staged replacement CA gets the same confirmation if it -is not already trusted. Desktop checks both roots before setup. +cancels the launch. During a CA rotation, the same confirmation also lists the +staged replacement CA if it is not trusted yet, and installs both. ```sh jaynshare desktop # Anthropic account picker @@ -193,98 +203,48 @@ jaynshare desktop --auto # automatic selection jaynshare desktop --log # one line per request, no monitor ``` -This command opens Desktop after its authenticated loopback Gateway and fixed -egress proxy are ready. Its managed runtime can download through that proxy on -first startup; Chat's connection test waits until the runtime is verified. -Keep the command running: `q`, Ctrl-C or closing its terminal stops the -connection. Its terminal shows the account in use, each Anthropic account's -5-hour and weekly usage in the picker's table, and the last message. The arrow -keys move through the table and Enter switches every conversation, open ones -included, from its next message; a moved conversation starts without its prompt -cache on the new account. With `--log`, -or when standard error is not a terminal, it prints one line per request instead. - -A second command with the same account and enrollment reuses the active adapter. -Changing accounts never requires quitting Desktop. With `--auto`, existing -sessions keep their server-side account binding; an exhausted account returns an -error instead of switching accounts by itself. - -Desktop versions are checked automatically. Jaynshare reads the managed runtime -version and bundle checksum from Desktop's installed bundle, checks the matching +The command opens Desktop once its local Gateway is ready. Keep it running: +`q`, Ctrl-C or closing its terminal stops the connection. Its terminal shows +the account in use, each Anthropic account's 5-hour and weekly usage, and the +last message. The arrow keys and Enter switch every conversation, open ones +included, from its next message, without quitting Desktop; a moved +conversation starts without its prompt cache. With `--log`, or when standard +error is not a terminal, it prints one line per request instead. A second +command with the same account and enrollment reuses the running one. With +`--auto`, existing sessions keep their account; an exhausted account returns +an error instead of switching by itself. + +Chat and Code go through the pool, with the models its accounts offer. +Attachments, Cowork, Chrome, connectors, projects, memory and artifacts are +untested. + +Desktop versions are checked automatically: each launch reads the managed +runtime's version and checksum from Desktop's bundle, checks the matching verified runtime and runs a synthetic streaming exchange against a temporary -local gateway. This check uses no pooled account, sends no user prompt and runs -once per adapter launch. On first startup it runs after runtime provisioning, -before engine inference is forwarded. Invalid bundle metadata, mismatched runtime -verification, failed checks, untrusted pool CAs and managed device policies -produce a clear error. Existing runtimes are checked before profile setup. -This verifies the engine's protocol, not every Desktop UI feature. Desktop's -private profile format and startup/title contracts can still change and require -a Jaynshare update. The native app blocks ordinary remote debugging and custom -test profiles, so this check does not drive the GUI. The 2.31226.0 profile and -startup/title contracts were inspected from its installed bundle, and its genuine -Claude Code 2.1.293 runtime passed the local streaming check. -An app or verified runtime replacement stops the adapter; quit Desktop -fully and relaunch the command to check compatibility again. - -The integration selects a named **Jaynshare** Gateway in Desktop's separate -`Claude-3p` profile. Desktop receives a fresh local bearer, while the Rust client -uses your enrollment and server identity pin internally. Its native -`egressProxyUrl` points at the same loopback listener; the relay adds the proxy -credential only on its connection to the server. Desktop requires macOS CA -trust and receives `NODE_EXTRA_CA_CERTS` for its child engine. Setup leaves the -system proxy untouched and installs missing CAs only after confirmation. Only -**Chat** is in scope. Desktop lists the models the pool's accounts offer through -`/v1/models`, and the upstream refuses those an account -cannot use; live Chat was checked with Sonnet 4.6. Text and explicitly -permitted local-file access were exercised in the compatibility experiment; -uploaded images, PDFs and text attachments, Cowork, Code, Chrome, connectors, -projects, memory and artifacts have not passed the native app release gates. -The managed engine's token-count requests use the same enrolled pool transport -as inference; Desktop can issue many independent counts for its context breakdown. -Connection warming is answered locally. The [gateway compatibility guide](https://code.claude.com/docs/en/llm-gateway-protocol) -describes the engine's optional endpoint behavior. -Request logs identify the operation: relayed token counts use `count_tokens` and -model listings `models`. Direct token counts outside the managed engine and -`title_fallback` return local `501`s with `x-should-retry: false` to avoid SDK retries. -A successful relayed request logs `operation=inference` -with status `200`; `unsupported_direct` identifies a request needing a compatibility -update. These labels contain no prompts, session identifiers or credentials. - -Public catalogs, signatures and runtime downloads at `downloads.claude.ai` use -an anonymous streaming server route that retains cache and range behavior. -WebFetch domain checks receive the real upstream response without a pool -credential; other page requests use opaque tunnels. The relay has no direct -fallback when the VPS is unavailable. Native app and engine routing, first-run -downloads and IPv4/IPv6 failure behavior still need a traffic audit; a strict -guarantee covering every process requires an OS egress policy. The Jaynshare -profile disables Desktop auto-updates; install a newer version manually, then -relaunch Jaynshare to run its compatibility checks. -Upgrading an existing profile requires stopping the adapter and quitting -Desktop fully before setup adds the proxy and update settings and enables model -discovery. Repeat the trust check and fully relaunch after CA rotation. - -Quit Desktop and stop the adapter before removing the integration: +local gateway, with no pooled account and no prompt of yours. Invalid bundles, +failed checks, untrusted pool CAs and managed device policies stop with a +clear error. A new Desktop can still change its private profile or startup +contracts and need a jaynshare update. The Jaynshare profile disables +Desktop's auto-updates: after installing a newer version by hand, an app or +runtime replacement, or a CA rotation, quit Desktop fully and run the command +again. + +Quit Desktop and stop the command before removing the integration; your other +Gateways, preferences and conversations stay: ```sh jaynshare desktop --restore ``` -Restore and client uninstall remove the local credential and Jaynshare entry, -restore owned selection fields only while they still match the installed -values, and preserve other Gateways, preferences and conversation history. -An interrupted setup can be retried or restored. A port collision leaves the -recorded origin in place; stop the competing process, or restore while Desktop -is closed before setting up again. Unknown direct auxiliary requests fail -locally; changed probe/title formats need a compatibility update. - -Live attachment/tool/permission checks, current-app startup/title/chat timings -and comparison with normal Desktop remain release gates. The server rollout -must also include the independent incomplete-TLS-handshake fix. +[Claude Desktop details](docs/desktop.md) covers how the connection works, +its limits and recovery. ## Roadmap / Ideas - [x] Rust v2 - [x] `jaynshare codex` +- [x] Claude Desktop on macOS +- [ ] Claude Desktop on Windows - [ ] OpenAI API-key accounts for `jaynshare codex` - [ ] API-key subscriptions from other providers, like OpenCode Go - [ ] Account features (settings, plugins, skills, MCP servers) when you draw @@ -299,6 +259,7 @@ must also include the independent incomplete-TLS-handshake fix. - [Is subscription sharing safe?](is_this_safe.md) - [Security and privacy model](docs/security-and-privacy.md) - [Server installation and operator obligations](deploy/README-server.md) +- [Claude Desktop details](docs/desktop.md) - [Release tooling](tools/release/README.md) - `jaynshare help` and `jaynshare help `: every verb, its options, exit codes and examples diff --git a/docs/desktop.md b/docs/desktop.md new file mode 100644 index 0000000..8cc4772 --- /dev/null +++ b/docs/desktop.md @@ -0,0 +1,62 @@ +# Claude Desktop details + +`jaynshare desktop` and its setup are in the [README](../README.md#claude-desktop-on-macos). +This page covers how the connection works, its limits and recovery. + +## How it connects + +The integration selects a named **Jaynshare** Gateway in Desktop's separate +`Claude-3p` profile. Desktop receives a fresh local bearer, while the client +uses your enrollment and server identity pin internally. Desktop's native +`egressProxyUrl` points at the same loopback listener; the relay adds the proxy +credential only on its connection to the server. Setup leaves the system proxy +untouched and installs a missing pool CA in your login keychain only after +confirmation; the [MITM scope](security-and-privacy.md#mitm-scope) covers the CA. + +Desktop lists the models the pool's accounts offer through `/v1/models`, and +the upstream refuses those an account cannot use. The managed engine's token +counts use the same pool transport as inference; Desktop can issue many +independent counts for its context breakdown. Connection warming is answered +locally. On first startup, Desktop's managed runtime downloads through the +proxy, and the connection test waits until that runtime is verified. + +## Compatibility check + +The check runs once per launch: before profile setup when the runtime is +already there, otherwise after Desktop provisions it and before any inference +is forwarded. It verifies the engine's protocol, not Desktop's interface: the +native app blocks remote debugging and custom test profiles, so the check +cannot drive it. Desktop 2.31226.0 with Claude Code 2.1.293 is the last +version whose profile and startup contracts were inspected. + +## Network + +Public catalogs, signatures and runtime downloads at `downloads.claude.ai` use +an anonymous streaming server route that keeps cache and range behavior. +WebFetch domain checks receive the real upstream response without a pool +credential; other page requests use opaque tunnels. The relay has no direct +fallback when the server is unavailable. Not every Desktop process is +guaranteed to use the Gateway or the proxy; a strict guarantee requires an OS +egress policy. + +## Request logs + +Each request line names its operation: `inference`, `count_tokens` for relayed +token counts and `models` for model listings. Token counts outside the managed +engine and `title_fallback` get a local `501` with `x-should-retry: false`. +`unsupported_direct` marks a request that needs a compatibility update. These +labels contain no prompts, session identifiers or credentials. + +## Setup, upgrade and restore + +One jaynshare installation at a time sets up Desktop; restore the other one +first, the quickstart's with `bash quickstart.sh down`. + +A profile set up by an earlier release is upgraded at the next setup; stop the +command and quit Desktop fully first. An interrupted setup can be retried or +restored. The recorded loopback port is reused: if another process holds it, +stop that process, or restore while Desktop is closed and set up again. + +Restore and client uninstall remove the local credential and the Jaynshare +entry, restore the selection fields only while they still match the installed +values, and keep other Gateways, preferences and conversation history. diff --git a/src/cli/help.rs b/src/cli/help.rs index 8bef8ad..c12ac37 100644 --- a/src/cli/help.rs +++ b/src/cli/help.rs @@ -75,7 +75,7 @@ pub(super) static DOCS: &[VerbDoc] = &[ "desktop", Engineer, None, - "Open macOS Claude Desktop Chat through a foreground Gateway that monitors the pool's accounts; its arrow keys and Enter switch account, and closing this command stops the connection. Quit Desktop fully before initial setup; missing pool CAs are installed in macOS trust only after confirmation", + "Open Claude Desktop on macOS through a foreground Gateway that monitors the pool's accounts; its arrow keys and Enter switch account, and closing this command stops the connection. Quit Desktop fully before initial setup; missing pool CAs are installed in macOS trust only after confirmation", [4, 5, 6, 7, 11, 15, 16], [ "jaynshare desktop", diff --git a/src/desktop/config.rs b/src/desktop/config.rs index 442c9c1..d4e70a4 100644 --- a/src/desktop/config.rs +++ b/src/desktop/config.rs @@ -11,6 +11,7 @@ use crate::client::ClientInstallation; use crate::state; const RECORD: &str = "desktop.json"; +const NAME: &str = "Jaynshare"; pub fn profile() -> PathBuf { crate::config::platform::home().join("Library/Application Support/Claude-3p") @@ -79,10 +80,11 @@ impl Integration { origin: String, selector: Option, ) -> Result { - let (config, meta) = documents()?; + let id = uuid::Uuid::new_v4().to_string(); + let (config, meta) = documents(&id)?; Ok(Self { version: 1, - id: uuid::Uuid::new_v4().to_string(), + id, origin, key: crate::secret::Secret::generate(crate::secret::Role::ClientSecret).into_string(), selector, @@ -114,7 +116,7 @@ impl Integration { } fn entry(&self) -> Value { - json!({"id": self.id, "name": "Jaynshare"}) + json!({"id": self.id, "name": NAME}) } fn gateway_path(&self) -> PathBuf { @@ -137,7 +139,7 @@ impl Integration { } pub fn installed(&self) -> Result { - let (config, meta) = documents()?; + let (config, meta) = documents(&self.id)?; Ok(config["deploymentMode"] == "3p" && meta["appliedId"] == self.id && meta["entries"] @@ -148,7 +150,7 @@ impl Integration { } pub fn install(&self) -> Result<(), String> { - let (mut config, mut meta) = documents()?; + let (mut config, mut meta) = documents(&self.id)?; let gateway_path = self.gateway_path(); let exists = gateway_path.exists(); let mut gateway = if exists { @@ -298,13 +300,22 @@ fn restore_field(document: &mut Value, field: &str, installed: &Value, before: & } } -fn documents() -> Result<(Value, Value), String> { +/// Refuses a managed policy and another installation's entry, whose restore would undo this one. +fn documents(id: &str) -> Result<(Value, Value), String> { let (config, meta) = profile_documents()?; if meta.get("hybridPointer").is_some() { return Err( "Desktop uses a managed Gateway policy; ask its administrator to configure it".into(), ); } + if meta["entries"] + .as_array() + .expect("validated entries") + .iter() + .any(|entry| entry["name"] == NAME && entry["id"] != id) + { + return Err("another jaynshare installation set up Desktop; restore it first".into()); + } Ok((config, meta)) } diff --git a/src/desktop/egress.rs b/src/desktop/egress.rs index 5c229be..e095c38 100644 --- a/src/desktop/egress.rs +++ b/src/desktop/egress.rs @@ -1,7 +1,7 @@ //! Loopback forward proxy with the enrollment credential added only at the next hop. use std::io::IsTerminal as _; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::Arc; use std::time::Duration; @@ -32,31 +32,68 @@ pub async fn check_trust(installation: &client::ClientInstallation) -> Result<() if installation.ca_fingerprint.as_deref() != Some(crate::bundle::fingerprint(&ca)?.as_str()) { return Err("the enrolled pool CA does not match its recorded fingerprint; re-enrol before Desktop setup".into()); } - for certificate in CertificateDer::pem_slice_iter(ca.as_bytes()) { - let certificate = certificate.map_err(|_| "the enrolled CA bundle is invalid")?; + let certificates = CertificateDer::pem_slice_iter(ca.as_bytes()) + .collect::, _>>() + .map_err(|_| "the enrolled CA bundle is invalid")?; + let mut roots = Vec::new(); + for (index, certificate) in certificates.iter().enumerate() { let path = installation .directory .join(format!("desktop-ca-check-{}.pem", uuid::Uuid::new_v4())); - let pem = crate::mitm::ca::pem("CERTIFICATE", &certificate); + let pem = crate::mitm::ca::pem("CERTIFICATE", certificate); crate::state::write_private_atomic(&path, pem.as_bytes()) .map_err(|e| format!("could not prepare the Desktop CA check: {e}"))?; - let result = trust_certificate(&path, &crate::mitm::ca::fingerprint(&certificate)).await; - std::fs::remove_file(&path) - .map_err(|e| format!("could not remove the Desktop CA check: {e}"))?; - result?; + roots.push(Root { + path, + fingerprint: crate::mitm::ca::fingerprint(certificate), + // `ca.pem` holds the presented CA, then any staged one. + role: if index == 0 { + "current" + } else { + "staged replacement" + }, + }); + } + trust(&roots).await +} + +/// One root of `ca.pem` in its own file for `security`, removed with it. +struct Root { + path: PathBuf, + fingerprint: String, + role: &'static str, +} + +impl Drop for Root { + fn drop(&mut self) { + let _ = std::fs::remove_file(&self.path); } - Ok(()) } -async fn trust_certificate(path: &Path, fingerprint: &str) -> Result<(), String> { - if trusted(path).await? { +async fn trust(roots: &[Root]) -> Result<(), String> { + let mut untrusted = Vec::new(); + for root in roots { + if !trusted(&root.path).await? { + untrusted.push(root); + } + } + if untrusted.is_empty() { return Ok(()); } if !std::io::stdin().is_terminal() { return Err("installing the pool CA globally for Claude Desktop requires confirmation in a terminal".into()); } - eprintln!("Pool CA fingerprint: {fingerprint}"); - eprintln!("This CA will be trusted by other applications using your macOS trust settings."); + for root in &untrusted { + eprintln!("Pool CA fingerprint: {} ({})", root.fingerprint, root.role); + } + eprintln!( + "{} will be trusted by other applications using your macOS trust settings.", + if untrusted.len() == 1 { + "This CA" + } else { + "These CAs" + } + ); let prompt = "Install CA globally (needed for Claude Desktop) [y/N] "; let confirmed = crate::cli::confirm(prompt).map_err(|failure| { failure.error["message"] @@ -69,11 +106,16 @@ async fn trust_certificate(path: &Path, fingerprint: &str) -> Result<(), String> "CA installation cancelled; Claude Desktop needs macOS trust for the pool CA".into(), ); } - crate::deploy::trust_store::add(path, fingerprint)?; - if !trusted(path).await? { - return Err(format!( - "macOS still does not trust pool CA {fingerprint} after installation" - )); + for root in &untrusted { + crate::deploy::trust_store::add(&root.path, &root.fingerprint)?; + } + for root in &untrusted { + if !trusted(&root.path).await? { + return Err(format!( + "macOS still does not trust pool CA {} after installation", + root.fingerprint + )); + } } Ok(()) } diff --git a/src/desktop/mod.rs b/src/desktop/mod.rs index b09eb9b..4bc12fa 100644 --- a/src/desktop/mod.rs +++ b/src/desktop/mod.rs @@ -1,4 +1,4 @@ -//! macOS Desktop Chat through a foreground native Gateway adapter. +//! Claude Desktop on macOS through a foreground native Gateway adapter. mod app; mod bundle; @@ -183,6 +183,11 @@ async fn serve(adapter: Arc, listener: TcpListener) -> Resul } let result = loop { tokio::select! { + // In a cooked terminal, Ctrl-C also interrupts a running `open`: stopping wins. + biased; + _ = &mut interrupt => break Ok(()), + _ = &mut termination => break Ok(()), + _ = quitting.recv() => break Ok(()), result = &mut open, if !opened => { if let Err(why) = result { break Err(why); } opened = true; @@ -203,9 +208,6 @@ async fn serve(adapter: Arc, listener: TcpListener) -> Resul _ = compatibility.tick() => { if let Err(why) = adapter.app.unchanged() { break Err(why); } } - _ = &mut interrupt => break Ok(()), - _ = &mut termination => break Ok(()), - _ = quitting.recv() => break Ok(()), } }; if let Some(refresh) = refresh { diff --git a/tests/acceptance/desktop.rs b/tests/acceptance/desktop.rs index 30fca93..2f6c23c 100644 --- a/tests/acceptance/desktop.rs +++ b/tests/acceptance/desktop.rs @@ -432,6 +432,63 @@ mod macos { assert!(desktop.record().exists()); } + #[tokio::test(flavor = "multi_thread")] + async fn desktop_asks_once_for_every_untrusted_root() { + let _leak_sweep = crate::leaks::LeakGuard::default(); + let mut instance = Instance::start_client("desktop-ca-both-confirmed").await; + instance.add_fsub(); + let desktop = Desktop::new(&instance).await; + assert_eq!( + instance.cli_json(&["ca", "rotate", "--yes"], None)["ok"], + true + ); + instance.restart(); + fs::write(desktop.tools.dir.join("security/0000/match"), "verify-cert").unwrap(); + fs::write(desktop.tools.dir.join("security/0000/times"), "2").unwrap(); + fs::write(desktop.tools.dir.join("security/0000/exit"), "1").unwrap(); + let tools = desktop.tools.env(); + let env: Vec<(&str, &str)> = tools + .iter() + .map(|(k, v)| (k.as_str(), v.as_str())) + .collect(); + let (code, transcript) = desktop.client.pty( + &["desktop", "--auto", "--log"], + &env, + &[ + ( + "Install CA globally (needed for Claude Desktop) [y/N]", + "y\n", + ), + ("keep this command open", "\x03"), + ], + ); + assert_eq!(code, 0, "{transcript}"); + assert_eq!(transcript.matches("Install CA globally").count(), 1); + assert!(transcript.contains("(current)"), "{transcript}"); + assert!(transcript.contains("(staged replacement)"), "{transcript}"); + assert!(transcript.contains("These CAs"), "{transcript}"); + let calls = desktop.tools.calls("security"); + assert_eq!( + calls + .iter() + .map(|call| call[0].as_str()) + .collect::>(), + [ + "verify-cert", + "verify-cert", + "add-trusted-cert", + "add-trusted-cert", + "verify-cert", + "verify-cert" + ] + ); + assert_eq!(calls[0][4], calls[2][5]); + assert_eq!(calls[1][4], calls[3][5]); + assert!(!Path::new(&calls[0][4]).exists()); + assert!(!Path::new(&calls[1][4]).exists()); + assert!(desktop.record().exists()); + } + #[tokio::test(flavor = "multi_thread")] async fn proxy_requests_never_forward_the_local_gateway_bearer() { let _leak_sweep = crate::leaks::LeakGuard::default(); @@ -1533,6 +1590,15 @@ esac ); assert_eq!(desktop.cli(&["desktop", "--auto"]).0, 1); assert!(!desktop.record().exists()); + // Another installation's entry, such as the quickstart's. + let other = Uuid::new_v4().to_string(); + let foreign = json!({"appliedId": other, "entries": [{"id": other, "name": "Jaynshare"}]}); + write_private(&meta_path, &foreign.to_string()); + let (code, _, error) = desktop.cli(&["desktop", "--auto"]); + assert_eq!(code, 1); + assert!(error.contains("another jaynshare installation"), "{error}"); + assert!(!desktop.record().exists()); + assert_eq!(read(&meta_path), foreign); fs::remove_file(meta_path).unwrap(); let mut running = desktop.spawn(&["desktop", "--auto"]); let gateway = desktop.ready(&mut running).await; diff --git a/tests/acceptance/leaks.rs b/tests/acceptance/leaks.rs index 63e696d..3bffecb 100644 --- a/tests/acceptance/leaks.rs +++ b/tests/acceptance/leaks.rs @@ -225,6 +225,12 @@ fn sweep_tree( fn allowed_surface(path: &Path) -> bool { path.ends_with("state/state.json") + // A server killed mid-write (Windows' `stop()`) leaves its atomic write's temporary. + || (path.parent().is_some_and(|dir| dir.ends_with("state")) + && path + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with(".state.json.") && name.ends_with(".tmp"))) || path.ends_with("home/.claude/.credentials.json") || path .ancestors() @@ -260,6 +266,11 @@ mod tests { "token sk-ant-oat-leak-test here", ) .expect("write the allowed surface"); + fs::write( + dir.join("state/.state.json.924.tmp"), + "token sk-ant-oat-leak-test here", + ) + .expect("write a killed server's temporary"); let needles = vec![("test token".to_owned(), "sk-ant-oat-leak-test".to_owned())]; let mut hits = Vec::new(); sweep_tree(&dir, &needle_forms(&needles), &mut hits); diff --git a/tools/quickstart.sh b/tools/quickstart.sh index 975e4ad..801f97c 100755 --- a/tools/quickstart.sh +++ b/tools/quickstart.sh @@ -10,11 +10,14 @@ # # Usage: quickstart.sh [--release[=]] [up] build or download, (re)start the server, update the client # quickstart.sh [--release] claude|codex [args] run `jaynshare claude` or `jaynshare codex` as the client +# quickstart.sh [--release] desktop [args] run `jaynshare desktop` on your real Claude Desktop # quickstart.sh [--release] op an operator verb on the server # quickstart.sh [--release] client # quickstart.sh [--release] logs | down # # The join offers to add your accounts; later, `client account login` adds one. +# `desktop` asks to trust the pool's CA in your login keychain, and points your +# Desktop at the pool until `down`; `client trust-ca remove` removes the CA. # The server home persists, so an account logged in once stays logged in. # Removing the scratch home's client/ joins the client again; removing it all starts over. set -euo pipefail @@ -64,15 +67,19 @@ as_server() { HOME="$SERVER_HOME" "$BIN" "$@"; } client_bin() { echo "$(config_root "$CLIENT_HOME")/bin/jaynshare"; } -as_client() { HOME="$CLIENT_HOME" "$(client_bin)" "$@"; } +as_client() { HOME="$CLIENT_HOME" PATH="$SCRATCH/bin:$PATH" "$(client_bin)" "$@"; } -# Claude Code calls `security` from PATH for its login; this one runs it with -# your real home, so it finds your keychain. Its first run is marked done, or -# Claude Code would ask for a login before looking. -prepare_claude() { +# `security` from PATH runs with your real home, so it finds your keychain. +prepare_security() { mkdir -p "$SCRATCH/bin" printf '#!/bin/bash\nHOME=%q exec /usr/bin/security "$@"\n' "$HOME" >"$SCRATCH/bin/security" chmod +x "$SCRATCH/bin/security" +} + +# Claude Code calls `security` for its login. Its first run is marked done, or +# Claude Code would ask for a login before looking. +prepare_claude() { + prepare_security python3 - "$CLIENT_HOME/.claude.json" <<'EOF' import json, os, sys path = sys.argv[1] @@ -83,6 +90,24 @@ if not config.get("hasCompletedOnboarding"): EOF } +link() { [ -L "$2" ] || ln -s "$1" "$2"; } + +# Desktop reads its profile in your real home, and its CA prompt installs into +# your real login keychain: these links point the client's home at them. +prepare_desktop() { + prepare_security + mkdir -p "$HOME/Library/Application Support/Claude-3p" + link "$HOME/Library/Application Support/Claude-3p" "$CLIENT_HOME/Library/Application Support/Claude-3p" + link "$HOME/Library/Keychains" "$CLIENT_HOME/Library/Keychains" + link "$HOME/Applications" "$CLIENT_HOME/Applications" +} + +# Desktop refuses its restore while it runs, and the server keeps running then. +restore_desktop() { + [ -f "$(config_root "$CLIENT_HOME")/client/desktop.json" ] || return 0 + as_client desktop --restore +} + # The launcher finds `codex` on PATH; this one runs it with your real home. prepare_codex() { local codex @@ -215,15 +240,16 @@ up() { else join_client fi - echo "pool up on $LISTEN (proxy $PROXY_LISTEN); $SELF claude or $SELF codex to use it" + echo "pool up on $LISTEN (proxy $PROXY_LISTEN); $SELF claude, $SELF codex or $SELF desktop to use it" } [ "$(uname)" = Darwin ] || die "the quickstart is macOS-only" case ${1:-up} in up) up ;; -down) stop_server ;; +down) restore_desktop && stop_server ;; logs) tail -f "$SCRATCH/server.log" ;; claude | codex) tool=$1; shift; "prepare_$tool"; HOME="$CLIENT_HOME" PATH="$SCRATCH/bin:$PATH" exec "$(client_bin)" "$tool" "$@" ;; +desktop) shift; prepare_desktop; as_client desktop "$@" ;; op) shift; as_server "$@" ;; client) shift; as_client "$@" ;; *) die "unknown command $1; see the usage at the top of $0" ;;