kap 0.0.1-pre14

Run AI agents in secure capsules. Built on devcontainers with network controls and remote access.
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
use anyhow::Result;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};

/// Default directory for remote access data.
pub fn data_dir() -> PathBuf {
    dirs_home().join(".kap").join("remote")
}

fn dirs_home() -> PathBuf {
    std::env::var("HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| PathBuf::from("/tmp"))
}

/// A paired device record.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PairedDevice {
    pub id: String,
    pub name: String,
    pub token_hash: String,
    pub paired_at: String,
    pub last_seen: String,
}

/// Load or generate the pairing token.
pub fn load_or_generate_pairing_token(dir: &Path) -> Result<String> {
    std::fs::create_dir_all(dir)?;
    let token_path = dir.join("token");

    if token_path.exists() {
        let token = std::fs::read_to_string(&token_path)?.trim().to_string();
        if !token.is_empty() {
            return Ok(token);
        }
    }

    let token = generate_token();
    std::fs::write(&token_path, &token)?;

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&token_path, std::fs::Permissions::from_mode(0o600))?;
    }

    Ok(token)
}

/// Generate a random token as base64url (22 chars / 128 bits).
fn generate_token() -> String {
    use rand::RngCore;
    let mut bytes = [0u8; 16];
    rand::thread_rng().fill_bytes(&mut bytes);
    base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, bytes)
}

/// Rotate the pairing token (called after successful pairing).
pub fn rotate_pairing_token(dir: &Path) -> Result<String> {
    let token = generate_token();
    let token_path = dir.join("token");
    std::fs::write(&token_path, &token)?;
    Ok(token)
}

/// Hash a token for storage (we never store plaintext session tokens).
pub fn hash_token(token: &str) -> String {
    let hash = Sha256::digest(token.as_bytes());
    format!("sha256:{}", hex::encode(hash))
}

/// Load paired devices from devices.json.
pub fn load_devices(dir: &Path) -> Vec<PairedDevice> {
    let path = dir.join("devices.json");
    std::fs::read_to_string(&path)
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or_default()
}

/// Save paired devices to devices.json.
pub fn save_devices(dir: &Path, devices: &[PairedDevice]) -> Result<()> {
    let path = dir.join("devices.json");
    let json = serde_json::to_string_pretty(devices)?;
    std::fs::write(&path, json)?;
    Ok(())
}

/// Validate a bearer token against the pairing token or any paired device.
/// Returns Some(device_id) if valid session token, or Some("pairing") if pairing token.
pub fn validate_token(dir: &Path, token: &str) -> Option<String> {
    // Check pairing token
    let pairing_token = std::fs::read_to_string(dir.join("token"))
        .ok()
        .map(|s| s.trim().to_string())
        .unwrap_or_default();
    if !pairing_token.is_empty() && constant_time_eq(token, &pairing_token) {
        return Some("pairing".to_string());
    }

    // Check session tokens
    let token_hash = hash_token(token);
    let devices = load_devices(dir);
    for device in &devices {
        if device.token_hash == token_hash {
            return Some(device.id.clone());
        }
    }

    None
}

/// Pair a new device: consume the pairing token, issue a session token, rotate.
pub fn pair_device(dir: &Path, device_name: &str) -> Result<String> {
    let session_token = generate_token();
    let now = chrono::Utc::now().to_rfc3339();

    let device = PairedDevice {
        id: generate_short_id(),
        name: device_name.to_string(),
        token_hash: hash_token(&session_token),
        paired_at: now.clone(),
        last_seen: now,
    };

    let mut devices = load_devices(dir);
    devices.push(device);
    save_devices(dir, &devices)?;

    // Rotate pairing token so it can't be reused
    rotate_pairing_token(dir)?;

    Ok(session_token)
}

