agent-relay 0.3.2

Agent-to-agent messaging for AI coding tools. Local or networked — run a relay server and let Claude talk to Gemini across the internet.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Git-integrated identity, SSH signing, and collaborator verification.
//!
//! Links agent-relay authentication to Git's own infrastructure:
//! - Identity from `git config user.name` + `user.email`
//! - Message signing with SSH keys (same key used for `git push`)
//! - Collaborator verification via GitHub API (`gh` CLI)

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::Command;

// ── Git Identity ──

#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct GitIdentity {
    pub name: String,
    pub email: String,
    pub signing_key: Option<String>,
}

impl GitIdentity {
    /// Auto-detect identity from the current git config.
    pub fn from_git_config() -> Result<Self, String> {
        let name = git_config("user.name")?;
        let email = git_config("user.email")?;
        let signing_key = git_config("user.signingkey").ok();
        Ok(Self {
            name,
            email,
            signing_key,
        })
    }

    /// Fingerprint for this identity (used as a stable session seed).
    pub fn fingerprint(&self) -> String {
        format!("{}:{}", self.name, self.email)
    }
}

fn git_config(key: &str) -> Result<String, String> {
    let output = Command::new("git")
        .args(["config", "--get", key])
        .output()
        .map_err(|e| format!("Failed to run git config: {}", e))?;

    if !output.status.success() {
        return Err(format!("git config {} not set", key));
    }

    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}

// ── SSH Signing ──

/// Sign a message body using the user's SSH key.
/// Uses `ssh-keygen -Y sign` which is the same mechanism as `git commit -S`.
pub fn ssh_sign(content: &str, key_path: &Path) -> Result<String, String> {
    let tmp_data = std::env::temp_dir().join(format!("agent-relay-sign-{}", uuid::Uuid::new_v4()));
    std::fs::write(&tmp_data, content).map_err(|e| format!("Failed to write temp file: {}", e))?;

    let output = Command::new("ssh-keygen")
        .args([
            "-Y",
            "sign",
            "-f",
            &key_path.to_string_lossy(),
            "-n",
            "agent-relay",
        ])
        .arg(&tmp_data)
        .output()
        .map_err(|e| format!("ssh-keygen sign failed: {}", e))?;

    let sig_path = PathBuf::from(format!("{}.sig", tmp_data.display()));
    let signature = if sig_path.exists() {
        std::fs::read_to_string(&sig_path)
            .map_err(|e| format!("Failed to read signature: {}", e))?
    } else if output.status.success() {
        String::from_utf8_lossy(&output.stdout).to_string()
    } else {
        let _ = std::fs::remove_file(&tmp_data);
        return Err(format!(
            "ssh-keygen sign failed: {}",
            String::from_utf8_lossy(&output.stderr)
        ));
    };

    let _ = std::fs::remove_file(&tmp_data);
    let _ = std::fs::remove_file(&sig_path);

    Ok(signature.trim().to_string())
}

/// Verify an SSH signature against the message content.
/// Requires an `allowed_signers` file listing trusted public keys.
pub fn ssh_verify(
    content: &str,
    signature: &str,
    identity: &str,
    allowed_signers_path: &Path,
) -> Result<bool, String> {
    let tmp_data =
        std::env::temp_dir().join(format!("agent-relay-verify-data-{}", uuid::Uuid::new_v4()));
    let tmp_sig =
        std::env::temp_dir().join(format!("agent-relay-verify-sig-{}", uuid::Uuid::new_v4()));

    std::fs::write(&tmp_data, content).map_err(|e| format!("Failed to write temp data: {}", e))?;
    std::fs::write(&tmp_sig, signature).map_err(|e| format!("Failed to write temp sig: {}", e))?;

    let output = Command::new("ssh-keygen")
        .args([
            "-Y",
            "verify",
            "-f",
            &allowed_signers_path.to_string_lossy(),
            "-I",
            identity,
            "-n",
            "agent-relay",
            "-s",
        ])
        .arg(&tmp_sig)
        .stdin(std::process::Stdio::from(
            std::fs::File::open(&tmp_data)
                .map_err(|e| format!("Failed to open temp data: {}", e))?,
        ))
        .output()
        .map_err(|e| format!("ssh-keygen verify failed: {}", e))?;

    let _ = std::fs::remove_file(&tmp_data);
    let _ = std::fs::remove_file(&tmp_sig);

    Ok(output.status.success())
}

// ── SSH Key Discovery ──

/// Find the user's SSH private key.
/// Checks: git config user.signingkey, then common paths.
pub fn find_ssh_key() -> Option<PathBuf> {
    // 1. Check git config
    if let Ok(key) = git_config("user.signingkey") {
        let path = if key.starts_with("key::") {
            // Literal key, not a path
            return None;
        } else if key.starts_with('~') {
            expand_tilde(&key)
        } else {
            PathBuf::from(&key)
        };
        if path.exists() {
            return Some(path);
        }
    }

    // 2. Check common paths
    let home = dirs();
    for name in &["id_ed25519", "id_ecdsa", "id_rsa"] {
        let path = home.join(name);
        if path.exists() {
            return Some(path);
        }
    }

    None
}

