Skip to content

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

TypeScript

feat(desktop): add a Keychain store and native approval dialogs

Alan Buscaglia1c345b5fd17b
diff --git a/apps/desktop/src-tauri/Cargo.lock b/apps/desktop/src-tauri/Cargo.lock
index a3bfa99..80086f8 100644
--- a/apps/desktop/src-tauri/Cargo.lock
+++ b/apps/desktop/src-tauri/Cargo.lock
@@ -787,6 +787,16 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "dbus-secret-service"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6"
+dependencies = [
+ "dbus",
+ "zeroize",
+]
+
[[package]]
name = "deflate64"
version = "0.1.12"
@@ -1397,6 +1407,8 @@ dependencies = [
"base64 0.22.1",
"block2",
"bzip2 0.6.1",
+ "core-foundation",
+ "dbus-secret-service",
"getrandom 0.3.4",
"image",
"libc",
@@ -1410,6 +1422,7 @@ dependencies = [
"objc2-foundation",
"objc2-screen-capture-kit",
"objc2-speech",
+ "security-framework",
"serde",
"serde_json",
"sha2",
@@ -3432,6 +3445,29 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "security-framework"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
+dependencies = [
+ "bitflags 2.13.2",
+ "core-foundation",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "selectors"
version = "0.38.0"
diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml
index 39cf837..0c8f5cf 100644
--- a/apps/desktop/src-tauri/Cargo.toml
+++ b/apps/desktop/src-tauri/Cargo.toml
@@ -50,6 +50,14 @@ objc2-screen-capture-kit = { version = "0.3", default-features = false, features
objc2-speech = { version = "0.3", default-features = false, features = ["std", "block2", "objc2-avf-audio", "SFSpeechRecognizer", "SFSpeechRecognitionRequest", "SFSpeechRecognitionResult", "SFSpeechRecognitionTask", "SFTranscription"] }
objc2-avf-audio = { version = "0.3", default-features = false, features = ["std", "block2", "AVAudioBuffer", "AVAudioEngine", "AVAudioFormat", "AVAudioIONode", "AVAudioNode", "AVAudioTime", "AVAudioTypes"] }
objc2-av-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "AVCaptureDevice", "AVMediaFormat"] }
+# Connector secrets (S25.5): generic password items in the login keychain, created by the app.
+security-framework = "3.7"
+core-foundation = "0.10"
+
+# Connector secrets on Linux (S25.7): the Secret Service over D-Bus. Synchronous, and its `dbus`
+# dependency is already linked by tao on Linux.
+[target.'cfg(target_os = "linux")'.dependencies]
+dbus-secret-service = "4.1"
# Debug builds encode screenshots fast too (S24.8): `image` holds the JPEG encoder and `zune-*`
# decode JPEGs (tests). The encoder is generic, so most of its code is compiled in this crate,
diff --git a/apps/desktop/src-tauri/src/alert.rs b/apps/desktop/src-tauri/src/alert.rs
new file mode 100644
index 0000000..331b9c2
--- /dev/null
+++ b/apps/desktop/src-tauri/src/alert.rs
@@ -0,0 +1,74 @@
+//! Native yes/no alerts owned by the app (NSAlert through the dialog plugin on macOS), never the
+//! webview, whose default button is the safe one (L75 A2). NSAlert makes the first button the
+//! default (Return, highlighted, rightmost), so the refusing button goes first and only a click
+//! on the allowing button allows. Escape, closing, or aborting the alert refuses too.
+
+use tauri::AppHandle;
+use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind, MessageDialogResult};
+
+/// The two buttons of a yes/no alert.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Choice {
+ pub allow: &'static str,
+ pub refuse: &'static str,
+}
+
+impl Choice {
+ /// The buttons in the plugin's order: the first one is the alert's default.
+ pub fn buttons(&self) -> MessageDialogButtons {
+ MessageDialogButtons::OkCancelCustom(self.refuse.into(), self.allow.into())
+ }
+
+ /// True only when the allowing button was pressed.
+ pub fn allowed(&self, result: &MessageDialogResult) -> bool {
+ self.allow != self.refuse && matches!(result, MessageDialogResult::Custom(label) if label == self.allow)
+ }
+}
+
+/// Shows the alert and waits for the answer. Blocks, so it never runs on the main thread.
+pub fn ask(app: &AppHandle, title: &str, message: &str, choice: Choice) -> bool {
+ let result = app
+ .dialog()
+ .message(message)
+ .title(title)
+ .kind(MessageDialogKind::Warning)
+ .buttons(choice.buttons())
+ .blocking_show_with_result();
+ choice.allowed(&result)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const CHOICE: Choice = Choice { allow: "Allow", refuse: "Cancel" };
+
+ #[test]
+ fn the_refusing_button_comes_first_so_it_is_the_default() {
+ match CHOICE.buttons() {
+ MessageDialogButtons::OkCancelCustom(first, second) => {
+ assert_eq!(first, "Cancel");
+ assert_eq!(second, "Allow");
+ }
+ other => panic!("unexpected buttons: {other:?}"),
+ }
+ }
+
+ #[test]
+ fn only_the_allowing_button_allows() {
+ assert!(CHOICE.allowed(&MessageDialogResult::Custom("Allow".into())));
+ assert!(!CHOICE.allowed(&MessageDialogResult::Custom("Cancel".into())));
+ assert!(!CHOICE.allowed(&MessageDialogResult::Custom("allow".into())));
+ // Return on the default button, Escape, a closed or aborted alert.
+ assert!(!CHOICE.allowed(&MessageDialogResult::Ok));
+ assert!(!CHOICE.allowed(&MessageDialogResult::Yes));
+ assert!(!CHOICE.allowed(&MessageDialogResult::Cancel));
+ assert!(!CHOICE.allowed(&MessageDialogResult::No));
+ }
+
+ #[test]
+ fn identical_labels_never_allow() {
+ let same = Choice { allow: "OK", refuse: "OK" };
+ assert!(!same.allowed(&MessageDialogResult::Custom("OK".into())));
+ }
+}
diff --git a/apps/desktop/src-tauri/src/approvals/fake.rs b/apps/desktop/src-tauri/src/approvals/fake.rs
new file mode 100644
index 0000000..fe69cc0
--- /dev/null
+++ b/apps/desktop/src-tauri/src/approvals/fake.rs
@@ -0,0 +1,81 @@
+//! A scripted [`Prompt`] that records what it showed and how many dialogs were up at once.
+
+use super::{ApprovalDialog, Prompt};
+use std::collections::VecDeque;
+use std::sync::{Condvar, Mutex};
+use std::time::Duration;
+
+#[derive(Debug, Clone, Copy)]
+pub enum Answer {
+ /// Clicks after holding the dialog for a while.
+ After(Duration, bool),
+ /// Never answers until dismissed, then clicks Allow (a late click on a stale dialog). The
+ /// n-th hanging dialog waits for the n-th dismissal, even one that came before it showed.
+ Hang,
+}
+
+#[derive(Default)]
+pub struct FakePrompt {
+ answers: Mutex<VecDeque<Answer>>,
+ pub shown: Mutex<Vec<ApprovalDialog>>,
+ state: Mutex<Showing>,
+ dismissed: Condvar,
+}
+
+#[derive(Default)]
+struct Showing {
+ now: usize,
+ most: usize,
+ dismissals: usize,
+ hangs: usize,
+}
+
+impl FakePrompt {
+ pub fn new(answers: impl IntoIterator<Item = Answer>) -> Self {
+ FakePrompt { answers: Mutex::new(answers.into_iter().collect()), ..Default::default() }
+ }
+
+ pub fn most_at_once(&self) -> usize {
+ self.state.lock().unwrap().most
+ }
+
+ pub fn dismissals(&self) -> usize {
+ self.state.lock().unwrap().dismissals
+ }
+
+ pub fn shown_titles(&self) -> Vec<String> {
+ self.shown.lock().unwrap().iter().map(|d| d.title.clone()).collect()
+ }
+}
+
+impl Prompt for FakePrompt {
+ fn ask(&self, dialog: &ApprovalDialog) -> bool {
+ self.shown.lock().unwrap().push(dialog.clone());
+ let answer = self.answers.lock().unwrap().pop_front().unwrap_or(Answer::After(Duration::ZERO, false));
+ {
+ let mut state = self.state.lock().unwrap();
+ state.now += 1;
+ state.most = state.most.max(state.now);
+ }
+ let allowed = match answer {
+ Answer::After(hold, allowed) => {
+ std::thread::sleep(hold);
+ allowed
+ }
+ Answer::Hang => {
+ let mut state = self.state.lock().unwrap();
+ state.hangs += 1;
+ let turn = state.hangs;
+ drop(self.dismissed.wait_while(state, |s| s.dismissals < turn).unwrap());
+ true
+ }
+ };
+ self.state.lock().unwrap().now -= 1;
+ allowed
+ }
+
+ fn dismiss(&self) {
+ self.state.lock().unwrap().dismissals += 1;
+ self.dismissed.notify_all();
+ }
+}
diff --git a/apps/desktop/src-tauri/src/approvals/mod.rs b/apps/desktop/src-tauri/src/approvals/mod.rs
new file mode 100644
index 0000000..341a76c
--- /dev/null
+++ b/apps/desktop/src-tauri/src/approvals/mod.rs
@@ -0,0 +1,270 @@
+//! Native approvals for connector actions (S25.3): the daemon asks the app (over the app-key
+//! channel, wired in T23c) and the app shows a native dialog with the action's full preview,
+//! outside the agent's reach (L49). Declining, not answering in time, or a dialog that cannot be
+//! shown all refuse.
+//!
+//! The rules are pure and tested here: the dialog text ([`ApprovalDialog`]), one dialog at a
+//! time, and the timeout. [`Prompt`] is the seam to the real dialog (`native`); `fake` stands in
+//! for it in tests.
+
+#[cfg(test)]
+mod fake;
+pub mod native;
+
+use crate::alert::Choice;
+use serde::Deserialize;
+use std::sync::mpsc::{self, RecvTimeoutError};
+use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
+use std::time::{Duration, Instant};
+
+/// How long the user has to answer, waiting for an earlier dialog included.
+pub const APPROVAL_TIMEOUT: Duration = Duration::from_secs(120);
+/// The approval buttons; "Decline" is the default (Return).
+pub const APPROVAL_CHOICE: Choice = Choice { allow: "Allow", refuse: "Decline" };
+/// The most characters of one value shown when the preview is small.
+pub const VALUE_LIMIT: usize = 600;
+/// The most lines of one value.
+pub const LINE_LIMIT: usize = 12;
+/// Values share this many characters; each still shows at least [`MIN_VALUE_LIMIT`].
+pub const PREVIEW_BUDGET: usize = 4000;
+pub const MIN_VALUE_LIMIT: usize = 80;
+/// The most characters of a connector, action, or field name.
+pub const NAME_LIMIT: usize = 60;
+
+/// One argument of the action, in the order the daemon chose (key fields first).
+#[derive(Debug, Clone, PartialEq, Deserialize)]
+pub struct PreviewField {
+ pub name: String,
+ pub value: serde_json::Value,
+}
+
+/// What the daemon asks the user to approve.
+#[derive(Debug, Clone, PartialEq, Deserialize)]
+pub struct ApprovalRequest {
+ /// The connector's display name ("Notion").
+ pub connector: String,
+ /// What it will do ("create pages").
+ pub action: String,
+ pub preview: Vec<PreviewField>,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Decision {
+ Approved,
+ Declined,
+}
+
+/// The text of the native dialog.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ApprovalDialog {
+ /// "Allow Notion to create pages?"
+ pub title: String,
+ /// The sentence, every field with its (possibly cut) value, and the timeout note.
+ pub message: String,
+}
+
+impl ApprovalDialog {
+ pub fn new(request: &ApprovalRequest, timeout: Duration) -> Self {
+ let connector = name(&request.connector);
+ let action = name(&request.action);
+ let per_value = (PREVIEW_BUDGET / request.preview.len().max(1)).clamp(MIN_VALUE_LIMIT, VALUE_LIMIT);
+ let fields: Vec<String> = request
+ .preview
+ .iter()
+ .map(|field| {
+ let value = clip(&sanitize(&render(&field.value), false), per_value, LINE_LIMIT);
+ // Lines inside one value are indented, so they do not read as fields of their own.
+ format!("{}: {}", name(&field.name), value.replace('\n', "\n "))
+ })
+ .collect();
+ let details = if fields.is_empty() { "(no details)".to_owned() } else { fields.join("\n") };
+ ApprovalDialog {
+ title: format!("Allow {connector} to {action}?"),
+ message: format!(
+ "The assistant wants to {action} in {connector}.\n\n{details}\n\n\
+If you do not answer within {}, it is declined.",
+ spell(timeout)
+ ),
+ }
+ }
+}
+
+/// A connector, action, or field name: one line, at most [`NAME_LIMIT`] characters.
+fn name(text: &str) -> String {
+ clip(&sanitize(text, true), NAME_LIMIT, 1)
+}
+
+/// Strings as they are; anything else as indented JSON.
+fn render(value: &serde_json::Value) -> String {
+ match value {
+ serde_json::Value::String(text) => text.clone(),
+ other => serde_json::to_string_pretty(other).unwrap_or_else(|_| other.to_string()),
+ }
+}
+
+/// "2 minutes", "90 seconds".
+fn spell(timeout: Duration) -> String {
+ let seconds = timeout.as_secs();
+ match seconds {
+ 60 => "1 minute".into(),
+ s if s > 0 && s % 60 == 0 => format!("{} minutes", s / 60),
+ 1 => "1 second".into(),
+ s => format!("{s} seconds"),
+ }
+}
+
+/// Characters that render as nothing or reorder the text around them.
+fn invisible(c: char) -> bool {
+ matches!(c, '\u{ad}' | '\u{61c}' | '\u{180e}' | '\u{200b}'..='\u{200f}' | '\u{202a}'..='\u{202e}'
+ | '\u{2060}'..='\u{2064}' | '\u{2066}'..='\u{2069}' | '\u{feff}')
+}
+
+/// Makes text safe to show: control characters and invisible or direction-changing characters
+/// (which could disguise what is shown) become `\u{…}` escapes; `\r\n` becomes `\n`. With
+/// `one_line`, newlines and tabs become spaces.
+pub fn sanitize(text: &str, one_line: bool) -> String {
+ let mut out = String::with_capacity(text.len());
+ for c in text.replace("\r\n", "\n").chars() {
+ match c {
+ '\n' | '\t' if one_line => out.push(' '),
+ '\n' | '\t' => out.push(c),
+ c if c.is_control() || invisible(c) => out.push_str(&format!("\\u{{{:x}}}", c as u32)),
+ c => out.push(c),
+ }
+ }
+ out
+}
+
+/// Keeps at most `max_chars` characters and `max_lines` lines; when anything is cut, ends with
+/// "… (N more characters)".
+pub fn clip(text: &str, max_chars: usize, max_lines: usize) -> String {
+ let total = text.chars().count();
+ let (mut kept, mut count, mut lines) = (String::new(), 0, 1);
+ for c in text.chars() {
+ if count == max_chars || (c == '\n' && lines >= max_lines) {
+ break;
+ }
+ lines += usize::from(c == '\n');
+ kept.push(c);
+ count += 1;
+ }
+ if count == total {
+ kept
+ } else {
+ format!("{kept}… ({} more characters)", total - count)
+ }
+}
+
+/// The real dialog, or a fake in tests.
+pub trait Prompt: Send + Sync {
+ /// Shows the dialog and blocks until the user answers; true only for the allowing button.
+ fn ask(&self, dialog: &ApprovalDialog) -> bool;
+ /// Closes the dialog still on screen after the timeout (best effort). Its answer, if any,
+ /// is ignored.
+ fn dismiss(&self);
+}
+
+/// Shows one approval dialog at a time and declines when the user does not answer in time.
+pub struct Approvals {
+ prompt: Arc<dyn Prompt>,
+ timeout: Duration,
+ gate: Arc<Gate>,
+}
+
+impl Approvals {
+ pub fn new(prompt: Arc<dyn Prompt>, timeout: Duration) -> Self {
+ Approvals { prompt, timeout, gate: Arc::new(Gate::default()) }
+ }
+
+ /// Asks the user. Blocks until the answer or the timeout, so call it off the main thread.
+ pub fn confirm(&self, request: &ApprovalRequest) -> Decision {
+ let deadline = Instant::now() + self.timeout;
+ let dialog = ApprovalDialog::new(request, self.timeout);
+ let Some(ticket) = self.gate.acquire(deadline) else {
+ return Decision::Declined;
+ };
+ // The dialog runs on a thread of its own that holds the screen until the dialog closes,
+ // so a stale dialog left after the timeout still keeps the next one waiting.
+ let (answer, answered) = mpsc::channel();
+ let (prompt, gate) = (self.prompt.clone(), self.gate.clone());
+ let spawned = std::thread::Builder::new().name("approval-dialog".into()).spawn(move || {
+ let _screen = Ticket { gate, ticket };
+ let _ = answer.send(prompt.ask(&dialog));
+ });
+ if spawned.is_err() {
+ self.gate.release(ticket);
+ return Decision::Declined;
+ }
+ match answered.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
+ Ok(true) => Decision::Approved,
+ // Declined, or the dialog failed (its thread panicked).
+ Ok(false) | Err(RecvTimeoutError::Disconnected) => Decision::Declined,
+ Err(RecvTimeoutError::Timeout) => {
+ self.gate.while_held(ticket, || self.prompt.dismiss());
+ Decision::Declined
+ }
+ }
+ }
+}
+
+/// Who holds the screen: at most one dialog, identified by a ticket.
+#[derive(Default)]
+struct Gate {
+ state: Mutex<GateState>,
+ freed: Condvar,
+}
+
+#[derive(Default)]
+struct GateState {
+ holder: Option<u64>,
+ next: u64,
+}
+
+impl Gate {
+ fn lock(&self) -> MutexGuard<'_, GateState> {
+ self.state.lock().unwrap_or_else(PoisonError::into_inner)
+ }
+
+ /// Waits for the screen until the deadline.
+ fn acquire(&self, deadline: Instant) -> Option<u64> {
+ let mut state = self.lock();
+ while state.holder.is_some() {
+ let left = deadline.checked_duration_since(Instant::now()).filter(|left| !left.is_zero())?;
+ state = self.freed.wait_timeout(state, left).unwrap_or_else(PoisonError::into_inner).0;
+ }
+ state.next += 1;
+ state.holder = Some(state.next);
+ Some(state.next)
+ }
+
+ fn release(&self, ticket: u64) {
+ let mut state = self.lock();
+ if state.holder == Some(ticket) {
+ state.holder = None;
+ self.freed.notify_all();
+ }
+ }
+
+ /// Runs `f` only while `ticket` still holds the screen, so it cannot touch a later dialog.
+ fn while_held(&self, ticket: u64, f: impl FnOnce()) {
+ let state = self.lock();
+ if state.holder == Some(ticket) {
+ f();
+ }
+ }
+}
+
+/// Frees the screen when the dialog's thread ends, panics included.
+struct Ticket {
+ gate: Arc<Gate>,
+ ticket: u64,
+}
+
+impl Drop for Ticket {
+ fn drop(&mut self) {
+ self.gate.release(self.ticket);
+ }
+}
+
+#[cfg(test)]
+mod tests;
diff --git a/apps/desktop/src-tauri/src/approvals/native.rs b/apps/desktop/src-tauri/src/approvals/native.rs
new file mode 100644
index 0000000..53dd7ef
--- /dev/null
+++ b/apps/desktop/src-tauri/src/approvals/native.rs
@@ -0,0 +1,42 @@
+//! The real approval dialog: an alert shown by the app (NSAlert through the dialog plugin on
+//! macOS, as computer control does, S24.3), "Decline" as the default button.
+
+use super::{ApprovalDialog, Prompt, APPROVAL_CHOICE};
+use tauri::AppHandle;
+
+pub struct NativePrompt {
+ app: AppHandle,
+}
+
+impl NativePrompt {
+ pub fn new(app: AppHandle) -> Self {
+ NativePrompt { app }
+ }
+}
+
+impl Prompt for NativePrompt {
+ fn ask(&self, dialog: &ApprovalDialog) -> bool {
+ crate::alert::ask(&self.app, &dialog.title, &dialog.message, APPROVAL_CHOICE)
+ }
+
+ /// macOS: aborts the modal alert on screen. `-[NSApplication abortModal]` is the one modal
+ /// call meant for other threads; the aborted alert reads as Decline. The approvals gate
+ /// guarantees no other approval dialog is up, but a computer-control dialog stacked on top
+ /// would be aborted instead, which also refuses (fail closed). Elsewhere the stale dialog
+ /// stays until the user answers, and that answer is ignored.
+ fn dismiss(&self) {
+ #[cfg(target_os = "macos")]
+ {
+ use objc2::runtime::AnyObject;
+ use objc2::{class, msg_send};
+ // SAFETY: `sharedApplication` exists once the app runs (this is only called after a
+ // dialog was shown) and `abortModal` is documented as callable from any thread.
+ unsafe {
+ let app: *mut AnyObject = msg_send![class!(NSApplication), sharedApplication];
+ if !app.is_null() {
+ let _: () = msg_send![app, abortModal];
+ }
+ }
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/approvals/tests.rs b/apps/desktop/src-tauri/src/approvals/tests.rs
new file mode 100644
index 0000000..a1206d8
--- /dev/null
+++ b/apps/desktop/src-tauri/src/approvals/tests.rs
@@ -0,0 +1,203 @@
+use super::fake::{Answer, FakePrompt};
+use super::*;
+use serde_json::json;
+
+fn field(name: &str, value: serde_json::Value) -> PreviewField {
+ PreviewField { name: name.into(), value }
+}
+
+fn request(preview: Vec<PreviewField>) -> ApprovalRequest {
+ ApprovalRequest { connector: "Slack".into(), action: "send message".into(), preview }
+}
+
+fn approvals(prompt: &Arc<FakePrompt>, timeout: Duration) -> Approvals {
+ Approvals::new(prompt.clone(), timeout)
+}
+
+const LONG: Duration = Duration::from_secs(5);
+
+#[test]
+fn the_dialog_names_the_connector_the_action_and_every_field() {
+ let dialog = ApprovalDialog::new(
+ &request(vec![
+ field("channel", json!("#general")),
+ field("text", json!("Ship it\nnow")),
+ field("blocks", json!([{"type": "divider"}])),
+ field("unfurl", json!(false)),
+ ]),
+ Duration::from_secs(120),
+ );
+ assert_eq!(dialog.title, "Allow Slack to send message?");
+ assert_eq!(
+ dialog.message,
+ "The assistant wants to send message in Slack.\n\n\
+channel: #general\n\
+text: Ship it\n now\n\
+blocks: [\n {\n \"type\": \"divider\"\n }\n ]\n\
+unfurl: false\n\n\
+If you do not answer within 2 minutes, it is declined."
+ );
+}
+
+#[test]
+fn an_action_without_arguments_says_so() {
+ let dialog = ApprovalDialog::new(&request(vec![]), Duration::from_secs(90));
+ assert!(dialog.message.contains("\n\n(no details)\n\n"), "{}", dialog.message);
+ assert!(dialog.message.ends_with("If you do not answer within 90 seconds, it is declined."), "{}", dialog.message);
+}
+
+#[test]
+fn a_long_value_is_cut_with_a_clear_marker() {
+ let long = "x".repeat(VALUE_LIMIT + 250);
+ let dialog = ApprovalDialog::new(&request(vec![field("text", json!(long)), field("to", json!("ana"))]), LONG);
+ let expected = format!("text: {}… (250 more characters)\nto: ana", "x".repeat(VALUE_LIMIT));
+ assert!(dialog.message.contains(&expected), "{}", dialog.message);
+}
+
+#[test]
+fn many_long_fields_share_the_budget_but_every_name_shows() {
+ let fields: Vec<_> = (0..200).map(|i| field(&format!("field{i}"), json!("y".repeat(500)))).collect();
+ let dialog = ApprovalDialog::new(&request(fields), LONG);
+ for i in 0..200 {
+ assert!(dialog.message.contains(&format!("\nfield{i}: ")), "field{i} is missing");
+ }
+ let per_value = (PREVIEW_BUDGET / 200).max(MIN_VALUE_LIMIT);
+ assert_eq!(per_value, MIN_VALUE_LIMIT);
+ let cut = format!("{}… ({} more characters)", "y".repeat(per_value), 500 - per_value);
+ assert!(dialog.message.contains(&cut), "{}", &dialog.message[..400]);
+}
+
+#[test]
+fn clip_cuts_by_characters_or_lines_and_counts_what_is_hidden() {
+ assert_eq!(clip("short", 10, 3), "short");
+ assert_eq!(clip("ñandú🦀", 3, 3), "ñan… (3 more characters)");
+ assert_eq!(clip("a\nb\nc\nd", 100, 2), "a\nb… (4 more characters)");
+ assert_eq!(clip("", 0, 0), "");
+}
+
+#[test]
+fn hidden_and_direction_characters_are_shown_as_escapes() {
+ assert_eq!(sanitize("pay\u{202e}evil", false), "pay\\u{202e}evil");
+ assert_eq!(sanitize("a\u{200b}b\u{feff}c\u{7}d", false), "a\\u{200b}b\\u{feff}c\\u{7}d");
+ assert_eq!(sanitize("line\r\nnext\ttab", false), "line\nnext\ttab");
+ assert_eq!(sanitize("line\r\nnext\ttab", true), "line next tab");
+ assert_eq!(sanitize("plain ñ 🦀", true), "plain ñ 🦀");
+}
+
+#[test]
+fn names_are_one_line_and_short() {
+ let req = ApprovalRequest {
+ connector: format!("Evil\nAllow everything {}", "z".repeat(100)),
+ action: "send\u{202e}".into(),
+ preview: vec![field("a\nb", json!("v"))],
+ };
+ let dialog = ApprovalDialog::new(&req, LONG);
+ assert!(!dialog.title.contains('\n'), "{}", dialog.title);
+ assert!(dialog.title.starts_with("Allow Evil Allow everything zzz"), "{}", dialog.title);
+ assert!(dialog.title.contains("… (") && dialog.title.contains("send\\u{202e}?"), "{}", dialog.title);
+ assert!(dialog.message.contains("\na b: v\n"), "{}", dialog.message);
+}
+
+#[test]
+fn the_approval_buttons_default_to_decline() {
+ assert_eq!(APPROVAL_CHOICE, Choice { allow: "Allow", refuse: "Decline" });
+ match APPROVAL_CHOICE.buttons() {
+ tauri_plugin_dialog::MessageDialogButtons::OkCancelCustom(first, _) => assert_eq!(first, "Decline"),
+ other => panic!("unexpected buttons: {other:?}"),
+ }
+}
+
+#[test]
+fn allow_approves_and_decline_declines() {
+ let prompt = Arc::new(FakePrompt::new([Answer::After(Duration::ZERO, true), Answer::After(Duration::ZERO, false)]));
+ let approvals = approvals(&prompt, LONG);
+ assert_eq!(approvals.confirm(&request(vec![])), Decision::Approved);
+ assert_eq!(approvals.confirm(&request(vec![])), Decision::Declined);
+ assert_eq!(prompt.shown_titles(), vec!["Allow Slack to send message?"; 2]);
+}
+
+#[test]
+fn no_answer_in_time_declines_and_closes_the_dialog() {
+ let prompt = Arc::new(FakePrompt::new([Answer::Hang]));
+ let approvals = approvals(&prompt, Duration::from_millis(100));
+ let started = Instant::now();
+ assert_eq!(approvals.confirm(&request(vec![])), Decision::Declined);
+ assert!(started.elapsed() >= Duration::from_millis(100));
+ assert!(started.elapsed() < Duration::from_secs(2));
+ assert_eq!(prompt.dismissals(), 1);
+}
+
+#[test]
+fn a_late_click_on_a_stale_dialog_approves_nothing() {
+ // The hanging dialog "clicks Allow" once dismissed; the next request must not see it.
+ let prompt = Arc::new(FakePrompt::new([Answer::Hang, Answer::After(Duration::ZERO, false)]));
+ let approvals = approvals(&prompt, Duration::from_millis(100));
+ assert_eq!(approvals.confirm(&request(vec![])), Decision::Declined);
+ let approvals = Approvals { timeout: LONG, ..approvals };
+ assert_eq!(approvals.confirm(&request(vec![])), Decision::Declined);
+ assert_eq!(prompt.shown_titles().len(), 2);
+}
+
+#[test]
+fn only_one_dialog_shows_at_a_time() {
+ let hold = Duration::from_millis(40);
+ let prompt = Arc::new(FakePrompt::new([
+ Answer::After(hold, true),
+ Answer::After(hold, false),
+ Answer::After(hold, true),
+ Answer::After(hold, true),
+ ]));
+ let approvals = Arc::new(approvals(&prompt, LONG));
+ let threads: Vec<_> = (0..4)
+ .map(|_| {
+ let approvals = approvals.clone();
+ std::thread::spawn(move || approvals.confirm(&request(vec![])))
+ })
+ .collect();
+ let decisions: Vec<_> = threads.into_iter().map(|t| t.join().unwrap()).collect();
+ assert_eq!(prompt.most_at_once(), 1);
+ assert_eq!(prompt.shown_titles().len(), 4);
+ assert_eq!(decisions.iter().filter(|d| **d == Decision::Approved).count(), 3);
+}
+
+#[test]
+fn a_request_still_waiting_for_the_screen_at_its_deadline_is_declined_unseen() {
+ let prompt = Arc::new(FakePrompt::new([Answer::After(Duration::from_millis(300), true)]));
+ let first = Arc::new(approvals(&prompt, LONG));
+ let second = Approvals { prompt: first.prompt.clone(), timeout: Duration::from_millis(80), gate: first.gate.clone() };
+ let showing = {
+ let first = first.clone();
+ std::thread::spawn(move || first.confirm(&request(vec![])))
+ };
+ std::thread::sleep(Duration::from_millis(30));
+ assert_eq!(second.confirm(&request(vec![])), Decision::Declined);
+ assert_eq!(prompt.shown_titles().len(), 1, "the second dialog never showed");
+ assert_eq!(prompt.dismissals(), 0, "the first dialog was left alone");
+ assert_eq!(showing.join().unwrap(), Decision::Approved);
+}
+
+#[test]
+fn a_dialog_that_fails_declines() {
+ struct Broken;
+ impl Prompt for Broken {
+ fn ask(&self, _: &ApprovalDialog) -> bool {
+ panic!("no dialog");
+ }
+ fn dismiss(&self) {}
+ }
+ let approvals = Approvals::new(Arc::new(Broken), LONG);
+ assert_eq!(approvals.confirm(&request(vec![])), Decision::Declined);
+ // The screen is free again.
+ assert_eq!(approvals.confirm(&request(vec![])), Decision::Declined);
+}
+
+#[test]
+fn requests_read_the_daemon_json() {
+ let request: ApprovalRequest = serde_json::from_value(json!({
+ "connector": "Notion",
+ "action": "create pages",
+ "preview": [{"name": "title", "value": "Plan"}, {"name": "parent", "value": {"page_id": "1"}}]
+ }))
+ .unwrap();
+ assert_eq!(request.preview[1], field("parent", json!({"page_id": "1"})));
+}
diff --git a/apps/desktop/src-tauri/src/computer/app.rs b/apps/desktop/src-tauri/src/computer/app.rs
index 34fb486..7f036c7 100644
--- a/apps/desktop/src-tauri/src/computer/app.rs
+++ b/apps/desktop/src-tauri/src/computer/app.rs
@@ -12,6 +12,7 @@ use super::control::Control;
use super::server::Endpoint;
use super::session::{Reason, StateEvent};
use super::{Clock, PermissionKind, Permissions, SystemClock};
+use crate::alert::Choice;
use std::sync::Arc;
use tauri::{AppHandle, Emitter, Manager, State};
@@ -23,11 +24,12 @@ pub const GLOW_TITLE: &str = "Gentle Dot Glow";
/// ⌥⇧Esc ends the session from anywhere (S24.3).
pub const PANIC_SHORTCUT: &str = "Alt+Shift+Escape";
pub const GRANT_TEXT: &str = "Allow Gentle Dot to see and control this Mac for 30 minutes?";
-pub const GRANT_BUTTONS: (&str, &str) = ("Allow", "Deny");
-pub const CONFIRM_BUTTONS: (&str, &str) = ("Allow", "Cancel");
+/// Every computer-control dialog defaults to its refusing button (L75 A2).
+pub const GRANT_CHOICE: Choice = Choice { allow: "Allow", refuse: "Deny" };
+pub const CONFIRM_CHOICE: Choice = Choice { allow: "Allow", refuse: "Cancel" };
pub const YOLO_TEXT: &str = "Turn on yolo mode? Gentle Dot will send, pay, delete, and submit without asking you first, \
for up to 1 hour. Stop and ⌥⇧Esc still work.";
-pub const YOLO_BUTTONS: (&str, &str) = ("Turn On", "Cancel");
+pub const YOLO_CHOICE: Choice = Choice { allow: "Turn On", refuse: "Cancel" };
/// The tray's "Yolo mode" item, kept in step with the state.
pub struct YoloMenuItem(pub tauri::menu::CheckMenuItem<tauri::Wry>);
@@ -296,30 +298,23 @@ struct NativeDialogs {
#[cfg(target_os = "macos")]
impl NativeDialogs {
- fn ask(&self, message: &str, (allow, refuse): (&str, &str)) -> bool {
- use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
- self.app
- .dialog()
- .message(message)
- .title("Gentle Dot")
- .kind(MessageDialogKind::Warning)
- .buttons(MessageDialogButtons::OkCancelCustom(allow.into(), refuse.into()))
- .blocking_show()
+ fn ask(&self, message: &str, choice: Choice) -> bool {
+ crate::alert::ask(&self.app, "Gentle Dot", message, choice)
}
}
#[cfg(target_os = "macos")]
impl super::Dialogs for NativeDialogs {
fn ask_grant(&self) -> bool {
- self.ask(GRANT_TEXT, GRANT_BUTTONS)
+ self.ask(GRANT_TEXT, GRANT_CHOICE)
}
fn confirm(&self, message: &str) -> bool {
- self.ask(message, CONFIRM_BUTTONS)
+ self.ask(message, CONFIRM_CHOICE)
}
fn ask_yolo(&self) -> bool {
- self.ask(YOLO_TEXT, YOLO_BUTTONS)
+ self.ask(YOLO_TEXT, YOLO_CHOICE)
}
}
@@ -330,7 +325,7 @@ mod tests {
#[test]
fn the_grant_dialog_asks_exactly_what_the_spec_says() {
assert_eq!(GRANT_TEXT, "Allow Gentle Dot to see and control this Mac for 30 minutes?");
- assert_eq!(GRANT_BUTTONS, ("Allow", "Deny"));
+ assert_eq!(GRANT_CHOICE, Choice { allow: "Allow", refuse: "Deny" });
}
#[test]
@@ -340,7 +335,18 @@ mod tests {
"Turn on yolo mode? Gentle Dot will send, pay, delete, and submit without asking you first, \
for up to 1 hour. Stop and ⌥⇧Esc still work."
);
- assert_eq!(YOLO_BUTTONS, ("Turn On", "Cancel"));
+ assert_eq!(YOLO_CHOICE, Choice { allow: "Turn On", refuse: "Cancel" });
+ }
+
+ #[test]
+ fn every_computer_dialog_defaults_to_its_refusing_button() {
+ use tauri_plugin_dialog::MessageDialogButtons::OkCancelCustom;
+ for choice in [GRANT_CHOICE, CONFIRM_CHOICE, YOLO_CHOICE] {
+ match choice.buttons() {
+ OkCancelCustom(first, second) => assert_eq!((first.as_str(), second.as_str()), (choice.refuse, choice.allow)),
+ other => panic!("unexpected buttons: {other:?}"),
+ }
+ }
}
#[test]
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 1ad5481..b1c0f21 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1,3 +1,5 @@
+pub mod alert;
+pub mod approvals;
pub mod computer;
pub mod config;
pub mod daemon;
@@ -7,6 +9,7 @@ pub mod geometry;
pub mod health;
pub mod platform;
pub mod position;
+pub mod secure_store;
mod shell;
pub mod shortcut;
pub mod status;
diff --git a/apps/desktop/src-tauri/src/secure_store/linux.rs b/apps/desktop/src-tauri/src/secure_store/linux.rs
new file mode 100644
index 0000000..9840552
--- /dev/null
+++ b/apps/desktop/src-tauri/src/secure_store/linux.rs
@@ -0,0 +1,118 @@
+//! Connector secrets in the Secret Service (S25.7), over D-Bus: GNOME Keyring on Debian and
+//! Ubuntu, KWallet or GNOME Keyring elsewhere. Items carry the attributes `service` =
+//! [`SERVICE`](super::SERVICE) and `account` = the secret id.
+//!
+//! Documented limit (S25.7): the Secret Service has no per-caller access list, so any process of
+//! the same user can read items while the collection is unlocked (usually the whole session).
+//! Items are encrypted at rest. The session uses the plain transfer (the secret crosses the
+//! local session bus unencrypted), since every same-user process can read it anyway.
+//!
+//! Not compiled on the macOS development machine (no Linux target installed); T23g verifies it
+//! in a Linux container.
+
+use super::{check_id, wipe, Secret, SecretStore, StoreError, SERVICE};
+use dbus_secret_service::{EncryptionType, Error, Item, SecretService};
+use std::collections::HashMap;
+
+pub struct SecretServiceStore {
+ service: String,
+}
+
+impl SecretServiceStore {
+ pub fn new() -> Self {
+ Self::with_service(SERVICE)
+ }
+
+ pub fn with_service(service: impl Into<String>) -> Self {
+ SecretServiceStore { service: service.into() }
+ }
+
+ fn connect() -> Result<SecretService, StoreError> {
+ SecretService::connect(EncryptionType::Plain).map_err(store_error)
+ }
+
+ fn attributes<'a>(&'a self, id: &'a str) -> HashMap<&'a str, &'a str> {
+ HashMap::from([("service", self.service.as_str()), ("account", id)])
+ }
+}
+
+impl Default for SecretServiceStore {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl std::fmt::Debug for SecretServiceStore {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("SecretServiceStore").field("service", &self.service).finish()
+ }
+}
+
+fn store_error(error: Error) -> StoreError {
+ match error {
+ Error::Locked | Error::Prompt => StoreError::Denied,
+ Error::Unavailable => StoreError::Unavailable("no Secret Service on the session bus".into()),
+ other => StoreError::Failed(other.to_string()),
+ }
+}
+
+/// Every item matching the attributes, unlocked ones first.
+fn matching<'a>(ss: &'a SecretService, attributes: HashMap<&str, &str>) -> Result<Vec<Item<'a>>, StoreError> {
+ let found = ss.search_items(attributes).map_err(store_error)?;
+ Ok(found.unlocked.into_iter().chain(found.locked).collect())
+}
+
+impl SecretStore for SecretServiceStore {
+ fn put(&self, id: &str, secret: &Secret) -> Result<(), StoreError> {
+ check_id(id)?;
+ let ss = Self::connect()?;
+ let collection = ss.get_default_collection().map_err(store_error)?;
+ collection.ensure_unlocked().map_err(store_error)?;
+ let label = format!("Gentle Dot connector: {id}");
+ collection
+ .create_item(&label, self.attributes(id), secret.expose().as_bytes(), true, "text/plain")
+ .map_err(store_error)?;
+ Ok(())
+ }
+
+ fn get(&self, id: &str) -> Result<Option<Secret>, StoreError> {
+ check_id(id)?;
+ let ss = Self::connect()?;
+ let Some(item) = matching(&ss, self.attributes(id))?.into_iter().next() else {
+ return Ok(None);
+ };
+ item.ensure_unlocked().map_err(store_error)?;
+ let bytes = item.get_secret().map_err(store_error)?;
+ match String::from_utf8(bytes) {
+ Ok(text) => Ok(Some(Secret::new(text))),
+ Err(error) => {
+ wipe(&mut error.into_bytes());
+ Err(StoreError::NotText)
+ }
+ }
+ }
+
+ fn delete(&self, id: &str) -> Result<bool, StoreError> {
+ check_id(id)?;
+ let ss = Self::connect()?;
+ let items = matching(&ss, self.attributes(id))?;
+ for item in &items {
+ item.delete().map_err(store_error)?;
+ }
+ Ok(!items.is_empty())
+ }
+
+ fn list_ids(&self) -> Result<Vec<String>, StoreError> {
+ let ss = Self::connect()?;
+ let items = matching(&ss, HashMap::from([("service", self.service.as_str())]))?;
+ let mut ids = Vec::new();
+ for item in &items {
+ if let Some(id) = item.get_attributes().map_err(store_error)?.remove("account") {
+ ids.push(id);
+ }
+ }
+ ids.sort();
+ ids.dedup();
+ Ok(ids)
+ }
+}
diff --git a/apps/desktop/src-tauri/src/secure_store/macos.rs b/apps/desktop/src-tauri/src/secure_store/macos.rs
new file mode 100644
index 0000000..78d00bb
--- /dev/null
+++ b/apps/desktop/src-tauri/src/secure_store/macos.rs
@@ -0,0 +1,177 @@
+//! Connector secrets in the macOS login keychain (S25.5).
+//!
+//! Each secret is a generic password item: service [`SERVICE`](super::SERVICE), account = the
+//! secret id. Items live in the file-based login keychain (not the data protection keychain,
+//! which needs a keychain-access-groups entitlement and a provisioning profile). There, the
+//! item's access list trusts the application that created it, identified by its designated
+//! requirement; any other process that asks for the data (the agent's `security` CLI, a script)
+//! makes SecurityAgent ask the user, and computer control refuses to act on SecurityAgent
+//! (S24.4). Attributes (service, account) are readable without a prompt, so ids are not secrets.
+//!
+//! How the access list follows the signature (S29.2):
+//! - Stable self-signed identity ("Gentle Dot Local Signing", L85): the designated requirement
+//! is `identifier "dev.gentleman.gentle-dot" and certificate leaf = H"…"`, the same for every
+//! build signed with that certificate, so a new build reads the items without a prompt.
+//! - Ad-hoc builds (`tauri dev`, unsigned debug builds, `cargo test` binaries): the designated
+//! requirement is the code hash, so each rebuild is a different application. Reading an item
+//! created by an earlier build asks the user ("Allow", "Always Allow", "Deny"); "Always Allow"
+//! adds that build to the item's access list.
+//! - A signature change (a new certificate, a switch between ad-hoc and signed): the same
+//! prompt, once per item, asking for the login password; "Deny" reads as
+//! [`StoreError::Denied`], and the daemon fails closed. Deleting and storing the secret again
+//! from the new build makes it the owner.
+//!
+//! `put` deletes any existing item and adds a new one instead of updating in place, so the new
+//! 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.
+
+use super::{check_id, wipe, Secret, SecretStore, StoreError, SERVICE};
+use core_foundation::data::CFData;
+use security_framework::base::Error;
+use security_framework::item::{ItemAddOptions, ItemAddValue, ItemClass, ItemSearchOptions, Limit, Location};
+use security_framework::passwords::{delete_generic_password, generic_password, PasswordOptions};
+
+const NOT_FOUND: i32 = -25300; // errSecItemNotFound
+const DUPLICATE: i32 = -25299; // errSecDuplicateItem
+const AUTH_FAILED: i32 = -25293; // errSecAuthFailed
+const USER_CANCELED: i32 = -128; // errSecUserCanceled
+const NO_INTERACTION: i32 = -25308; // errSecInteractionNotAllowed
+
+/// The login keychain, under [`SERVICE`] (or another service, for tests).
+pub struct Keychain {
+ service: String,
+}
+
+impl Keychain {
+ pub fn new() -> Self {
+ Self::with_service(SERVICE)
+ }
+
+ pub fn with_service(service: impl Into<String>) -> Self {
+ Keychain { service: service.into() }
+ }
+}
+
+impl Default for Keychain {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl std::fmt::Debug for Keychain {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Keychain").field("service", &self.service).finish()
+ }
+}
+
+fn store_error(error: Error) -> StoreError {
+ match error.code() {
+ USER_CANCELED | AUTH_FAILED => StoreError::Denied,
+ NO_INTERACTION => StoreError::Unavailable("the keychain is locked and cannot ask".into()),
+ code => StoreError::Failed(format!("{error} ({code})")),
+ }
+}
+
+impl SecretStore for Keychain {
+ fn put(&self, id: &str, secret: &Secret) -> Result<(), StoreError> {
+ check_id(id)?;
+ self.delete(id)?;
+ let mut options = ItemAddOptions::new(ItemAddValue::Data {
+ class: ItemClass::generic_password(),
+ data: CFData::from_buffer(secret.expose().as_bytes()),
+ });
+ options
+ .set_service(&self.service)
+ .set_account_name(id)
+ .set_label(format!("Gentle Dot connector: {id}"))
+ .set_location(Location::DefaultFileKeychain);
+ options.add().map_err(|error| match error.code() {
+ DUPLICATE => StoreError::Failed("another item with this id appeared while storing it".into()),
+ _ => store_error(error),
+ })
+ }
+
+ fn get(&self, id: &str) -> Result<Option<Secret>, StoreError> {
+ check_id(id)?;
+ match generic_password(PasswordOptions::new_generic_password(&self.service, id)) {
+ Ok(bytes) => match String::from_utf8(bytes) {
+ Ok(text) => Ok(Some(Secret::new(text))),
+ Err(error) => {
+ wipe(&mut error.into_bytes());
+ Err(StoreError::NotText)
+ }
+ },
+ Err(error) if error.code() == NOT_FOUND => Ok(None),
+ Err(error) => Err(store_error(error)),
+ }
+ }
+
+ fn delete(&self, id: &str) -> Result<bool, StoreError> {
+ check_id(id)?;
+ match delete_generic_password(&self.service, id) {
+ Ok(()) => Ok(true),
+ Err(error) if error.code() == NOT_FOUND => Ok(false),
+ Err(error) => Err(store_error(error)),
+ }
+ }
+
+ fn list_ids(&self) -> Result<Vec<String>, StoreError> {
+ let found = ItemSearchOptions::new()
+ .class(ItemClass::generic_password())
+ .service(&self.service)
+ .load_attributes(true)
+ .limit(Limit::All)
+ .search();
+ let results = match found {
+ Ok(results) => results,
+ Err(error) if error.code() == NOT_FOUND => return Ok(Vec::new()),
+ Err(error) => return Err(store_error(error)),
+ };
+ let mut ids: Vec<String> = results
+ .iter()
+ .filter_map(|result| result.simplify_dict()?.remove("acct"))
+ .collect();
+ ids.sort();
+ ids.dedup();
+ Ok(ids)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_keychain_shows_its_service_only() {
+ assert_eq!(format!("{:?}", Keychain::new()), "Keychain { service: \"dev.gentleman.gentle-dot.connectors\" }");
+ }
+
+ #[test]
+ fn keychain_errors_map_to_denied_or_unavailable() {
+ assert_eq!(store_error(Error::from_code(USER_CANCELED)), StoreError::Denied);
+ assert_eq!(store_error(Error::from_code(AUTH_FAILED)), StoreError::Denied);
+ assert!(matches!(store_error(Error::from_code(NO_INTERACTION)), StoreError::Unavailable(_)));
+ assert!(matches!(store_error(Error::from_code(-50)), StoreError::Failed(_)));
+ }
+
+ /// Touches the real login keychain under a throwaway service and removes what it created.
+ /// Run by hand: `cargo test real_keychain -- --ignored`.
+ #[test]
+ #[ignore = "uses the real login keychain"]
+ fn real_keychain_keeps_the_contract_under_a_throwaway_service() {
+ let mut random = [0u8; 8];
+ getrandom::fill(&mut random).unwrap();
+ let suffix: String = random.iter().map(|b| format!("{b:02x}")).collect();
+ let store = Keychain::with_service(format!("dev.gentleman.gentle-dot.test.{suffix}"));
+ let outcome = std::panic::catch_unwind(|| super::super::check_contract(&store));
+ // Leave nothing behind, whatever happened.
+ for id in store.list_ids().unwrap_or_default() {
+ let _ = store.delete(&id);
+ }
+ assert!(store.list_ids().unwrap().is_empty());
+ if let Err(panic) = outcome {
+ std::panic::resume_unwind(panic);
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/secure_store/memory.rs b/apps/desktop/src-tauri/src/secure_store/memory.rs
new file mode 100644
index 0000000..3cd76a8
--- /dev/null
+++ b/apps/desktop/src-tauri/src/secure_store/memory.rs
@@ -0,0 +1,71 @@
+//! An in-memory [`SecretStore`] for tests (and for callers' tests in T23c).
+
+use super::{check_id, Secret, SecretStore, StoreError};
+use std::collections::BTreeMap;
+use std::sync::Mutex;
+
+#[derive(Default)]
+pub struct MemoryStore {
+ secrets: Mutex<BTreeMap<String, Secret>>,
+}
+
+impl MemoryStore {
+ pub fn new() -> Self {
+ Self::default()
+ }
+}
+
+/// Shows the ids only.
+impl std::fmt::Debug for MemoryStore {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let secrets = self.secrets.lock().unwrap_or_else(|e| e.into_inner());
+ f.debug_struct("MemoryStore").field("ids", &secrets.keys().collect::<Vec<_>>()).finish()
+ }
+}
+
+impl MemoryStore {
+ fn secrets(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, Secret>> {
+ self.secrets.lock().unwrap_or_else(|e| e.into_inner())
+ }
+}
+
+impl SecretStore for MemoryStore {
+ fn put(&self, id: &str, secret: &Secret) -> Result<(), StoreError> {
+ check_id(id)?;
+ self.secrets().insert(id.to_owned(), Secret::new(secret.expose()));
+ Ok(())
+ }
+
+ fn get(&self, id: &str) -> Result<Option<Secret>, StoreError> {
+ check_id(id)?;
+ Ok(self.secrets().get(id).map(|secret| Secret::new(secret.expose())))
+ }
+
+ fn delete(&self, id: &str) -> Result<bool, StoreError> {
+ check_id(id)?;
+ Ok(self.secrets().remove(id).is_some())
+ }
+
+ fn list_ids(&self) -> Result<Vec<String>, StoreError> {
+ Ok(self.secrets().keys().cloned().collect())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_memory_store_keeps_the_contract() {
+ super::super::check_contract(&MemoryStore::new());
+ }
+
+ #[test]
+ fn the_memory_store_shows_ids_but_not_secrets() {
+ let store = MemoryStore::new();
+ store.put("slack/bot", &Secret::new("xoxb-secret-value")).unwrap();
+ let shown = format!("{store:?}");
+ assert!(shown.contains("slack/bot"), "{shown}");
+ assert!(!shown.contains("xoxb"), "{shown}");
+ }
+}
diff --git a/apps/desktop/src-tauri/src/secure_store/mod.rs b/apps/desktop/src-tauri/src/secure_store/mod.rs
new file mode 100644
index 0000000..b19bc0b
--- /dev/null
+++ b/apps/desktop/src-tauri/src/secure_store/mod.rs
@@ -0,0 +1,186 @@
+//! 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.
+//!
+//! - 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
+//! the items' access list follows the app's code signature.
+//! - Linux (`SecretServiceStore`): the Secret Service over D-Bus (GNOME Keyring, KWallet).
+//! Items are encrypted at rest, but any same-user process can read unlocked items (S25.7).
+//! - `MemoryStore`: an in-memory store for tests.
+//!
+//! Secrets are never logged: [`Secret`] and every store redact themselves in `Debug`, have no
+//! `Display`, and errors never carry a secret.
+
+mod memory;
+#[cfg(target_os = "linux")]
+mod linux;
+#[cfg(target_os = "macos")]
+mod macos;
+
+pub use memory::MemoryStore;
+#[cfg(target_os = "linux")]
+pub use linux::SecretServiceStore;
+#[cfg(target_os = "macos")]
+pub use macos::Keychain;
+
+/// The keychain service (macOS) or `service` attribute (Linux) of every connector secret.
+pub const SERVICE: &str = "dev.gentleman.gentle-dot.connectors";
+/// The longest secret id, in bytes.
+pub const MAX_ID_LEN: usize = 200;
+
+/// A secret value. Redacted in `Debug`, no `Display`, and its bytes are overwritten on drop
+/// (best effort: copies made by the OS or by callers are out of reach).
+pub struct Secret(String);
+
+impl Secret {
+ pub fn new(value: impl Into<String>) -> Self {
+ Secret(value.into())
+ }
+
+ /// The value, for handing it to the daemon. Never log it.
+ pub fn expose(&self) -> &str {
+ &self.0
+ }
+}
+
+impl std::fmt::Debug for Secret {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("Secret(<redacted>)")
+ }
+}
+
+impl Drop for Secret {
+ fn drop(&mut self) {
+ wipe(&mut std::mem::take(&mut self.0).into_bytes());
+ }
+}
+
+/// Overwrites a buffer with zeros in a way the compiler does not drop as a dead store.
+pub(crate) fn wipe(bytes: &mut [u8]) {
+ for byte in bytes.iter_mut() {
+ // SAFETY: `byte` is a valid, aligned, exclusive reference.
+ unsafe { std::ptr::write_volatile(byte, 0) };
+ }
+ std::sync::atomic::compiler_fence(std::sync::atomic::Ordering::SeqCst);
+}
+
+/// Why a store call failed. Never holds a secret.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum StoreError {
+ /// The id is empty, too long, or has characters outside `[A-Za-z0-9._:@/-]`.
+ InvalidId,
+ /// The stored value is not UTF-8 text.
+ NotText,
+ /// The user or the system refused access (a declined keychain prompt, a locked item).
+ Denied,
+ /// The store cannot be reached (no Secret Service, a locked keychain that cannot ask).
+ Unavailable(String),
+ /// Anything else, with the store's own message.
+ Failed(String),
+}
+
+impl std::fmt::Display for StoreError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ StoreError::InvalidId => write!(f, "invalid secret id"),
+ StoreError::NotText => write!(f, "the stored secret is not text"),
+ StoreError::Denied => write!(f, "access to the secret store was denied"),
+ StoreError::Unavailable(why) => write!(f, "the secret store is unavailable: {why}"),
+ StoreError::Failed(why) => write!(f, "the secret store failed: {why}"),
+ }
+ }
+}
+
+impl std::error::Error for StoreError {}
+
+/// Where connector secrets live.
+pub trait SecretStore: Send + Sync {
+ /// Stores the secret under `id`, replacing any previous one.
+ fn put(&self, id: &str, secret: &Secret) -> Result<(), StoreError>;
+ /// The secret under `id`, or `None` when there is none.
+ fn get(&self, id: &str) -> Result<Option<Secret>, StoreError>;
+ /// Removes the secret under `id`; true when one was there.
+ fn delete(&self, id: &str) -> Result<bool, StoreError>;
+ /// Every id in this store, sorted, without duplicates.
+ fn list_ids(&self) -> Result<Vec<String>, StoreError>;
+}
+
+/// 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);
+ if id.is_empty() || id.len() > MAX_ID_LEN || !id.chars().all(allowed) {
+ return Err(StoreError::InvalidId);
+ }
+ Ok(())
+}
+
+/// The contract every store keeps, run against `MemoryStore` here and against a throwaway
+/// keychain service in the ignored macOS test.
+#[cfg(test)]
+pub(crate) fn check_contract(store: &dyn SecretStore) {
+ assert!(store.get("contract/missing").unwrap().is_none());
+ assert!(!store.delete("contract/missing").unwrap());
+
+ store.put("contract/b", &Secret::new("first")).unwrap();
+ store.put("contract/a", &Secret::new("xoxb-123")).unwrap();
+ assert_eq!(store.get("contract/a").unwrap().unwrap().expose(), "xoxb-123");
+ store.put("contract/a", &Secret::new("replaced ✓")).unwrap();
+ assert_eq!(store.get("contract/a").unwrap().unwrap().expose(), "replaced ✓");
+ store.put("contract/empty", &Secret::new("")).unwrap();
+ assert_eq!(store.get("contract/empty").unwrap().unwrap().expose(), "");
+
+ let ids = store.list_ids().unwrap();
+ assert_eq!(ids, vec!["contract/a", "contract/b", "contract/empty"]);
+
+ assert!(store.delete("contract/a").unwrap());
+ assert!(!store.delete("contract/a").unwrap());
+ assert!(store.get("contract/a").unwrap().is_none());
+ assert!(store.delete("contract/b").unwrap());
+ assert!(store.delete("contract/empty").unwrap());
+ assert!(store.list_ids().unwrap().is_empty());
+
+ for bad in ["", "has space", "new\nline", "tab\t", "ünicode", &"x".repeat(MAX_ID_LEN + 1)] {
+ assert_eq!(store.put(bad, &Secret::new("s")).unwrap_err(), StoreError::InvalidId, "{bad:?}");
+ assert_eq!(store.get(bad).unwrap_err(), StoreError::InvalidId, "{bad:?}");
+ assert_eq!(store.delete(bad).unwrap_err(), StoreError::InvalidId, "{bad:?}");
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn ids_allow_a_small_safe_alphabet() {
+ for good in ["notion", "slack/bot-token", "gmail:client_secret", "a.b@c", &"x".repeat(MAX_ID_LEN)] {
+ assert_eq!(check_id(good), Ok(()), "{good:?}");
+ }
+ for bad in ["", " ", "a b", "a\u{0}b", "a\nb", "ñ", "a\u{202e}b", &"x".repeat(MAX_ID_LEN + 1)] {
+ assert_eq!(check_id(bad), Err(StoreError::InvalidId), "{bad:?}");
+ }
+ }
+
+ #[test]
+ fn a_secret_never_shows_in_debug() {
+ let secret = Secret::new("hunter2-very-secret");
+ let shown = format!("{secret:?} {secret:#?}");
+ assert!(!shown.contains("hunter2"), "{shown}");
+ assert!(shown.contains("redacted"), "{shown}");
+ let some = Some(Secret::new("hunter2"));
+ assert!(!format!("{some:?}").contains("hunter2"));
+ }
+
+ #[test]
+ fn errors_say_what_failed_without_a_secret() {
+ assert_eq!(StoreError::Denied.to_string(), "access to the secret store was denied");
+ assert_eq!(StoreError::InvalidId.to_string(), "invalid secret id");
+ }
+
+ #[test]
+ fn wipe_zeroes_the_buffer() {
+ let mut bytes = b"token".to_vec();
+ wipe(&mut bytes);
+ assert_eq!(bytes, vec![0; 5]);
+ }
+}