/// Remove a paired device by ID.
pub fn revoke_device(dir: &Path, device_id: &str) -> Result<bool> {
    let mut devices = load_devices(dir);
    let before = devices.len();
    devices.retain(|d| d.id != device_id);
    let removed = devices.len() < before;
    save_devices(dir, &devices)?;
    Ok(removed)
}

fn generate_short_id() -> String {
    use rand::RngCore;
    let mut bytes = [0u8; 6];
    rand::thread_rng().fill_bytes(&mut bytes);
    hex::encode(bytes)
}

/// Constant-time string comparison.
fn constant_time_eq(a: &str, b: &str) -> bool {
    if a.len() != b.len() {
        return false;
    }
    a.bytes()
        .zip(b.bytes())
        .fold(0u8, |acc, (x, y)| acc | (x ^ y))
        == 0
}

/// Detect the local LAN IP address reachable by devices on the same WiFi.
/// Prefers broadcast-capable interfaces (en0, etc.) over VPN tunnels (utun*),
/// which have point-to-point addresses only routable through the VPN.
pub fn local_ip() -> Option<String> {
    // First try: enumerate interfaces and pick a private, non-loopback,
    // broadcast-capable (i.e. not point-to-point) IPv4 address.
    if let Some(ip) = lan_ip_from_interfaces() {
        return Some(ip);
    }
    // Fallback: UDP connect trick (may pick VPN address if VPN is active).
    let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
    socket.connect("8.8.8.8:80").ok()?;
    let addr = socket.local_addr().ok()?;
    let ip = addr.ip();
    if ip.is_loopback() || ip.is_unspecified() {
        return None;
    }
    Some(ip.to_string())
}

/// Enumerate network interfaces via getifaddrs, return the first private IPv4
/// address on a non-loopback, non-point-to-point (broadcast-capable) interface.
fn lan_ip_from_interfaces() -> Option<String> {
    use std::net::Ipv4Addr;

    unsafe {
        let mut ifaddrs: *mut libc::ifaddrs = std::ptr::null_mut();
        if libc::getifaddrs(&mut ifaddrs) != 0 {
            return None;
        }

        let mut result = None;
        let mut cur = ifaddrs;
        while !cur.is_null() {
            let ifa = &*cur;
            cur = ifa.ifa_next;

            // Skip if no address
            if ifa.ifa_addr.is_null() {
                continue;
            }

            // IPv4 only
            if (*ifa.ifa_addr).sa_family as i32 != libc::AF_INET {
                continue;
            }

            let flags = ifa.ifa_flags as i32;

            // Skip loopback and down interfaces
            if flags & libc::IFF_LOOPBACK != 0 || flags & libc::IFF_UP == 0 {
                continue;
            }

            // Skip point-to-point (VPN tunnels like utun*)
            if flags & libc::IFF_POINTOPOINT != 0 {
                continue;
            }

            let sockaddr = ifa.ifa_addr as *const libc::sockaddr_in;
            let ip_bytes = (*sockaddr).sin_addr.s_addr.to_ne_bytes();
            let ip = Ipv4Addr::new(ip_bytes[0], ip_bytes[1], ip_bytes[2], ip_bytes[3]);

            // Only private addresses
            if ip.is_private() && !ip.is_loopback() {
                result = Some(ip.to_string());
                break;
            }
        }

        libc::freeifaddrs(ifaddrs);
        result
    }
}