/// Generate an `allowed_signers` file from the collaborators' public keys.
/// Each line: `email namespace public-key`
pub fn write_allowed_signers(
    output_path: &Path,
    entries: &[(String, String)], // (email, public_key_content)
) -> Result<(), String> {
    let mut lines = Vec::new();
    for (email, pubkey) in entries {
        let key = pubkey.trim();
        lines.push(format!("{} agent-relay {}", email, key));
    }
    std::fs::write(output_path, lines.join("\n"))
        .map_err(|e| format!("Failed to write allowed_signers: {}", e))?;
    Ok(())
}

fn dirs() -> PathBuf {
    if let Ok(home) = std::env::var("HOME") {
        PathBuf::from(home).join(".ssh")
    } else {
        PathBuf::from(".ssh")
    }
}

fn expand_tilde(path: &str) -> PathBuf {
    if let Some(rest) = path.strip_prefix("~/") {
        if let Ok(home) = std::env::var("HOME") {
            return PathBuf::from(home).join(rest);
        }
    }
    PathBuf::from(path)
}

// ── GitHub Collaborator Discovery ──

/// Fetch collaborators from a GitHub repo using the `gh` CLI.
/// Returns list of (username, email) pairs.
pub fn github_collaborators(owner: &str, repo: &str) -> Result<Vec<Collaborator>, String> {
    let output = Command::new("gh")
        .args([
            "api",
            &format!("repos/{}/{}/collaborators", owner, repo),
            "--jq",
            ".[] | {login: .login, permissions: .permissions}",
        ])
        .output()
        .map_err(|e| format!("gh api failed: {}", e))?;

    if !output.status.success() {
        return Err(format!(
            "Failed to fetch collaborators: {}",
            String::from_utf8_lossy(&output.stderr)
        ));
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut collabs = Vec::new();

    for line in stdout.lines() {
        if let Ok(val) = serde_json::from_str::<serde_json::Value>(line) {
            if let Some(login) = val["login"].as_str() {
                collabs.push(Collaborator {
                    username: login.to_string(),
                    can_push: val["permissions"]["push"].as_bool().unwrap_or(false),
                });
            }
        }
    }

    Ok(collabs)
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Collaborator {
    pub username: String,
    pub can_push: bool,
}

/// Extract owner/repo from a git remote URL.
/// Handles: `git@github.com:owner/repo.git`, `https://github.com/owner/repo.git`
pub fn parse_github_remote() -> Option<(String, String)> {
    let output = Command::new("git")
        .args(["remote", "get-url", "origin"])
        .output()
        .ok()?;

    if !output.status.success() {
        return None;
    }

    let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    parse_github_url(&url)
}

fn parse_github_url(url: &str) -> Option<(String, String)> {
    // SSH: git@github.com:owner/repo.git
    if let Some(rest) = url.strip_prefix("git@github.com:") {
        let rest = rest.trim_end_matches(".git");
        let parts: Vec<&str> = rest.splitn(2, '/').collect();
        if parts.len() == 2 {
            return Some((parts[0].to_string(), parts[1].to_string()));
        }
    }

    // HTTPS: https://github.com/owner/repo.git
    if url.contains("github.com/") {
        let after = url.split("github.com/").nth(1)?;
        let after = after.trim_end_matches(".git");
        let parts: Vec<&str> = after.splitn(2, '/').collect();
        if parts.len() == 2 {
            return Some((parts[0].to_string(), parts[1].to_string()));
        }
    }

    None
}

// ── Secure Relay ──

use crate::{Message, Relay};

/// A relay with Git identity + SSH signing.
///
/// Messages are signed on send and can be verified on read.
/// Identity comes from `git config`.
pub struct SecureRelay {
    pub relay: Relay,
    pub identity: GitIdentity,
    pub ssh_key: Option<PathBuf>,
    pub allowed_signers: Option<PathBuf>,
}

/// A message with an attached SSH signature.
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct SignedMessage {
    pub message: Message,
    pub git_identity: GitIdentity,
    pub signature: Option<String>,
    pub verified: Option<bool>,
}

impl SecureRelay {
    /// Create from the current git repo. Auto-detects identity and SSH key.
    pub fn from_git_repo(relay_dir: PathBuf) -> Result<Self, String> {
        let identity = GitIdentity::from_git_config()?;
        let ssh_key = find_ssh_key();
        let allowed_signers_path = relay_dir.join("allowed_signers");
        let allowed_signers = if allowed_signers_path.exists() {
            Some(allowed_signers_path)
        } else {
            None
        };

        let relay = Relay::new(relay_dir);
        // Ensure base directories exist for allowed_signers writes
        let _ = std::fs::create_dir_all(&relay.base_dir);

        Ok(Self {
            relay,
            identity,
            ssh_key,
            allowed_signers,
        })
    }

    /// Send a signed message. The content is signed with the user's SSH key.
    pub fn send_signed(
        &self,
        session_id: &str,
        to_session: Option<&str>,
        content: &str,
    ) -> Result<SignedMessage, String> {
        let msg = self
            .relay
            .send(session_id, &self.identity.name, to_session, content);

        let signature = if let Some(ref key) = self.ssh_key {
            match ssh_sign(content, key) {
                Ok(sig) => Some(sig),
                Err(e) => {
                    eprintln!("Warning: could not sign message: {}", e);
                    None
                }
            }
        } else {
            None
        };

        let signed = SignedMessage {
            message: msg.clone(),
            git_identity: self.identity.clone(),
            signature,
            verified: None,
        };

        // Write the signed envelope alongside the message
        let sig_path = self
            .relay
            .base_dir
            .join("signatures")
            .join(format!("{}.json", msg.id));
        let _ = std::fs::create_dir_all(sig_path.parent().unwrap());
        if let Ok(json) = serde_json::to_string_pretty(&signed) {
            let _ = std::fs::write(&sig_path, json);
        }

        Ok(signed)
    }

    /// Read inbox with signature verification.
    pub fn inbox_verified(&self, session_id: &str, limit: usize) -> Vec<SignedMessage> {
        let msgs = self.relay.inbox(session_id, limit);
        let sig_dir = self.relay.base_dir.join("signatures");

        msgs.into_iter()
            .map(|(msg, _is_new)| {
                let sig_path = sig_dir.join(format!("{}.json", msg.id));
                if let Ok(content) = std::fs::read_to_string(&sig_path) {
                    if let Ok(mut signed) = serde_json::from_str::<SignedMessage>(&content) {
                        // Verify if we have allowed_signers and a signature
                        if let (Some(ref sig), Some(ref allowed)) =
                            (&signed.signature, &self.allowed_signers)
                        {
                            signed.verified = Some(
                                ssh_verify(&msg.content, sig, &signed.git_identity.email, allowed)
                                    .unwrap_or(false),
                            );
                        }
                        signed.message = msg;
                        return signed;
                    }
                }
                // No signature found — unsigned message
                SignedMessage {
                    message: msg,
                    git_identity: GitIdentity {
                        name: "unknown".to_string(),
                        email: "unknown".to_string(),
                        signing_key: None,
                    },
                    signature: None,
                    verified: None,
                }
            })
            .collect()
    }

    /// Check if a user is a collaborator on the current GitHub repo.
    pub fn verify_collaborator(&self, username: &str) -> Result<bool, String> {
        let (owner, repo) = parse_github_remote()
            .ok_or_else(|| "Not a GitHub repo or no origin remote".to_string())?;
        let collabs = github_collaborators(&owner, &repo)?;
        Ok(collabs.iter().any(|c| c.username == username && c.can_push))
    }

    /// Initialize the allowed_signers file from GitHub collaborators' SSH keys.
    pub fn init_allowed_signers(&self) -> Result<usize, String> {
        let (owner, repo) = parse_github_remote()
            .ok_or_else(|| "Not a GitHub repo or no origin remote".to_string())?;

        // Fetch each collaborator's SSH keys from GitHub
        let collabs = github_collaborators(&owner, &repo)?;
        let mut entries = Vec::new();

        for collab in &collabs {
            if !collab.can_push {
                continue;
            }
            // Fetch SSH keys via gh api
            let output = Command::new("gh")
                .args([
                    "api",
                    &format!("users/{}/keys", collab.username),
                    "--jq",
                    ".[].key",
                ])
                .output();

            if let Ok(out) = output {
                if out.status.success() {
                    let keys = String::from_utf8_lossy(&out.stdout);
                    for key in keys.lines() {
                        if !key.is_empty() {
                            entries.push((format!("{}@github", collab.username), key.to_string()));
                        }
                    }
                }
            }
        }

        let count = entries.len();
        let path = self.relay.base_dir.join("allowed_signers");
        write_allowed_signers(&path, &entries)?;
        Ok(count)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_github_url_ssh() {
        let result = parse_github_url("git@github.com:Naridon-Inc/agent-relay.git");
        assert_eq!(result, Some(("Naridon-Inc".into(), "agent-relay".into())));
    }

    #[test]
    fn test_parse_github_url_https() {
        let result = parse_github_url("https://github.com/Naridon-Inc/agent-relay.git");
        assert_eq!(result, Some(("Naridon-Inc".into(), "agent-relay".into())));
    }

    #[test]
    fn test_parse_github_url_no_git_suffix() {
        let result = parse_github_url("https://github.com/owner/repo");
        assert_eq!(result, Some(("owner".into(), "repo".into())));
    }

    #[test]
    fn test_parse_github_url_invalid() {
        let result = parse_github_url("https://gitlab.com/owner/repo");
        assert_eq!(result, None);
    }
}