Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(security): keep connector secrets in the Keychain, out of every file

Alan Buscaglia8b29bab67cb2
diff --git a/README.md b/README.md
index 6418fb3..aa3fed2 100644
--- a/README.md
+++ b/README.md
@@ -145,9 +145,9 @@ A small Node daemon starts the agent engine (Gentle Shell, `gentle-shell --mode
## Security status
-What already holds: computer control's grant, panic stop, blocklist, rate limit, and risky-action confirmations are enforced by the desktop app, not the agent, and the agent's processes do not inherit the app's macOS permissions. Connectors are reached only through the assistant's own proxy, which hides what their mode does not allow. Approving a connector's action and changing a connector (its mode, connecting, removing, importing) happen only in the desktop app that started the assistant, in native dialogs, over a private channel the agent cannot open; in the browser those controls are read-only. Credentials are typed in the app, never in the chat, and the assistant cannot read them with its file tools.
+What already holds: computer control's grant, panic stop, blocklist, rate limit, and risky-action confirmations are enforced by the desktop app, not the agent, and the agent's processes do not inherit the app's macOS permissions. Connectors are reached only through the assistant's own proxy, which hides what their mode does not allow. Approving a connector's action and changing a connector (its mode, connecting, removing, importing) happen only in the desktop app that started the assistant, in native dialogs, over a private channel the agent cannot open; in the browser those controls are read-only. Credentials are typed in the app, never in the chat. On macOS, connector tokens, client secrets, and sign-ins live in the Keychain, in items the signed app creates, and reach the assistant only in memory over that private channel; they are never written to a file, and tokens from older versions move there once. Without the app, connectors that need a token stop working instead of falling back to a file.
-What does not yet: the agent has a shell, and its shell commands are checked on a best-effort basis only. Connector tokens live in files rather than the Keychain. Moving them to the Keychain, and protecting the connector settings file, are the next steps before a stable release.
+What does not yet: the agent has a shell, and its shell commands are checked on a best-effort basis only. The connector settings file is trusted when the assistant starts, and the app cannot yet tell its own Keychain items from ones another program of yours planted. Protecting the connector settings file is the next step before a stable release. On Linux, tokens go to the system keyring, which any program of yours can read while it is unlocked, and that path is not yet verified on a Linux desktop.
<div align="right"><a href="#top">Back to top</a></div>
diff --git a/apps/desktop/src-tauri/src/app_channel.rs b/apps/desktop/src-tauri/src/app_channel.rs
index 4e0e1bc..0828d57 100644
--- a/apps/desktop/src-tauri/src/app_channel.rs
+++ b/apps/desktop/src-tauri/src/app_channel.rs
@@ -11,8 +11,15 @@
//! `computer_register`, and `computer_unregister`. The daemon sends `approve` with an
//! [`ApprovalRequest`]; the app shows the native dialog on a worker thread (never the main thread)
//! and answers `{"approved": bool}`. A failed dialog, malformed request, or closed channel refuses.
+//!
+//! The daemon also keeps connector secrets in the app's secure store (S25.5), on worker threads too:
+//! `secret_get {id}` answers `{"secret": …}` or `null`, `secret_put {id, secret}` answers `{}`,
+//! `secret_delete {id}` answers `{"deleted": bool}`, and `secret_list` answers `{"ids": […]}`.
+//! Ids are checked with [`check_id`]; a refusal names what failed and never the secret, and nothing
+//! about a secret request is logged. The answer goes back over this channel only.
use crate::approvals::ApprovalRequest;
+use crate::secure_store::{check_id, Secret, SecretStore};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::HashMap;
@@ -78,6 +85,58 @@ pub trait Handler: Send + Sync {
fn approve(&self, request: &ApprovalRequest) -> bool;
/// The channel to a freshly spawned daemon is open (for example, register the computer helper).
fn opened(&self, _channel: &Arc<AppChannel>) {}
+ /// Where connector secrets live (the Keychain on macOS); `None` refuses secret requests.
+ fn secrets(&self) -> Option<&dyn SecretStore> {
+ None
+ }
+}
+
+/// The id (and, for `secret_put`, the secret) of a secret request. Shows the id only.
+pub(crate) struct SecretParams {
+ id: String,
+ secret: Option<Secret>,
+}
+
+impl std::fmt::Debug for SecretParams {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SecretParams").field("id", &self.id).field("secret", &self.secret).finish()
+ }
+}
+
+impl SecretParams {
+ /// Reads `{id, secret?}` by hand, so a refusal never repeats a value the daemon sent.
+ pub(crate) fn parse(params: &Value) -> Result<Self, String> {
+ let id = params.get("id").and_then(Value::as_str).ok_or("A secret request needs an id.")?;
+ check_id(id).map_err(|error| error.to_string())?;
+ let secret = match params.get("secret") {
+ None | Some(Value::Null) => None,
+ Some(Value::String(text)) => Some(Secret::new(text.as_str())),
+ Some(_) => return Err("A secret must be text.".into()),
+ };
+ Ok(SecretParams { id: id.to_owned(), secret })
+ }
+}
+
+/// Answers one secret request from `store`. Errors name what failed, never a secret.
+pub(crate) fn serve_secret(store: &dyn SecretStore, method: &str, params: &Value) -> Result<Value, String> {
+ if method == "secret_list" {
+ return store.list_ids().map(|ids| json!({ "ids": ids })).map_err(|error| error.to_string());
+ }
+ let request = SecretParams::parse(params)?;
+ let failed = |error: crate::secure_store::StoreError| error.to_string();
+ match method {
+ "secret_get" => Ok(match store.get(&request.id).map_err(failed)? {
+ Some(secret) => json!({ "secret": secret.expose() }),
+ None => Value::Null,
+ }),
+ "secret_put" => {
+ let secret = request.secret.as_ref().ok_or("A secret to store is needed.")?;
+ store.put(&request.id, secret).map_err(failed)?;
+ Ok(json!({}))
+ }
+ "secret_delete" => Ok(json!({ "deleted": store.delete(&request.id).map_err(failed)? })),
+ other => Err(format!("Unknown request: {other}")),
+ }
}
type Reply = mpsc::Sender<Result<Value, String>>;
@@ -199,6 +258,16 @@ impl AppChannel {
let approved = serde_json::from_value::<ApprovalRequest>(params).is_ok_and(|r| handler.approve(&r));
Frame::Response { id, result: Some(json!({"approved": approved})), error: None }
}
+ "secret_get" | "secret_put" | "secret_delete" | "secret_list" => {
+ let answer = match handler.secrets() {
+ Some(store) => serve_secret(store, method, &params),
+ None => Err("This app has no secure store for connector secrets.".into()),
+ };
+ match answer {
+ Ok(result) => Frame::Response { id, result: Some(result), error: None },
+ Err(error) => Frame::Response { id, result: None, error: Some(error) },
+ }
+ }
other => Frame::Response { id, result: None, error: Some(format!("Unknown request: {other}")) },
};
let _ = self.write(&frame);
@@ -210,6 +279,7 @@ mod tests {
use super::*;
use crate::approvals::fake::{Answer, FakePrompt};
use crate::approvals::{Approvals, Decision};
+ use crate::secure_store::{MemoryStore, MAX_ID_LEN};
use std::time::Instant;
/// The daemon's side of the pair, read and written frame by frame.
@@ -364,6 +434,86 @@ mod tests {
assert!(prompt.shown.lock().unwrap()[0].message.contains("channel: #general"));
}
+ /// A handler with the in-memory secure store, as the app has the Keychain.
+ #[derive(Default)]
+ struct WithStore {
+ store: MemoryStore,
+ }
+
+ impl Handler for WithStore {
+ fn approve(&self, _: &ApprovalRequest) -> bool {
+ false
+ }
+
+ fn secrets(&self) -> Option<&dyn SecretStore> {
+ Some(&self.store)
+ }
+ }
+
+ fn ask(daemon: &mut FakeDaemon, id: u64, method: &str, params: Value) -> Frame {
+ daemon.send(&Frame::Request { id, method: method.into(), params });
+ daemon.next()
+ }
+
+ #[test]
+ fn the_daemon_stores_reads_lists_and_deletes_secrets_in_the_apps_store() {
+ let handler = Arc::new(WithStore::default());
+ let (_channel, mut daemon) = pair(handler.clone());
+ let id = "connector/discord/value/token";
+ let ok = |id, result| Frame::Response { id, result: Some(result), error: None };
+ assert_eq!(ask(&mut daemon, 1, "secret_put", json!({"id": id, "secret": "xoxb-123"})), ok(1, json!({})));
+ assert_eq!(handler.store.get(id).unwrap().unwrap().expose(), "xoxb-123");
+ assert_eq!(ask(&mut daemon, 2, "secret_get", json!({"id": id})), ok(2, json!({"secret": "xoxb-123"})));
+ assert_eq!(ask(&mut daemon, 3, "secret_list", json!({})), ok(3, json!({"ids": [id]})));
+ assert_eq!(ask(&mut daemon, 4, "secret_delete", json!({"id": id})), ok(4, json!({"deleted": true})));
+ assert_eq!(ask(&mut daemon, 5, "secret_delete", json!({"id": id})), ok(5, json!({"deleted": false})));
+ // A missing secret is `"result": null` on the wire (which reads back as no result), not an error.
+ assert_eq!(ask(&mut daemon, 6, "secret_get", json!({"id": id})), Frame::Response { id: 6, result: None, error: None });
+ let line = serde_json::to_string(&Frame::Response { id: 6, result: Some(Value::Null), error: None }).unwrap();
+ assert_eq!(line, r#"{"kind":"response","id":6,"result":null}"#);
+ }
+
+ #[test]
+ fn secret_ids_are_checked_and_malformed_requests_refused_without_echoing_the_secret() {
+ let handler = Arc::new(WithStore::default());
+ let (_channel, mut daemon) = pair(handler.clone());
+ let refused = |frame: Frame| match frame {
+ Frame::Response { result: None, error: Some(error), .. } => error,
+ other => panic!("not refused: {other:?}"),
+ };
+ for (n, params) in [
+ json!({"id": "has space", "secret": "hunter2-secret"}),
+ json!({"id": "../x\n", "secret": "hunter2-secret"}),
+ json!({"id": "x".repeat(MAX_ID_LEN + 1), "secret": "hunter2-secret"}),
+ json!({"id": "ok/id", "secret": 7_123_456}),
+ json!({"id": "ok/id"}),
+ json!({"secret": "hunter2-secret"}),
+ json!("hunter2-secret"),
+ ]
+ .into_iter()
+ .enumerate()
+ {
+ let error = refused(ask(&mut daemon, n as u64 + 1, "secret_put", params));
+ assert!(!error.contains("hunter2") && !error.contains("7123456"), "{error}");
+ }
+ assert_eq!(refused(ask(&mut daemon, 20, "secret_get", json!({"id": "a b"}))), "invalid secret id");
+ assert!(handler.store.list_ids().unwrap().is_empty());
+
+ // An app without a secure store refuses every secret request.
+ let (_channel, mut bare) = pair(Arc::new(Recorder::default()));
+ assert!(refused(ask(&mut bare, 1, "secret_get", json!({"id": "ok/id"}))).contains("secure store"));
+ }
+
+ #[test]
+ fn secret_requests_and_their_answers_never_show_the_secret_in_debug_output() {
+ let params = SecretParams::parse(&json!({"id": "slack/bot", "secret": "xoxb-very-secret"})).unwrap();
+ let shown = format!("{params:?}");
+ assert!(shown.contains("slack/bot") && !shown.contains("xoxb"), "{shown}");
+ let store = MemoryStore::new();
+ serve_secret(&store, "secret_put", &json!({"id": "slack/bot", "secret": "xoxb-very-secret"})).unwrap();
+ assert!(!format!("{store:?}").contains("xoxb"));
+ }
+
#[test]
fn a_request_without_an_answer_times_out() {
let (channel, mut daemon) = pair(Arc::new(Recorder::default()));
diff --git a/apps/desktop/src-tauri/src/secure_store/macos.rs b/apps/desktop/src-tauri/src/secure_store/macos.rs
index 78d00bb..77c94c6 100644
--- a/apps/desktop/src-tauri/src/secure_store/macos.rs
+++ b/apps/desktop/src-tauri/src/secure_store/macos.rs
@@ -25,6 +25,19 @@
//! item's access list is the default one (only this app), even if another process created an
//! item under the same name first with a wider list. If an item reappears between the two
//! calls, `put` fails rather than write into it.
+//!
+//! What `get` can and cannot check (T23d, L110 advisory): whether an item was created by this
+//! app is recorded only in its access list, and `security-framework` 3.7 has no binding to read
+//! it (`SecKeychainItemCopyAccess`, `SecAccessCopyACLList`, `SecACLCopyContents`, and
+//! `SecTrustedApplicationCopyData` are deprecated file-keychain calls the crate leaves out).
+//! The attributes it can read (label, creator code, dates) are set by whoever adds the item, so
+//! checking them would prove nothing. So `get` does not verify the item: a same-user process
+//! could plant an item with an open access list before the first `put`, or delete one and plant
+//! its own. The daemon narrows this: it only reads ids it recorded after its own `put` (the
+//! `secretRef`s in `connectors.json`; T23e adds an HMAC to it), it never imports a sign-in file after
+//! the one-time migration, and every `put` replaces whatever item was there. An item planted
+//! with an access list that does not trust this app makes `get` ask the user through
+//! SecurityAgent ("Deny" fails closed).
use super::{check_id, wipe, Secret, SecretStore, StoreError, SERVICE};
use core_foundation::data::CFData;
diff --git a/apps/desktop/src-tauri/src/secure_store/mod.rs b/apps/desktop/src-tauri/src/secure_store/mod.rs
index b19bc0b..b1ee22a 100644
--- a/apps/desktop/src-tauri/src/secure_store/mod.rs
+++ b/apps/desktop/src-tauri/src/secure_store/mod.rs
@@ -1,6 +1,7 @@
//! Connector secrets in the OS secure store (S25.5, S25.7): OAuth tokens, bot tokens, client
//! secrets, and imported headers, keyed by a connector secret id. The app owns the store; the
-//! daemon gets a secret in memory over the app channel (wired in T23c), never from a file.
+//! daemon gets a secret in memory over the app channel (`secret_get`, `secret_put`,
+//! `secret_delete`, `secret_list` in `app_channel`, T23d), never from a file.
//!
//! - macOS (`Keychain`): generic password items in the login keychain, service
//! [`SERVICE`], account = the secret id, created by the app process. See `macos.rs` for how
@@ -106,6 +107,17 @@ pub trait SecretStore: Send + Sync {
fn list_ids(&self) -> Result<Vec<String>, StoreError>;
}
+/// The store the app serves connector secrets from: the login keychain on macOS, the Secret
+/// Service on Linux. Nothing is touched until the first request.
+pub fn connector_store() -> Box<dyn SecretStore> {
+ #[cfg(target_os = "macos")]
+ return Box::new(Keychain::new());
+ #[cfg(target_os = "linux")]
+ return Box::new(SecretServiceStore::new());
+ #[cfg(not(any(target_os = "macos", target_os = "linux")))]
+ return Box::new(MemoryStore::new());
+}
+
/// Accepts 1 to [`MAX_ID_LEN`] bytes of `[A-Za-z0-9._:@/-]`.
pub fn check_id(id: &str) -> Result<(), StoreError> {
let allowed = |c: char| c.is_ascii_alphanumeric() || "._:@/-".contains(c);
diff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rs
index ca1a904..291943a 100644
--- a/apps/desktop/src-tauri/src/shell.rs
+++ b/apps/desktop/src-tauri/src/shell.rs
@@ -12,6 +12,7 @@ use crate::daemon::{self, Daemon, RestartOutcome};
use crate::geometry::{self, Rect};
use crate::platform::{self, LaunchRequest, Os, DOT_TITLE, PANEL_TITLE};
use crate::position::{self, DotPosition};
+use crate::secure_store::{self, SecretStore};
use crate::shortcut;
use crate::status::{is_template, tray_status, TrayGlyph};
use crate::voice::app as voice;
@@ -121,11 +122,13 @@ fn read_connection_info(config: &DesktopConfig) -> CommandResult<ConnectionInfo>
Ok(config::connection_info(config.port, token.trim()))
}
-/// Serves the daemon's requests on the app channel: native approvals (S25.3), and registering the
-/// computer helper with a daemon this app just spawned (S24.7, L61).
+/// Serves the daemon's requests on the app channel: native approvals (S25.3), connector secrets
+/// from the secure store (S25.5), and registering the computer helper with a daemon this app just
+/// spawned (S24.7, L61).
struct ChannelService {
approvals: Approvals,
computer: Option<Endpoint>,
+ secrets: Box<dyn SecretStore>,
}
impl app_channel::Handler for ChannelService {
@@ -133,6 +136,10 @@ impl app_channel::Handler for ChannelService {
self.approvals.confirm(request) == Decision::Approved
}
+ fn secrets(&self) -> Option<&dyn SecretStore> {
+ Some(self.secrets.as_ref())
+ }
+
fn opened(&self, channel: &Arc<AppChannel>) {
let Some(endpoint) = self.computer.clone() else {
return;
@@ -775,6 +782,7 @@ pub fn run() {
let service = ChannelService {
approvals: Approvals::new(Arc::new(NativePrompt::new(handle.clone())), APPROVAL_TIMEOUT),
computer: computer.endpoint(),
+ secrets: secure_store::connector_store(),
};
app.manage(computer);
let runtime_dir = daemon::runtime_dir(|key| std::env::var(key).ok(), app.path().resource_dir().ok());
diff --git a/docs/design.md b/docs/design.md
index 3770067..d22b6cf 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -93,9 +93,9 @@ Client to daemon:
| `auth_login` | `providerId`, `method` (`oauth` \| `api_key`) | daemon `ModelRuntime.login()`; one flow at a time |
| `auth_reply` | `flowId`, `value` \| `cancelled` | answers the flow's current prompt |
| `auth_logout` | `providerId` | daemon `ModelRuntime.logout()` |
-| `connectors_list` | — | daemon `connectors.json` and `<data>/connector-signin/mcp-auth.json` key presence |
-| `connector_connect` | `connectorId` | adds or turns on the connector (new `mcp.json`, agent restart when idle), then `mcp login` when not signed in |
-| `connector_signin` | `connectorId` | `mcp login <id>`; one flow at a time |
+| `connectors_list` | — | daemon `connectors.json` (each sign-in is a reference to its item in the app's secure store) |
+| `connector_connect` | `connectorId` | adds or turns on the connector (new `mcp.json`, agent restart when idle), then the daemon's OAuth sign-in when not signed in |
+| `connector_signin` | `connectorId` | the daemon's OAuth sign-in (pi-mcp); one flow at a time |
| `connector_disconnect` | `connectorId` | turns it off (the sign-in stays); agent restart when idle |
| `connector_mode` | `connectorId`, `mode` (`read_only` \| `read_write`) | new `mcp.json`; agent restart when idle |
| `connector_remove` | `connectorId` | `mcp logout <id>`, then forgets it; agent restart when idle |
@@ -137,18 +137,19 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete
- Discord: the community server `npx -y @pasympa/[email protected]` (MIT, monthly releases, declares `readOnlyHint` on its tools; Discord has no official server), with the bot token in `env.DISCORD_TOKEN`. The guide covers the application, the bot, the Message Content and Server Members intents, and the invite (scope `bot` with read, send, and react permissions).
- Slack: the official `https://mcp.slack.com/mcp` (no dynamic client registration) with the user's own Slack app: `oauth.clientId`, an optional `oauth.clientSecret`, and the fixed redirect `http://localhost:38417/callback` (`oauth.callbackUrl`, sent exactly as written). Slack accepts a loopback redirect only with PKCE turned on, which makes the app a public client (refresh tokens last 30 days), so the secret may be left empty; the guide lists the user token scopes.
- Gmail: the official `https://gmailmcp.googleapis.com/mcp/v1` (Developer Preview) with the user's own Google Cloud project: the Gmail API and Gmail MCP API enabled, the consent screen in testing (refresh tokens last 7 days), and a Web application client with the redirect `http://localhost:38418/callback`; `oauth.scope` asks for `gmail.readonly` and `gmail.compose`. `gmail.compose` can also send mail, so the copy says so: drafting and sending ask for approval each time, and read only hides them. Each guided connector's copy describes only what its guide's permissions allow (Slack: send and schedule messages with `chat:write`; Discord: send messages and reactions).
-- Typed values (S18, S19): a connector's `fields` are asked one at a time with sign-in prompts (`auth_prompt` `secret` or `text`, flow id `connector-setup-*`, `optional` when the answer may be empty), in the window that started them. A catalog connector is added only when every required value is there (cancel changes nothing); an approved draft or an import is added first and stays `needs_setup` until its values are typed. The values live in the in-memory state and `connectors.json` (both protected), are written into the sign-in home's `mcp.json` in place of `${input:<key>}` placeholders (never into the engine's), and are never sent to a window or logged. Env values, headers, and `oauth.clientSecret` follow the engine's syntax (a leading `!` runs a shell command and `$NAME` expands), so typed and imported literals are escaped (`$` → `$$`, `!` → `$!`); the proxy resolves them the same way before it sends them upstream, so a typed value arrives exactly as typed. `clientId`, the command, its arguments, and URLs are used as written. `connector_setup` asks again (a new token). A connector whose value is missing is `needs_setup` and is left out of `mcp.json`.
-- Drafts (S19): the approval guard registers `propose_connector({name, description, transport, command?, args?, url?, env_names?, needs_oauth?})`, with secrets by name only. Its result to the model is only "The user will review this connector in the app". The draft travels to the daemon as `ctx.ui.setStatus("gentle-dot:connector-draft", <json>)`: a fire-and-forget record on the engine's own RPC output, which only the daemon reads (the agent's commands cannot write to it, and no file, socket, or key is added that the agent could reach). A typed value (`${input:NAME}`) may only stand for an env value (or an http server's header): anywhere else (the command, its arguments, the URL) it would put the secret into the command line or an address the model chose, so the guard answers the model "Secrets can only go into environment variables." and sends nothing, and the daemon refuses such a draft as well. The daemon checks it (lengths, `https` or loopback URLs, env names, typed values), keeps the newest five (`MAX_CONNECTOR_DRAFTS`; the windows keep the same five and take the waiting list again after each `ready`), and shows every window a card (`connector_draft`) with the command or URL and the secret names. `connector_draft_reply` decides: declining forgets it; approving adds the server (`origin` "Drafted by the assistant"), turned on, read only with every tool hidden (`toolExposure {"*": "hidden"}`, no curated list, so in "Read and send" every call asks), then asks for each secret in the app and signs in when `needs_oauth`. The assistant still cannot write `mcp.json` or run `mcp add` (guard), so the card is the only way in. Residual, as for the rest of the state (S25): `connectors.json` edited while the daemon is not running is loaded at its next start, and it can now hold a server of the user's own (a command).
-- Import (S20, `packages/daemon/src/connector-import.ts`): "Import my MCP servers" (`connectors_scan`) reads, never writes, the configs below the user's home (`GENTLE_DOT_IMPORT_HOME` in tests): Claude Desktop (`Library/Application Support/Claude/` and `.config/Claude/claude_desktop_config.json`), Claude Code (`.claude.json` `mcpServers`, its `projects[*].mcpServers`, and each project's `.mcp.json`), Cursor (`.cursor/mcp.json`), VS Code (`User/mcp.json` with `servers` and `inputs`, macOS and Linux), Windsurf (`.codeium/windsurf/mcp_config.json`, `serverUrl`), OpenCode (`.config/opencode/opencode.json`, `mcp` with command arrays and `environment`), and Gentle Shell (`.gentle-shell/agent/mcp.json`). Each entry maps to the engine's schema: `${VAR}` (Claude Code), `${env:VAR}` (VS Code, Cursor, Windsurf), and `{env:VAR}` (OpenCode) become `${VAR}`; `${userHome}` becomes the home folder; a VS Code `${input:id}` becomes a value the user types after the import; everything else is a literal. SSE servers (`type: "sse"`, or an address ending in `/sse`) are listed as not importable. The list (`connector_imports`) shows the name, the source apps, the command or address (`summary`), and env and header names only; values stay in the daemon. The summary, also shown for a custom connector in the Connectors list, is masked by structure, not by a word list: an address (an argument or the server URL, any scheme) keeps its scheme, host, and path, loses its user and password and its fragment, shows its query keys with every value as `•••`, and masks long opaque path segments (20 or more letters, digits, `_`, or `-`, mixing digits or cases); the argument after `--header`/`-H`, the value of `--header=`, and any `Name: value` argument whose name looks like a credential (Authorization, Cookie, `*key*`, `*token*`, `*secret*`, and so on) keep only the name; the argument after a flag named like a credential (`/token|secret|key|pass|auth|cred|bearer/i`) and the value of `name=value` forms of the same are masked; known token prefixes (`ghp_`, `sk-`, `xoxb-`, `AKIA`, `glpat-`, and others) and long opaque words are masked. Values the engine resolves at start are noted before the import (`notes`): "Runs a command on your computer to get this value." for a leading `!` (the command is not shown), and "Reads the environment variable NAME." for `$NAME`/`${NAME}`. Duplicates (the same command without npm versions, or the same URL) of a connector the user has, or of a catalog entry, are marked and cannot be imported. `connector_import` copies the chosen entries with their values into the private state, read only with every tool hidden, and never touches the source files.
-- The daemon holds the approved connector state (each connector's `enabled` and `mode`) in memory. It reads `<dataDir>/connectors.json` once, when it starts; after that the state changes only through the Connectors screen. The daemon is the only writer of `connectors.json`, `<agentHome>/mcp.json`, and the sign-in home's `mcp.json`, all rendered from memory, atomically, mode 0600. The sign-in home's `mcp-auth.json` changes only while a sign-in command runs or when the proxy saves a refreshed token; any other change is put back to what those left (or the file is removed when there was none). The engine's policy (below) also comes from memory, never from the files. The files are watched (folder watches plus a check every second, because file events on macOS can be missed right after a watch starts), and they are also checked before every agent start and after every run. A change made by anything else is put back, a project `<workspace>/.pi/mcp.json` is removed (a `.pi` link loses the link, never its target), and every window gets "A change to your connectors was blocked." Residual: a change made to the files while the daemon is not running is loaded at its next start; stage 2 (S25) moves enforcement out of the files. Every server is `exposure: "direct"` (the assistant turns codemode off). Read only is enforced by the proxy (above); the sign-in home's `mcp.json` still carries `toolExposure: {"*": "hidden", <curated tool>: "direct"}` for read only, as the engine would read it.
+- Typed values (S18, S19): a connector's `fields` are asked one at a time with sign-in prompts (`auth_prompt` `secret` or `text`, flow id `connector-setup-*`, `optional` when the answer may be empty), in the window that started them. A catalog connector is added only when every required value is there (cancel changes nothing); an approved draft or an import is added first and stays `needs_setup` until its values are typed. A secret value (a field marked `secret`) goes to the app's secure store (below, Secrets) and only its reference stays in memory and `connectors.json`; other values (a client id) stay in `connectors.json` (protected). Values fill the real server in the daemon's memory in place of `${input:<key>}` placeholders (never the engine's `mcp.json`) and are never sent to a window or logged. Env values, headers, and `oauth.clientSecret` follow the engine's syntax (a leading `!` runs a shell command and `$NAME` expands), so typed and imported literals are escaped (`$` → `$$`, `!` → `$!`); the proxy resolves them the same way before it sends them upstream, so a typed value arrives exactly as typed. `clientId`, the command, its arguments, and URLs are used as written. `connector_setup` asks again (a new token). A connector whose value is missing is `needs_setup` and is left out of `mcp.json`.
+- Drafts (S19): the approval guard registers `propose_connector({name, description, transport, command?, args?, url?, env_names?, needs_oauth?})`, with secrets by name only. Its result to the model is only "The user will review this connector in the app". The draft travels to the daemon as `ctx.ui.setStatus("gentle-dot:connector-draft", <json>)`: a fire-and-forget record on the engine's own RPC output, which only the daemon reads (the agent's commands cannot write to it, and no file, socket, or key is added that the agent could reach). A typed value (`${input:NAME}`) may only stand for an env value (or an http server's header): anywhere else (the command, its arguments, the URL) it would put the secret into the command line or an address the model chose, so the guard answers the model "Secrets can only go into environment variables." and sends nothing, and the daemon refuses such a draft as well. The daemon checks it (lengths, `https` or loopback URLs, env names, typed values), keeps the newest five (`MAX_CONNECTOR_DRAFTS`; the windows keep the same five and take the waiting list again after each `ready`), and shows every window a card (`connector_draft`) with the command or URL and the secret names. `connector_draft_reply` decides: declining forgets it; approving adds the server (`origin` "Drafted by the assistant"), turned on, read only with every tool hidden (no curated list, so the proxy shows none, and in "Read and send" every call asks), then asks for each secret in the app and signs in when `needs_oauth`. The assistant still cannot write `mcp.json` or run `mcp add` (guard), so the card is the only way in. Residual, as for the rest of the state (S25): `connectors.json` edited while the daemon is not running is loaded at its next start, and it can now hold a server of the user's own (a command).
+- Import (S20, `packages/daemon/src/connector-import.ts`): "Import my MCP servers" (`connectors_scan`) reads, never writes, the configs below the user's home (`GENTLE_DOT_IMPORT_HOME` in tests): Claude Desktop (`Library/Application Support/Claude/` and `.config/Claude/claude_desktop_config.json`), Claude Code (`.claude.json` `mcpServers`, its `projects[*].mcpServers`, and each project's `.mcp.json`), Cursor (`.cursor/mcp.json`), VS Code (`User/mcp.json` with `servers` and `inputs`, macOS and Linux), Windsurf (`.codeium/windsurf/mcp_config.json`, `serverUrl`), OpenCode (`.config/opencode/opencode.json`, `mcp` with command arrays and `environment`), and Gentle Shell (`.gentle-shell/agent/mcp.json`). Each entry maps to the engine's schema: `${VAR}` (Claude Code), `${env:VAR}` (VS Code, Cursor, Windsurf), and `{env:VAR}` (OpenCode) become `${VAR}`; `${userHome}` becomes the home folder; a VS Code `${input:id}` becomes a value the user types after the import; everything else is a literal. SSE servers (`type: "sse"`, or an address ending in `/sse`) are listed as not importable. The list (`connector_imports`) shows the name, the source apps, the command or address (`summary`), and env and header names only; values stay in the daemon. The summary, also shown for a custom connector in the Connectors list, is masked by structure, not by a word list: an address (an argument or the server URL, any scheme) keeps its scheme, host, and path, loses its user and password and its fragment, shows its query keys with every value as `•••`, and masks long opaque path segments (20 or more letters, digits, `_`, or `-`, mixing digits or cases); the argument after `--header`/`-H`, the value of `--header=`, and any `Name: value` argument whose name looks like a credential (Authorization, Cookie, `*key*`, `*token*`, `*secret*`, and so on) keep only the name; the argument after a flag named like a credential (`/token|secret|key|pass|auth|cred|bearer/i`) and the value of `name=value` forms of the same are masked; known token prefixes (`ghp_`, `sk-`, `xoxb-`, `AKIA`, `glpat-`, and others) and long opaque words are masked. Values the engine resolves at start are noted before the import (`notes`): "Runs a command on your computer to get this value." for a leading `!` (the command is not shown), and "Reads the environment variable NAME." for `$NAME`/`${NAME}`. Duplicates (the same command without npm versions, or the same URL) of a connector the user has, or of a catalog entry, are marked and cannot be imported. `connector_import` copies the chosen entries, read only with every tool hidden, and never touches the source files; their header and environment values go to the app's secure store (below, Secrets), with references in `connectors.json`. A credential inside an imported address or command-line argument stays where it is (masked when shown; a documented limit).
+- The daemon holds the approved connector state (each connector's `enabled` and `mode`) in memory. It reads `<dataDir>/connectors.json` once, when it starts; after that the state changes only through the Connectors screen. The daemon is the only writer of `connectors.json` and `<agentHome>/mcp.json`, both rendered from memory, atomically, mode 0600; neither holds a secret. The engine's policy (below) also comes from memory, never from the files. The files are watched (folder watches plus a check every second, because file events on macOS can be missed right after a watch starts), and they are also checked before every agent start and after every run. A change made by anything else is put back, a project `<workspace>/.pi/mcp.json` is removed (a `.pi` link loses the link, never its target), and every window gets "A change to your connectors was blocked." Residual: a change made to the files while the daemon is not running is loaded at its next start; stage 2 (S25) moves enforcement out of the files. Every server is `exposure: "direct"` (the assistant turns codemode off). Read only is enforced by the proxy (above).
- MCP proxy (S25.4, `packages/daemon/src/mcp-proxy.ts`): the engine's `<agentHome>/mcp.json` lists every connector as `{url: "http://127.0.0.1:<port>/mcp/<id>", headers: {Authorization: "Bearer <proxy key>"}, exposure: "direct", timeout: 300}` (plus `enabled: false` when turned off) and nothing else: no real address, token, environment, or command. The key is random, kept only in memory, and new for every engine launch; the proxy accepts it only in the `Authorization` header (401 otherwise, never from the address) and refuses any request with an `Origin`. It answers JSON-RPC 2.0 as plain `application/json` over POST, like the computer helper (GET is 405, notifications 202): `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list`, and `prompts/get`. Upstream, the daemon keeps one pi-mcp `McpClient` per connector, connected on first use: streamable HTTP for a remote server, with its headers and the stored sign-in (sent as a bearer token and refreshed after a 401 with the stored refresh token, never a new browser sign-in), or stdio for a server the daemon runs itself, with the engine's environment plus the server's values. A dropped connection is made again on the next request; turning a connector off, removing it, or changing its server or values closes it, and so does the daemon's shutdown. Every request reads the connector's state from the daemon's memory, so a mode change applies at once, without an engine restart (the engine still restarts to list newly allowed tools). Policy: `tools/list` shows in read only only the tools that declare `readOnlyHint: true` AND are on the curated list (the same `isReadOnlyTool` rule the guard uses), and every tool in "Read and send"; `tools/call` refuses a hidden or unknown tool with a JSON-RPC error however it is called, taking the annotations from the server's own list, never the caller; a sending action (any tool that is not read-only) is forwarded only after the user approves its preview (connector, action, and every argument, key fields first) in the desktop app's native dialog, asked over the app channel (below; `DotBridge.askInApp`); windows only show an informational card. Declining, no answer (the app declines after 120 s, the daemon gives up at 130 s), no app to ask, the app quitting while it asks, an answer that is stopped, or a connector changed while it was asked refuses it with a JSON-RPC error that says nothing was sent. Resources and prompts are reads: they are shown in "Read and send", and in read only only for a connector with a curated read-only list (the catalog's); a server of the user's own in read only exposes no resources or prompts, like its tools. Errors from the server are passed on with their code and message; a refused sign-in says to sign in again in Connectors; anything else says the connector could not be reached (the log masks addresses).
-- Sign-in home: the engine's `mcp login`/`mcp logout` read the server from `mcp.json`, so they run with `PI_CODING_AGENT_DIR=<data>/connector-signin` (0700), the daemon's own folder: its `mcp.json` (0600) holds the real servers in the engine's format, rendered from memory, and its `mcp-auth.json` (0600) the sign-ins in pi-mcp's OAuth state format, keyed `mcp__<id>|<url>`. The first start with the proxy moves `<agentHome>/mcp-auth.json` there once (the copy is read back before the old file is removed; a file that shows up there later is not taken over). T23d moves these secrets to the Keychain.
-- Sign-in runs the engine's own command line as a separate process, `node <pi-coding-agent>/dist/bundle/cli.js mcp login <id>`, with the agent's isolated environment and `PI_CODING_AGENT_DIR=<data>/connector-signin`. The daemon relays the printed authorization URL (`auth_event` `auth_url`) and offers a `manual_code` prompt: when the browser cannot reach this computer's loopback callback, the user pastes the address it ended on, and the daemon opens it locally only when its origin and path equal the authorization URL's `redirect_uri` and its `state` matches. Cancel stops the process by PID. Flow ids start with `connector-`, so `auth_reply` reaches the right flow; typed and printed text is never logged (URLs are masked).
-- Status: `needs_setup` while a typed value is missing; for servers that sign in with OAuth, `connected` when the sign-in home's `mcp-auth.json` holds tokens under `mcp__<id>|<url>` (the id with `-` as `_`, like the engine; token values are dropped while parsing) and `needs_signin` otherwise; `connected` for servers with a token or none; `error` after a failed sign-in.
-- App channel (S25.1–S25.3, `packages/daemon/src/app-channel.ts`, `apps/desktop/src-tauri/src/app_channel.rs`): when the desktop app spawns the daemon it creates a connected pair of Unix sockets and puts one end on the daemon's fd 3 (posix_spawn `adddup2` on macOS, with `POSIX_SPAWN_CLOEXEC_DEFAULT` closing every other descriptor; a `pre_exec` `dup2` on Linux); it keeps the other. The connection is the authentication: nothing is written to a file or an environment variable, and nothing listens. The daemon (`cli.ts`) opens fd 3 before it spawns anything, only when it is a socket and not Node's own IPC channel, and first checks that a child spawned the daemon's way would not hold it (a probe child compares the socket's identity on its fd 3); if one would, it closes it and runs without a channel. On macOS, libuv spawns with `POSIX_SPAWN_CLOEXEC_DEFAULT`, so the engine, stdio servers, and sign-in commands never get it (`app-channel-fd.test.ts`); Node cannot mark an inherited descriptor close-on-exec, which is why the probe checks rather than assumes. Frames are line-delimited JSON (`{"kind":"request","id","method","params"}`, `{"kind":"response","id","result"|"error"}`), each side numbering its own requests. The app sends `command {clientId, message}`, `computer_register {url, token}`, and `computer_unregister`; the daemon sends `approve` with `{connector, action, preview: [{name, value}], title?, summary?}` and gets `{approved}`. The app answers on a worker thread with T23b's `approvals` (one native dialog at a time, Decline the default, 120 s timeout); a malformed request, a dialog that fails, or the channel closing refuses.
+- Secrets (S25.5, `packages/daemon/src/secret-source.ts`): bot tokens, client secrets, imported header and environment values, and OAuth sign-ins live in the desktop app's secure store (macOS: Keychain items the signed app creates, service `dev.gentleman.gentle-dot.connectors`; `apps/desktop/src-tauri/src/secure_store`). The daemon asks for them over the app channel (`secret_get`, `secret_put`, `secret_delete`, `secret_list`, below) and keeps them in memory only, until the channel closes; no secret is written to a file or a log. `connectors.json` holds `{"secretRef": "<id>"}` in each secret's place, with ids `connector/<id>/value/<key>`, `connector/<id>/env/<NAME>`, `connector/<id>/header/<Name>`, `connector/<id>/client-secret`, and `connector/<id>/signin` (pi-mcp's OAuth state as JSON). In a server of the user's own, every environment value, header, and `oauth.clientSecret` is treated as a secret unless it only names a typed field. Before the proxy uses a connector it reads the secrets it refers to; the daemon only reads ids it recorded after its own `put`. Without the app (a daemon it only attached to, `pnpm dev`, the web), a connector that needs a secret fails closed with "Open the Gentle Dot app to use this connector." (the proxy answers it to every request), and a connector without secrets keeps working; there is no file fallback. Removing a connector deletes its items.
+- Migration (once, when the app's channel is there): text secrets still in `connectors.json`, then the sign-ins of the old sign-in home (`<data>/connector-signin/mcp-auth.json`, the daemon's own, which win) and of the engine's old `<agentHome>/mcp-auth.json` (keyed `mcp__<id>|<url>`), are stored, read back, and compared before they leave the files; if one fails, the files stay as they were and the next start tries again. A sign-in for a connector that is no longer added is dropped (counted in the log). The old sign-in home (its `mcp.json` held the real servers) is removed. A 0-byte sign-in file is removed and an unreadable one is left alone and reported; neither blocks the rest. `connectors.json` then says `version: 2`, and a sign-in file that appears afterwards is reported once and left alone, never imported (L114 N1). Until a text secret has moved it stays in the file and is not used. Nothing secret is logged.
+- Sign-in (S25.5, `packages/daemon/src/connector-oauth.ts`) runs in the daemon with pi-mcp's OAuth, as the engine's `mcp login` did (the CLI is no longer run): a stored refresh token signs in again without the browser; otherwise the authorization code flow (PKCE, dynamic client registration or the user's own client) against a loopback callback (`127.0.0.1`, a random port, or the connector's fixed redirect such as Slack's `http://localhost:38417/callback`). The whole flow keeps its state in memory; only the result is stored, once, with `secret_put`, and a refresh after a 401 stores the new tokens the same way. The daemon relays the authorization URL to the window that started it (`auth_event` `auth_url`, which opens the browser) and offers a `manual_code` prompt: when the browser cannot reach the loopback callback, the user pastes the address it ended on, and the daemon takes the code from it only when it is this sign-in's loopback address (port and path) with its `state`; nothing is fetched. Cancel closes the callback. Flow ids start with `connector-`, so `auth_reply` reaches the right flow; typed text and codes are never logged (URLs are masked).
+- Status: `needs_setup` while a typed value is missing; for servers that sign in with OAuth, `connected` when the connector refers to a stored sign-in with tokens and `needs_signin` otherwise; `connected` for servers with a token or none; `error` after a failed sign-in.
+- App channel (S25.1–S25.3, `packages/daemon/src/app-channel.ts`, `apps/desktop/src-tauri/src/app_channel.rs`): when the desktop app spawns the daemon it creates a connected pair of Unix sockets and puts one end on the daemon's fd 3 (posix_spawn `adddup2` on macOS, with `POSIX_SPAWN_CLOEXEC_DEFAULT` closing every other descriptor; a `pre_exec` `dup2` on Linux); it keeps the other. The connection is the authentication: nothing is written to a file or an environment variable, and nothing listens. The daemon (`cli.ts`) opens fd 3 before it spawns anything, only when it is a socket and not Node's own IPC channel, and first checks that a child spawned the daemon's way would not hold it (a probe child compares the socket's identity on its fd 3); if one would, it closes it and runs without a channel. On macOS, libuv spawns with `POSIX_SPAWN_CLOEXEC_DEFAULT`, so the engine, stdio servers, and sign-in commands never get it (`app-channel-fd.test.ts`); Node cannot mark an inherited descriptor close-on-exec, which is why the probe checks rather than assumes. Frames are line-delimited JSON (`{"kind":"request","id","method","params"}`, `{"kind":"response","id","result"|"error"}`), each side numbering its own requests. The app sends `command {clientId, message}`, `computer_register {url, token}`, and `computer_unregister`; the daemon sends `approve` with `{connector, action, preview: [{name, value}], title?, summary?}` and gets `{approved}`, and the secret requests `secret_get {id}` (`{secret}` or `null`), `secret_put {id, secret}`, `secret_delete {id}` (`{deleted}`), and `secret_list` (`{ids}`). The app answers on worker threads: approvals with T23b's `approvals` (one native dialog at a time, Decline the default, 120 s timeout), secrets from `secure_store` with ids checked (`check_id`), refusals that never repeat a value, and nothing logged; a malformed request, a dialog that fails, or the channel closing refuses.
- Privileged messages (S25.2, `APP_COMMANDS` in the protocol): `connector_connect`, `connector_signin`, `connector_setup`, `connector_disconnect`, `connector_remove`, `connector_mode`, `connector_draft_reply` approving, `connector_import`, `computer_register`, and `computer_unregister` are refused on the WebSocket (`error app_required`, "Open the Gentle Dot app to change connectors.") whoever sends them, the access key notwithstanding (L49). The desktop panel sends them with the `connector_command` Tauri command, which the app forwards over the channel with the panel's `clientId` (from `ready`; it only routes the sign-in steps and refusals to that window and authorizes nothing by itself). Every other message stays on the WebSocket: chat, history, accounts, profiles, models, uploads, `connectors_list`, `connectors_scan`, sign-in answers (`auth_reply`, owner-checked), and declining a draft. Changes that widen access are confirmed natively even though the app sent them: switching to "Read and send", connecting or setting up a connector that is off, approving a draft, and importing (each with what it adds); declining sends the window `error declined` and changes nothing. Narrowing (read only, disconnecting, removing) and signing in again need no dialog. Without a channel (an attached daemon, `pnpm dev`, the web, a VPS until T23h) these messages and every approval fail closed. Approvals the daemon asks show in every window as an `ask` with `method: "app"` ("Waiting for your answer in the Gentle Dot app."); `ui_response` to it is refused.
- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): the tools of a connector the proxy fronts (`proxied` in the policy: turned on and set up) pass, since the proxy filters them and asks itself; a card here would ask twice. A turned-off connector is not in `proxied` or the approved list, so its tools stay blocked here as well. For any other connector tool: it runs without asking only when it declares `readOnlyHint: true` AND it is on the curated list. Anything else asks through `ctx.ui.confirm`: an ask card ("Allow Notion to create pages?") with every argument, key fields first, up to 8,000 characters (beyond that it says "(truncated, N more characters)"), shown in a scrollable block. It is blocked when declined, when no one can answer, or when the connector is "Read only". A server outside the policy is blocked; without a valid policy every connector call asks.
-- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json` (where it was before the proxy), `models.json` (it can hold API keys), `mcp.json`, the sign-in home `<dataDir>/connector-signin` with its `mcp.json` and `mcp-auth.json`, `<dataDir>/connectors.json`, `<dataDir>/token`, and the guard itself. The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.
+- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json` (where it was before the proxy), `models.json` (it can hold API keys), `mcp.json`, the old sign-in home `<dataDir>/connector-signin` with its `mcp.json` and `mcp-auth.json` (gone after the migration, still protected in case they appear again), `<dataDir>/connectors.json`, `<dataDir>/token`, and the guard itself. The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.
- Stage 2 integrity (S25) must cover the user's own servers too. Today `connectors.json` is trusted when the daemon starts, so a file edited while the daemon is not running can add a custom or imported server that runs an arbitrary command, turn it on, claim any `origin` ("Imported from …", "Drafted by the assistant"), and carry env or header values that are not escaped (`!command`, `$NAME`), which the engine runs or expands at the next start. S25's integrity check (state the agent cannot write, or a signature it cannot forge) must cover every field of those entries: command, arguments, URL, env, headers, `enabled`, `mode`, and `origin`.
- Subagents are off in the assistant's engine (`GENTLE_PI_AGENTS=0`, §3): Gentle Shell's subagent child engines get only its own child extensions, not the approval guard, so a child could run connector tools or read credentials unchecked. Turning them back on needs S25 (enforcement in the daemon) or forwarding the guard to child engines. With the proxy (S25.4) a child's connector calls are filtered and approved by the daemon too; subagents stay off until T23f checks the rest (credential reads, a real-engine probe).
@@ -285,7 +286,7 @@ The user changes the main assistant's model from the chat, in the panel and the
- The daemon binds `127.0.0.1` only. A random 256-bit token is stored in `~/.gentle-dot/token` (mode 0600). The desktop app reads it; the browser receives it once by URL fragment.
- WebSocket upgrades check `Origin` against an allowlist (`http://127.0.0.1:4317`, `tauri://localhost`).
- The VPS guide requires HTTPS, a reverse proxy with authentication, and a dedicated Docker container with no access to personal machines.
-- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon: the MCP proxy (S25.4, done) keeps every token, real address, and server environment out of the engine's `mcp.json`, and enforces mode, hidden tools, and approvals in the daemon. Connector changes and approvals come only from the desktop app that launched the daemon, over its private channel, and are answered in native dialogs (§4, App channel); the WebSocket's access key no longer reaches them. Still open: the sign-ins are files in the daemon's sign-in home (Keychain in T23d), Linux children could inherit the channel if libuv there does not close it (the daemon then refuses it; T23g), and the proxy key is in the engine's `mcp.json`, so the agent's shell could call the proxy directly; that reaches only what the proxy allows, and every sending action still needs the user's approval.
+- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon: the MCP proxy (S25.4, done) keeps every token, real address, and server environment out of the engine's `mcp.json`, and enforces mode, hidden tools, and approvals in the daemon. Connector changes and approvals come only from the desktop app that launched the daemon, over its private channel, and are answered in native dialogs (§4, App channel); the WebSocket's access key no longer reaches them. Connector secrets (tokens, client secrets, imported headers, sign-ins) are in Keychain items the signed app creates and reach the daemon only in memory over that channel (S25.5, §4 Secrets); without the app, connectors that need one fail closed. What the Keychain cannot check: `security-framework` exposes no item access list, so the app cannot tell an item it created from one a same-user process planted (before the first `put`, or after deleting the app's); the daemon only reads ids it recorded, and every `put` replaces the item. Still open: `connectors.json` (with its references) is trusted at start until T23e signs it, Linux children could inherit the channel if libuv there does not close it (the daemon then refuses it; T23g), and the proxy key is in the engine's `mcp.json`, so the agent's shell could call the proxy directly; that reaches only what the proxy allows, and every sending action still needs the user's approval.
## 9. Desktop shell contract (Tauri 2 <-> UI)
@@ -371,4 +372,4 @@ On launch, the app checks `GET /health`. If the daemon does not answer, the app
All keys are optional. `workspace` is the user's preferred working folder: the engine is told about it but always runs in `<dataDir>/workspace`. Changing the shortcut in Settings rewrites `shortcut` and keeps every other key.
-Environment overrides: `GENTLE_DOT_AGENT_HOME` (default `~/.gentle-dot/agent`), `GENTLE_DOT_ENGRAM_DATA_DIR` (default: the user's Engram data folder), `GENTLE_DOT_ENGRAM` (`private` for a memory of the assistant's own), `GENTLE_DOT_ENGRAM_PORT` (private memory only, default `7438`), `GENTLE_DOT_PORT`, `GENTLE_DOT_HOST` (default `127.0.0.1`; `0.0.0.0` only inside a container), `GENTLE_DOT_DATA_DIR`, `GENTLE_DOT_WORKSPACE`, `GENTLE_DOT_UI_DIR`, `GENTLE_DOT_AGENT_BIN`, `GENTLE_DOT_AGENT_ARGS` (JSON array), `GENTLE_DOT_ALLOWED_ORIGINS` (JSON array), `GENTLE_DOT_CONVERSATIONS` (`1` turns the conversations list on), `GENTLE_DOT_ROTATE_BYTES` (default 20 MB), `GENTLE_DOT_ROTATE_COMPACTIONS` (default 10), `GENTLE_DOT_HISTORY_PAGE` (default 100), `GENTLE_DOT_MCP_CLI` (JSON array: the command line used for connector sign-in, for tests; default the bundled engine's).
+Environment overrides: `GENTLE_DOT_AGENT_HOME` (default `~/.gentle-dot/agent`), `GENTLE_DOT_ENGRAM_DATA_DIR` (default: the user's Engram data folder), `GENTLE_DOT_ENGRAM` (`private` for a memory of the assistant's own), `GENTLE_DOT_ENGRAM_PORT` (private memory only, default `7438`), `GENTLE_DOT_PORT`, `GENTLE_DOT_HOST` (default `127.0.0.1`; `0.0.0.0` only inside a container), `GENTLE_DOT_DATA_DIR`, `GENTLE_DOT_WORKSPACE`, `GENTLE_DOT_UI_DIR`, `GENTLE_DOT_AGENT_BIN`, `GENTLE_DOT_AGENT_ARGS` (JSON array), `GENTLE_DOT_ALLOWED_ORIGINS` (JSON array), `GENTLE_DOT_CONVERSATIONS` (`1` turns the conversations list on), `GENTLE_DOT_ROTATE_BYTES` (default 20 MB), `GENTLE_DOT_ROTATE_COMPACTIONS` (default 10), `GENTLE_DOT_HISTORY_PAGE` (default 100).
diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.ts
index 7e0a42d..0325214 100644
--- a/packages/daemon/src/bridge.ts
+++ b/packages/daemon/src/bridge.ts
@@ -481,7 +481,7 @@ export class DotBridge {
return;
this.deliver(client, {
type: "connector_imported",
- names: connectors.importServers(message.ids, plan.servers),
+ names: await connectors.importServers(message.ids, plan.servers),
});
return;
}
diff --git a/packages/daemon/src/connector-oauth.ts b/packages/daemon/src/connector-oauth.ts
new file mode 100644
index 0000000..b20f308
--- /dev/null
+++ b/packages/daemon/src/connector-oauth.ts
@@ -0,0 +1,220 @@
+/**
+ * A connector's OAuth sign-in, run by the daemon itself (S25.5) with pi-mcp's OAuth client, the way
+ * the engine's `mcp login` ran it before: a refresh when the stored tokens allow it, otherwise the
+ * authorization code flow (PKCE, dynamic client registration or the user's own client) against a
+ * loopback callback. The browser comes back to that callback, or the user pastes the address it
+ * landed on. The whole flow keeps its state in memory; the caller stores the result once, in the
+ * app's secure store, so nothing of it is ever written to a file.
+ */
+import { oauthErrorHtml, oauthSuccessHtml } from "@earendil-works/pi-ai/utils/oauth-page";
+import {
+ authorizeMcp,
+ McpOAuthProvider,
+ type McpOAuthState,
+ MemoryOAuthStateStore,
+ OAuthCallbackServer,
+ type OAuthClientInformationMixed,
+} from "@earendil-works/pi-mcp/oauth";
+
+const CALLBACK_HOST = "127.0.0.1";
+const CALLBACK_PATH = "/callback";
+export const CLIENT_NAME = "Gentle Dot";
+
+/** The user's own OAuth client and its fixed redirect, when the connector has one. */
+export interface OAuthSettings {
+ clientId?: string;
+ clientSecret?: string;
+ callbackUrl?: string;
+ callbackPort?: number;
+ scope?: string;
+}
+
+export interface SignInOptions {
+ serverUrl: string;
+ /** The sign-in stored so far (its client registration and tokens), if any. */
+ stored?: McpOAuthState;
+ settings: OAuthSettings;
+ /** The fetch for discovery, registration, and tokens; tests pass a stand-in. */
+ fetch?: typeof fetch;
+ /** The page the user approves access on; the window that started the sign-in opens it. */
+ onAuthorizationUrl(url: URL): void;
+}
+
+export interface SignIn {
+ /** The new sign-in (with its tokens), when it is done. */
+ done: Promise<McpOAuthState>;
+ /**
+ * An address the user pasted from the browser's address bar; false when it is not this sign-in's
+ * loopback address with its `state` (the sign-in keeps waiting).
+ */
+ paste(text: string): boolean;
+ cancel(): void;
+}
+
+export class SignInCancelledError extends Error {
+ constructor() {
+ super("Sign-in cancelled");
+ this.name = "SignInCancelledError";
+ }
+}
+
+function callbackSettings(settings: OAuthSettings) {
+ const url = new URL(settings.callbackUrl ?? `http://${CALLBACK_HOST}${CALLBACK_PATH}`);
+ const address = url.hostname.replace(/^\[|\]$/g, "");
+ const port = url.port ? Number(url.port) : settings.callbackPort;
+ let fixedRedirectUrl: string | undefined;
+ // A configured address with a port is sent exactly as written: servers compare it as a string.
+ if (url.port) fixedRedirectUrl = settings.callbackUrl;
+ else if (port !== undefined) {
+ url.port = String(port);
+ fixedRedirectUrl = url.href;
+ }
+ return {
+ // `localhost` is served on 127.0.0.1; browsers fall back to it when ::1 refuses.
+ host: address === "localhost" ? CALLBACK_HOST : address,
+ redirectHost: address,
+ port,
+ path: url.pathname,
+ fixedRedirectUrl,
+ };
+}
+
+const registeredRedirects = (client: OAuthClientInformationMixed | undefined) =>
+ client && "redirect_uris" in client ? client.redirect_uris : [];
+
+/** Listens on `port`, or on a free one when it is taken and not `required`. */
+async function listen(
+ callback: ReturnType<typeof callbackSettings>,
+ port: number | undefined,
+ required: boolean,
+) {
+ const options = {
+ host: callback.host,
+ redirectHost: callback.redirectHost,
+ path: callback.path,
+ renderPage: (page: { ok: true } | { ok: false; message: string; details?: string }) =>
+ page.ok
+ ? oauthSuccessHtml("Signed in. You can close this page and go back to Gentle Dot.")
+ : oauthErrorHtml(page.message, page.details),
+ };
+ try {
+ return await OAuthCallbackServer.listen({ ...options, port: port ?? 0 });
+ } catch (error) {
+ if (required || port === undefined) throw error;
+ return OAuthCallbackServer.listen(options);
+ }
+}
+
+/** Starts a sign-in; `done` settles when it finished, failed, or was cancelled. */
+export function startSignIn(options: SignInOptions): SignIn {
+ let expected: { redirect: URL; state: string } | undefined;
+ let fromUser: ((response: { code: string; iss?: string }) => void) | undefined;
+ let cancelled: (() => void) | undefined;
+ let isCancelled = false;
+ const pasted = new Promise<{ code: string; iss?: string }>((resolve) => {
+ fromUser = resolve;
+ });
+ const stopped = new Promise<never>((_resolve, reject) => {
+ cancelled = () => reject(new SignInCancelledError());
+ });
+ stopped.catch(() => {});
+
+ const done = (async () => {
+ const { serverUrl, stored, settings } = options;
+ const callbackOptions = callbackSettings(settings);
+ // The port of the registered redirect, so the registered client stays valid.
+ const registered = registeredRedirects(stored?.clientInformation)[0];
+ const preferredPort =
+ callbackOptions.port ?? (registered ? Number(new URL(registered).port) || undefined : undefined);
+ const callback = await listen(callbackOptions, preferredPort, callbackOptions.port !== undefined);
+ try {
+ if (isCancelled) throw new SignInCancelledError();
+ const redirectUrl = callbackOptions.fixedRedirectUrl ?? callback.redirectUrl;
+ const store = new MemoryOAuthStateStore();
+ if (stored) {
+ const next: McpOAuthState = { ...stored };
+ // Every sign-in gets a fresh `state`.
+ delete next.oauthState;
+ // A registered client cannot use another redirect, and its tokens belong to it.
+ const keepClient =
+ settings.clientId || registeredRedirects(stored.clientInformation).includes(redirectUrl);
+ if (!keepClient) {
+ delete next.clientInformation;
+ delete next.tokens;
+ delete next.tokensExpireAt;
+ }
+ store.save(next);
+ }
+ let authorizationUrl: URL | undefined;
+ const provider = new McpOAuthProvider({
+ serverUrl,
+ redirectUrl,
+ clientMetadata: { client_name: CLIENT_NAME },
+ ...(settings.clientId ? { clientId: settings.clientId } : {}),
+ ...(settings.clientSecret ? { clientSecret: settings.clientSecret } : {}),
+ store,
+ onRedirect: (url) => {
+ authorizationUrl = url;
+ },
+ });
+ const flow = {
+ serverUrl,
+ ...(settings.scope ? { scope: settings.scope } : {}),
+ ...(options.fetch ? { fetch: options.fetch } : {}),
+ };
+ // A stored refresh token signs in again without the browser.
+ if ((await Promise.race([authorizeMcp(provider, flow), stopped])) === "AUTHORIZED")
+ return finished(store);
+ if (!authorizationUrl) throw new Error("The sign-in did not produce an address to approve.");
+ const state = await provider.state();
+ const redirect = new URL(authorizationUrl.searchParams.get("redirect_uri") ?? redirectUrl);
+ expected = { redirect, state };
+ const fromBrowser = callback.waitForCallback(state, redirect.pathname);
+ fromBrowser.catch(() => {});
+ options.onAuthorizationUrl(authorizationUrl);
+ const { code, iss } = await Promise.race([fromBrowser, pasted, stopped]);
+ await Promise.race([
+ authorizeMcp(provider, { ...flow, authorizationCode: code, ...(iss ? { iss } : {}) }),
+ stopped,
+ ]);
+ return finished(store);
+ } finally {
+ expected = undefined;
+ await callback.close().catch(() => {});
+ }
+ })();
+
+ return {
+ done,
+ paste(text) {
+ const want = expected;
+ const url = URL.canParse(text.trim()) ? new URL(text.trim()) : undefined;
+ const loopback = url && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
+ const code = url?.searchParams.get("code");
+ if (
+ !want ||
+ !url ||
+ !loopback ||
+ url.protocol !== "http:" ||
+ url.port !== want.redirect.port ||
+ url.pathname !== want.redirect.pathname ||
+ url.searchParams.get("state") !== want.state ||
+ !code
+ )
+ return false;
+ const iss = url.searchParams.get("iss");
+ fromUser?.({ code, ...(iss ? { iss } : {}) });
+ return true;
+ },
+ cancel() {
+ isCancelled = true;
+ cancelled?.();
+ },
+ };
+}
+
+function finished(store: MemoryOAuthStateStore): McpOAuthState {
+ const state = store.load();
+ if (!state?.tokens?.access_token) throw new Error("The sign-in finished without a token.");
+ return state;
+}
diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.ts
index 09d6e12..3c6d291 100644
--- a/packages/daemon/src/connectors.ts
+++ b/packages/daemon/src/connectors.ts
@@ -1,12 +1,13 @@
-import { type ChildProcess, spawn } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import {
existsSync,
type FSWatcher,
lstatSync,
mkdirSync,
+ readdirSync,
readFileSync,
renameSync,
+ rmdirSync,
unlinkSync,
watch,
writeFileSync,
@@ -27,10 +28,11 @@ import type {
import { MAX_CONNECTOR_DRAFTS } from "@gentle-dot/protocol";
import { resolveRecord, resolveValue, storedSignIn } from "./connector-credentials.ts";
import { type ScannedServer, scanClientConfigs, valueNotes } from "./connector-import.ts";
+import { type OAuthSettings, type SignIn, SignInCancelledError, startSignIn } from "./connector-oauth.ts";
import { type ConnectorPolicy, draftSecretProblem, POLICY_ENV } from "./extensions/approval-guard.ts";
-import { ensurePrivateDir } from "./isolation.ts";
import type { ProxiedConnector, UpstreamCredentials } from "./mcp-proxy.ts";
import { runtimeDir, runtimeModules } from "./runtime.ts";
+import { NO_APP, type SecretSource, SecretsUnavailableError } from "./secret-source.ts";
/** A value the user types in the app (a token, client credentials); kept only in the assistant's private state. */
export interface SetupField {
@@ -73,7 +75,7 @@ export interface CatalogEntry {
server: ServerTemplate;
/** Values the user types before connecting. */
fields?: readonly SetupField[];
- /** Signs in through the engine's `mcp login` (OAuth). */
+ /** Signs in with OAuth (run by the daemon). */
oauth: boolean;
/** Steps shown before "Connect". */
guide?: ConnectorGuide;
@@ -347,9 +349,14 @@ export interface CustomConnector {
export interface SavedConnector {
enabled: boolean;
mode: ConnectorMode;
- /** The values the user typed, by field key; never sent to a window or written to the log. */
+ /**
+ * The values the user typed, by field key; never sent to a window or written to the log. A secret
+ * one is only a reference to its item in the app's secure store ({@link secretRef}).
+ */
values?: Record<string, string>;
custom?: CustomConnector;
+ /** The OAuth sign-in: a reference to its item in the app's secure store. */
+ signIn?: string;
}
export interface ConnectorsState {
@@ -398,6 +405,75 @@ export function literal(text: string): string {
const PLACEHOLDER = /\$\$|\$\{input:([A-Za-z0-9_.-]{1,64})\}/g;
+/**
+ * A secret in the daemon's memory is only a reference to its item in the app's secure store (S25.5):
+ * this prefix and the item's id. No typed or imported text can start with NUL. Files get
+ * `{"secretRef": "<id>"}` in its place, and the value itself is fetched from the app when needed.
+ */
+const REF = "\u0000secret-ref:";
+const SECRET_ID = /^[A-Za-z0-9._:@/-]{1,200}$/;
+/** The reference to the secret item `id`. */
+export const secretRef = (id: string) => `${REF}${id}`;
+const refId = (text: string) => (text.startsWith(REF) ? text.slice(REF.length) : undefined);
+
+/** A part of a secret id: as it is when the app accepts it, otherwise a hash of it. */
+const idPart = (text: string) =>
+ /^[A-Za-z0-9._-]{1,64}$/.test(text) ? text : createHash("sha256").update(text).digest("hex").slice(0, 32);
+/** Where a connector's secrets live in the app's store: `connector/<id>/…`. */
+export const secretPrefix = (connectorId: string) => `connector/${idPart(connectorId)}/`;
+const signInId = (connectorId: string) => `${secretPrefix(connectorId)}signin`;
+
+/** A value of a server of the user's own that is a secret: anything but an empty one or one with a field in it. */
+const FIELD_START = placeholder("").slice(0, -1);
+const secretText = (text: string) => text !== "" && !text.includes(FIELD_START);
+
+/**
+ * The connector with each secret it holds passed through `map(id, text)`: the values of secret
+ * fields, and for a server of the user's own its environment values, headers, and OAuth client
+ * secret (imported or drafted servers keep them in their entry). The sign-in is not included.
+ */
+function mapSecrets(
+ id: string,
+ saved: SavedConnector,
+ map: (secretId: string, text: string) => string,
+): SavedConnector {
+ const spec = specOf(id, saved);
+ const out = structuredClone(saved);
+ const prefix = secretPrefix(id);
+ if (out.values && spec)
+ for (const field of spec.fields) {
+ const text = out.values[field.key];
+ if (field.secret && text) out.values[field.key] = map(`${prefix}value/${idPart(field.key)}`, text);
+ }
+ const server = out.custom?.server;
+ const record = (entries: Record<string, string> | undefined, kind: string) => {
+ for (const [name, text] of Object.entries(entries ?? {}))
+ if (entries && typeof text === "string" && secretText(text))
+ entries[name] = map(`${prefix}${kind}/${idPart(name)}`, text);
+ };
+ if (server && "command" in server) record(server.env, "env");
+ else if (server) {
+ record(server.headers, "header");
+ const secret = server.oauth?.clientSecret;
+ if (server.oauth && secret && secretText(secret))
+ server.oauth.clientSecret = map(`${prefix}client-secret`, secret);
+ }
+ return out;
+}
+
+/** Every secret item a connector refers to, its sign-in included. */
+function refsOf(id: string, saved: SavedConnector): string[] {
+ const ids: string[] = [];
+ mapSecrets(id, saved, (_secretId, text) => {
+ const ref = refId(text);
+ if (ref) ids.push(ref);
+ return text;
+ });
+ const signIn = saved.signIn && refId(saved.signIn);
+ if (signIn) ids.push(signIn);
+ return ids;
+}
+
/** The server entry with the user's values in place, or undefined while a required one is missing. */
export function fillServer(
template: ServerTemplate,
@@ -500,34 +576,6 @@ export function renderMcpJson(
return `${JSON.stringify({ mcpServers: servers }, null, 2)}\n`;
}
-/**
- * The real servers, in the engine's format, for the daemon's own sign-in home: only the engine's
- * `mcp login` and `mcp logout` commands read it, never the engine that talks to the model. Read only
- * still hides every tool (`*`) except the curated ones, as the engine would have.
- */
-export function renderSigninMcpJson(state: ConnectorsState): string {
- const servers: Record<string, unknown> = {};
- for (const [id, saved] of ordered(state)) {
- const filled = filledServer(id, saved);
- if (!filled) continue;
- const { spec, server } = filled;
- servers[id] = {
- ...server,
- exposure: "direct",
- ...(saved.mode === "read_only"
- ? {
- toolExposure: {
- "*": "hidden",
- ...Object.fromEntries(spec.readOnlyTools.map((tool) => [tool, "direct"])),
- },
- }
- : {}),
- ...(saved.enabled ? {} : { enabled: false }),
- };
- }
- return `${JSON.stringify({ mcpServers: servers }, null, 2)}\n`;
-}
-
function writePrivate(path: string, text: string): void {
const temp = `${path}.${process.pid}.tmp`;
writeFileSync(temp, text, { mode: 0o600 });
@@ -538,6 +586,11 @@ export interface ConnectorStoreOptions {
dataDir: string;
/** The engine's home, which holds its `mcp.json` (and held `mcp-auth.json` before the proxy). */
agentHome: string;
+ /**
+ * Where the connectors' secrets live: the desktop app's secure store over its channel (S25.5).
+ * Without one, connectors that need a secret fail closed with {@link NO_APP}.
+ */
+ secrets?: SecretSource;
/** The environment the values of imported servers may read (`$NAME`); default the daemon's. */
env?: NodeJS.ProcessEnv;
/** The engine's working folder; a project `.pi/mcp.json` there would add servers. */
@@ -547,29 +600,36 @@ export interface ConnectorStoreOptions {
log?: (line: string) => void;
}
+/** What a remote connector's OAuth sign-in needs: its server, the user's own client, and the stored sign-in. */
+export interface SignInTarget {
+ serverUrl: string;
+ settings: OAuthSettings;
+ stored?: McpOAuthState;
+}
+
/**
* The connectors the user approved. The daemon reads `<data>/connectors.json` once, when it
* starts, and from then on the state lives in memory and changes only through the Connectors
- * screen. The files (`connectors.json`, the engine's `mcp.json`, and the sign-in home's `mcp.json`)
- * are written from memory; a change made by anything else (the assistant has a shell) is put back,
- * and a project `.pi/mcp.json` in the workspace is removed. The sign-ins (`mcp-auth.json`) change
- * only during a sign-in or a token refresh; other changes are put back too. Checked on every file
- * event, before every engine start, and after every run. A change made while the daemon is not
- * running is loaded at its next start (S25.6).
+ * screen. The files (`connectors.json` and the engine's `mcp.json`) are written from memory; a change
+ * made by anything else (the assistant has a shell) is put back, and a project `.pi/mcp.json` in the
+ * workspace is removed. Checked on every file event, before every engine start, and after every
+ * run. A change made while the daemon is not running is loaded at its next start (S25.6).
*
- * The engine's `mcp.json` lists only the daemon's proxy (S25.4). The real servers and the sign-ins
- * are in the daemon's own sign-in home (`<data>/connector-signin`), which only the engine's
- * `mcp login`/`mcp logout` commands are pointed at.
+ * Secrets (S25.5) are never in a file: `connectors.json` holds `{"secretRef": "<id>"}` in their
+ * place, the values live in the desktop app's secure store, and the daemon keeps the ones it read
+ * in memory until the app's channel closes. The engine's `mcp.json` lists only the daemon's proxy
+ * (S25.4). Secrets that files held before (`connectors.json`, the old sign-in home, and the
+ * engine's `mcp-auth.json`) move into the app's store once, with {@link ConnectorStore.migrate}.
*/
export class ConnectorStore {
readonly file: string;
readonly mcpFile: string;
- /** The daemon's own folder for the sign-in command: the real servers and the sign-ins. */
+ /** Where the daemon kept the real servers and the sign-ins before T23d; removed once migrated. */
readonly signinHome: string;
readonly signinMcpFile: string;
- /** The sign-ins (pi-mcp's OAuth state by `mcp__<server>|<url>`), in the sign-in home. */
+ /** The sign-ins of the old sign-in home (pi-mcp's OAuth state by `mcp__<server>|<url>`). */
readonly authFile: string;
- /** Where the engine kept the sign-ins before the proxy; moved once into the sign-in home. */
+ /** Where the engine kept the sign-ins before the proxy. */
readonly legacyAuthFile: string;
/** Called after a change made outside the Connectors screen was put back. */
onReverted: () => void = () => {};
@@ -580,10 +640,17 @@ export class ConnectorStore {
private computer: ComputerEndpoint | undefined;
/** The daemon's proxy for the running engine; only in memory and `mcp.json`. */
private proxy: ProxyEndpoint | undefined;
- /** The sign-ins as the last sign-in or refresh left them (undefined: no file). */
- private authText: string | undefined;
- /** Sign-in commands running now; they write the sign-ins themselves. */
- private signins = 0;
+ /** Secrets read from or stored in the app's store, by id; only in memory. */
+ private readonly cache = new Map<string, string>();
+ /** Secrets `connectors.json` still holds as text, by the id they move to; kept in the file until then. */
+ private readonly pending = new Map<string, string>();
+ /** True once the sign-in files were moved (`version: 2`); files that appear later are not imported. */
+ private migrated: boolean;
+ private migrating: Promise<void> | undefined;
+ /** Stores still running (a secret sealed by {@link update}). */
+ private readonly writes = new Set<Promise<unknown>>();
+ /** Sign-in files that appeared after the move and were reported. */
+ private readonly reported = new Set<string>();
private watchers: FSWatcher[] = [];
private readonly options: ConnectorStoreOptions;
@@ -595,10 +662,11 @@ export class ConnectorStore {
this.signinMcpFile = join(this.signinHome, "mcp.json");
this.authFile = join(this.signinHome, "mcp-auth.json");
this.legacyAuthFile = join(options.agentHome, "mcp-auth.json");
- this.moveLegacySignIns();
- this.authText = readOrUndefined(this.authFile);
- const { state, renamed } = this.load();
+ const { state, renamed, version } = this.load();
this.saved = state;
+ // A new install has nothing to move.
+ this.migrated =
+ version >= 2 || (version === 0 && ![this.authFile, this.legacyAuthFile].some((f) => existsSync(f)));
if (renamed) writePrivate(this.file, this.recordText());
}
@@ -610,16 +678,84 @@ export class ConnectorStore {
return structuredClone(this.saved);
}
- /** Changes the state, then writes the files (each atomically, mode 0600). */
+ /**
+ * Changes the state, then writes the files (each atomically, mode 0600). A secret the change put
+ * in as text is stored in the app's store and replaced by its reference first; without the app it
+ * is dropped (the connector then needs it again).
+ */
update(change: (state: ConnectorsState) => void): void {
const state = this.state();
change(state);
+ for (const [id, saved] of Object.entries(state.connectors))
+ state.connectors[id] = mapSecrets(id, saved, (secretId, text) =>
+ refId(text) !== undefined ? text : this.seal(secretId, text),
+ );
this.saved = state;
mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });
- ensurePrivateDir(this.signinHome);
writePrivate(this.file, this.recordText());
writePrivate(this.mcpFile, this.engineMcpText());
- writePrivate(this.signinMcpFile, renderSigninMcpJson(state));
+ this.onUpdated();
+ }
+
+ /** Waits for the secrets {@link update} is still storing. */
+ async settled(): Promise<void> {
+ while (this.writes.size > 0) await Promise.allSettled([...this.writes]);
+ }
+
+ /**
+ * Stores the values the user typed for a connector: the secret ones in the app's store (only
+ * their references in memory and `connectors.json`), the others as they are. A secret left empty
+ * removes its item. Rejects without the app, and then nothing changes.
+ */
+ async keepValues(id: string, values: Record<string, string>): Promise<void> {
+ const current = this.saved.connectors[id] ?? { enabled: false, mode: "read_only" };
+ const spec = specOf(id, current);
+ if (!spec) throw new Error(`The connector ${id} is not available.`);
+ const prefix = secretPrefix(id);
+ const kept: Record<string, string> = {};
+ for (const [key, value] of Object.entries(values)) {
+ const field = spec.fields.find((f) => f.key === key);
+ const secretId = `${prefix}value/${idPart(key)}`;
+ if (!field?.secret) kept[key] = value;
+ else if (value) {
+ await this.keep(secretId, value);
+ kept[key] = secretRef(secretId);
+ } else {
+ kept[key] = "";
+ await this.secrets().delete(secretId);
+ this.cache.delete(secretId);
+ }
+ }
+ this.update((state) => {
+ state.connectors[id] = { ...(state.connectors[id] ?? current), values: kept };
+ });
+ }
+
+ /** Forgets a connector's secrets in the app's store (when it is removed); the state is not changed. */
+ async forget(id: string): Promise<void> {
+ const prefix = secretPrefix(id);
+ for (const key of [...this.cache.keys(), ...this.pending.keys()])
+ if (key.startsWith(prefix)) {
+ this.cache.delete(key);
+ this.pending.delete(key);
+ }
+ const source = this.options.secrets;
+ if (!source?.available) {
+ this.log(`the secrets of connector ${id} stay in the app's secure store: the app is not connected`);
+ return;
+ }
+ try {
+ for (const secretId of await source.list())
+ if (secretId.startsWith(prefix)) await source.delete(secretId);
+ } catch (error) {
+ this.log(`could not remove the secrets of connector ${id}: ${(error as Error).message}`);
+ }
+ }
+
+ /** Forgets every secret read so far (the app's channel closed); the next use asks the app again. */
+ lock(): void {
+ if (this.cache.size === 0) return;
+ this.cache.clear();
this.onUpdated();
}
@@ -642,11 +778,21 @@ export class ConnectorStore {
return true;
}
- /** A connector as the proxy sees it, from the state in memory; undefined when it cannot run. */
+ /** Reads a connector's secrets from the app before the proxy uses it; failures leave it locked. */
+ async prepare(id: string): Promise<void> {
+ await this.unlock(id).catch(() => {});
+ }
+
+ /**
+ * A connector as the proxy sees it, from the state in memory; undefined when it cannot run. When
+ * a secret it needs is not in memory (no app, or its item is gone), `unavailable` says why.
+ */
proxyView(id: string): ProxiedConnector | undefined {
const saved = this.saved.connectors[id];
- const filled = saved && filledServer(id, saved);
- if (!saved || !filled) return undefined;
+ if (!saved) return undefined;
+ const { open, locked } = this.open(id, saved);
+ const filled = filledServer(id, open);
+ if (!filled) return undefined;
const { spec, server } = filled;
return {
id,
@@ -663,19 +809,21 @@ export class ConnectorStore {
...(server.cwd !== undefined ? { cwd: server.cwd } : {}),
},
// The server with its values: a new token or address makes a new connection.
- revision: createHash("sha256").update(JSON.stringify(server)).digest("hex"),
+ revision: createHash("sha256")
+ .update(JSON.stringify(server))
+ .update(locked ?? "")
+ .digest("hex"),
+ ...(locked ? { unavailable: locked } : {}),
};
}
/**
* What the proxy adds to the real server: the values the user typed (headers, a stdio server's
* environment) as they were typed, and for a remote server without its own Authorization header,
- * the stored sign-in, refreshed when it expires.
+ * the stored sign-in, refreshed when it expires (the new tokens go to the app's store).
*/
async credentials(id: string): Promise<UpstreamCredentials> {
- const filled = filledServer(id, this.saved.connectors[id]);
- if (!filled) throw new Error(`The connector ${id} is not set up.`);
- const { spec, server } = filled;
+ const { spec, server } = await this.unlocked(id);
const env = this.options.env ?? process.env;
if ("command" in server) {
const resolved = resolveRecord(server.env, env, spec.name);
@@ -686,42 +834,65 @@ export class ConnectorStore {
(h) => h.toLowerCase() === "authorization",
);
if (ownAuthorization) return headers ? { headers } : {};
- const key = authKey(id, server.url);
- const { oauth } = server;
const authProvider = storedSignIn(
server.url,
- { load: () => this.signIn(key), save: (state) => this.saveSignIn(key, state) },
- () => ({
- ...(oauth?.clientId ? { clientId: oauth.clientId } : {}),
- ...(oauth?.clientSecret
- ? { clientSecret: resolveValue(oauth.clientSecret, env, `${spec.name} client secret`) }
- : {}),
- ...(oauth?.callbackUrl ? { redirectUrl: oauth.callbackUrl } : {}),
- }),
+ { load: () => this.signInState(id), save: (state) => this.saveSignIn(id, state) },
+ () => {
+ const { clientId, clientSecret, callbackUrl } = oauthSettings(spec.name, server, env);
+ return {
+ ...(clientId ? { clientId } : {}),
+ ...(clientSecret ? { clientSecret } : {}),
+ ...(callbackUrl ? { redirectUrl: callbackUrl } : {}),
+ };
+ },
);
return { ...(headers ? { headers } : {}), authProvider };
}
- /**
- * While the engine's sign-in command runs, it writes the sign-ins itself; call the returned
- * function when it ended, so what it wrote is kept.
- */
- signingIn(): () => void {
- this.signins++;
- let done = false;
- return () => {
- if (done) return;
- done = true;
- this.signins--;
- this.authText = readOrUndefined(this.authFile);
+ /** What a sign-in to a remote connector needs; rejects when its secrets cannot be read. */
+ async signInTarget(id: string): Promise<SignInTarget> {
+ const { spec, server } = await this.unlocked(id);
+ if (!("url" in server)) throw new Error(`${spec.name} does not use a sign-in.`);
+ const stored = this.signInState(id);
+ return {
+ serverUrl: server.url,
+ settings: oauthSettings(spec.name, server, this.options.env ?? process.env),
+ ...(stored ? { stored } : {}),
};
}
+ /** Stores a sign-in (new, or refreshed) in the app's store and refers to it from the state. */
+ async saveSignIn(id: string, state: McpOAuthState): Promise<void> {
+ const secretId = signInId(id);
+ await this.keep(secretId, JSON.stringify(state));
+ if (this.saved.connectors[id] && this.saved.connectors[id].signIn !== secretRef(secretId))
+ this.update((current) => {
+ const saved = current.connectors[id];
+ if (saved) saved.signIn = secretRef(secretId);
+ });
+ }
+
/** The helper's address while it is registered (never its key). */
computerUrl(): string | undefined {
return this.computer?.url;
}
+ /**
+ * Moves the secrets files still hold into the app's store, once the app is there (S25.5): text
+ * secrets in `connectors.json`, then the sign-ins of the old sign-in home and of the engine's old
+ * `mcp-auth.json` (the daemon's own win). Each one is stored, read back, and compared before the
+ * file loses it; when one fails, the files stay as they were and the next start tries again. A
+ * file that is empty or cannot be read is skipped and does not stop the rest. Afterwards
+ * `connectors.json` says so (`version: 2`), and sign-in files that appear later are reported once
+ * and left alone, never imported. Nothing secret is logged.
+ */
+ migrate(): Promise<void> {
+ this.migrating ??= this.runMigration().finally(() => {
+ this.migrating = undefined;
+ });
+ return this.migrating;
+ }
+
/**
* Puts back every connector file that differs from the approved state; true when one did.
* `report: false` only writes them (the daemon's start, where the files are what it just read).
@@ -734,25 +905,15 @@ export class ConnectorStore {
for (const [file, text, empty] of [
[this.file, this.recordText(), noConnectors],
[this.mcpFile, this.engineMcpText(), noConnectors && !this.computer],
- [this.signinMcpFile, renderSigninMcpJson(this.saved), noConnectors],
] as const) {
const current = readOrUndefined(file);
if (current === text || (current === undefined && empty)) continue;
mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });
- ensurePrivateDir(this.signinHome);
writePrivate(file, text);
changed.push(file);
}
- // The sign-ins change only through a sign-in or a refresh.
- if (this.signins === 0 && readOrUndefined(this.authFile) !== this.authText) {
- if (this.authText === undefined) unlinkSync(this.authFile);
- else {
- ensurePrivateDir(this.signinHome);
- writePrivate(this.authFile, this.authText);
- }
- changed.push(this.authFile);
- }
if (this.removeProjectConfig()) changed.push("the workspace's .pi/mcp.json");
+ this.reportPlanted();
if (changed.length === 0 || !report) return changed.length > 0;
this.options.log?.(
`connector files were changed outside the Connectors screen; put back ${changed.join(", ")}`,
@@ -779,8 +940,7 @@ export class ConnectorStore {
this.watchProjectConfig();
}, 20);
};
- ensurePrivateDir(this.signinHome);
- const folders = [this.options.dataDir, this.options.agentHome, this.signinHome, this.options.workspace];
+ const folders = [this.options.dataDir, this.options.agentHome, this.options.workspace];
for (const folder of folders) {
if (!folder) continue;
mkdirSync(folder, { recursive: true, mode: 0o700 });
@@ -802,6 +962,7 @@ export class ConnectorStore {
/**
* What the approval guard enforces: the turned-on connectors, which of them the proxy fronts (it
* filters and asks, so the guard lets their tools through), and the files only the daemon writes.
+ * The old sign-in files stay protected in case they appear again.
*/
policy(): ConnectorPolicy {
const connectors: NonNullable<ConnectorPolicy["connectors"]> = {};
@@ -832,86 +993,249 @@ export class ConnectorStore {
};
}
- /**
- * True when the sign-in command stored tokens for the connector (key `mcp__<server>|<url>`, `-`
- * as `_`). Token values are dropped while parsing, so they are never kept or passed on.
- */
+ /** True when the connector has a stored sign-in with tokens. No token value is kept or passed on. */
isSignedIn(id: string): boolean {
- const server = filledServer(id, this.saved.connectors[id])?.server;
- if (!server || !("url" in server) || !URL.canParse(server.url) || !existsSync(this.authFile))
- return false;
- try {
- const states = JSON.parse(readFileSync(this.authFile, "utf8"), (key, value) =>
- key === "tokens" && typeof value === "object" && value !== null ? {} : value,
- ) as Record<string, { tokens?: unknown } | undefined>;
- return typeof states[authKey(id, server.url)]?.tokens === "object";
- } catch {
- return false;
+ const saved = this.saved.connectors[id];
+ const ref = saved?.signIn && refId(saved.signIn);
+ if (!ref) return false;
+ const text = this.cache.get(ref);
+ // Stored only once it had tokens; until it is read again it counts as signed in.
+ if (text === undefined) return true;
+ return typeof this.signInState(id)?.tokens?.access_token === "string";
+ }
+
+ private secrets(): SecretSource {
+ const source = this.options.secrets;
+ if (!source?.available) throw new SecretsUnavailableError();
+ return source;
+ }
+
+ /** Stores a secret in the app's store and keeps it in memory. */
+ private async keep(id: string, secret: string): Promise<void> {
+ await this.secrets().put(id, secret);
+ this.cache.set(id, secret);
+ }
+
+ /** A secret {@link update} got as text: stored in the app's store in the background, or dropped without one. */
+ private seal(id: string, text: string): string {
+ const source = this.options.secrets;
+ if (!source?.available) {
+ this.log("a connector secret was not kept: the app's secure store is not connected");
+ return secretRef(id);
}
+ this.cache.set(id, text);
+ const write = source
+ .put(id, text)
+ .catch((error: Error) => {
+ if (this.cache.get(id) === text) this.cache.delete(id);
+ this.log(`a connector secret could not be stored: ${error.message}`);
+ })
+ .finally(() => this.writes.delete(write));
+ this.writes.add(write);
+ return secretRef(id);
+ }
+
+ /** Reads every secret the connector refers to that is not in memory yet; rejects without the app. */
+ private async unlock(id: string): Promise<void> {
+ await this.migrating;
+ const saved = this.saved.connectors[id];
+ if (!saved) return;
+ const missing = refsOf(id, saved).filter((ref) => !this.cache.has(ref) && !this.pending.has(ref));
+ if (missing.length === 0) return;
+ const source = this.secrets();
+ for (const ref of missing) {
+ const secret = await source.get(ref);
+ if (secret !== undefined) this.cache.set(ref, secret);
+ }
+ }
+
+ /** The connector's server with its secrets in place; rejects with why when one is missing. */
+ private async unlocked(id: string) {
+ await this.unlock(id);
+ const saved = this.saved.connectors[id];
+ if (!saved) throw new Error(`The connector ${id} is not set up.`);
+ const { open, locked } = this.open(id, saved);
+ if (locked) throw new SecretsUnavailableError(locked);
+ const filled = filledServer(id, open);
+ if (!filled) throw new Error(`The connector ${id} is not set up.`);
+ return filled;
}
- /** One server's stored sign-in, for the proxy. */
- private signIn(key: string): McpOAuthState | undefined {
+ /**
+ * The connector with the secrets in memory in place of their references, and why it cannot run
+ * when one is not there: no app (or a secret still waiting in a file), or an item that is gone.
+ */
+ private open(id: string, saved: SavedConnector): { open: SavedConnector; locked?: string } {
+ let missing = false;
+ let waiting = false;
+ const open = mapSecrets(id, saved, (_secretId, text) => {
+ const ref = refId(text);
+ if (ref === undefined) return text;
+ const secret = this.cache.get(ref);
+ if (secret !== undefined) return secret;
+ if (this.pending.has(ref)) waiting = true;
+ missing = true;
+ // Kept as the reference, so the connector still counts as set up.
+ return text;
+ });
+ const signIn = saved.signIn && refId(saved.signIn);
+ if (signIn && !this.cache.has(signIn) && !this.options.secrets?.available) missing = true;
+ // A reference anywhere else (a changed file) never reaches a server.
+ if (!missing && JSON.stringify(open.custom ?? {}).includes(JSON.stringify(REF).slice(1, -1)))
+ missing = true;
+ if (!missing) return { open };
+ const name = specOf(id, saved)?.name ?? id;
+ const locked =
+ waiting || !this.options.secrets?.available
+ ? NO_APP
+ : `A secret ${name} needs is missing from the app's secure store. Ask the user to set up ${name} again in Connectors.`;
+ return { open, locked };
+ }
+
+ /** One connector's sign-in, from memory. */
+ private signInState(id: string): McpOAuthState | undefined {
+ const ref = this.saved.connectors[id]?.signIn;
+ const text = ref && refId(ref) && this.cache.get(refId(ref) ?? "");
+ if (!text) return undefined;
try {
- const states = JSON.parse(readFileSync(this.authFile, "utf8")) as Record<
- string,
- McpOAuthState | undefined
- >;
- return states[key];
+ return JSON.parse(text) as McpOAuthState;
} catch {
return undefined;
}
}
- /** Keeps a refreshed sign-in; the file is then what it should be. */
- private saveSignIn(key: string, state: McpOAuthState): void {
- let states: Record<string, unknown> = {};
- try {
- states = JSON.parse(readFileSync(this.authFile, "utf8")) as Record<string, unknown>;
- } catch {}
- states[key] = state;
- const text = `${JSON.stringify(states, null, 2)}\n`;
- ensurePrivateDir(this.signinHome);
- writePrivate(this.authFile, text);
- this.authText = text;
+ private async runMigration(): Promise<void> {
+ const source = this.options.secrets;
+ if (!source?.available) return;
+ // Secrets `connectors.json` still holds as text: all of them, or none.
+ if (this.pending.size > 0) {
+ try {
+ for (const [id, secret] of this.pending) await this.verifiedPut(source, id, secret);
+ } catch (error) {
+ this.log(
+ `could not move the connector secrets into the app's secure store (${(error as Error).message}); the files stay as they were`,
+ );
+ return;
+ }
+ const moved = this.pending.size;
+ for (const [id, secret] of this.pending) this.cache.set(id, secret);
+ this.pending.clear();
+ writePrivate(this.file, this.recordText());
+ this.log(`moved ${moved} connector secrets from connectors.json into the app's secure store`);
+ }
+ if (!this.migrated) {
+ let moved = 0;
+ let dropped = 0;
+ // The daemon's own sign-ins first: they win over the engine's older ones.
+ for (const file of [this.authFile, this.legacyAuthFile]) {
+ const states = this.readSignIns(file);
+ if (!states) continue;
+ const refs: Record<string, string> = {};
+ try {
+ for (const [key, state] of Object.entries(states)) {
+ const id = this.connectorForKey(key);
+ if (!id) {
+ dropped++;
+ continue;
+ }
+ if (this.saved.connectors[id]?.signIn || refs[id]) continue;
+ const secretId = signInId(id);
+ const text = JSON.stringify(state);
+ await this.verifiedPut(source, secretId, text);
+ this.cache.set(secretId, text);
+ refs[id] = secretRef(secretId);
+ moved++;
+ }
+ } catch (error) {
+ this.log(
+ `could not move the connector sign-ins into the app's secure store (${(error as Error).message}); they stay where they were`,
+ );
+ this.applySignIns(refs);
+ return;
+ }
+ this.applySignIns(refs);
+ unlinkSync(file);
+ }
+ if (existsSync(this.signinMcpFile)) unlinkSync(this.signinMcpFile);
+ try {
+ if (readdirSync(this.signinHome).length === 0) rmdirSync(this.signinHome);
+ } catch {}
+ this.migrated = true;
+ mkdirSync(this.options.dataDir, { recursive: true, mode: 0o700 });
+ writePrivate(this.file, this.recordText());
+ if (moved > 0) this.log(`moved ${moved} connector sign-ins into the app's secure store`);
+ if (dropped > 0)
+ this.log(
+ `dropped ${dropped} sign-in${dropped === 1 ? "" : "s"} for a connector that is no longer added`,
+ );
+ }
+ this.reportPlanted();
}
- /**
- * Before the proxy, the engine kept the sign-ins in its home. Whenever that file is there it is
- * moved: verbatim when the daemon holds no sign-ins yet, otherwise only the sign-ins the daemon
- * does not hold (its own always win, so a file planted later never replaces one). The result is
- * read back before the old file is removed, so a move that stopped halfway finishes next time.
- */
- private moveLegacySignIns(): void {
- ensurePrivateDir(this.signinHome);
- const text = readOrUndefined(this.legacyAuthFile);
- if (text === undefined) return;
- const legacy = signInStates(text);
- const currentText = readOrUndefined(this.authFile);
- const current = currentText === undefined ? {} : signInStates(currentText);
- if (!legacy || !current) {
- this.options.log?.("could not read the connector sign-ins to move; they stay where they were");
- return;
+ /** Stores a secret and reads it back; throws when it is not the same. */
+ private async verifiedPut(source: SecretSource, id: string, secret: string): Promise<void> {
+ await source.put(id, secret);
+ if ((await source.get(id)) !== secret) throw new Error("a secret did not read back the same");
+ }
+
+ /** The sign-ins of an old file, by key; undefined when there is none, it is empty, or it cannot be read. */
+ private readSignIns(file: string): Record<string, unknown> | undefined {
+ let text: string;
+ try {
+ text = readFileSync(file, "utf8");
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT")
+ this.log(`could not read ${file}; it was left as it is`);
+ return undefined;
}
- const missing = Object.keys(legacy).filter((key) => !(key in current));
- if (currentText === undefined) writePrivate(this.authFile, text);
- else if (missing.length > 0) {
- const merged = { ...Object.fromEntries(missing.map((key) => [key, legacy[key]])), ...current };
- writePrivate(this.authFile, `${JSON.stringify(merged, null, 2)}\n`);
+ if (text.trim() === "") {
+ unlinkSync(file);
+ return undefined;
}
- const moved = signInStates(readOrUndefined(this.authFile) ?? "");
- if (!moved || Object.keys(legacy).some((key) => !(key in moved))) {
- this.options.log?.("could not move the connector sign-ins; they stay where they were");
- return;
+ const states = signInStates(text);
+ if (!states) this.log(`${file} is not a list of sign-ins; it was left as it is`);
+ return states;
+ }
+
+ /** The added connector whose remote server an old sign-in key names (`mcp__<server>|<url>`). */
+ private connectorForKey(key: string): string | undefined {
+ for (const [id, saved] of Object.entries(this.saved.connectors)) {
+ const server = filledServer(id, saved)?.server;
+ if (server && "url" in server && URL.canParse(server.url) && authKey(id, server.url) === key) return id;
+ }
+ return undefined;
+ }
+
+ private applySignIns(refs: Record<string, string>): void {
+ if (Object.keys(refs).length === 0) return;
+ this.update((state) => {
+ for (const [id, ref] of Object.entries(refs)) {
+ const saved = state.connectors[id];
+ if (saved) saved.signIn = ref;
+ }
+ });
+ }
+
+ /** After the move, an old sign-in file that appears again is reported once and never read. */
+ private reportPlanted(): void {
+ if (!this.migrated) return;
+ for (const file of [this.authFile, this.legacyAuthFile]) {
+ if (this.reported.has(file) || !existsSync(file)) continue;
+ this.reported.add(file);
+ this.log(
+ `found ${file} after the connector sign-ins moved to the app's secure store; it was not imported and was left as it is`,
+ );
}
- unlinkSync(this.legacyAuthFile);
- this.options.log?.("moved the connector sign-ins to the daemon's sign-in folder");
}
private engineMcpText(): string {
return renderMcpJson(this.saved, this.computer, this.proxy);
}
+ private log(line: string): void {
+ this.options.log?.(line);
+ }
+
private check: () => void = () => {};
private poll: NodeJS.Timeout | undefined;
private projectWatcher: FSWatcher | undefined;
@@ -950,49 +1274,89 @@ export class ConnectorStore {
return true;
}
+ /** `connectors.json`: each secret as `{"secretRef": "<id>"}`, or as the text it still was until it moves. */
private recordText(): string {
- return `${JSON.stringify({ version: 1, connectors: this.saved.connectors }, null, 2)}\n`;
+ const record = { version: this.migrated ? 2 : 1, connectors: this.saved.connectors };
+ return `${JSON.stringify(
+ record,
+ (_key, value: unknown) => {
+ const ref = typeof value === "string" ? refId(value) : undefined;
+ return ref === undefined ? value : (this.pending.get(ref) ?? { secretRef: ref });
+ },
+ 2,
+ )}\n`;
}
- /** The saved state; a connector saved as `computer` (the built-in helper's name) gets `computer-2`. */
- private load(): { state: ConnectorsState; renamed: boolean } {
+ /**
+ * The saved state; a connector saved as `computer` (the built-in helper's name) gets `computer-2`.
+ * A secret saved as text (before T23d) waits in memory for {@link migrate} and is not used.
+ */
+ private load(): { state: ConnectorsState; renamed: boolean; version: number } {
+ let saved: { version?: unknown; connectors?: Record<string, Record<string, unknown> | undefined> };
try {
- const saved = JSON.parse(readFileSync(this.file, "utf8")) as {
- connectors?: Record<string, Record<string, unknown> | undefined>;
- };
- const connectors: ConnectorsState["connectors"] = {};
- const entries = Object.entries(saved.connectors ?? {});
- const ordered = [
- ...entries.filter(([id]) => id !== COMPUTER_ID),
- ...entries.filter(([id]) => id === COMPUTER_ID),
- ];
- let renamed = false;
- for (const [savedId, value] of ordered) {
- let id = savedId;
- if (id === COMPUTER_ID) {
- let n = 2;
- while (`${COMPUTER_ID}-${n}` in connectors || catalogEntry(`${COMPUTER_ID}-${n}`)) n++;
- id = `${COMPUTER_ID}-${n}`;
- }
- const custom = catalogEntry(id) ? undefined : parseCustom(value?.custom);
- if (!catalogEntry(id) && !custom) continue;
- renamed ||= id !== savedId;
- const entry: SavedConnector = {
- enabled: value?.enabled === true,
- mode: value?.mode === "read_write" ? "read_write" : "read_only",
- };
- const values = stringRecord(value?.values);
- if (values) entry.values = values;
- if (custom) entry.custom = custom;
- connectors[id] = entry;
- }
- return { state: { connectors }, renamed };
+ saved = JSON.parse(readFileSync(this.file, "utf8"), (_key, value: unknown) => {
+ const ref = (value as { secretRef?: unknown } | null)?.secretRef;
+ return typeof value === "object" && typeof ref === "string" && SECRET_ID.test(ref)
+ ? secretRef(ref)
+ : value;
+ });
} catch {
- return { state: { connectors: {} }, renamed: false };
+ return { state: { connectors: {} }, renamed: false, version: existsSync(this.file) ? 1 : 0 };
+ }
+ const connectors: ConnectorsState["connectors"] = {};
+ const entries = Object.entries(saved.connectors ?? {});
+ const ordered = [
+ ...entries.filter(([id]) => id !== COMPUTER_ID),
+ ...entries.filter(([id]) => id === COMPUTER_ID),
+ ];
+ let renamed = false;
+ for (const [savedId, value] of ordered) {
+ let id = savedId;
+ if (id === COMPUTER_ID) {
+ let n = 2;
+ while (`${COMPUTER_ID}-${n}` in connectors || catalogEntry(`${COMPUTER_ID}-${n}`)) n++;
+ id = `${COMPUTER_ID}-${n}`;
+ }
+ const custom = catalogEntry(id) ? undefined : parseCustom(value?.custom);
+ if (!catalogEntry(id) && !custom) continue;
+ renamed ||= id !== savedId;
+ const entry: SavedConnector = {
+ enabled: value?.enabled === true,
+ mode: value?.mode === "read_write" ? "read_write" : "read_only",
+ };
+ const values = stringRecord(value?.values);
+ if (values) entry.values = values;
+ if (custom) entry.custom = custom;
+ if (typeof value?.signIn === "string" && refId(value.signIn)) entry.signIn = value.signIn;
+ connectors[id] = mapSecrets(id, entry, (secretId, text) => {
+ if (refId(text) !== undefined) return text;
+ this.pending.set(secretId, text);
+ return secretRef(secretId);
+ });
}
+ const version = typeof saved.version === "number" ? saved.version : 1;
+ return { state: { connectors }, renamed, version };
}
}
+/** The user's own OAuth client of a remote server, its secret resolved like the engine resolved it. */
+function oauthSettings(
+ name: string,
+ server: Extract<ServerTemplate, { url: string }>,
+ env: NodeJS.ProcessEnv,
+): OAuthSettings {
+ const { oauth } = server;
+ return {
+ ...(oauth?.clientId ? { clientId: oauth.clientId } : {}),
+ ...(oauth?.clientSecret
+ ? { clientSecret: resolveValue(oauth.clientSecret, env, `${name} client secret`) }
+ : {}),
+ ...(oauth?.callbackUrl ? { callbackUrl: oauth.callbackUrl } : {}),
+ ...(oauth?.callbackPort !== undefined ? { callbackPort: oauth.callbackPort } : {}),
+ ...(oauth?.scope ? { scope: oauth.scope } : {}),
+ };
+}
+
function stringRecord(value: unknown): Record<string, string> | undefined {
if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
const entries = Object.entries(value).filter(
@@ -1116,13 +1480,9 @@ interface Flow {
connectorId: string;
owner: object;
emit: Emit;
- child: ChildProcess;
- /** From the authorization URL: where the browser returns, and the sign-in's `state`. */
- redirect?: { url: URL; state: string | null };
+ /** The OAuth flow, once the connector's settings were read. */
+ signIn?: SignIn;
cancelled: boolean;
- /** What the command printed so far: stdout until the link appears, the tail of stderr for the log. */
- printed: string | undefined;
- output: string;
}
/** The values a connector needs, asked one at a time in the window that started it. */
@@ -1141,12 +1501,17 @@ const PASTE_PROMPT =
const DRAFT_ORIGIN = "Drafted by the assistant";
const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
+/** How sign-ins reach the provider and the user's browser; tests replace both. */
+export interface ConnectorOAuthOptions {
+ /** The fetch for discovery, client registration, and tokens; default the global one. */
+ fetch?: typeof fetch;
+ /** Called with each page to approve access on, besides sending it to the window (tests act as the browser). */
+ openBrowser?: (url: string) => void;
+}
+
export interface ConnectorManagerOptions {
store: ConnectorStore;
- cli: McpCli;
- /** The engine's environment (its own HOME, XDG folders, and memory settings). */
- env: NodeJS.ProcessEnv;
- cwd: string;
+ oauth?: ConnectorOAuthOptions;
/** The home folder "Import my MCP servers" scans; default the user's. */
importHome?: string;
log?: (line: string) => void;
@@ -1154,12 +1519,13 @@ export interface ConnectorManagerOptions {
/**
* Connects, sets up, signs in, changes, and removes connectors. Values the user types (a bot token,
- * an OAuth client) are asked one at a time with sign-in prompts, kept in the assistant's private
- * state, and never logged or sent back. Sign-in runs the engine's own `mcp login <server>` as a
- * separate process (one at a time; its loopback callback port is shared), relays the authorization
- * URL, and can finish with an address the user pastes when the browser could not reach this
- * computer. Drafts from the assistant and servers found in other apps are added only when the user
- * says so, read only, with every tool hidden. Nothing typed or printed is logged.
+ * an OAuth client) are asked one at a time with sign-in prompts; the secret ones go to the desktop
+ * app's secure store (S25.5) and are never logged, sent back, or written to a file. Sign-in runs in
+ * the daemon with pi-mcp's OAuth (one at a time; a fixed loopback callback port may be shared),
+ * relays the authorization URL to the window that started it, and can finish with an address the
+ * user pastes when the browser could not reach this computer; the tokens go to the app's store.
+ * Drafts from the assistant and servers found in other apps are added only when the user says so,
+ * read only, with every tool hidden. Nothing typed or printed is logged.
*/
export class ConnectorManager {
/** `restart`: the engine must restart (when idle) to read the new `mcp.json`. */
@@ -1260,10 +1626,16 @@ export class ConnectorManager {
if (this.busy()) return REFUSALS.busy;
if (missingValues(spec, saved?.values)) {
// Nothing is added until every value is there.
- this.askValues(owner, id, spec.fields, emit, (values, flowId) => {
- this.save(id, (current) => ({ ...current, enabled: true, values }));
- this.afterSetup(owner, id, emit, flowId);
- });
+ this.askValues(owner, id, spec.fields, emit, (values, flowId) =>
+ this.keepValues(
+ id,
+ values,
+ emit,
+ flowId,
+ (current) => ({ ...current, enabled: true }),
+ () => this.afterSetup(owner, id, emit, flowId),
+ ),
+ );
return undefined;
}
this.save(id, (current) => ({ ...current, enabled: true }));
@@ -1279,10 +1651,16 @@ export class ConnectorManager {
if (!saved) return REFUSALS.notAdded;
if (spec.fields.length === 0) return REFUSALS.noSetup;
if (this.busy()) return REFUSALS.busy;
- this.askValues(owner, id, spec.fields, emit, (values, flowId) => {
- this.save(id, (current) => ({ ...current, values }));
- this.afterSetup(owner, id, emit, flowId);
- });
+ this.askValues(owner, id, spec.fields, emit, (values, flowId) =>
+ this.keepValues(
+ id,
+ values,
+ emit,
+ flowId,
+ (current) => current,
+ () => this.afterSetup(owner, id, emit, flowId),
+ ),
+ );
return undefined;
}
@@ -1314,7 +1692,7 @@ export class ConnectorManager {
return true;
}
if (answer.value === undefined) return false;
- void this.finishWithPastedAddress(flow, answer.value);
+ this.finishWithPastedAddress(flow, answer.value);
return true;
}
@@ -1342,7 +1720,7 @@ export class ConnectorManager {
return this.change(id, (saved) => ({ ...saved, mode }));
}
- /** Signs out (`mcp logout`, which needs the server still configured), then forgets the connector. */
+ /** Forgets the connector and its secrets (its sign-in, tokens, and typed values) in the app's store. */
async remove(id: string): Promise<ConnectorRefusal | undefined> {
const saved = this.options.store.state().connectors[id];
const spec = specOf(id, saved);
@@ -1350,14 +1728,7 @@ export class ConnectorManager {
if (!saved) return REFUSALS.notAdded;
if (this.flow?.connectorId === id) this.cancel(this.flow);
if (this.setupFlow?.connectorId === id) this.cancelSetup(this.setupFlow);
- if (spec.oauth) {
- const code = await new Promise<number | null>((done) => {
- const child = this.run("logout", id);
- child.on("error", () => done(-1));
- child.on("close", (exit) => done(exit));
- });
- if (code !== 0) this.log(`sign-out of connector ${id} failed (exit ${code})`);
- }
+ await this.options.store.forget(id);
this.failed.delete(id);
this.options.store.update((state) => {
delete state.connectors[id];
@@ -1417,10 +1788,16 @@ export class ConnectorManager {
this.log(`added connector ${id} from the assistant's draft`);
if (custom.fields.length === 0) this.afterSetup(owner, id, emit, `connector-${randomUUID()}`);
else
- this.askValues(owner, id, custom.fields, emit, (values, flowId) => {
- this.save(id, (current) => ({ ...current, values }));
- this.afterSetup(owner, id, emit, flowId);
- });
+ this.askValues(owner, id, custom.fields, emit, (values, flowId) =>
+ this.keepValues(
+ id,
+ values,
+ emit,
+ flowId,
+ (current) => current,
+ () => this.afterSetup(owner, id, emit, flowId),
+ ),
+ );
return undefined;
}
@@ -1475,10 +1852,14 @@ export class ConnectorManager {
}
/**
- * Copies the chosen servers, with their values, read only with every tool hidden: from `from`
- * (a confirmed plan) when given, else from the last scan.
+ * Copies the chosen servers, read only with every tool hidden: from `from` (a confirmed plan) when
+ * given, else from the last scan. Their header and environment values go to the app's secure
+ * store, with only references in the files.
*/
- importServers(ids: string[], from: ReadonlyMap<string, ScannedServer> = this.scanned): string[] {
+ async importServers(
+ ids: string[],
+ from: ReadonlyMap<string, ScannedServer> = this.scanned,
+ ): Promise<string[]> {
const imported: string[] = [];
for (const key of ids) {
const found = from.get(key);
@@ -1497,6 +1878,7 @@ export class ConnectorManager {
});
imported.push(id);
}
+ await this.options.store.settled();
if (imported.length > 0) {
this.log(`imported ${imported.length} MCP servers: ${imported.join(", ")}`);
this.onChanged(true);
@@ -1577,6 +1959,37 @@ export class ConnectorManager {
this.onChanged(true);
}
+ /**
+ * Stores the typed values (the secret ones in the app's store), then changes the connector with
+ * `update` and continues; without the app the window is told why and nothing changes.
+ */
+ private keepValues(
+ id: string,
+ values: Record<string, string>,
+ emit: Emit,
+ flowId: string,
+ update: (current: SavedConnector) => SavedConnector,
+ then: () => void,
+ ): void {
+ this.options.store.keepValues(id, values).then(
+ () => {
+ this.save(id, update);
+ then();
+ },
+ (error: Error) => {
+ this.log(`could not keep the values of connector ${id}: ${error.message}`);
+ emit({
+ type: "auth_done",
+ flowId,
+ providerId: id,
+ ok: false,
+ message:
+ error instanceof SecretsUnavailableError ? error.message : "Could not save it. Please try again.",
+ });
+ },
+ );
+ }
+
/** After the values are there: sign in when the connector needs it, otherwise it is done. */
private afterSetup(owner: object, id: string, emit: Emit, flowId: string): void {
const spec = specOf(id, this.options.store.state().connectors[id]);
@@ -1661,53 +2074,60 @@ export class ConnectorManager {
return undefined;
}
- /** The engine's sign-in command, pointed at the daemon's sign-in home (the real servers), never the engine's. */
- private run(subcommand: "login" | "logout", id: string): ChildProcess {
- const { cli, env, cwd, store } = this.options;
- const done = store.signingIn();
- const child = spawn(cli.command, [...cli.args, "mcp", subcommand, id], {
- cwd,
- env: { ...env, PI_CODING_AGENT_DIR: store.signinHome },
- stdio: ["ignore", "pipe", "pipe"],
- });
- child.on("error", done);
- child.on("close", done);
- return child;
- }
-
private startLogin(owner: object, connectorId: string, emit: Emit, flowId?: string): void {
- const child = this.run("login", connectorId);
const flow: Flow = {
id: flowId ?? `connector-${randomUUID()}`,
connectorId,
owner,
emit,
- child,
cancelled: false,
- printed: "",
- output: "",
};
this.flow = flow;
this.failed.delete(connectorId);
- child.stdout?.on("data", (chunk: Buffer) => this.onOutput(flow, chunk.toString("utf8")));
- child.stderr?.on("data", (chunk: Buffer) => {
- flow.output = `${flow.output}${chunk.toString("utf8")}`.slice(-2000);
- });
- child.on("error", (error) => this.log(`connector sign-in could not start: ${error.message}`));
- child.on("close", (code) => this.onExit(flow, code));
- }
-
- private onOutput(flow: Flow, text: string): void {
- if (flow.printed === undefined) return;
- flow.printed = `${flow.printed}${text}`.slice(-8000);
- // The link ends with its line; a chunk may stop in the middle of it.
- const url = flow.printed.match(/https?:\/\/\S+(?=\s)/)?.[0];
- if (!url || !URL.canParse(url)) return;
- flow.printed = undefined;
- const authorization = new URL(url);
- const redirect = authorization.searchParams.get("redirect_uri");
- if (redirect && URL.canParse(redirect))
- flow.redirect = { url: new URL(redirect), state: authorization.searchParams.get("state") };
+ void this.runLogin(flow);
+ }
+
+ /** The sign-in, run here with pi-mcp's OAuth; the result goes to the app's secure store only. */
+ private async runLogin(flow: Flow): Promise<void> {
+ const { store, oauth } = this.options;
+ const done = { type: "auth_done", flowId: flow.id, providerId: flow.connectorId } as const;
+ try {
+ const target = await store.signInTarget(flow.connectorId);
+ if (flow.cancelled) throw new SignInCancelledError();
+ flow.signIn = startSignIn({
+ ...target,
+ ...(oauth?.fetch ? { fetch: oauth.fetch } : {}),
+ onAuthorizationUrl: (url) => this.onAuthorizationUrl(flow, url),
+ });
+ const state = await flow.signIn.done;
+ await store.saveSignIn(flow.connectorId, state);
+ this.log(`signed in to connector ${flow.connectorId}`);
+ flow.emit({ ...done, ok: true });
+ } catch (error) {
+ if (flow.cancelled || error instanceof SignInCancelledError)
+ flow.emit({ ...done, ok: false, message: "Sign-in cancelled." });
+ else {
+ this.failed.add(flow.connectorId);
+ const detail = ((error as Error)?.message ?? String(error)).replace(/https?:\/\/\S+/g, "[address]");
+ this.log(`sign-in to connector ${flow.connectorId} failed: ${detail.slice(0, 200)}`);
+ flow.emit({
+ ...done,
+ ok: false,
+ message:
+ error instanceof SecretsUnavailableError
+ ? error.message
+ : "Sign-in did not finish. Please try again.",
+ });
+ }
+ } finally {
+ if (this.flow === flow) this.flow = undefined;
+ this.onChanged(false);
+ }
+ }
+
+ /** The page to approve access on goes to the window that started the sign-in. */
+ private onAuthorizationUrl(flow: Flow, url: URL): void {
+ if (flow.cancelled) return;
const name =
specOf(flow.connectorId, this.options.store.state().connectors[flow.connectorId])?.name ??
flow.connectorId;
@@ -1716,10 +2136,11 @@ export class ConnectorManager {
flowId: flow.id,
event: {
kind: "auth_url",
- url,
+ url: url.href,
instructions: `Open the ${name} page and approve access. You can come back here when it says you are done.`,
},
});
+ this.options.oauth?.openBrowser?.(url.href);
this.askForAddress(flow);
}
@@ -1736,59 +2157,16 @@ export class ConnectorManager {
/**
* The browser could not reach this computer's sign-in page (for example, the assistant runs
- * elsewhere): the pasted address is that page's address, so open it here. Only the exact
- * loopback address of this sign-in, with its `state`, is accepted.
+ * elsewhere): the pasted address is that page's address. Only this sign-in's loopback address,
+ * with its `state`, is accepted; nothing is fetched.
*/
- private async finishWithPastedAddress(flow: Flow, pasted: string): Promise<void> {
- const expected = flow.redirect;
- const url = URL.canParse(pasted.trim()) ? new URL(pasted.trim()) : undefined;
- const loopback = url && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
- if (
- !expected ||
- !url ||
- !loopback ||
- url.protocol !== "http:" ||
- url.origin !== expected.url.origin ||
- url.pathname !== expected.url.pathname ||
- url.searchParams.get("state") !== expected.state
- ) {
- this.askForAddress(flow, true);
- return;
- }
- if (url.hostname === "localhost") url.hostname = "127.0.0.1";
- try {
- // Only this loopback address; where it redirects is not followed.
- await fetch(url, { redirect: "manual", signal: AbortSignal.timeout(10_000) });
- } catch {
- if (this.flow === flow) this.askForAddress(flow, true);
- }
+ private finishWithPastedAddress(flow: Flow, pasted: string): void {
+ if (!flow.signIn?.paste(pasted)) this.askForAddress(flow, true);
}
private cancel(flow: Flow): void {
flow.cancelled = true;
- flow.child.kill("SIGTERM");
- }
-
- private onExit(flow: Flow, code: number | null): void {
- if (this.flow === flow) this.flow = undefined;
- const done = { type: "auth_done", flowId: flow.id, providerId: flow.connectorId } as const;
- if (code === 0 && !flow.cancelled) {
- this.log(`signed in to connector ${flow.connectorId}`);
- flow.emit({ ...done, ok: true });
- } else if (flow.cancelled) {
- flow.emit({ ...done, ok: false, message: "Sign-in cancelled." });
- } else {
- this.failed.add(flow.connectorId);
- const detail =
- flow.output
- .trim()
- .split("\n")
- .pop()
- ?.replace(/https?:\/\/\S+/g, "[address]") ?? "";
- this.log(`sign-in to connector ${flow.connectorId} failed (exit ${code}): ${detail.slice(0, 200)}`);
- flow.emit({ ...done, ok: false, message: "Sign-in did not finish. Please try again." });
- }
- this.onChanged(false);
+ flow.signIn?.cancel();
}
private log(line: string): void {
diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.ts
index 3fc20b5..fed053e 100644
--- a/packages/daemon/src/daemon.ts
+++ b/packages/daemon/src/daemon.ts
@@ -18,10 +18,9 @@ import { AuthManager, type AuthRuntime, createModelAuthRuntime, resolveAgentHome
import { type BridgeClient, DotBridge } from "./bridge.ts";
import {
APPROVAL_GUARD,
- bundledMcpCli,
ConnectorManager,
+ type ConnectorOAuthOptions,
ConnectorStore,
- type McpCli,
policyEnv,
} from "./connectors.ts";
import { approvalRequest } from "./extensions/approval-guard.ts";
@@ -29,6 +28,7 @@ import { ensureMemoryProject, ensurePrivateDir, isolatedAgentEnv, privateMemory
import { MCP_PREFIX, McpProxy, type ProxiedConnector, type UpstreamCredentials } from "./mcp-proxy.ts";
import { defaultImportPath, ProfileStore } from "./profiles.ts";
import { type RotationLimits, rotationLimits } from "./rotation.ts";
+import { AppSecretSource } from "./secret-source.ts";
import { AgentSupervisor } from "./supervisor.ts";
import { UploadStore } from "./uploads.ts";
import { VoiceService } from "./voice.ts";
@@ -56,8 +56,8 @@ export interface DaemonOptions {
authRuntime?: () => Promise<AuthRuntime>;
/** The fetch for voice requests to OpenAI; tests pass a fake one. */
voiceFetch?: typeof fetch;
- /** The engine's command line for connector sign-in; default `GENTLE_DOT_MCP_CLI` (JSON array) or the bundled one. */
- connectorCli?: McpCli;
+ /** How connector sign-ins reach the provider and the browser; tests pass stand-ins. */
+ connectorOAuth?: ConnectorOAuthOptions;
/** The home folder "Import my MCP servers" reads other apps' configs from; default `GENTLE_DOT_IMPORT_HOME` or the user's. */
importHome?: string;
/** The connection the MCP proxy makes to a connector's real server; tests pass a stand-in. */
@@ -151,19 +151,28 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
agentEnv.GENTLE_PI_CONFIG_HOME = join(options.dataDir, "gentle-ai");
}
const agentHome = options.agentHome ?? resolveAgentHome(process.env, options.dataDir);
+ const app = options.appChannel
+ ? new AppChannel(options.appChannel, {
+ log,
+ ...(options.approvalWaitMs ? { approvalWaitMs: options.approvalWaitMs } : {}),
+ })
+ : undefined;
// The approved connectors are read once, here; the engine cannot change them (docs/design.md).
+ // Their secrets come from the app's secure store over its channel, and only into memory (S25.5).
const connectorStore = new ConnectorStore({
dataDir: options.dataDir,
agentHome,
workspace: options.workspace,
guardPath: APPROVAL_GUARD,
env: agentEnv,
+ secrets: new AppSecretSource(app),
log,
});
// The engine reaches every connector through the proxy (S25.4); its key changes with every launch.
let port = options.port;
const proxy = new McpProxy({
connector: (id) => connectorStore.proxyView(id),
+ prepare: (id) => connectorStore.prepare(id),
credentials: (id) => connectorStore.credentials(id),
// In the desktop app's native dialog, outside the agent's reach (S25.3).
approve: (preview, signal) =>
@@ -215,9 +224,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
});
const connectors = new ConnectorManager({
store: connectorStore,
- cli: options.connectorCli ?? mcpCliFromEnv(process.env) ?? bundledMcpCli(),
- env: { ...agentEnv },
- cwd: options.workspace,
+ ...(options.connectorOAuth ? { oauth: options.connectorOAuth } : {}),
...((options.importHome ?? process.env.GENTLE_DOT_IMPORT_HOME)
? { importHome: options.importHome ?? process.env.GENTLE_DOT_IMPORT_HOME }
: {}),
@@ -233,12 +240,6 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
...(options.uploadLimits ? { limits: options.uploadLimits } : {}),
});
const historyPage = options.historyPage ?? Number(process.env.GENTLE_DOT_HISTORY_PAGE);
- const app = options.appChannel
- ? new AppChannel(options.appChannel, {
- log,
- ...(options.approvalWaitMs ? { approvalWaitMs: options.approvalWaitMs } : {}),
- })
- : undefined;
const bridge = new DotBridge(supervisor, {
dataDir: options.dataDir,
log,
@@ -259,8 +260,17 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
app.onClose(() => {
log("the desktop app's channel closed");
connectors.unregisterComputer(app);
+ // Secrets read from the app are forgotten; connectors that need one fail closed until it is back.
+ connectorStore.lock();
});
- } else log("no desktop app channel: connector changes and approvals are refused");
+ // Secrets that files still hold move into the app's store, once.
+ void connectorStore
+ .migrate()
+ .catch((error: Error) => log(`connector secrets were not moved: ${error.message}`));
+ } else
+ log(
+ "no desktop app channel: connector changes and approvals are refused, and connectors that need a secret fail closed",
+ );
// The files as the daemon writes them (an older version kept a hash), then watched.
connectorStore.enforce(false);
@@ -345,12 +355,6 @@ async function appRequest(
}
}
-function mcpCliFromEnv(env: NodeJS.ProcessEnv): McpCli | undefined {
- if (!env.GENTLE_DOT_MCP_CLI) return undefined;
- const [command, ...args] = JSON.parse(env.GENTLE_DOT_MCP_CLI) as string[];
- return command ? { command, args } : undefined;
-}
-
function allowedOrigins(port: number, options: DaemonOptions): Set<string> {
return new Set([
`http://127.0.0.1:${port}`,
diff --git a/packages/daemon/src/mcp-proxy.ts b/packages/daemon/src/mcp-proxy.ts
index 284bef3..5693477 100644
--- a/packages/daemon/src/mcp-proxy.ts
+++ b/packages/daemon/src/mcp-proxy.ts
@@ -34,6 +34,7 @@ import {
} from "@earendil-works/pi-mcp";
import { McpOAuthAuthorizationRequiredError } from "@earendil-works/pi-mcp/oauth";
import { type ConnectorMode, isReadOnlyTool } from "./extensions/approval-guard.ts";
+import { SecretsUnavailableError } from "./secret-source.ts";
/** Where the engine reaches a connector: `/mcp/<id>`. */
export const MCP_PREFIX = "/mcp/";
@@ -50,6 +51,8 @@ export interface ProxiedConnector {
server: { url: string } | { command: string; args?: string[]; cwd?: string };
/** Changes whenever the server or its values change, so the connection to it is made again. */
revision: string;
+ /** Why it cannot run now (a secret it needs is not available); safe to show. */
+ unavailable?: string;
}
/** What the daemon adds to the real server's requests: headers and tokens, or a stdio server's environment. */
@@ -71,6 +74,8 @@ export interface ApprovalPreview {
export interface McpProxyOptions {
/** The connector's current state, read on every request. */
connector(id: string): ProxiedConnector | undefined;
+ /** Runs before the state is read (the daemon reads the connector's secrets from the app). */
+ prepare?(id: string): Promise<void>;
credentials(id: string): Promise<UpstreamCredentials>;
/** Asks the user; false or a failure refuses the action. The signal aborts when the engine gave up. */
approve(preview: ApprovalPreview, signal: AbortSignal): Promise<boolean>;
@@ -182,6 +187,7 @@ export class McpProxy {
}
return this.empty(req, res, 202);
}
+ await this.options.prepare?.(id).catch(() => {});
const connector = this.options.connector(id);
if (!connector)
return this.reply(req, res, 404, rpcId, {
@@ -221,6 +227,8 @@ export class McpProxy {
REFUSED,
`${connector.name} is turned off. If the user wants it, ask them to turn it on in Connectors.`,
);
+ // Without its secrets it fails closed, with the reason.
+ if (connector.unavailable) throw new ProxyError(REFUSED, connector.unavailable);
const reads = readsAllowed(connector);
switch (method) {
case "initialize": {
@@ -401,6 +409,7 @@ export class McpProxy {
private rpcError(connector: ProxiedConnector, error: unknown): { code: number; message: string } {
if (error instanceof ProxyError) return { code: error.code, message: error.message };
+ if (error instanceof SecretsUnavailableError) return { code: REFUSED, message: error.message };
// The server's own answer, passed on as it came.
if (error instanceof McpError) return { code: error.code, message: error.message };
const upstream = this.upstreams.get(connector.id);
diff --git a/packages/daemon/src/secret-source.ts b/packages/daemon/src/secret-source.ts
new file mode 100644
index 0000000..13cfb23
--- /dev/null
+++ b/packages/daemon/src/secret-source.ts
@@ -0,0 +1,123 @@
+/**
+ * Where the daemon gets connector secrets (S25.5, docs/design.md "Security"): bot tokens, client
+ * secrets, imported headers and environment values, and OAuth sign-ins. On the desktop they live in
+ * Keychain items the signed app creates (`apps/desktop` `secure_store`), and reach the daemon over
+ * the app's private channel (`secret_get`, `secret_put`, `secret_delete`, `secret_list`). The daemon
+ * keeps them in memory only and never writes them to a file or a log. Without the app (a daemon it
+ * only attached to, one started from a terminal, the web) there is no source, and connectors that
+ * need a secret fail closed with {@link NO_APP}; there is no file fallback.
+ */
+import { APPROVAL_WAIT_MS, type AppChannel } from "./app-channel.ts";
+
+/** Why a connector that needs a secret cannot run: the secrets are only in the app's store. */
+export const NO_APP = "Open the Gentle Dot app to use this connector.";
+
+/** The secret store is not reachable; `message` is safe to show. */
+export class SecretsUnavailableError extends Error {
+ constructor(message = NO_APP) {
+ super(message);
+ this.name = "SecretsUnavailableError";
+ }
+}
+
+export interface SecretSource {
+ /** False while there is no app to ask; every call then rejects with {@link SecretsUnavailableError}. */
+ readonly available: boolean;
+ /** The secret under `id`, or undefined when there is none. */
+ get(id: string): Promise<string | undefined>;
+ /** Stores `secret` under `id`, replacing any previous one. */
+ put(id: string, secret: string): Promise<void>;
+ /** Removes the secret under `id`; true when one was there. */
+ delete(id: string): Promise<boolean>;
+ /** Every id in the store. */
+ list(): Promise<string[]>;
+}
+
+/** Secret ids the app accepts (`secure_store::check_id`). */
+const ID = /^[A-Za-z0-9._:@/-]{1,200}$/;
+
+/**
+ * The desktop app's Keychain over its channel. A Keychain read can wait for a SecurityAgent prompt
+ * (an item made by another build), so calls wait as long as an approval does. A failure never
+ * carries a secret: the app answers with the store's error, and the daemon adds nothing.
+ */
+export class AppSecretSource implements SecretSource {
+ private readonly channel: AppChannel | undefined;
+ private readonly timeoutMs: number;
+
+ constructor(channel: AppChannel | undefined, timeoutMs = APPROVAL_WAIT_MS) {
+ this.channel = channel;
+ this.timeoutMs = timeoutMs;
+ }
+
+ get available(): boolean {
+ return this.channel?.connected === true;
+ }
+
+ async get(id: string): Promise<string | undefined> {
+ const result = (await this.call("secret_get", { id })) as { secret?: unknown } | null | undefined;
+ return typeof result?.secret === "string" ? result.secret : undefined;
+ }
+
+ async put(id: string, secret: string): Promise<void> {
+ await this.call("secret_put", { id, secret });
+ }
+
+ async delete(id: string): Promise<boolean> {
+ const result = (await this.call("secret_delete", { id })) as { deleted?: unknown } | undefined;
+ return result?.deleted === true;
+ }
+
+ async list(): Promise<string[]> {
+ const result = (await this.call("secret_list", {})) as { ids?: unknown } | undefined;
+ return Array.isArray(result?.ids) ? result.ids.filter((id): id is string => typeof id === "string") : [];
+ }
+
+ private async call(method: string, params: { id?: string; secret?: string }): Promise<unknown> {
+ const channel = this.channel;
+ if (!channel?.connected) throw new SecretsUnavailableError();
+ if (params.id !== undefined && !ID.test(params.id)) throw new Error("That secret id is not valid.");
+ try {
+ return await channel.request(method, params, this.timeoutMs);
+ } catch (error) {
+ if (!channel.connected) throw new SecretsUnavailableError();
+ throw new Error(`The app's secure store refused it: ${(error as Error).message}`);
+ }
+ }
+}
+
+/** An in-memory store, for tests; `corrupt` makes reads of an id return something else. */
+export class MemorySecretSource implements SecretSource {
+ available = true;
+ readonly values = new Map<string, string>();
+ /** The ids of every put, in order. */
+ readonly puts: string[] = [];
+ corrupt: (id: string) => boolean = () => false;
+
+ async get(id: string): Promise<string | undefined> {
+ this.check(id);
+ const value = this.values.get(id);
+ return value !== undefined && this.corrupt(id) ? `${value}-changed` : value;
+ }
+
+ async put(id: string, secret: string): Promise<void> {
+ this.check(id);
+ this.values.set(id, secret);
+ this.puts.push(id);
+ }
+
+ async delete(id: string): Promise<boolean> {
+ this.check(id);
+ return this.values.delete(id);
+ }
+
+ async list(): Promise<string[]> {
+ if (!this.available) throw new SecretsUnavailableError();
+ return [...this.values.keys()].sort();
+ }
+
+ private check(id: string): void {
+ if (!this.available) throw new SecretsUnavailableError();
+ if (!ID.test(id)) throw new Error("That secret id is not valid.");
+ }
+}
diff --git a/packages/daemon/test/app-channel.test.ts b/packages/daemon/test/app-channel.test.ts
index b911bb1..24e2764 100644
--- a/packages/daemon/test/app-channel.test.ts
+++ b/packages/daemon/test/app-channel.test.ts
@@ -3,16 +3,15 @@
// register the computer helper; the app can, and confirms natively what widens access.
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
import { APP_REQUIRED, type ServerMessage } from "@gentle-dot/protocol";
import { afterEach, describe, expect, it } from "vitest";
import WebSocket from "ws";
import { type DotDaemon, startDaemon } from "../src/daemon.ts";
import { fakeApp } from "./fake-app.ts";
import { fakeAuthRuntime } from "./fake-auth-runtime.ts";
+import { oauthOptions } from "./fake-oauth.ts";
import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
-const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
const HELPER = "http://127.0.0.1:51234/mcp";
const KEY = "s3cr3t-Computer-Key-0123456789abcdef";
@@ -66,9 +65,8 @@ async function setup(options: { channel?: boolean } = {}) {
agentArgs: [FAKE_AGENT],
agentHome,
backoffMs: [50],
- agentEnv: { ...process.env, FAKE_MCP_CLI_MODE: "auto" },
authRuntime: async () => fake.runtime,
- connectorCli: { command: process.execPath, args: [FAKE_CLI] },
+ connectorOAuth: oauthOptions(true),
importHome,
...(options.channel === false ? {} : { appChannel: app.daemonEnd }),
});
diff --git a/packages/daemon/test/computer.test.ts b/packages/daemon/test/computer.test.ts
index fce05e0..2baff63 100644
--- a/packages/daemon/test/computer.test.ts
+++ b/packages/daemon/test/computer.test.ts
@@ -1,15 +1,14 @@
import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
import type { ConnectorInfo, ServerMessage } from "@gentle-dot/protocol";
import { afterEach, describe, expect, it } from "vitest";
import WebSocket from "ws";
import { type DotDaemon, startDaemon } from "../src/daemon.ts";
import { fakeApp, sendLikeThePanel } from "./fake-app.ts";
import { fakeAuthRuntime } from "./fake-auth-runtime.ts";
+import { oauthOptions } from "./fake-oauth.ts";
import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
-const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
const HELPER = "http://127.0.0.1:51234/mcp";
const KEY = "s3cr3t-Computer-Key-0123456789abcdef";
@@ -19,7 +18,7 @@ afterEach(async () => {
});
interface Setup {
- cliMode?: "auto";
+ browser?: "auto";
/** Written to `<data>/connectors.json` before the daemon starts. */
saved?: object;
/** Files below the home folder the import scan reads, by relative path. */
@@ -53,10 +52,9 @@ async function setup(options: Setup = {}) {
agentEnv: {
...process.env,
FAKE_AGENT_ENV_FILE: envFile,
- ...(options.cliMode ? { FAKE_MCP_CLI_MODE: options.cliMode } : {}),
},
authRuntime: async () => fake.runtime,
- connectorCli: { command: process.execPath, args: [FAKE_CLI] },
+ connectorOAuth: oauthOptions(options.browser === "auto"),
importHome,
appChannel: app.daemonEnd,
log: (line) => logs.push(line),
@@ -339,7 +337,7 @@ describe("computer control registration (S24.7)", () => {
describe("connectors next to the computer (regression)", () => {
it("connects, changes, and removes a connector while the helper is registered, and puts back a tampered mcp.json", async () => {
- const { d, mcpFile, servers, send, find, list, policy } = await setup({ cliMode: "auto" });
+ const { d, mcpFile, servers, send, find, list, policy } = await setup({ browser: "auto" });
send({ type: "computer_register", url: HELPER, token: KEY });
await waitFor(() => servers().computer);
diff --git a/packages/daemon/test/connector-drafts.test.ts b/packages/daemon/test/connector-drafts.test.ts
index 2bf8ea6..afdcf1e 100644
--- a/packages/daemon/test/connector-drafts.test.ts
+++ b/packages/daemon/test/connector-drafts.test.ts
@@ -2,7 +2,6 @@
// S19: the assistant drafts a connector with `propose_connector`; only the user's approval adds it.
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
-import { fileURLToPath } from "node:url";
import type { ServerMessage, ServerPayload } from "@gentle-dot/protocol";
import { afterEach, describe, expect, it } from "vitest";
import WebSocket from "ws";
@@ -15,11 +14,12 @@ import approvalGuard, {
PROPOSE_TOOL,
proposeConnector,
} from "../src/extensions/approval-guard.ts";
+import { MemorySecretSource } from "../src/secret-source.ts";
import { fakeApp, sendLikeThePanel } from "./fake-app.ts";
import { fakeAuthRuntime } from "./fake-auth-runtime.ts";
+import { oauthOptions } from "./fake-oauth.ts";
import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
-const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
const SECRET = "gh-token-$top!secret";
/** Drafts that would put a typed secret into the command line or an address the model chose. */
@@ -146,16 +146,15 @@ afterEach(() => {
for (const manager of managers.splice(0)) manager.cancelAll();
});
-function setup(cliEnv: Record<string, string> = {}) {
+function setup() {
const dataDir = tempDir();
const agentHome = join(dataDir, "agent");
const logs: string[] = [];
- const store = new ConnectorStore({ dataDir, agentHome });
+ const secrets = new MemorySecretSource();
+ const store = new ConnectorStore({ dataDir, agentHome, secrets });
const manager = new ConnectorManager({
store,
- cli: { command: process.execPath, args: [FAKE_CLI] },
- env: { ...process.env, HOME: join(dataDir, "home"), ...cliEnv },
- cwd: dataDir,
+ oauth: oauthOptions(true),
log: (line) => logs.push(line),
});
managers.push(manager);
@@ -165,7 +164,7 @@ function setup(cliEnv: Record<string, string> = {}) {
const sent: ServerPayload[] = [];
const emit = (payload: ServerPayload) => sent.push(payload);
const prompts = () => sent.flatMap((m) => (m.type === "auth_prompt" ? [m.prompt] : []));
- return { dataDir, agentHome, store, manager, changes, owner, sent, emit, prompts, logs };
+ return { dataDir, agentHome, store, manager, changes, owner, sent, emit, prompts, logs, secrets };
}
describe("connector drafts", () => {
@@ -235,7 +234,7 @@ describe("connector drafts", () => {
});
it("on approval asks for each secret in the app, then adds the server read only with every tool hidden", async () => {
- const { manager, store, owner, emit, sent, prompts, logs, changes } = setup();
+ const { manager, store, owner, emit, sent, prompts, logs, changes, secrets, dataDir } = setup();
const draft = manager.propose(JSON.stringify(stdioDraft));
expect(manager.decideDraft(owner, draft?.draftId ?? "", true, emit)).toBeUndefined();
const prompt = await waitFor(() => prompts()[0]);
@@ -246,19 +245,16 @@ describe("connector drafts", () => {
expect(done).toMatchObject({ providerId: "github", ok: true });
expect(changes).toContain(true);
const saved = store.state().connectors.github;
- expect(saved).toMatchObject({
- enabled: true,
+ expect(saved).toMatchObject({ enabled: true, mode: "read_only" });
+ expect(secrets.values.get("connector/github/value/GITHUB_PERSONAL_ACCESS_TOKEN")).toBe(SECRET);
+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).not.toContain(SECRET);
+ // Read only with no curated list: the proxy shows none of its tools.
+ expect(store.proxyView("github")).toMatchObject({
mode: "read_only",
- values: { GITHUB_PERSONAL_ACCESS_TOKEN: SECRET },
- });
- const server = JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers.github;
- expect(server).toMatchObject({
- command: "npx",
- args: ["-y", "@modelcontextprotocol/[email protected]"],
- exposure: "direct",
- toolExposure: { "*": "hidden" },
+ readOnlyTools: [],
+ server: { command: "npx", args: ["-y", "@modelcontextprotocol/[email protected]"] },
});
- expect(server.env.GITHUB_PERSONAL_ACCESS_TOKEN).not.toBe(SECRET);
+ expect((await store.credentials("github")).env).toEqual({ GITHUB_PERSONAL_ACCESS_TOKEN: SECRET });
expect(store.policy().connectors?.github).toEqual({
name: "GitHub",
mode: "read_only",
@@ -281,17 +277,11 @@ describe("connector drafts", () => {
expect(logs.join("\n")).not.toContain(SECRET);
// Read and send shows every tool, and each call asks (no curated list).
manager.setMode("github", "read_write");
- expect(
- JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers.github.toolExposure,
- ).toBeUndefined();
expect(store.proxyView("github")).toMatchObject({ mode: "read_write", readOnlyTools: [] });
});
it("gives a draft with a taken name its own id, and signs in when it needs OAuth", async () => {
- const { manager, store, owner, emit, sent } = setup({
- FAKE_MCP_CLI_MODE: "auto",
- FAKE_MCP_CLI_URL: "https://mcp.notion.com/mcp",
- });
+ const { manager, store, owner, emit, sent } = setup();
store.update((state) => {
state.connectors.notion = { enabled: true, mode: "read_only" };
});
@@ -362,7 +352,7 @@ describe("connector drafts through the daemon", () => {
backoffMs: [50],
agentHome: join(dataDir, "agent"),
authRuntime: async () => fake.runtime,
- connectorCli: { command: process.execPath, args: [FAKE_CLI] },
+ connectorOAuth: oauthOptions(),
importHome: tempDir(),
appChannel: app.daemonEnd,
});
@@ -393,11 +383,12 @@ describe("connector drafts through the daemon", () => {
m.type === "connectors" && m.connectors.some((c) => c.id === "github" && c.custom !== undefined),
),
);
+ // Added read only: with no curated list, the proxy shows none of its tools.
expect(
- JSON.parse(readFileSync(join(dataDir, "connector-signin", "mcp.json"), "utf8")).mcpServers.github
- .toolExposure,
- ).toEqual({
- "*": "hidden",
+ JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8")).connectors.github,
+ ).toMatchObject({
+ enabled: true,
+ mode: "read_only",
});
// The engine reaches it only through the proxy.
expect(
diff --git a/packages/daemon/test/connector-import.test.ts b/packages/daemon/test/connector-import.test.ts
index 3446c86..59e42af 100644
--- a/packages/daemon/test/connector-import.test.ts
+++ b/packages/daemon/test/connector-import.test.ts
@@ -1,17 +1,15 @@
// biome-ignore-all lint/suspicious/noTemplateCurlyInString: the fixtures are other apps' configs, written with their `${...}` references.
// S20: the user's MCP servers from other apps, found read-only in a fixture home, imported on request.
import { createHash } from "node:crypto";
-import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
-import { createRequire } from "node:module";
+import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
import type { ImportCandidate, ServerPayload } from "@gentle-dot/protocol";
import { afterEach, describe, expect, it } from "vitest";
import { scanClientConfigs } from "../src/connector-import.ts";
import { ConnectorManager, ConnectorStore } from "../src/connectors.ts";
+import { MemorySecretSource } from "../src/secret-source.ts";
import { tempDir, waitFor } from "./helpers.ts";
-const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
const SECRETS = ["ghp_desktopsecret", "sk_cursorsecret", "bar-secret-value", "lin-token-123"];
function write(home: string, path: string, value: unknown) {
@@ -128,21 +126,6 @@ function snapshot(home: string): Record<string, string> {
return out;
}
-async function engine() {
- const require = createRequire(import.meta.url);
- const load = async <T>(path: string) => {
- const file = (require.resolve.paths("@earendil-works/pi-coding-agent") ?? [])
- .map((dir) => join(dir, "@earendil-works", "pi-coding-agent", "dist", "core", path))
- .find((candidate) => existsSync(candidate));
- if (!file) throw new Error("the engine package is missing");
- return (await import(pathToFileURL(file).href)) as T;
- };
- return {
- ...(await load<{ validateMcpServerConfig(name: string, raw: unknown): unknown }>("mcp-servers.js")),
- ...(await load<{ resolveConfigValue(config: string): string | undefined }>("resolve-config-value.js")),
- };
-}
-
describe("scanning other apps' MCP configs", () => {
it("reads every client format and maps it to the engine's schema", () => {
const home = fixtureHome();
@@ -213,12 +196,15 @@ function setup(home: string) {
const dataDir = tempDir();
const agentHome = join(dataDir, "agent");
const logs: string[] = [];
- const store = new ConnectorStore({ dataDir, agentHome });
+ const secrets = new MemorySecretSource();
+ const store = new ConnectorStore({
+ dataDir,
+ agentHome,
+ secrets,
+ env: { PATH: "/usr/bin", GH_TOKEN: "gh-from-env" },
+ });
const manager = new ConnectorManager({
store,
- cli: { command: process.execPath, args: [FAKE_CLI] },
- env: { ...process.env, HOME: join(dataDir, "home") },
- cwd: dataDir,
importHome: home,
log: (line) => logs.push(line),
});
@@ -226,7 +212,7 @@ function setup(home: string) {
const owner = {};
const sent: ServerPayload[] = [];
const emit = (payload: ServerPayload) => sent.push(payload);
- return { agentHome, dataDir, store, manager, logs, owner, sent, emit };
+ return { agentHome, dataDir, store, manager, logs, owner, sent, emit, secrets };
}
const pick = (found: ImportCandidate[], name: string) => {
@@ -278,43 +264,33 @@ describe("importing MCP servers", () => {
expect(found.filter((c) => c.name === "github")).toHaveLength(1);
});
- it("copies the chosen servers with their values into private state, read only and hidden, without touching the sources", async () => {
+ it("copies the chosen servers, their values into the app's secure store, read only and hidden, without touching the sources", async () => {
const home = fixtureHome();
const before = snapshot(home);
- const { manager, store, agentHome, dataDir, logs, owner, emit, sent } = setup(home);
- const { validateMcpServerConfig, resolveConfigValue } = await engine();
+ const { manager, store, agentHome, dataDir, logs, owner, emit, sent, secrets } = setup(home);
const found = manager.scan();
const chosen = ["github", "stripe", "copilot", "everything", "perplexity", "legacy", "linear"].map(
(name) => pick(found, name).id,
);
- expect(manager.importServers(chosen).sort()).toEqual([
+ expect((await manager.importServers(chosen)).sort()).toEqual([
"copilot",
"everything",
"github",
"perplexity",
"stripe",
]);
- const mcp = JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers as Record<
- string,
- Record<string, unknown>
- >;
- for (const [name, config] of Object.entries(mcp)) {
- expect(typeof validateMcpServerConfig(name, config), name).toBe("object");
- expect(config.toolExposure, name).toEqual({ "*": "hidden" });
- }
- expect(
- resolveConfigValue(
- (mcp.github?.env as Record<string, string> | undefined)?.GITHUB_PERSONAL_ACCESS_TOKEN ?? "",
- ),
- ).toBe("ghp_desktopsecret");
- expect(
- resolveConfigValue((mcp.stripe?.headers as Record<string, string> | undefined)?.Authorization ?? ""),
- ).toBe("Bearer sk_cursorsecret");
- expect((mcp.copilot?.headers as Record<string, string> | undefined)?.Authorization).toBe(
- "Bearer ${GH_TOKEN}",
- );
+ // Read only with no curated list: the proxy shows none of their tools.
+ for (const id of ["copilot", "everything", "github", "stripe"])
+ expect(store.proxyView(id), id).toMatchObject({ mode: "read_only", readOnlyTools: [] });
+ expect((await store.credentials("github")).env).toEqual({
+ GITHUB_PERSONAL_ACCESS_TOKEN: "ghp_desktopsecret",
+ });
+ expect((await store.credentials("stripe")).headers).toEqual({ Authorization: "Bearer sk_cursorsecret" });
+ // An environment reference stays one, resolved only when the proxy connects.
+ expect(secrets.values.get("connector/copilot/header/Authorization")).toBe("Bearer ${GH_TOKEN}");
+ expect((await store.credentials("copilot")).headers).toEqual({ Authorization: "Bearer gh-from-env" });
// A server that still needs a typed value waits for it.
- expect(mcp.perplexity).toBeUndefined();
+ expect(store.proxyView("perplexity")).toBeUndefined();
const list = manager.list();
expect(list.find((c) => c.id === "perplexity")).toMatchObject({
status: "needs_setup",
@@ -335,15 +311,26 @@ describe("importing MCP servers", () => {
expect(JSON.stringify(list)).not.toContain(secret);
expect(logs.join("\n")).not.toContain(secret);
}
- expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toContain("ghp_desktopsecret");
+ const record = readFileSync(join(dataDir, "connectors.json"), "utf8");
+ for (const secret of ["ghp_desktopsecret", "Bearer sk_cursorsecret"])
+ expect(record).not.toContain(secret);
+ const saved = JSON.parse(record).connectors;
+ expect(saved.everything.custom.server.env).toEqual({
+ FOO: { secretRef: "connector/everything/env/FOO" },
+ });
+ expect(secrets.values.get("connector/everything/env/FOO")).toBe("bar-secret-value");
+ // A credential inside the address or the command line stays there (a documented limit; masked when shown).
+ expect(saved.stripe.custom.server.url).toBe("https://mcp.stripe.com?key=sk_cursorsecret");
+ expect(saved.everything.custom.server.args).toContain("bar-secret-value");
+ expect(JSON.parse(record).connectors.github.custom.server.env).toEqual({
+ GITHUB_PERSONAL_ACCESS_TOKEN: { secretRef: "connector/github/env/GITHUB_PERSONAL_ACCESS_TOKEN" },
+ });
// The VS Code input is typed in the app.
expect(manager.setup(owner, "perplexity", emit)).toBeUndefined();
const prompt = await waitFor(() => sent.flatMap((m) => (m.type === "auth_prompt" ? [m.prompt] : []))[0]);
expect(prompt).toMatchObject({ kind: "secret", message: expect.stringContaining("Perplexity API Key") });
manager.reply(owner, prompt.flowId, { value: "pplx-typed" });
await waitFor(() => sent.find((m) => m.type === "auth_done"));
- const perplexity = JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers.perplexity;
- expect(resolveConfigValue(perplexity.env.PERPLEXITY_API_KEY)).toBe("pplx-typed");
// The proxy hands the server what was typed, and what it reads from the environment.
expect((await store.credentials("perplexity")).env).toEqual({ PERPLEXITY_API_KEY: "pplx-typed" });
expect(readFileSync(join(agentHome, "mcp.json"), "utf8")).not.toContain("pplx-typed");
@@ -351,13 +338,13 @@ describe("importing MCP servers", () => {
// Importing again adds nothing: they are already connectors.
const again = manager.scan();
expect(pick(again, "github")).toMatchObject({ importable: false, duplicateOf: "github" });
- expect(manager.importServers([pick(again, "github").id, "unknown:id"])).toEqual([]);
+ expect(await manager.importServers([pick(again, "github").id, "unknown:id"])).toEqual([]);
expect(snapshot(home)).toEqual(before);
});
- it("imports nothing before a scan", () => {
+ it("imports nothing before a scan", async () => {
const { manager, store } = setup(fixtureHome());
- expect(manager.importServers(["Cursor:github"])).toEqual([]);
+ expect(await manager.importServers(["Cursor:github"])).toEqual([]);
expect(store.state()).toEqual({ connectors: {} });
});
});
diff --git a/packages/daemon/test/connector-masking.test.ts b/packages/daemon/test/connector-masking.test.ts
index 11c33e3..c9819be 100644
--- a/packages/daemon/test/connector-masking.test.ts
+++ b/packages/daemon/test/connector-masking.test.ts
@@ -3,14 +3,12 @@
// wherever it sits in the command line or address, and still shows the useful shape (command, host, path).
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, join } from "node:path";
-import { fileURLToPath } from "node:url";
import type { ImportCandidate } from "@gentle-dot/protocol";
import { afterEach, describe, expect, it } from "vitest";
import { ConnectorManager, ConnectorStore, summarize } from "../src/connectors.ts";
+import { MemorySecretSource } from "../src/secret-source.ts";
import { tempDir } from "./helpers.ts";
-const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
-
function write(home: string, path: string, value: unknown) {
const file = join(home, path);
mkdirSync(dirname(file), { recursive: true });
@@ -168,14 +166,12 @@ afterEach(() => {
function setup(home: string) {
const dataDir = tempDir();
- const store = new ConnectorStore({ dataDir, agentHome: join(dataDir, "agent") });
- const manager = new ConnectorManager({
- store,
- cli: { command: process.execPath, args: [FAKE_CLI] },
- env: { ...process.env, HOME: join(dataDir, "home") },
- cwd: dataDir,
- importHome: home,
+ const store = new ConnectorStore({
+ dataDir,
+ agentHome: join(dataDir, "agent"),
+ secrets: new MemorySecretSource(),
});
+ const manager = new ConnectorManager({ store, importHome: home });
managers.push(manager);
return { store, manager };
}
@@ -197,10 +193,10 @@ describe("masking credentials in server summaries", () => {
}
});
- it("keeps every credential out of the Connectors list after the import", () => {
+ it("keeps every credential out of the Connectors list after the import", async () => {
const { manager } = setup(fixtureHome());
const found = manager.scan();
- const imported = manager.importServers(found.map((c) => c.id));
+ const imported = await manager.importServers(found.map((c) => c.id));
expect(imported).toHaveLength(CASES.length);
const list = manager.list();
for (const { name, secret, summary } of CASES) {
diff --git a/packages/daemon/test/connector-secrets.test.ts b/packages/daemon/test/connector-secrets.test.ts
new file mode 100644
index 0000000..966828c
--- /dev/null
+++ b/packages/daemon/test/connector-secrets.test.ts
@@ -0,0 +1,693 @@
+// biome-ignore-all lint/suspicious/noTemplateCurlyInString: `${input:<key>}` is the placeholder connectors use.
+// Connector secrets in the desktop app's secure store (S25.5, T23d): the daemon asks the app for
+// them over its private channel and keeps them in memory only; typed values, OAuth sign-ins, and
+// refreshed tokens go there and to no file; without the app, connectors that need a secret fail
+// closed while the others keep working; and the secrets that files held before move there once.
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { createServer, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { McpClient, StreamableHttpTransport, type Tool } from "@earendil-works/pi-mcp";
+import type { ServerMessage, ServerPayload } from "@gentle-dot/protocol";
+import { afterEach, describe, expect, it } from "vitest";
+import WebSocket from "ws";
+import { AppChannel } from "../src/app-channel.ts";
+import { ConnectorManager, ConnectorStore, type CustomConnector } from "../src/connectors.ts";
+import { type DotDaemon, startDaemon } from "../src/daemon.ts";
+import { AppSecretSource, MemorySecretSource, NO_APP } from "../src/secret-source.ts";
+import { fakeApp, sendLikeThePanel } from "./fake-app.ts";
+import { fakeAuthRuntime } from "./fake-auth-runtime.ts";
+import { fakeOAuth } from "./fake-oauth.ts";
+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
+
+const FAKE_SERVER = fileURLToPath(new URL("./fixtures/fake-mcp-server.ts", import.meta.url));
+const TOKEN = "discord-bot-token-0f9c2b7e";
+const NOTION_KEY = "mcp__notion|https://mcp.notion.com/mcp";
+const LINEAR_KEY = "mcp__linear|https://mcp.linear.app/mcp";
+
+const stores: ConnectorStore[] = [];
+const managers: ConnectorManager[] = [];
+const daemons: DotDaemon[] = [];
+const closers: (() => Promise<unknown>)[] = [];
+afterEach(async () => {
+ for (const manager of managers.splice(0)) manager.cancelAll();
+ for (const store of stores.splice(0)) store.close();
+ await Promise.all(closers.splice(0).map((close) => close().catch(() => undefined)));
+ await Promise.all(daemons.splice(0).map((d) => d.close()));
+});
+
+/** Every file below `dir` whose bytes contain `needle`. */
+function filesContaining(dir: string, needle: string): string[] {
+ const found: string[] = [];
+ const walk = (folder: string) => {
+ for (const entry of readdirSync(folder, { withFileTypes: true })) {
+ const path = join(folder, entry.name);
+ if (entry.isDirectory()) walk(path);
+ else if (entry.isFile()) {
+ try {
+ if (readFileSync(path).includes(needle)) found.push(path);
+ } catch {}
+ }
+ }
+ };
+ walk(dir);
+ return found;
+}
+
+function storeWith(dataDir: string, secrets?: MemorySecretSource, logs: string[] = []) {
+ const store = new ConnectorStore({
+ dataDir,
+ agentHome: join(dataDir, "agent"),
+ ...(secrets ? { secrets } : {}),
+ log: (line) => logs.push(line),
+ });
+ stores.push(store);
+ return store;
+}
+
+function managerWith(store: ConnectorStore, oauth?: ReturnType<typeof fakeOAuth>, logs: string[] = []) {
+ const manager = new ConnectorManager({
+ store,
+ ...(oauth ? { oauth: { fetch: oauth.fetch } } : {}),
+ log: (line) => logs.push(line),
+ });
+ managers.push(manager);
+ const owner = {};
+ const sent: ServerPayload[] = [];
+ const emit = (payload: ServerPayload) => sent.push(payload);
+ const find = <T extends ServerPayload["type"]>(
+ type: T,
+ where: (m: Extract<ServerPayload, { type: T }>) => boolean = () => true,
+ ) =>
+ waitFor(() =>
+ sent.find(
+ (m): m is Extract<ServerPayload, { type: T }> =>
+ m.type === type && where(m as Extract<ServerPayload, { type: T }>),
+ ),
+ );
+ return { manager, owner, sent, emit, find };
+}
+
+const linkOf = (m: ServerPayload) =>
+ m.type === "auth_event" && m.event.kind === "auth_url" ? m.event.url : "";
+
+describe("the app's secret store over its channel", () => {
+ it("puts, reads back, lists, and deletes through the app; a missing secret reads as undefined", async () => {
+ const app = fakeApp();
+ const channel = new AppChannel(app.daemonEnd);
+ closers.push(async () => channel.close());
+ const source = new AppSecretSource(channel);
+ expect(source.available).toBe(true);
+ await source.put("connector/discord/value/token", TOKEN);
+ expect(app.secrets.get("connector/discord/value/token")).toBe(TOKEN);
+ expect(await source.get("connector/discord/value/token")).toBe(TOKEN);
+ expect(await source.get("connector/missing")).toBeUndefined();
+ expect(await source.list()).toEqual(["connector/discord/value/token"]);
+ expect(await source.delete("connector/discord/value/token")).toBe(true);
+ expect(await source.delete("connector/discord/value/token")).toBe(false);
+ expect(app.secrets.size).toBe(0);
+ expect(app.secretCalls.join("\n")).not.toContain(TOKEN);
+ });
+
+ it("without the app, every call fails closed with the reason", async () => {
+ const app = fakeApp();
+ const channel = new AppChannel(app.daemonEnd);
+ const source = new AppSecretSource(channel);
+ app.close();
+ await waitFor(() => !channel.connected);
+ expect(source.available).toBe(false);
+ await expect(source.get("connector/x")).rejects.toThrow(NO_APP);
+ await expect(source.put("connector/x", "s")).rejects.toThrow(NO_APP);
+ await expect(new AppSecretSource(undefined).list()).rejects.toThrow(NO_APP);
+ expect(NO_APP).toBe("Open the Gentle Dot app to use this connector.");
+ });
+});
+
+describe("typed connector secrets", () => {
+ it("stores a typed bot token in the app's store and in no file; a restart reads it back from there", async () => {
+ const dataDir = tempDir();
+ const source = new MemorySecretSource();
+ const logs: string[] = [];
+ const store = storeWith(dataDir, source, logs);
+ const { manager, owner, emit, sent, find } = managerWith(store, undefined, logs);
+ manager.connect(owner, "discord", emit);
+ const prompt = await find("auth_prompt");
+ manager.reply(owner, prompt.prompt.flowId, { value: TOKEN });
+ expect(await find("auth_done")).toMatchObject({ providerId: "discord", ok: true });
+ expect(source.values.get("connector/discord/value/token")).toBe(TOKEN);
+ expect(filesContaining(dataDir, TOKEN)).toEqual([]);
+ const record = JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8"));
+ expect(record.connectors.discord.values).toEqual({
+ token: { secretRef: "connector/discord/value/token" },
+ });
+ expect((await store.credentials("discord")).env).toEqual({ DISCORD_TOKEN: TOKEN });
+ expect(JSON.stringify(sent)).not.toContain(TOKEN);
+ expect(logs.join("\n")).not.toContain(TOKEN);
+
+ store.close();
+ const restarted = storeWith(dataDir, source);
+ expect((await restarted.credentials("discord")).env).toEqual({ DISCORD_TOKEN: TOKEN });
+ expect(filesContaining(dataDir, TOKEN)).toEqual([]);
+ });
+
+ it("without the app, a connector that needs a secret fails closed and one without secrets keeps working", async () => {
+ const dataDir = tempDir();
+ const source = new MemorySecretSource();
+ const first = storeWith(dataDir, source);
+ const plain: CustomConnector = {
+ name: "Plain",
+ description: "",
+ origin: "Drafted by the assistant",
+ server: { command: "plain-mcp", args: ["--stdio"] },
+ fields: [],
+ oauth: false,
+ };
+ await first.keepValues("discord", { token: TOKEN });
+ first.update((state) => {
+ state.connectors.discord = { ...state.connectors.discord, enabled: true, mode: "read_only" };
+ state.connectors.plain = { enabled: true, mode: "read_write", custom: plain };
+ });
+ first.close();
+
+ const alone = storeWith(dataDir);
+ await expect(alone.credentials("discord")).rejects.toThrow(NO_APP);
+ expect(alone.proxyView("discord")?.unavailable).toBe(NO_APP);
+ expect(await alone.credentials("plain")).toEqual({});
+ expect(alone.proxyView("plain")).toMatchObject({ server: { command: "plain-mcp", args: ["--stdio"] } });
+ expect(alone.proxyView("plain")?.unavailable).toBeUndefined();
+ expect(filesContaining(dataDir, TOKEN)).toEqual([]);
+ });
+});
+
+describe("OAuth sign-in in the daemon", () => {
+ it("signs in with its own OAuth flow, keeps the tokens only in the app's store, and stores a refresh there", async () => {
+ const dataDir = tempDir();
+ const source = new MemorySecretSource();
+ const oauth = fakeOAuth();
+ const logs: string[] = [];
+ const store = storeWith(dataDir, source, logs);
+ const { manager, owner, emit, sent, find } = managerWith(store, oauth, logs);
+ manager.connect(owner, "notion", emit);
+ const link = linkOf(await find("auth_event", (m) => linkOf(m) !== ""));
+ expect(link).toMatch(/^https:\/\/auth\.example\.com\/authorize\?/);
+ expect(new URL(link).searchParams.get("redirect_uri")).toMatch(/^http:\/\/127\.0\.0\.1:\d+\/callback$/);
+ expect(await oauth.browse(link)).toBe(200);
+ expect(await find("auth_done")).toMatchObject({ providerId: "notion", ok: true });
+ expect(manager.list()[0]?.status).toBe("connected");
+ const saved = JSON.parse(source.values.get("connector/notion/signin") ?? "{}");
+ expect(saved.tokens).toMatchObject({ access_token: "access-token-1", refresh_token: "refresh-token-1" });
+ for (const secret of ["access-token-1", "refresh-token-1"]) {
+ expect(filesContaining(dataDir, secret)).toEqual([]);
+ expect(logs.join("\n")).not.toContain(secret);
+ expect(JSON.stringify(sent)).not.toContain(secret);
+ }
+ expect(existsSync(join(dataDir, "connector-signin"))).toBe(false);
+
+ const { authProvider } = await store.credentials("notion");
+ expect(await authProvider?.token()).toBe("access-token-1");
+ await authProvider?.onUnauthorized?.({
+ response: new Response(null, { status: 401 }),
+ serverUrl: new URL("https://mcp.notion.com/mcp"),
+ fetch: oauth.fetch,
+ token: "access-token-1",
+ });
+ expect(await authProvider?.token()).toBe("access-token-2");
+ expect(JSON.parse(source.values.get("connector/notion/signin") ?? "{}").tokens.refresh_token).toBe(
+ "refresh-token-2",
+ );
+ expect(filesContaining(dataDir, "access-token-2")).toEqual([]);
+ expect(filesContaining(dataDir, "refresh-token-2")).toEqual([]);
+ });
+
+ it("finishes with an address the user pastes, refusing one for another place or sign-in", async () => {
+ const store = storeWith(tempDir(), new MemorySecretSource());
+ const oauth = fakeOAuth();
+ const { manager, owner, emit, sent, find } = managerWith(store, oauth);
+ expect(manager.signIn(owner, "notion", emit)).toMatchObject({ code: "connector_not_added" });
+ manager.connect(owner, "notion", emit);
+ const link = linkOf(await find("auth_event", (m) => linkOf(m) !== ""));
+ const prompt = await find("auth_prompt", (m) => m.prompt.kind === "manual_code");
+ const callback = oauth.callbackFor(link);
+ for (const pasted of [
+ `https://evil.example.com${callback.pathname}${callback.search}`,
+ `${callback.origin}${callback.pathname}?code=c&state=other-state`,
+ "not an address",
+ ]) {
+ const before = sent.filter((m) => m.type === "auth_prompt").length;
+ expect(manager.reply(owner, prompt.prompt.flowId, { value: pasted })).toBe(true);
+ await waitFor(() => sent.filter((m) => m.type === "auth_prompt").length > before);
+ }
+ expect(sent.some((m) => m.type === "auth_done")).toBe(false);
+ expect(manager.reply({}, prompt.prompt.flowId, { value: callback.href })).toBe(false);
+ expect(manager.reply(owner, prompt.prompt.flowId, { value: callback.href })).toBe(true);
+ expect(await find("auth_done")).toMatchObject({ providerId: "notion", ok: true });
+ expect(manager.list()[0]?.status).toBe("connected");
+ });
+
+ it("reports a refused sign-in in plain words, and a cancelled one stores nothing", async () => {
+ const source = new MemorySecretSource();
+ const logs: string[] = [];
+ const store = storeWith(tempDir(), source, logs);
+ const failing = fakeOAuth({ mode: "fail" });
+ const { manager, owner, emit, find, sent } = managerWith(store, failing, logs);
+ manager.connect(owner, "notion", emit);
+ const link = linkOf(await find("auth_event", (m) => linkOf(m) !== ""));
+ await failing.browse(link);
+ expect(await find("auth_done")).toMatchObject({
+ ok: false,
+ message: "Sign-in did not finish. Please try again.",
+ });
+ expect(manager.list()[0]?.status).toBe("error");
+ expect(logs.join("\n")).not.toMatch(/auth\.example\.com|authorization-code/);
+ sent.splice(0);
+ manager.signIn(owner, "notion", emit);
+ const prompt = await find("auth_prompt", (m) => m.prompt.kind === "manual_code");
+ expect(manager.reply(owner, prompt.prompt.flowId, { cancelled: true })).toBe(true);
+ expect(await find("auth_done")).toMatchObject({ ok: false, message: "Sign-in cancelled." });
+ expect(source.values.has("connector/notion/signin")).toBe(false);
+ });
+
+ it("removing a connector deletes its secrets from the app's store", async () => {
+ const source = new MemorySecretSource();
+ const store = storeWith(tempDir(), source);
+ const { manager, owner, emit, find } = managerWith(store);
+ manager.connect(owner, "discord", emit);
+ const prompt = await find("auth_prompt");
+ manager.reply(owner, prompt.prompt.flowId, { value: TOKEN });
+ await find("auth_done");
+ source.values.set("connector/discordant/value/token", "another connector's");
+ expect(await manager.remove("discord")).toBeUndefined();
+ expect([...source.values.keys()]).toEqual(["connector/discordant/value/token"]);
+ });
+});
+
+/** An install from before T23d: secrets in connectors.json, the sign-in home, and the engine's old file. */
+function legacyInstall() {
+ const dataDir = tempDir();
+ const agentHome = join(dataDir, "agent");
+ const signin = join(dataDir, "connector-signin");
+ mkdirSync(agentHome, { recursive: true });
+ mkdirSync(signin, { recursive: true });
+ const tracker: CustomConnector = {
+ name: "Tracker",
+ description: "",
+ origin: "Imported from Cursor",
+ server: {
+ url: "https://tracker.example.com/mcp",
+ headers: { Authorization: "Bearer lit-header-secret" },
+ },
+ fields: [],
+ oauth: false,
+ };
+ const files: CustomConnector = {
+ name: "Files",
+ description: "",
+ origin: "Imported from Claude Desktop",
+ server: { command: "files-mcp", env: { FILES_TOKEN: "lit-env-secret", MODE: "${input:mode}" } },
+ fields: [{ key: "mode", label: "Mode", secret: false }],
+ oauth: false,
+ };
+ writeFileSync(
+ join(dataDir, "connectors.json"),
+ JSON.stringify({
+ version: 1,
+ connectors: {
+ notion: { enabled: true, mode: "read_only" },
+ linear: { enabled: true, mode: "read_write" },
+ discord: { enabled: true, mode: "read_only", values: { token: TOKEN } },
+ slack: {
+ enabled: true,
+ mode: "read_only",
+ values: { client_id: "slack-client-id", client_secret: "slack-client-secret" },
+ },
+ tracker: { enabled: true, mode: "read_only", custom: tracker },
+ files: { enabled: true, mode: "read_only", values: { mode: "fast" }, custom: files },
+ },
+ }),
+ );
+ const state = (access: string) => ({
+ serverUrl: "x",
+ tokens: { access_token: access, token_type: "Bearer", refresh_token: `${access}-refresh` },
+ });
+ writeFileSync(join(signin, "mcp-auth.json"), JSON.stringify({ [NOTION_KEY]: state("notion-access") }));
+ writeFileSync(
+ join(signin, "mcp.json"),
+ JSON.stringify({ mcpServers: { discord: { env: { DISCORD_TOKEN: TOKEN } } } }),
+ );
+ writeFileSync(
+ join(agentHome, "mcp-auth.json"),
+ JSON.stringify({
+ [LINEAR_KEY]: state("linear-access"),
+ [NOTION_KEY]: state("older-notion-access"),
+ "mcp__ghost|https://ghost.example.com/mcp": state("ghost-access"),
+ }),
+ );
+ const secrets = [
+ TOKEN,
+ "slack-client-secret",
+ "lit-header-secret",
+ "lit-env-secret",
+ "notion-access",
+ "linear-access",
+ "ghost-access",
+ ];
+ return { dataDir, agentHome, signin, secrets };
+}
+
+describe("one-time migration into the app's store", () => {
+ it("moves every secret there, checks each one, and removes them from the files", async () => {
+ const { dataDir, agentHome, signin, secrets } = legacyInstall();
+ const source = new MemorySecretSource();
+ const logs: string[] = [];
+ const store = storeWith(dataDir, source, logs);
+ // Before the move, a secret that is still in a file is not used.
+ await expect(store.credentials("discord")).rejects.toThrow(NO_APP);
+ await store.migrate();
+ for (const secret of secrets) expect(filesContaining(dataDir, secret)).toEqual([]);
+ expect(existsSync(signin)).toBe(false);
+ expect(existsSync(join(agentHome, "mcp-auth.json"))).toBe(false);
+ const record = JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8"));
+ expect(record.version).toBe(2);
+ expect(record.connectors.discord.values).toEqual({
+ token: { secretRef: "connector/discord/value/token" },
+ });
+ expect(record.connectors.slack.values).toEqual({
+ client_id: "slack-client-id",
+ client_secret: { secretRef: "connector/slack/value/client_secret" },
+ });
+ expect(record.connectors.tracker.custom.server.headers).toEqual({
+ Authorization: { secretRef: "connector/tracker/header/Authorization" },
+ });
+ expect(record.connectors.files.custom.server.env).toEqual({
+ FILES_TOKEN: { secretRef: "connector/files/env/FILES_TOKEN" },
+ MODE: "${input:mode}",
+ });
+ expect(record.connectors.notion.signIn).toEqual({ secretRef: "connector/notion/signin" });
+ expect((await store.credentials("discord")).env).toEqual({ DISCORD_TOKEN: TOKEN });
+ expect((await store.credentials("tracker")).headers).toEqual({
+ Authorization: "Bearer lit-header-secret",
+ });
+ expect((await store.credentials("files")).env).toEqual({ FILES_TOKEN: "lit-env-secret", MODE: "fast" });
+ // The daemon's own sign-in wins over the engine's older one.
+ expect(await (await store.credentials("notion")).authProvider?.token()).toBe("notion-access");
+ expect(await (await store.credentials("linear")).authProvider?.token()).toBe("linear-access");
+ expect([...source.values.keys()].sort()).toEqual([
+ "connector/discord/value/token",
+ "connector/files/env/FILES_TOKEN",
+ "connector/linear/signin",
+ "connector/notion/signin",
+ "connector/slack/value/client_secret",
+ "connector/tracker/header/Authorization",
+ ]);
+ const log = logs.join("\n");
+ for (const secret of secrets) expect(log).not.toContain(secret);
+ expect(log).toMatch(/1 sign-in for a connector that is no longer added/);
+ });
+
+ it("runs once: a second run or a restart stores nothing again", async () => {
+ const { dataDir } = legacyInstall();
+ const source = new MemorySecretSource();
+ const store = storeWith(dataDir, source);
+ await store.migrate();
+ const puts = source.puts.length;
+ const record = readFileSync(join(dataDir, "connectors.json"), "utf8");
+ await store.migrate();
+ store.close();
+ const restarted = storeWith(dataDir, source);
+ await restarted.migrate();
+ expect(source.puts.length).toBe(puts);
+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toBe(record);
+ expect((await restarted.credentials("discord")).env).toEqual({ DISCORD_TOKEN: TOKEN });
+ });
+
+ it("after it, a planted sign-in file is not imported: it is reported once and left alone (N1)", async () => {
+ const { dataDir, agentHome, signin } = legacyInstall();
+ const source = new MemorySecretSource();
+ await storeWith(dataDir, source).migrate();
+ const planted = JSON.stringify({
+ [NOTION_KEY]: { tokens: { access_token: "planted-token", token_type: "Bearer" } },
+ });
+ mkdirSync(signin, { recursive: true });
+ writeFileSync(join(signin, "mcp-auth.json"), planted);
+ writeFileSync(join(agentHome, "mcp-auth.json"), planted);
+ const logs: string[] = [];
+ const store = storeWith(dataDir, source, logs);
+ await store.migrate();
+ store.enforce();
+ await store.migrate();
+ store.enforce();
+ expect(await (await store.credentials("notion")).authProvider?.token()).toBe("notion-access");
+ expect([...source.values.values()].join("\n")).not.toContain("planted-token");
+ expect(readFileSync(join(signin, "mcp-auth.json"), "utf8")).toBe(planted);
+ expect(readFileSync(join(agentHome, "mcp-auth.json"), "utf8")).toBe(planted);
+ const reports = logs.filter((line) => line.includes("not imported"));
+ expect(reports).toHaveLength(2);
+ expect(logs.join("\n")).not.toContain("planted-token");
+ });
+
+ it("a 0-byte or unreadable sign-in file never blocks the rest (N2)", async () => {
+ const { dataDir, agentHome, signin } = legacyInstall();
+ writeFileSync(join(signin, "mcp-auth.json"), "");
+ const source = new MemorySecretSource();
+ const logs: string[] = [];
+ const store = storeWith(dataDir, source, logs);
+ await store.migrate();
+ expect(await (await store.credentials("notion")).authProvider?.token()).toBe("older-notion-access");
+ expect(await (await store.credentials("linear")).authProvider?.token()).toBe("linear-access");
+ expect((await store.credentials("discord")).env).toEqual({ DISCORD_TOKEN: TOKEN });
+ expect(existsSync(join(agentHome, "mcp-auth.json"))).toBe(false);
+ expect(JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8")).version).toBe(2);
+
+ const other = legacyInstall();
+ const unreadable = join(other.agentHome, "mcp-auth.json");
+ chmodSync(unreadable, 0o000);
+ const blocked = statSync(unreadable).mode;
+ const second = storeWith(other.dataDir, new MemorySecretSource(), logs);
+ await second.migrate();
+ expect(await (await second.credentials("notion")).authProvider?.token()).toBe("notion-access");
+ expect((await second.credentials("discord")).env).toEqual({ DISCORD_TOKEN: TOKEN });
+ expect(existsSync(unreadable)).toBe(true);
+ expect(statSync(unreadable).mode).toBe(blocked);
+ chmodSync(unreadable, 0o600);
+ expect(logs.join("\n")).not.toMatch(/notion-access|linear-access/);
+ });
+
+ it("keeps the files as they were when a secret does not read back the same, and finishes next time", async () => {
+ const { dataDir, signin } = legacyInstall();
+ const before = readFileSync(join(dataDir, "connectors.json"), "utf8");
+ const broken = new MemorySecretSource();
+ broken.corrupt = (id) => id === "connector/discord/value/token";
+ const store = storeWith(dataDir, broken);
+ await store.migrate();
+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toContain(TOKEN);
+ expect(JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8")).version).toBe(1);
+ expect(existsSync(join(signin, "mcp-auth.json"))).toBe(true);
+ await expect(store.credentials("discord")).rejects.toThrow(NO_APP);
+ store.close();
+ expect(JSON.parse(before).connectors.discord.values.token).toBe(TOKEN);
+
+ const fixed = new MemorySecretSource();
+ const next = storeWith(dataDir, fixed);
+ await next.migrate();
+ expect(filesContaining(dataDir, TOKEN)).toEqual([]);
+ expect((await next.credentials("discord")).env).toEqual({ DISCORD_TOKEN: TOKEN });
+ });
+});
+
+/** Notion's server as the proxy reaches it: plain JSON over HTTP, recording each Authorization. */
+async function fakeNotion() {
+ const seen: (string | undefined)[] = [];
+ const tools: Tool[] = [
+ { name: "notion-search", inputSchema: { type: "object" }, annotations: { readOnlyHint: true } },
+ ];
+ const server: Server = createServer((req, res) => {
+ let body = "";
+ req.on("data", (chunk: Buffer) => {
+ body += chunk.toString("utf8");
+ });
+ req.on("end", () => {
+ const message = JSON.parse(body) as {
+ id?: number;
+ method: string;
+ params?: { protocolVersion?: string };
+ };
+ seen.push(req.headers.authorization);
+ if (message.id === undefined) {
+ res.writeHead(202).end();
+ return;
+ }
+ const result =
+ message.method === "initialize"
+ ? {
+ protocolVersion: message.params?.protocolVersion,
+ capabilities: { tools: {} },
+ serverInfo: { name: "notion", version: "1" },
+ }
+ : message.method === "tools/list"
+ ? { tools }
+ : { content: [{ type: "text", text: "found" }] };
+ res.writeHead(200, { "content-type": "application/json" });
+ res.end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result }));
+ });
+ });
+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
+ closers.push(() => new Promise((done) => server.close(done)));
+ return { url: `http://127.0.0.1:${(server.address() as AddressInfo).port}/mcp`, seen };
+}
+
+async function daemonWith(options: { dataDir: string; app?: ReturnType<typeof fakeApp> }) {
+ const { dataDir, app } = options;
+ const notion = await fakeNotion();
+ const oauth = fakeOAuth();
+ const d = await startDaemon({
+ port: 0,
+ host: "127.0.0.1",
+ dataDir,
+ workspace: join(dataDir, "workspace"),
+ uiDir: dataDir,
+ agentCommand: process.execPath,
+ agentArgs: [FAKE_AGENT],
+ agentHome: join(dataDir, "agent"),
+ backoffMs: [50],
+ authRuntime: async () => fakeAuthRuntime().runtime,
+ connectorOAuth: { fetch: oauth.fetch, openBrowser: (url) => void oauth.browse(url) },
+ connectorTransport: (connector, credentials) =>
+ "url" in connector.server
+ ? new StreamableHttpTransport({
+ url: notion.url,
+ ...(credentials.headers ? { headers: credentials.headers } : {}),
+ ...(credentials.authProvider ? { authProvider: credentials.authProvider } : {}),
+ openGetStream: false,
+ })
+ : (() => {
+ throw new Error("only remote servers here");
+ })(),
+ ...(app ? { appChannel: app.daemonEnd } : {}),
+ });
+ daemons.push(d);
+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);
+ const messages: ServerMessage[] = [];
+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));
+ await new Promise((resolve) => ws.on("open", resolve));
+ closers.push(async () => ws.close());
+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));
+ const ready = await waitFor(() => messages.find((m) => m.type === "ready"));
+ const clientId = ready.type === "ready" ? (ready.clientId ?? "") : "";
+ const mcpText = () => readFileSync(join(dataDir, "agent", "mcp.json"), "utf8");
+ const engineClient = async (id: string) => {
+ const entry = JSON.parse(mcpText()).mcpServers[id] as { url: string; headers: Record<string, string> };
+ const client = new McpClient({ name: "engine", version: "1" });
+ closers.push(() => client.close());
+ await client.connect(new StreamableHttpTransport({ url: entry.url, headers: entry.headers }));
+ return client;
+ };
+ return { d, notion, messages, mcpText, engineClient, clientId, ws };
+}
+
+describe("connector secrets end to end", () => {
+ it("connects Notion through the app: OAuth runs in the daemon, the token lives only in the app's store, and the proxy sends it", async () => {
+ const dataDir = tempDir();
+ const app = fakeApp([], "allow");
+ const { d, notion, messages, mcpText, engineClient, clientId, ws } = await daemonWith({ dataDir, app });
+ const send = sendLikeThePanel(
+ app,
+ () => clientId,
+ (m) => ws.send(JSON.stringify(m)),
+ );
+ const pid = d.supervisor.pid;
+ send({ type: "connector_connect", connectorId: "notion" });
+ await waitFor(() => messages.find((m) => m.type === "auth_done" && m.ok));
+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");
+ await waitFor(() => JSON.parse(mcpText()).mcpServers.notion);
+ const client = await engineClient("notion");
+ expect((await client.listTools()).map((t) => t.name)).toEqual(["notion-search"]);
+ expect(notion.seen.every((auth) => auth === "Bearer access-token-1")).toBe(true);
+ expect(JSON.parse(app.secrets.get("connector/notion/signin") ?? "{}").tokens.access_token).toBe(
+ "access-token-1",
+ );
+ expect(app.secretCalls.join("\n")).not.toContain("access-token-1");
+ expect(filesContaining(dataDir, "access-token-1")).toEqual([]);
+ expect(filesContaining(dataDir, "refresh-token-1")).toEqual([]);
+ });
+
+ it("without the app, a connector without secrets still works end to end, and one with a secret says why it cannot (regression)", async () => {
+ const dataDir = tempDir();
+ writeFileSync(
+ join(dataDir, "connectors.json"),
+ JSON.stringify({
+ version: 2,
+ connectors: {
+ discord: {
+ enabled: true,
+ mode: "read_only",
+ values: { token: { secretRef: "connector/discord/value/token" } },
+ },
+ chat: {
+ enabled: true,
+ mode: "read_write",
+ custom: {
+ name: "Chat",
+ description: "",
+ origin: "Drafted by the assistant",
+ server: { command: process.execPath, args: [FAKE_SERVER] },
+ fields: [],
+ oauth: false,
+ },
+ },
+ },
+ }),
+ );
+ const { mcpText, engineClient } = await daemonWithStdio(dataDir);
+ await waitFor(() => JSON.parse(mcpText()).mcpServers.chat);
+ const chat = await engineClient("chat");
+ expect((await chat.listTools()).map((t) => t.name)).toEqual([
+ "list_messages",
+ "notion-search",
+ "send_message",
+ ]);
+ const discord = new McpClient({ name: "engine", version: "1" });
+ closers.push(() => discord.close());
+ const entry = JSON.parse(mcpText()).mcpServers.discord as {
+ url: string;
+ headers: Record<string, string>;
+ };
+ await expect(
+ discord.connect(new StreamableHttpTransport({ url: entry.url, headers: entry.headers })),
+ ).rejects.toThrow(NO_APP);
+ });
+});
+
+/** A daemon without the app that runs stdio servers itself (the default transport). */
+async function daemonWithStdio(dataDir: string) {
+ const d = await startDaemon({
+ port: 0,
+ host: "127.0.0.1",
+ dataDir,
+ workspace: join(dataDir, "workspace"),
+ uiDir: dataDir,
+ agentCommand: process.execPath,
+ agentArgs: [FAKE_AGENT],
+ agentHome: join(dataDir, "agent"),
+ backoffMs: [50],
+ authRuntime: async () => fakeAuthRuntime().runtime,
+ });
+ daemons.push(d);
+ const mcpText = () => readFileSync(join(dataDir, "agent", "mcp.json"), "utf8");
+ const engineClient = async (id: string) => {
+ const entry = JSON.parse(mcpText()).mcpServers[id] as { url: string; headers: Record<string, string> };
+ const client = new McpClient({ name: "engine", version: "1" });
+ closers.push(() => client.close());
+ await client.connect(new StreamableHttpTransport({ url: entry.url, headers: entry.headers }));
+ return client;
+ };
+ return { d, mcpText, engineClient };
+}
diff --git a/packages/daemon/test/connectors-gateway.test.ts b/packages/daemon/test/connectors-gateway.test.ts
index 8ed79ef..65cf2ef 100644
--- a/packages/daemon/test/connectors-gateway.test.ts
+++ b/packages/daemon/test/connectors-gateway.test.ts
@@ -7,9 +7,9 @@ import WebSocket from "ws";
import { type DotDaemon, startDaemon } from "../src/daemon.ts";
import { fakeApp, sendLikeThePanel } from "./fake-app.ts";
import { fakeAuthRuntime } from "./fake-auth-runtime.ts";
+import { oauthOptions } from "./fake-oauth.ts";
import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
-const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
const GUARD = fileURLToPath(new URL("../src/extensions/approval-guard.ts", import.meta.url));
/** The engine's mcp.json without the proxy key, which changes with every engine launch. */
@@ -20,7 +20,7 @@ afterEach(async () => {
await Promise.all(daemons.splice(0).map((d) => d.close()));
});
-async function setup(options: { home?: boolean; cliMode?: "auto" } = {}) {
+async function setup(options: { home?: boolean; browser?: "auto" } = {}) {
const dataDir = tempDir();
const agentHome = join(dataDir, "agent");
const envFile = join(dataDir, "agent-env.json");
@@ -42,11 +42,10 @@ async function setup(options: { home?: boolean; cliMode?: "auto" } = {}) {
...process.env,
FAKE_AGENT_ENV_FILE: envFile,
FAKE_AGENT_ARGS_FILE: argsFile,
- ...(options.cliMode ? { FAKE_MCP_CLI_MODE: options.cliMode } : {}),
},
...(options.home ? { agentHome } : {}),
authRuntime: async () => fake.runtime,
- connectorCli: { command: process.execPath, args: [FAKE_CLI] },
+ connectorOAuth: oauthOptions(options.browser === "auto"),
appChannel: app.daemonEnd,
log: (line) => logs.push(line),
});
@@ -112,7 +111,7 @@ describe("connectors over the protocol", () => {
});
it("connects: the sign-in goes to the window that asked, every window is refreshed, and the agent restarts with the new policy", async () => {
- const { d, send, find, agentEnv, connect: other } = await setup({ cliMode: "auto" });
+ const { d, send, find, agentEnv, connect: other } = await setup({ browser: "auto" });
const second = await other();
const pid = d.supervisor.pid;
expect(JSON.parse(agentEnv().GENTLE_DOT_CONNECTOR_POLICY ?? "{}").connectors).toEqual({});
@@ -130,7 +129,7 @@ describe("connectors over the protocol", () => {
});
it("waits for the running answer before restarting for a connector change", async () => {
- const { d, send, find } = await setup({ cliMode: "auto" });
+ const { d, send, find } = await setup({ browser: "auto" });
send({ type: "send", text: "hang" });
await find("agent_state", (m) => m.state === "thinking");
const pid = d.supervisor.pid;
@@ -153,7 +152,7 @@ describe("connectors over the protocol", () => {
});
it("restores a changed mcp.json before the agent starts again", async () => {
- const { d, send, find, agentHome, logs } = await setup({ cliMode: "auto" });
+ const { d, send, find, agentHome, logs } = await setup({ browser: "auto" });
send({ type: "connector_connect", connectorId: "notion" });
await find("auth_done");
await waitFor(() => d.supervisor.state === "ready");
@@ -167,9 +166,12 @@ describe("connectors over the protocol", () => {
});
it("keeps a connector the user turned off turned off when the agent edits the files and ends itself (B1)", async () => {
- const { d, send, find, messages, dataDir, agentHome, agentEnv } = await setup({ cliMode: "auto" });
+ const { d, send, find, messages, dataDir, agentHome, agentEnv } = await setup({ browser: "auto" });
+ const started = d.supervisor.pid;
send({ type: "connector_connect", connectorId: "notion" });
await find("auth_done");
+ // The sign-in is quick: let the restart for connecting finish before the next change.
+ await waitFor(() => d.supervisor.pid !== started && d.supervisor.state === "ready");
send({ type: "connector_disconnect", connectorId: "notion" });
await waitFor(() => !JSON.parse(agentEnv().GENTLE_DOT_CONNECTOR_POLICY ?? "{}").connectors?.notion);
await waitFor(() => d.supervisor.state === "ready" && !d.supervisor.busy);
diff --git a/packages/daemon/test/connectors-guided.test.ts b/packages/daemon/test/connectors-guided.test.ts
index 8e54fc5..62c059a 100644
--- a/packages/daemon/test/connectors-guided.test.ts
+++ b/packages/daemon/test/connectors-guided.test.ts
@@ -3,13 +3,14 @@
import { existsSync, readFileSync } from "node:fs";
import { createRequire } from "node:module";
import { join } from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
+import { pathToFileURL } from "node:url";
import type { ServerPayload } from "@gentle-dot/protocol";
import { afterEach, describe, expect, it } from "vitest";
-import { CATALOG, ConnectorManager, ConnectorStore, renderSigninMcpJson } from "../src/connectors.ts";
+import { CATALOG, ConnectorManager, ConnectorStore, renderMcpJson } from "../src/connectors.ts";
+import { MemorySecretSource } from "../src/secret-source.ts";
+import { fakeOAuth } from "./fake-oauth.ts";
import { tempDir, waitFor } from "./helpers.ts";
-const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
const TOKEN = "discord-bot-token-$ecret!value";
const CLIENT_SECRET = "slack-client-secret-value";
@@ -124,50 +125,48 @@ describe("guided catalog entries", () => {
});
});
-describe("guided mcp.json rendering (the sign-in home)", () => {
- it("puts typed values in as literals the engine does not run or expand, and hides unknown tools", async () => {
- const [{ validateMcpServerConfig, getMcpToolExposure }, { resolveConfigValue }] = await engine();
- const rendered = JSON.parse(
- renderSigninMcpJson({
- connectors: {
- discord: { enabled: true, mode: "read_only", values: { token: TOKEN } },
- slack: { enabled: true, mode: "read_write", values: { client_id: "123.456", client_secret: "" } },
- gmail: {
- enabled: false,
- mode: "read_only",
- values: { client_id: "g-id.apps.googleusercontent.com", client_secret: "!echo pwned" },
- },
- },
- }),
- ) as { mcpServers: Record<string, Record<string, unknown>> };
- const { discord, slack, gmail } = rendered.mcpServers;
- for (const [name, config] of Object.entries(rendered.mcpServers))
- expect(typeof validateMcpServerConfig(name, config), name).toBe("object");
- expect(discord).toMatchObject({
+describe("guided values reach the real server as they were typed", () => {
+ it("never runs or expands a typed value, and leaves an empty optional one out", async () => {
+ const [, { resolveConfigValue }] = await engine();
+ const store = new ConnectorStore({
+ dataDir: tempDir(),
+ agentHome: join(tempDir(), "agent"),
+ secrets: new MemorySecretSource(),
+ });
+ store.update((state) => {
+ state.connectors.discord = { enabled: true, mode: "read_only", values: { token: TOKEN } };
+ state.connectors.slack = {
+ enabled: true,
+ mode: "read_write",
+ values: { client_id: "123.456", client_secret: "" },
+ };
+ state.connectors.gmail = {
+ enabled: false,
+ mode: "read_only",
+ values: { client_id: "g-id.apps.googleusercontent.com", client_secret: "!echo pwned" },
+ };
+ });
+ expect(store.proxyView("discord")?.server).toEqual({
command: "npx",
args: ["-y", "@pasympa/[email protected]"],
- exposure: "direct",
});
- const token = (discord?.env as Record<string, string> | undefined)?.DISCORD_TOKEN ?? "";
- expect(token).not.toBe(TOKEN);
- expect(resolveConfigValue(token)).toBe(TOKEN);
- expect(getMcpToolExposure(discord, "discord_read_messages")).toBe("direct");
- expect(getMcpToolExposure(discord, "discord_send_message")).toBe("hidden");
- // An optional value left empty is left out; the client id is used as is.
- expect(slack?.oauth).toEqual({ clientId: "123.456", callbackUrl: "http://localhost:38417/callback" });
- expect(slack?.toolExposure).toBeUndefined();
- const oauth = gmail?.oauth as Record<string, string>;
- expect(oauth.clientId).toBe("g-id.apps.googleusercontent.com");
- expect(oauth.clientSecret?.startsWith("!")).toBe(false);
- expect(resolveConfigValue(oauth.clientSecret ?? "")).toBe("!echo pwned");
- expect(gmail?.enabled).toBe(false);
+ expect((await store.credentials("discord")).env).toEqual({ DISCORD_TOKEN: TOKEN });
+ expect((await store.signInTarget("slack")).settings).toEqual({
+ clientId: "123.456",
+ callbackUrl: "http://localhost:38417/callback",
+ });
+ const gmail = (await store.signInTarget("gmail")).settings;
+ expect(gmail.clientId).toBe("g-id.apps.googleusercontent.com");
+ expect(gmail.clientSecret).toBe("!echo pwned");
+ // The engine would have run it; the engine never sees it now.
+ expect(resolveConfigValue("!echo pwned")).toBe("pwned");
+ store.close();
});
it("leaves out a guided connector whose required values are missing", () => {
- const rendered = JSON.parse(
- renderSigninMcpJson({ connectors: { discord: { enabled: true, mode: "read_only" } } }),
- ) as { mcpServers: Record<string, unknown> };
- expect(rendered.mcpServers).toEqual({});
+ const state = { connectors: { discord: { enabled: true, mode: "read_only" as const } } };
+ const proxy = { url: "http://127.0.0.1:4999/mcp", key: "k".repeat(32) };
+ expect(JSON.parse(renderMcpJson(state, undefined, proxy)).mcpServers).toEqual({});
});
});
@@ -176,17 +175,16 @@ afterEach(() => {
for (const manager of managers.splice(0)) manager.cancelAll();
});
-function setup(cliEnv: Record<string, string> = {}) {
+function setup() {
const dataDir = tempDir();
const agentHome = join(dataDir, "agent");
- const cliLog = join(dataDir, "cli.jsonl");
const logs: string[] = [];
- const store = new ConnectorStore({ dataDir, agentHome });
+ const secrets = new MemorySecretSource();
+ const oauth = fakeOAuth();
+ const store = new ConnectorStore({ dataDir, agentHome, secrets });
const manager = new ConnectorManager({
store,
- cli: { command: process.execPath, args: [FAKE_CLI] },
- env: { ...process.env, HOME: join(dataDir, "home"), FAKE_MCP_CLI_LOG: cliLog, ...cliEnv },
- cwd: dataDir,
+ oauth: { fetch: oauth.fetch, openBrowser: (url) => void oauth.browse(url).catch(() => {}) },
log: (line) => logs.push(line),
});
managers.push(manager);
@@ -194,19 +192,12 @@ function setup(cliEnv: Record<string, string> = {}) {
const sent: ServerPayload[] = [];
const emit = (payload: ServerPayload) => sent.push(payload);
const prompts = () => sent.flatMap((m) => (m.type === "auth_prompt" ? [m.prompt] : []));
- const cliRuns = () =>
- existsSync(cliLog)
- ? readFileSync(cliLog, "utf8")
- .trim()
- .split("\n")
- .map((line) => JSON.parse(line) as { argv: string[] })
- : [];
- return { dataDir, agentHome, store, manager, owner, sent, emit, prompts, logs, cliRuns };
+ return { dataDir, agentHome, store, manager, owner, sent, emit, prompts, logs, secrets, oauth };
}
describe("guided connector setup", () => {
it("asks for the Discord bot token as a secret, then adds it read only; the value is never shown or logged", async () => {
- const { manager, store, owner, emit, sent, prompts, logs, dataDir, agentHome, cliRuns } = setup();
+ const { manager, store, owner, emit, sent, prompts, logs, dataDir, agentHome, secrets, oauth } = setup();
expect(manager.connect(owner, "discord", emit)).toBeUndefined();
const prompt = await waitFor(() => prompts()[0]);
expect(prompt).toMatchObject({ kind: "secret", flowId: expect.stringMatching(/^connector-setup-/) });
@@ -216,27 +207,24 @@ describe("guided connector setup", () => {
expect(manager.reply(owner, prompt.flowId, { value: TOKEN })).toBe(true);
const done = await waitFor(() => sent.find((m) => m.type === "auth_done"));
expect(done).toMatchObject({ flowId: prompt.flowId, providerId: "discord", ok: true });
- expect(store.state().connectors.discord).toEqual({
- enabled: true,
- mode: "read_only",
- values: { token: TOKEN },
- });
+ expect(store.state().connectors.discord).toMatchObject({ enabled: true, mode: "read_only" });
+ expect(secrets.values.get("connector/discord/value/token")).toBe(TOKEN);
expect(manager.list().find((c) => c.id === "discord")).toMatchObject({
added: true,
enabled: true,
status: "connected",
guide: expect.objectContaining({ steps: expect.any(Array) }),
});
- // A server with a token signs in with nothing else; `mcp login` never runs.
- expect(cliRuns()).toEqual([]);
+ // A server with a token signs in with nothing else.
+ expect(oauth.tokenRequests).toEqual([]);
expect(JSON.stringify(manager.list())).not.toContain(TOKEN);
expect(JSON.stringify(sent)).not.toContain(TOKEN);
expect(logs.join("\n")).not.toContain(TOKEN);
- // The real server is only in the daemon's sign-in home; the proxy hands the token to the server it runs.
- expect(readFileSync(store.signinMcpFile, "utf8")).toContain("DISCORD_TOKEN");
+ // The token is only in the app's store; the proxy hands it to the server it runs.
expect(readFileSync(join(agentHome, "mcp.json"), "utf8")).not.toContain("DISCORD_TOKEN");
expect((await store.credentials("discord")).env).toEqual({ DISCORD_TOKEN: TOKEN });
expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).toContain("discord");
+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).not.toContain(TOKEN);
expect(store.policy().connectors?.discord?.readOnlyTools).toContain("discord_read_messages");
});
@@ -251,11 +239,8 @@ describe("guided connector setup", () => {
expect(manager.connect(owner, "slack", emit)).toBeUndefined();
});
- it("asks for Slack's client id and an optional secret, writes them to mcp.json, then signs in on the same flow", async () => {
- const { manager, store, owner, emit, sent, prompts, cliRuns, logs } = setup({
- FAKE_MCP_CLI_MODE: "auto",
- FAKE_MCP_CLI_URL: "https://mcp.slack.com/mcp",
- });
+ it("asks for Slack's client id and an optional secret, keeps the secret in the app's store, then signs in with them on the same flow", async () => {
+ const { manager, store, owner, emit, sent, prompts, logs, secrets, oauth, dataDir } = setup();
manager.connect(owner, "slack", emit);
const first = await waitFor(() => prompts()[0]);
expect(first).toMatchObject({ kind: "text" });
@@ -266,17 +251,24 @@ describe("guided connector setup", () => {
expect(manager.reply(owner, second.flowId, { value: CLIENT_SECRET })).toBe(true);
const done = await waitFor(() => sent.find((m) => m.type === "auth_done"));
expect(done).toMatchObject({ flowId: first.flowId, providerId: "slack", ok: true });
- expect(cliRuns().map((r) => r.argv)).toEqual([["mcp", "login", "slack"]]);
- const slack = JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers.slack;
- expect(slack.oauth).toMatchObject({
- clientId: "123.456",
- callbackUrl: "http://localhost:38417/callback",
- });
+ // The user's own client, on its fixed redirect; nothing is registered.
+ const link = sent.find((m) => m.type === "auth_event");
+ const url = new URL(link?.type === "auth_event" && link.event.kind === "auth_url" ? link.event.url : "");
+ expect(url.searchParams.get("client_id")).toBe("123.456");
+ expect(url.searchParams.get("redirect_uri")).toBe("http://localhost:38417/callback");
+ expect(oauth.registered).toEqual([]);
+ expect(oauth.tokenRequests).toEqual([
+ { grant: "authorization_code", clientId: "123.456", clientSecret: CLIENT_SECRET },
+ ]);
expect(manager.list().find((c) => c.id === "slack")?.status).toBe("connected");
- expect(store.state().connectors.slack?.values).toEqual({
+ expect(secrets.values.get("connector/slack/value/client_secret")).toBe(CLIENT_SECRET);
+ expect(
+ JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8")).connectors.slack.values,
+ ).toEqual({
client_id: "123.456",
- client_secret: CLIENT_SECRET,
+ client_secret: { secretRef: "connector/slack/value/client_secret" },
});
+ expect(store.state().connectors.slack?.signIn).toBeDefined();
expect(JSON.stringify(sent)).not.toContain(CLIENT_SECRET);
expect(logs.join("\n")).not.toContain(CLIENT_SECRET);
});
@@ -292,7 +284,7 @@ describe("guided connector setup", () => {
});
it("changes the stored values from Set up, and refuses connectors that need none", async () => {
- const { manager, store, owner, emit, sent, prompts } = setup();
+ const { manager, store, owner, emit, sent, prompts, secrets } = setup();
store.update((state) => {
state.connectors.discord = { enabled: true, mode: "read_write", values: { token: "old" } };
});
@@ -300,11 +292,9 @@ describe("guided connector setup", () => {
const prompt = await waitFor(() => prompts()[0]);
manager.reply(owner, prompt.flowId, { value: "new-token" });
await waitFor(() => sent.find((m) => m.type === "auth_done"));
- expect(store.state().connectors.discord).toEqual({
- enabled: true,
- mode: "read_write",
- values: { token: "new-token" },
- });
+ expect(store.state().connectors.discord).toMatchObject({ enabled: true, mode: "read_write" });
+ expect(secrets.values.get("connector/discord/value/token")).toBe("new-token");
+ expect((await store.credentials("discord")).env).toEqual({ DISCORD_TOKEN: "new-token" });
expect(manager.setup(owner, "notion", emit)).toMatchObject({ code: "connector_not_added" });
expect(manager.setup(owner, "nope", emit)).toMatchObject({ code: "unknown_connector" });
});
diff --git a/packages/daemon/test/connectors-proxy-gateway.test.ts b/packages/daemon/test/connectors-proxy-gateway.test.ts
index f9dd4f4..2928ada 100644
--- a/packages/daemon/test/connectors-proxy-gateway.test.ts
+++ b/packages/daemon/test/connectors-proxy-gateway.test.ts
@@ -6,19 +6,19 @@ import { readFileSync } from "node:fs";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { join } from "node:path";
-import { fileURLToPath } from "node:url";
import { McpClient, type McpError, StreamableHttpTransport, type Tool } from "@earendil-works/pi-mcp";
import { APP_REQUIRED, type ServerMessage } from "@gentle-dot/protocol";
import { afterEach, describe, expect, it } from "vitest";
import WebSocket from "ws";
import { type DotDaemon, startDaemon } from "../src/daemon.ts";
+import { NO_APP } from "../src/secret-source.ts";
import { fakeApp, sendLikeThePanel } from "./fake-app.ts";
import { fakeAuthRuntime } from "./fake-auth-runtime.ts";
+import { oauthOptions } from "./fake-oauth.ts";
import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";
-const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
-/** What the fake sign-in command stores (see fixtures/fake-mcp-cli.ts). */
-const SIGNED_IN_TOKEN = "fake-access-token-value";
+/** What the stand-in provider issues first (see fake-oauth.ts). */
+const SIGNED_IN_TOKEN = "access-token-1";
const TOOLS: Tool[] = [
{ name: "notion-search", inputSchema: { type: "object" }, annotations: { readOnlyHint: true } },
@@ -90,9 +90,8 @@ async function setup() {
agentArgs: [FAKE_AGENT],
agentHome,
backoffMs: [50],
- agentEnv: { ...process.env, FAKE_MCP_CLI_MODE: "auto" },
authRuntime: async () => fake.runtime,
- connectorCli: { command: process.execPath, args: [FAKE_CLI] },
+ connectorOAuth: oauthOptions(true),
// The real credentials, sent to a stand-in for Notion's address.
connectorTransport: (_connector, credentials) =>
new StreamableHttpTransport({
@@ -164,8 +163,12 @@ describe("connectors through the daemon's proxy (regression, S25.4)", () => {
it("asks the app once before a sending action: declined or unanswered sends nothing, allowed runs it, and windows cannot answer", async () => {
const { d, notion, app, send, raw, messages, mcpText, engineClient } = await setup();
+ // Connecting restarts the engine, and so does the mode change; each restart rotates the proxy
+ // key, so wait for both before reading the key the engine would use.
+ const beforeConnect = d.supervisor.pid;
send({ type: "connector_connect", connectorId: "notion" });
await waitFor(() => messages.find((m) => m.type === "auth_done" && m.ok));
+ await waitFor(() => d.supervisor.pid !== beforeConnect && d.supervisor.state === "ready");
const pid = d.supervisor.pid;
send({ type: "connector_mode", connectorId: "notion", mode: "read_write" });
await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");
@@ -237,8 +240,12 @@ describe("connectors through the daemon's proxy (regression, S25.4)", () => {
it("refuses a sending action when the app quits while asking, and when there is no app", async () => {
const { d, notion, app, send, raw, messages, engineClient } = await setup();
+ // Connecting restarts the engine, and so does the mode change; each restart rotates the proxy
+ // key, so wait for both before reading the key the engine would use.
+ const beforeConnect = d.supervisor.pid;
send({ type: "connector_connect", connectorId: "notion" });
await waitFor(() => messages.find((m) => m.type === "auth_done" && m.ok));
+ await waitFor(() => d.supervisor.pid !== beforeConnect && d.supervisor.state === "ready");
const pid = d.supervisor.pid;
send({ type: "connector_mode", connectorId: "notion", mode: "read_write" });
await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");
@@ -257,9 +264,8 @@ describe("connectors through the daemon's proxy (regression, S25.4)", () => {
app.close();
expect((await pending)?.message).toMatch(/did not allow/);
- expect((await failure(client.callTool("notion-create-pages", { title: "y" })))?.message).toMatch(
- /approval/,
- );
+ // Without the app its sign-in is gone from memory too: it fails closed before anything is asked.
+ expect((await failure(client.callTool("notion-create-pages", { title: "y" })))?.message).toBe(NO_APP);
expect(notion.calls()).toEqual([]);
// And a window cannot turn it back on or change it without the app.
raw({ type: "connector_mode", connectorId: "notion", mode: "read_only" });
diff --git a/packages/daemon/test/connectors-proxy.test.ts b/packages/daemon/test/connectors-proxy.test.ts
index 269d9f4..5fb950a 100644
--- a/packages/daemon/test/connectors-proxy.test.ts
+++ b/packages/daemon/test/connectors-proxy.test.ts
@@ -1,15 +1,17 @@
// biome-ignore-all lint/suspicious/noTemplateCurlyInString: `${input:<key>}` and `${NAME}` are the placeholders connectors use.
// The connector files with the MCP proxy (S25.4): the engine's mcp.json lists only the daemon's
-// proxy addresses, the real servers and their secrets stay in the daemon's own sign-in home, and the
-// approval guard lets proxied tools through (the proxy asks) while it keeps protecting the files.
-import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+// proxy addresses, the real servers stay in the daemon's memory and their secrets in the app's
+// secure store (S25.5), and the approval guard lets proxied tools through (the proxy asks) while it
+// keeps protecting the files, the old sign-in files included.
+import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { afterEach, describe, expect, it } from "vitest";
import { ConnectorStore, type CustomConnector, renderMcpJson } from "../src/connectors.ts";
import { decide, parsePolicy } from "../src/extensions/approval-guard.ts";
-import { tempDir, waitFor } from "./helpers.ts";
+import { MemorySecretSource } from "../src/secret-source.ts";
+import { tempDir } from "./helpers.ts";
const NOTION_KEY = "mcp__notion|https://mcp.notion.com/mcp";
const KEY = "proxy-key-for-this-launch-0123456789abcdef";
@@ -46,18 +48,20 @@ function setup(options: { env?: NodeJS.ProcessEnv } = {}) {
const workspace = join(dataDir, "workspace");
mkdirSync(agentHome);
mkdirSync(workspace);
+ const secrets = new MemorySecretSource();
const make = () => {
const s = new ConnectorStore({
dataDir,
agentHome,
workspace,
+ secrets,
guardPath: "/app/guard.ts",
...(options.env ? { env: options.env } : {}),
});
stores.push(s);
return s;
};
- return { dataDir, agentHome, workspace, make };
+ return { dataDir, agentHome, workspace, make, secrets };
}
const httpCustom: CustomConnector = {
@@ -109,12 +113,14 @@ describe("the engine's mcp.json with the proxy", () => {
const s = make();
s.setProxy(PROXY);
fill(s);
- writeFileSync(
- s.authFile,
- JSON.stringify({
- [NOTION_KEY]: { tokens: { access_token: SECRETS.oauthAccess, refresh_token: SECRETS.oauthRefresh } },
- }),
- );
+ await s.saveSignIn("notion", {
+ serverUrl: "https://mcp.notion.com/mcp",
+ tokens: {
+ access_token: SECRETS.oauthAccess,
+ token_type: "Bearer",
+ refresh_token: SECRETS.oauthRefresh,
+ },
+ });
const text = readFileSync(join(agentHome, "mcp.json"), "utf8");
const servers = JSON.parse(text).mcpServers as Record<string, Record<string, unknown>>;
expect(Object.keys(servers)).toEqual(["notion", "linear", "discord", "slack", "tracker", "files"]);
@@ -141,13 +147,12 @@ describe("the engine's mcp.json with the proxy", () => {
expect(text).not.toContain(upstream);
for (const name of ["DISCORD_TOKEN", "FILES_TOKEN", "env", "oauth", "toolExposure", "command"])
expect(text).not.toContain(name);
- // The real servers are only in the daemon's own sign-in home, for the sign-in command.
- expect(s.signinHome).toBe(join(dataDir, "connector-signin"));
- const signin = JSON.parse(readFileSync(s.signinMcpFile, "utf8")).mcpServers;
- expect(signin.notion.url).toBe("https://mcp.notion.com/mcp");
- expect(signin.slack.oauth.clientId).toBe("slack-client-id");
- expect(statSync(s.signinHome).mode & 0o777).toBe(0o700);
- expect(statSync(s.signinMcpFile).mode & 0o777).toBe(0o600);
+ // The real servers are only in the daemon's memory, and their secrets only in the app's store.
+ expect(existsSync(s.signinHome)).toBe(false);
+ const record = readFileSync(join(dataDir, "connectors.json"), "utf8");
+ for (const secret of Object.values(SECRETS)) expect(record).not.toContain(secret);
+ expect(JSON.parse(record).connectors.slack.values.client_id).toBe("slack-client-id");
+ expect(statSync(join(dataDir, "connectors.json")).mode & 0o777).toBe(0o600);
});
it("leaves the connectors out until the proxy listens, keeps the computer helper as it is, and changes the key per launch", () => {
@@ -241,80 +246,19 @@ describe("the proxy's view of a connector and its credentials", () => {
expect((await s.credentials("team")).headers).toEqual({ "X-Team": "team-7", "X-Price": "$5" });
const notion = await s.credentials("notion");
expect(await notion.authProvider?.token()).toBeUndefined();
- writeFileSync(
- s.authFile,
- JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: SECRETS.oauthAccess } } }),
- );
+ // A planted sign-in file is never read; only a sign-in the daemon stored is used.
+ mkdirSync(s.signinHome, { recursive: true });
+ writeFileSync(s.authFile, JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: "planted" } } }));
+ expect(await notion.authProvider?.token()).toBeUndefined();
+ await s.saveSignIn("notion", {
+ serverUrl: "https://mcp.notion.com/mcp",
+ tokens: { access_token: SECRETS.oauthAccess, token_type: "Bearer" },
+ });
expect(await notion.authProvider?.token()).toBe(SECRETS.oauthAccess);
});
});
-describe("the daemon's sign-in home", () => {
- it("moves the engine's old mcp-auth.json there once, after checking the copy", () => {
- const { make, agentHome, dataDir } = setup();
- const old = join(agentHome, "mcp-auth.json");
- const stored = JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: SECRETS.oauthAccess } } });
- writeFileSync(old, stored);
- const s = make();
- expect(existsSync(old)).toBe(false);
- expect(readFileSync(s.authFile, "utf8")).toBe(stored);
- expect(s.authFile).toBe(join(dataDir, "connector-signin", "mcp-auth.json"));
- expect(statSync(s.authFile).mode & 0o777).toBe(0o600);
- expect(s.isSignedIn("notion")).toBe(true);
- expect(s.isSignedIn("linear")).toBe(false);
- // A file that shows up in the engine's home later never replaces a sign-in the daemon holds,
- // and it does not stay there.
- writeFileSync(old, JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: "planted" } } }));
- const next = make();
- expect(readFileSync(next.authFile, "utf8")).toBe(stored);
- expect(existsSync(old)).toBe(false);
- expect(readdirSync(join(dataDir, "connector-signin")).filter((f) => f.includes(".tmp"))).toEqual([]);
- });
-
- it("finishes a move that stopped halfway: an empty sign-in home, the old file still there (A2)", () => {
- const { make, agentHome, dataDir } = setup();
- const old = join(agentHome, "mcp-auth.json");
- const stored = JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: SECRETS.oauthAccess } } });
- writeFileSync(old, stored);
- mkdirSync(join(dataDir, "connector-signin"), { mode: 0o700 });
- const s = make();
- expect(existsSync(old)).toBe(false);
- expect(readFileSync(s.authFile, "utf8")).toBe(stored);
- expect(s.isSignedIn("notion")).toBe(true);
- });
-
- it("moves the sign-ins the daemon does not hold yet when both files exist, keeping its own (A2)", () => {
- const { make, agentHome, dataDir } = setup();
- const old = join(agentHome, "mcp-auth.json");
- const linearKey = NOTION_KEY.replace("notion", "linear").replace("mcp.notion.com", "mcp.linear.app");
- writeFileSync(
- old,
- JSON.stringify({
- [NOTION_KEY]: { tokens: { access_token: "older-notion" } },
- [linearKey]: { tokens: { access_token: SECRETS.oauthAccess } },
- }),
- );
- mkdirSync(join(dataDir, "connector-signin"), { mode: 0o700 });
- const current = { [NOTION_KEY]: { tokens: { access_token: "current-notion" } } };
- writeFileSync(join(dataDir, "connector-signin", "mcp-auth.json"), JSON.stringify(current));
- const s = make();
- expect(existsSync(old)).toBe(false);
- const moved = JSON.parse(readFileSync(s.authFile, "utf8"));
- expect(moved[NOTION_KEY].tokens.access_token).toBe("current-notion");
- expect(moved[linearKey].tokens.access_token).toBe(SECRETS.oauthAccess);
- expect(statSync(s.authFile).mode & 0o777).toBe(0o600);
- });
-
- it("leaves the old file where it is when it cannot be read as sign-ins (A2)", () => {
- const { make, agentHome, dataDir } = setup();
- const old = join(agentHome, "mcp-auth.json");
- mkdirSync(join(dataDir, "connector-signin"), { mode: 0o700 });
- writeFileSync(join(dataDir, "connector-signin", "mcp-auth.json"), "{}");
- writeFileSync(old, "not json");
- make();
- expect(readFileSync(old, "utf8")).toBe("not json");
- });
-
+describe("the old sign-in files", () => {
it("protects the sign-in home and its files from the file tools and shell commands like the other credential files", () => {
const { make, agentHome, dataDir } = setup();
const s = make();
@@ -330,6 +274,7 @@ describe("the daemon's sign-in home", () => {
join(signin, "mcp-auth.json"),
]),
);
+ mkdirSync(signin, { recursive: true });
writeFileSync(s.authFile, "{}");
const cwd = join(dataDir, "workspace");
for (const call of [
@@ -344,37 +289,21 @@ describe("the daemon's sign-in home", () => {
expect(decide({ ...call, cwd }, policy).action).toBe("block");
});
- it("puts back the sign-in files when they change outside a sign-in, and keeps what a sign-in wrote", async () => {
- const { make } = setup();
+ it("are never written again: the daemon keeps no sign-in home while it runs", async () => {
+ const { make, secrets } = setup();
const s = make();
+ s.watch();
fill(s);
- const signinMcp = readFileSync(s.signinMcpFile, "utf8");
- writeFileSync(
- s.signinMcpFile,
- JSON.stringify({ mcpServers: { notion: { url: "https://evil.example/mcp" } } }),
- );
- expect(s.enforce()).toBe(true);
- expect(readFileSync(s.signinMcpFile, "utf8")).toBe(signinMcp);
- // Planted sign-in state is removed while no sign-in runs.
- writeFileSync(s.authFile, JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: "planted" } } }));
- expect(s.enforce()).toBe(true);
- expect(existsSync(s.authFile)).toBe(false);
- // A sign-in writes it, and what it wrote is kept.
- const done = s.signingIn();
- const signedIn = JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: SECRETS.oauthAccess } } });
- writeFileSync(s.authFile, signedIn);
- expect(s.enforce()).toBe(false);
- done();
+ await s.settled();
+ await s.saveSignIn("notion", {
+ serverUrl: "https://mcp.notion.com/mcp",
+ tokens: { access_token: SECRETS.oauthAccess, token_type: "Bearer" },
+ });
expect(s.enforce()).toBe(false);
- writeFileSync(s.authFile, "{}");
- expect(s.enforce()).toBe(true);
- expect(readFileSync(s.authFile, "utf8")).toBe(signedIn);
- // And the watcher does the same while the daemon runs.
- s.watch();
- rmSync(s.signinMcpFile);
- await waitFor(() => existsSync(s.signinMcpFile) && readFileSync(s.signinMcpFile, "utf8") === signinMcp);
- writeFileSync(s.authFile, "{}");
- await waitFor(() => readFileSync(s.authFile, "utf8") === signedIn);
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ expect(existsSync(s.signinHome)).toBe(false);
+ expect(secrets.values.get("connector/discord/value/token")).toBe(SECRETS.discordToken);
+ expect(secrets.values.get("connector/files/value/FILES_TOKEN")).toBe(SECRETS.envToken);
});
});
diff --git a/packages/daemon/test/connectors.test.ts b/packages/daemon/test/connectors.test.ts
index ae9ca5d..eabf2f9 100644
--- a/packages/daemon/test/connectors.test.ts
+++ b/packages/daemon/test/connectors.test.ts
@@ -9,10 +9,8 @@ import {
writeFileSync,
} from "node:fs";
import { createServer } from "node:http";
-import { createRequire } from "node:module";
import type { AddressInfo } from "node:net";
import { join } from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
import type { ServerPayload } from "@gentle-dot/protocol";
import { afterEach, describe, expect, it } from "vitest";
import {
@@ -21,27 +19,12 @@ import {
ConnectorManager,
ConnectorStore,
renderMcpJson,
- renderSigninMcpJson,
} from "../src/connectors.ts";
import { isReadOnlyCall } from "../src/extensions/approval-guard.ts";
+import { MemorySecretSource } from "../src/secret-source.ts";
+import { fakeOAuth } from "./fake-oauth.ts";
import { tempDir, waitFor } from "./helpers.ts";
-const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));
-const NOTION_KEY = "mcp__notion|https://mcp.notion.com/mcp";
-
-/** The engine's own MCP config validator, loaded by file path (the package exports only its entry). */
-async function engineMcp() {
- const require = createRequire(import.meta.url);
- const file = (require.resolve.paths("@earendil-works/pi-coding-agent") ?? [])
- .map((dir) => join(dir, "@earendil-works", "pi-coding-agent", "dist", "core", "mcp-servers.js"))
- .find((path) => existsSync(path));
- if (!file) throw new Error("the engine package is missing");
- return (await import(pathToFileURL(file).href)) as {
- validateMcpServerConfig(name: string, raw: unknown): unknown;
- getMcpToolExposure(config: unknown, tool: string): string;
- };
-}
-
describe("connectors catalog", () => {
it("lists Notion, Linear, and Atlassian with their official remote servers", () => {
expect(CATALOG.slice(0, 3).map(({ id, name, server, oauth }) => ({ id, name, server, oauth }))).toEqual([
@@ -75,39 +58,8 @@ describe("connectors catalog", () => {
});
describe("mcp.json rendering", () => {
- it("renders the real servers for the sign-in command as the engine accepts them; read only hides every tool but the curated ones", async () => {
- const { validateMcpServerConfig, getMcpToolExposure } = await engineMcp();
- const rendered = JSON.parse(
- renderSigninMcpJson({
- connectors: {
- notion: { enabled: true, mode: "read_only" },
- linear: { enabled: true, mode: "read_write" },
- atlassian: { enabled: false, mode: "read_write" },
- unknown: { enabled: true, mode: "read_write" },
- },
- }),
- ) as { mcpServers: Record<string, Record<string, unknown>> };
- expect(Object.keys(rendered.mcpServers)).toEqual(["notion", "linear", "atlassian"]);
- expect(rendered.mcpServers.linear).toEqual({ url: "https://mcp.linear.app/mcp", exposure: "direct" });
- expect(rendered.mcpServers.atlassian).toEqual({
- url: "https://mcp.atlassian.com/v2/mcp",
- exposure: "direct",
- enabled: false,
- });
- const notion = rendered.mcpServers.notion;
- expect(notion).toMatchObject({ url: "https://mcp.notion.com/mcp", exposure: "direct" });
- for (const [name, config] of Object.entries(rendered.mcpServers)) {
- expect(typeof validateMcpServerConfig(name, config)).toBe("object");
- }
- expect(getMcpToolExposure(notion, "notion-search")).toBe("direct");
- expect(getMcpToolExposure(notion, "notion-create-pages")).toBe("hidden");
- expect(getMcpToolExposure(notion, "some-new-tool")).toBe("hidden");
- expect(getMcpToolExposure(rendered.mcpServers.linear, "create_issue")).toBe("direct");
- });
-
it("renders an empty server list when nothing is added", () => {
expect(JSON.parse(renderMcpJson({ connectors: {} }))).toEqual({ mcpServers: {} });
- expect(JSON.parse(renderSigninMcpJson({ connectors: {} }))).toEqual({ mcpServers: {} });
});
});
@@ -154,16 +106,15 @@ describe("connector store", () => {
s.update((state) => {
state.connectors.notion = { enabled: true, mode: "read_only" };
});
- expect(JSON.parse(readFileSync(s.signinMcpFile, "utf8")).mcpServers.notion.url).toBe(
- "https://mcp.notion.com/mcp",
- );
+ // A new install has no secrets in files to move, so the record says they are in the app's store.
expect(JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8"))).toEqual({
- version: 1,
+ version: 2,
connectors: { notion: { enabled: true, mode: "read_only" } },
});
expect(statSync(join(dataDir, "connectors.json")).mode & 0o777).toBe(0o600);
expect(statSync(join(agentHome, "mcp.json")).mode & 0o777).toBe(0o600);
- expect(statSync(s.signinMcpFile).mode & 0o777).toBe(0o600);
+ // The old sign-in home is never made again.
+ expect(existsSync(s.signinHome)).toBe(false);
expect(readdirSync(agentHome).filter((f) => f.includes(".tmp"))).toEqual([]);
const next = new ConnectorStore({ dataDir, agentHome, workspace });
stores.push(next);
@@ -224,7 +175,6 @@ describe("connector store", () => {
version: 1,
connectors: { linear: { enabled: true, mode: "read_write" } },
});
- expect(JSON.parse(readFileSync(s.signinMcpFile, "utf8")).mcpServers.linear).toBeDefined();
expect(s.enforce()).toBe(false);
});
@@ -332,22 +282,28 @@ describe("connector store", () => {
]);
});
- it("tells a stored sign-in from a pending one without exposing token values", () => {
- const { store: s } = store();
+ it("tells a stored sign-in from a pending one without exposing token values", async () => {
+ const { dataDir, agentHome } = store();
+ const s = new ConnectorStore({ dataDir, agentHome, secrets: new MemorySecretSource() });
+ stores.push(s);
+ s.update((state) => {
+ state.connectors.notion = { enabled: true, mode: "read_only" };
+ state.connectors.linear = { enabled: true, mode: "read_only" };
+ });
expect(s.isSignedIn("notion")).toBe(false);
- writeFileSync(s.authFile, "{oops");
+ // A planted sign-in file is never read.
+ mkdirSync(s.signinHome, { recursive: true });
+ writeFileSync(s.authFile, JSON.stringify({ "mcp__notion|https://mcp.notion.com/mcp": { tokens: {} } }));
expect(s.isSignedIn("notion")).toBe(false);
- writeFileSync(
- s.authFile,
- JSON.stringify({ [NOTION_KEY]: { clientInformation: { client_id: "c" }, codeVerifier: "v" } }),
- );
+ await s.saveSignIn("notion", { serverUrl: "https://mcp.notion.com/mcp", codeVerifier: "v" });
expect(s.isSignedIn("notion")).toBe(false);
- writeFileSync(
- s.authFile,
- JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: "secret-token-value" } } }),
- );
+ await s.saveSignIn("notion", {
+ serverUrl: "https://mcp.notion.com/mcp",
+ tokens: { access_token: "secret-token-value", token_type: "Bearer" },
+ });
expect(s.isSignedIn("notion")).toBe(true);
expect(s.isSignedIn("linear")).toBe(false);
+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).not.toContain("secret-token-value");
});
});
@@ -356,23 +312,20 @@ afterEach(() => {
for (const manager of managers.splice(0)) manager.cancelAll();
});
-function setup(mode?: "fail" | "auto", extraEnv: Record<string, string> = {}) {
+/** `auto`: the browser approves at once; `fail`: it does, and the provider refuses the code. */
+function setup(mode?: "fail" | "auto") {
const dataDir = tempDir();
const agentHome = join(dataDir, "agent");
- const cliLog = join(dataDir, "cli.jsonl");
const logs: string[] = [];
- const store = new ConnectorStore({ dataDir, agentHome });
+ const secrets = new MemorySecretSource();
+ const oauth = fakeOAuth(mode === "fail" ? { mode: "fail" } : {});
+ const store = new ConnectorStore({ dataDir, agentHome, secrets });
const manager = new ConnectorManager({
store,
- cli: { command: process.execPath, args: [FAKE_CLI] },
- env: {
- ...process.env,
- HOME: join(dataDir, "home"),
- FAKE_MCP_CLI_LOG: cliLog,
- ...(mode ? { FAKE_MCP_CLI_MODE: mode } : {}),
- ...extraEnv,
+ oauth: {
+ fetch: oauth.fetch,
+ ...(mode ? { openBrowser: (url: string) => void oauth.browse(url).catch(() => {}) } : {}),
},
- cwd: dataDir,
log: (line) => logs.push(line),
});
managers.push(manager);
@@ -381,13 +334,6 @@ function setup(mode?: "fail" | "auto", extraEnv: Record<string, string> = {}) {
const owner = {};
const sent: ServerPayload[] = [];
const emit = (payload: ServerPayload) => sent.push(payload);
- const cliRuns = () =>
- existsSync(cliLog)
- ? readFileSync(cliLog, "utf8")
- .trim()
- .split("\n")
- .map((line) => JSON.parse(line) as { argv: string[]; pid: number; env: Record<string, string> })
- : [];
function find<T extends ServerPayload["type"]>(
type: T,
where: (m: Extract<ServerPayload, { type: T }>) => boolean = () => true,
@@ -399,17 +345,11 @@ function setup(mode?: "fail" | "auto", extraEnv: Record<string, string> = {}) {
),
);
}
- return { dataDir, agentHome, store, manager, changes, owner, sent, emit, find, logs, cliRuns };
+ return { dataDir, agentHome, store, manager, changes, owner, sent, emit, find, logs, secrets, oauth };
}
-const alive = (pid: number) => {
- try {
- process.kill(pid, 0);
- return true;
- } catch {
- return false;
- }
-};
+const linkOf = (m: ServerPayload) =>
+ m.type === "auth_event" && m.event.kind === "auth_url" ? m.event.url : "";
describe("connector sign-in", () => {
it("finds the engine's own command line", () => {
@@ -449,11 +389,11 @@ describe("connector sign-in", () => {
});
it("connects: adds the server, relays the sign-in link, finishes through a pasted address", async () => {
- const { manager, store, dataDir, changes, owner, emit, find, sent, logs, cliRuns } = setup();
+ const { manager, store, changes, owner, emit, find, sent, logs, oauth, dataDir } = setup();
expect(manager.connect(owner, "notion", emit)).toBeUndefined();
expect(store.state().connectors.notion).toEqual({ enabled: true, mode: "read_only" });
expect(changes).toEqual([true]);
- const link = await find("auth_event", (m) => m.event.kind === "auth_url");
+ const link = await find("auth_event", (m) => linkOf(m) !== "");
expect(link.flowId).toMatch(/^connector-/);
expect(link.event).toMatchObject({
kind: "auth_url",
@@ -462,63 +402,52 @@ describe("connector sign-in", () => {
});
const prompt = await find("auth_prompt");
expect(prompt.prompt).toMatchObject({ flowId: link.flowId, kind: "manual_code" });
- const [run] = cliRuns();
- expect(run?.argv).toEqual(["mcp", "login", "notion"]);
- // The sign-in command reads the real servers from the daemon's sign-in home, never the engine's.
- expect(run?.env).toEqual({ PI_CODING_AGENT_DIR: store.signinHome, HOME: join(dataDir, "home") });
- const redirect = new URL(
- new URL(link.event.kind === "auth_url" ? link.event.url : "").searchParams.get("redirect_uri") ?? "",
- );
- redirect.searchParams.set("code", "very-secret-code");
- redirect.searchParams.set("state", "fake-state");
- expect(manager.reply(owner, link.flowId, { value: redirect.href })).toBe(true);
+ const pasted = oauth.callbackFor(linkOf(link));
+ expect(manager.reply(owner, link.flowId, { value: pasted.href })).toBe(true);
const done = await find("auth_done");
expect(done).toEqual({ type: "auth_done", flowId: link.flowId, providerId: "notion", ok: true });
expect(manager.list()[0]?.status).toBe("connected");
expect(changes).toEqual([true, false]);
- expect(logs.join("\n")).not.toContain("very-secret-code");
- expect(JSON.stringify(sent)).not.toContain("very-secret-code");
- expect(JSON.stringify(sent)).not.toContain("fake-access-token-value");
- await waitFor(() => !alive(run?.pid ?? 0));
+ const code = pasted.searchParams.get("code") ?? "";
+ expect(logs.join("\n")).not.toContain(code);
+ expect(JSON.stringify(sent)).not.toContain(code);
+ expect(JSON.stringify(sent)).not.toContain("access-token-1");
+ expect(readFileSync(join(dataDir, "connectors.json"), "utf8")).not.toContain("access-token-1");
});
- it("opens the pasted address without following where it redirects (A5)", async () => {
+ it("never opens a pasted address: one on another port of this computer is refused (A5)", async () => {
let followed = 0;
const elsewhere = createServer((_req, res) => {
followed++;
res.end("followed");
});
await new Promise<void>((resolve) => elsewhere.listen(0, "127.0.0.1", resolve));
- const target = `http://127.0.0.1:${(elsewhere.address() as AddressInfo).port}/landing`;
try {
- const { manager, owner, emit, find } = setup(undefined, { FAKE_MCP_CLI_REDIRECT: target });
+ const { manager, owner, emit, find, sent, oauth } = setup();
manager.connect(owner, "notion", emit);
- const link = await find("auth_event", (m) => m.event.kind === "auth_url");
+ const link = await find("auth_event", (m) => linkOf(m) !== "");
await find("auth_prompt");
- const redirect = new URL(
- new URL(link.event.kind === "auth_url" ? link.event.url : "").searchParams.get("redirect_uri") ?? "",
- );
- redirect.searchParams.set("code", "c");
- redirect.searchParams.set("state", "fake-state");
- manager.reply(owner, link.flowId, { value: redirect.href });
- expect((await find("auth_done")).ok).toBe(true);
- await new Promise((resolve) => setTimeout(resolve, 200));
+ const pasted = oauth.callbackFor(linkOf(link));
+ pasted.port = String((elsewhere.address() as AddressInfo).port);
+ const before = sent.filter((m) => m.type === "auth_prompt").length;
+ manager.reply(owner, link.flowId, { value: pasted.href });
+ await waitFor(() => sent.filter((m) => m.type === "auth_prompt").length > before);
+ expect(sent.some((m) => m.type === "auth_done")).toBe(false);
expect(followed).toBe(0);
} finally {
elsewhere.close();
}
});
- it("refuses a pasted address for another place or sign-in, keeps waiting, and cancels by stopping the process", async () => {
- const { manager, owner, emit, find, sent, cliRuns } = setup();
+ it("refuses a pasted address for another place or sign-in, keeps waiting, and cancels by closing the sign-in page", async () => {
+ const { manager, owner, emit, find, sent, oauth } = setup();
manager.connect(owner, "notion", emit);
- const link = await find("auth_event", (m) => m.event.kind === "auth_url");
+ const link = await find("auth_event", (m) => linkOf(m) !== "");
await find("auth_prompt");
- const url = new URL(link.event.kind === "auth_url" ? link.event.url : "");
- const redirect = new URL(url.searchParams.get("redirect_uri") ?? "");
+ const redirect = oauth.callbackFor(linkOf(link));
for (const pasted of [
- `${redirect.href}?code=c&state=other-state`,
- `https://evil.example.com${redirect.pathname}?code=c&state=fake-state`,
+ `${redirect.origin}${redirect.pathname}?code=c&state=other-state`,
+ `https://evil.example.com${redirect.pathname}${redirect.search}`,
"not a url",
]) {
const before = sent.filter((m) => m.type === "auth_prompt").length;
@@ -527,12 +456,11 @@ describe("connector sign-in", () => {
}
expect(sent.some((m) => m.type === "auth_done")).toBe(false);
expect(manager.reply({}, link.flowId, { cancelled: true })).toBe(false);
- const pid = cliRuns()[0]?.pid ?? 0;
- expect(alive(pid)).toBe(true);
expect(manager.reply(owner, link.flowId, { cancelled: true })).toBe(true);
const done = await find("auth_done");
expect(done).toMatchObject({ ok: false, message: "Sign-in cancelled." });
- await waitFor(() => !alive(pid));
+ // The loopback sign-in page is gone.
+ await expect(oauth.browse(linkOf(link))).rejects.toThrow();
expect(manager.list()[0]?.status).toBe("needs_signin");
});
@@ -554,7 +482,7 @@ describe("connector sign-in", () => {
const done = await find("auth_done");
expect(done).toMatchObject({ ok: false, message: "Sign-in did not finish. Please try again." });
expect(manager.list()[0]?.status).toBe("error");
- expect(logs.some((l) => l.includes("notion") && l.includes("exit 1"))).toBe(true);
+ expect(logs.some((l) => l.includes("sign-in to connector notion failed"))).toBe(true);
expect(logs.join("\n")).not.toContain("https://auth.example.com");
});
@@ -570,15 +498,11 @@ describe("connector sign-in", () => {
expect(manager.signIn(owner, "nope", emit)).toMatchObject({ code: "unknown_connector" });
});
- it("turns a connector off, changes its mode, and removes it with a sign-out", async () => {
- const { manager, store, owner, emit, find, sent, changes, agentHome, cliRuns } = setup("auto");
+ it("turns a connector off, changes its mode, and removes it with its sign-in", async () => {
+ const { manager, store, owner, emit, find, sent, changes, agentHome, secrets, oauth } = setup("auto");
manager.connect(owner, "notion", emit);
await find("auth_done");
expect(manager.setMode("notion", "read_write")).toBeUndefined();
- expect(JSON.parse(readFileSync(store.signinMcpFile, "utf8")).mcpServers.notion).toEqual({
- url: "https://mcp.notion.com/mcp",
- exposure: "direct",
- });
expect(manager.disconnect("notion")).toBeUndefined();
expect(manager.list()[0]).toMatchObject({ added: true, enabled: false, status: "off" });
expect(changes).toEqual([true, false, true, true]);
@@ -589,18 +513,14 @@ describe("connector sign-in", () => {
{ type: "auth_done", flowId: expect.stringMatching(/^connector-/), providerId: "notion", ok: true },
]);
expect(manager.list()[0]).toMatchObject({ enabled: true, status: "connected" });
- expect(cliRuns()).toHaveLength(1);
+ expect(oauth.issued()).toBe(1);
+ expect([...secrets.values.keys()]).toEqual(["connector/notion/signin"]);
expect(manager.disconnect("notion")).toBeUndefined();
changes.splice(4);
expect(await manager.remove("notion")).toBeUndefined();
- expect(cliRuns().map((r) => r.argv)).toEqual([
- ["mcp", "login", "notion"],
- ["mcp", "logout", "notion"],
- ]);
+ expect(secrets.values.size).toBe(0);
expect(store.state().connectors).toEqual({});
expect(JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8"))).toEqual({ mcpServers: {} });
- expect(JSON.parse(readFileSync(store.signinMcpFile, "utf8"))).toEqual({ mcpServers: {} });
- expect(JSON.parse(readFileSync(store.authFile, "utf8"))).toEqual({});
expect(manager.list()[0]).toMatchObject({ added: false, status: "off" });
expect(changes).toEqual([true, false, true, true, true]);
expect(manager.setMode("notion", "read_only")).toMatchObject({ code: "connector_not_added" });
diff --git a/packages/daemon/test/fake-app.ts b/packages/daemon/test/fake-app.ts
index 787f860..7b09dbe 100644
--- a/packages/daemon/test/fake-app.ts
+++ b/packages/daemon/test/fake-app.ts
@@ -24,6 +24,9 @@ type Frame =
export function fakeApp(answers: Answer[] = [], otherwise: Answer = "decline") {
const [daemonEnd, appEnd] = duplexPair();
const asked: AskedApproval[] = [];
+ /** The app's Keychain, by secret id; `secretCalls` records the methods and ids only. */
+ const secrets = new Map<string, string>();
+ const secretCalls: string[] = [];
const queue = [...answers];
const pending = new Map<number, { resolve(v: unknown): void; reject(e: Error): void }>();
const held: number[] = [];
@@ -43,6 +46,19 @@ export function fakeApp(answers: Answer[] = [], otherwise: Answer = "decline") {
else waiting?.resolve(frame.result);
continue;
}
+ if (frame.method.startsWith("secret_")) {
+ const params = (frame.params ?? {}) as { id?: string; secret?: string };
+ secretCalls.push(params.id === undefined ? frame.method : `${frame.method} ${params.id}`);
+ const id = params.id ?? "";
+ let result: unknown = { ids: [...secrets.keys()].sort() };
+ if (frame.method === "secret_get") result = secrets.has(id) ? { secret: secrets.get(id) } : null;
+ else if (frame.method === "secret_put") {
+ secrets.set(id, params.secret ?? "");
+ result = {};
+ } else if (frame.method === "secret_delete") result = { deleted: secrets.delete(id) };
+ write({ kind: "response", id: frame.id, result });
+ continue;
+ }
if (frame.method !== "approve") {
write({ kind: "response", id: frame.id, error: `unknown method ${frame.method}` });
continue;
@@ -63,6 +79,8 @@ export function fakeApp(answers: Answer[] = [], otherwise: Answer = "decline") {
return {
daemonEnd: daemonEnd as Duplex,
asked,
+ secrets,
+ secretCalls,
/** Answers the oldest held approval, as a user clicking in the dialog later. */
release: (approved: boolean) => {
const id = held.shift();
diff --git a/packages/daemon/test/fake-oauth.ts b/packages/daemon/test/fake-oauth.ts
new file mode 100644
index 0000000..dad488d
--- /dev/null
+++ b/packages/daemon/test/fake-oauth.ts
@@ -0,0 +1,126 @@
+// A stand-in for an MCP server's OAuth authorization server (protected resource metadata,
+// authorization server metadata, dynamic client registration, the token endpoint) behind a `fetch`
+// the daemon is given, and for the user's browser: `browse(url)` approves an authorization URL the
+// way the provider would, by calling its loopback `redirect_uri` with a code and the `state`.
+
+const ISSUER = "https://auth.example.com";
+
+export interface FakeOAuthOptions {
+ /** "fail": the token endpoint refuses every code. */
+ mode?: "ok" | "fail";
+}
+
+export function fakeOAuth(options: FakeOAuthOptions = {}) {
+ let issued = 0;
+ const codes = new Map<string, string>();
+ const refreshTokens = new Set<string>();
+ const tokenRequests: { grant: string; clientId?: string; clientSecret?: string }[] = [];
+ const registered: { redirect_uris: string[] }[] = [];
+
+ const json = (status: number, body: unknown) =>
+ new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
+
+ const tokens = () => {
+ issued++;
+ const refresh = `refresh-token-${issued}`;
+ refreshTokens.add(refresh);
+ return {
+ access_token: `access-token-${issued}`,
+ token_type: "Bearer",
+ expires_in: 3600,
+ refresh_token: refresh,
+ };
+ };
+
+ const fetch: typeof globalThis.fetch = async (input, init) => {
+ const url = new URL(input instanceof Request ? input.url : String(input));
+ const method = init?.method ?? (input instanceof Request ? input.method : "GET");
+ if (url.pathname.startsWith("/.well-known/oauth-protected-resource")) {
+ const resource = `${url.origin}${url.pathname.slice("/.well-known/oauth-protected-resource".length) || "/"}`;
+ return json(200, { resource, authorization_servers: [ISSUER] });
+ }
+ if (url.origin !== ISSUER) return new Response("not found", { status: 404 });
+ if (url.pathname === "/.well-known/oauth-authorization-server")
+ return json(200, {
+ issuer: ISSUER,
+ authorization_endpoint: `${ISSUER}/authorize`,
+ token_endpoint: `${ISSUER}/token`,
+ registration_endpoint: `${ISSUER}/register`,
+ response_types_supported: ["code"],
+ grant_types_supported: ["authorization_code", "refresh_token"],
+ code_challenge_methods_supported: ["S256"],
+ token_endpoint_auth_methods_supported: ["none", "client_secret_post", "client_secret_basic"],
+ });
+ if (url.pathname === "/register" && method === "POST") {
+ const body = JSON.parse(String(init?.body ?? "{}")) as { redirect_uris: string[] };
+ registered.push(body);
+ return json(201, { ...body, client_id: `registered-client-${registered.length}` });
+ }
+ if (url.pathname === "/token" && method === "POST") {
+ const form = new URLSearchParams(String(init?.body ?? ""));
+ const grant = form.get("grant_type") ?? "";
+ const basic = new Headers(init?.headers).get("authorization");
+ const [basicId, basicSecret] = basic?.startsWith("Basic ")
+ ? decodeURIComponent(atob(basic.slice(6))).split(":")
+ : [];
+ const clientId = form.get("client_id") ?? basicId;
+ const clientSecret = form.get("client_secret") ?? basicSecret;
+ tokenRequests.push({
+ grant,
+ ...(clientId ? { clientId } : {}),
+ ...(clientSecret ? { clientSecret } : {}),
+ });
+ if (options.mode === "fail") return json(400, { error: "invalid_grant" });
+ if (grant === "authorization_code") {
+ const code = form.get("code") ?? "";
+ if (!codes.has(code)) return json(400, { error: "invalid_grant" });
+ codes.delete(code);
+ return json(200, tokens());
+ }
+ if (grant === "refresh_token") {
+ const refresh = form.get("refresh_token") ?? "";
+ if (!refreshTokens.delete(refresh)) return json(400, { error: "invalid_grant" });
+ return json(200, tokens());
+ }
+ return json(400, { error: "unsupported_grant_type" });
+ }
+ return new Response("not found", { status: 404 });
+ };
+
+ /** What the user's browser does after they approve: the provider redirects to the loopback address. */
+ const callbackFor = (authorization: string) => {
+ const url = new URL(authorization);
+ const redirect = new URL(url.searchParams.get("redirect_uri") ?? "");
+ const code = `authorization-code-${codes.size + issued + 1}`;
+ codes.set(code, url.searchParams.get("code_challenge") ?? "");
+ redirect.searchParams.set("code", code);
+ redirect.searchParams.set("state", url.searchParams.get("state") ?? "");
+ if (redirect.hostname === "localhost") redirect.hostname = "127.0.0.1";
+ return redirect;
+ };
+
+ return {
+ fetch,
+ /** The redirect the provider would send the browser to; nothing is opened. */
+ callbackFor,
+ /** The browser follows the provider's redirect to this computer's sign-in page. */
+ browse: async (authorization: string | URL) => {
+ const response = await globalThis.fetch(callbackFor(String(authorization)));
+ await response.text();
+ return response.status;
+ },
+ tokenRequests,
+ registered,
+ /** The access token the provider issued last. */
+ lastAccessToken: () => `access-token-${issued}`,
+ issued: () => issued,
+ };
+}
+
+/** The daemon's `connectorOAuth` with a stand-in provider; `auto`: the user approves as soon as the page opens. */
+export function oauthOptions(auto = false, oauth = fakeOAuth()) {
+ return {
+ fetch: oauth.fetch,
+ ...(auto ? { openBrowser: (url: string) => void oauth.browse(url).catch(() => {}) } : {}),
+ };
+}
diff --git a/packages/daemon/test/models-gateway.test.ts b/packages/daemon/test/models-gateway.test.ts
index 671c432..7644527 100644
--- a/packages/daemon/test/models-gateway.test.ts
+++ b/packages/daemon/test/models-gateway.test.ts
@@ -122,7 +122,8 @@ describe("the in-chat model picker (S32)", () => {
});
await client.find("profiles", (m) => m.profiles.length === 1);
client.send({ type: "models_list" });
- const list = await client.find("models");
+ // The engine also sends the list when it becomes ready (L101); wait for one made after the save.
+ const list = await client.find("models", (m) => m.profiles.some((p) => p.name === "quick"));
expect(list.current).toEqual({
provider: "fake",
id: "fake-model",