/// Render a QR code to the terminal.
pub fn print_qr(data: &str) {
    use qrcode::QrCode;

    let code = match QrCode::new(data) {
        Ok(c) => c,
        Err(e) => {
            eprintln!("[remote] failed to generate QR code: {e}");
            eprintln!("[remote] pairing URL: {data}");
            return;
        }
    };

    // Render using Unicode half-blocks for compact output.
    // Each character encodes two vertical modules: top and bottom.
    let colors = code.to_colors();
    let width = code.width();
    let modules: Vec<bool> = colors.iter().map(|c| *c == qrcode::Color::Dark).collect();

    // Add 1-module quiet zone
    let total_w = width + 2;
    let total_h = width + 2;

    let get = |r: usize, c: usize| -> bool {
        if r == 0 || r == total_h - 1 || c == 0 || c == total_w - 1 {
            false // quiet zone
        } else {
            modules[(r - 1) * width + (c - 1)]
        }
    };

    println!();
    // Process two rows at a time using half-block characters
    let mut row = 0;
    while row < total_h {
        let mut line = String::from("  "); // indent
        for col in 0..total_w {
            let top = get(row, col);
            let bottom = if row + 1 < total_h {
                get(row + 1, col)
            } else {
                false
            };
            line.push(match (top, bottom) {
                (true, true) => 'â–ˆ',
                (true, false) => 'â–€',
                (false, true) => 'â–„',
                (false, false) => ' ',
            });
        }
        println!("{line}");
        row += 2;
    }
    println!();
    println!("  Scan with the kap app to pair");
    println!("  {data}");
    println!();
}

// We need hex encoding. Use sha2's digest output directly.
mod hex {
    pub fn encode(bytes: impl AsRef<[u8]>) -> String {
        bytes.as_ref().iter().map(|b| format!("{b:02x}")).collect()
    }
}

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

    fn temp_dir(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "kap-auth-{name}-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn pairing_token_lifecycle() {
        let dir = temp_dir("token");
        let token1 = load_or_generate_pairing_token(&dir).unwrap();
        assert!(!token1.is_empty());

        // Loading again returns the same token
        let token2 = load_or_generate_pairing_token(&dir).unwrap();
        assert_eq!(token1, token2);

        // Rotating gives a new token
        let token3 = rotate_pairing_token(&dir).unwrap();
        assert_ne!(token1, token3);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn device_pairing_and_validation() {
        let dir = temp_dir("pair");
        let _pairing_token = load_or_generate_pairing_token(&dir).unwrap();

        // Pair a device
        let session_token = pair_device(&dir, "Test iPhone").unwrap();
        assert!(!session_token.is_empty());

        // Session token validates
        let result = validate_token(&dir, &session_token);
        assert!(result.is_some());
        assert_ne!(result.unwrap(), "pairing");

        // Random token does not validate
        assert!(validate_token(&dir, "bogus-token").is_none());

        // Pairing token was rotated
        let old_pairing = _pairing_token;
        let new_pairing = std::fs::read_to_string(dir.join("token"))
            .unwrap()
            .trim()
            .to_string();
        assert_ne!(old_pairing, new_pairing);

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn revoke_device() {
        let dir = temp_dir("revoke");
        load_or_generate_pairing_token(&dir).unwrap();
        let _token = pair_device(&dir, "Test").unwrap();

        let devices = load_devices(&dir);
        assert_eq!(devices.len(), 1);
        let id = devices[0].id.clone();

        let removed = super::revoke_device(&dir, &id).unwrap();
        assert!(removed);
        assert!(load_devices(&dir).is_empty());

        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn constant_time_eq_works() {
        assert!(constant_time_eq("abc", "abc"));
        assert!(!constant_time_eq("abc", "abd"));
        assert!(!constant_time_eq("ab", "abc"));
    }

    #[test]
    fn local_ip_returns_something() {
        // This may fail in CI with no network, but should work locally
        let ip = local_ip();
        if let Some(ref ip) = ip {
            assert!(!ip.is_empty());
            assert!(!ip.starts_with("127."));
        }
    }

    #[test]
    fn lan_ip_skips_vpn_tunnel() {
        // lan_ip_from_interfaces should return a broadcast-capable LAN address,
        // not a point-to-point VPN tunnel address.
        if let Some(ip) = lan_ip_from_interfaces() {
            let addr: std::net::Ipv4Addr = ip.parse().unwrap();
            assert!(addr.is_private());
            assert!(!addr.is_loopback());
        }
    }
}