swapdex 0.24.5

Switch between multiple Claude Code, Codex, Gemini, and Antigravity login accounts, locally and safely.
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! The profile store at ~/.local/share/swapdex: named snapshots, a switch
//! timeline, an active-name hint, a cross-process lock, and bounded backups.
//! Everything is 0600, the store dir 0700; it holds plaintext refresh tokens and
//! is single-machine, single-user - never sync it.

use crate::adapters::Snapshot;
use crate::paths::Paths;
use crate::secret::Secret;
use anyhow::{Context, Result};
use fs2::FileExt;
use std::fs;
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
use std::path::PathBuf;

pub struct Store {
    dir: PathBuf,
}

pub struct ProfileInfo {
    pub name: String,
    pub tools: Vec<String>,
}

/// Holds an exclusive flock for its lifetime (released on drop). The file is
/// kept only to keep the lock; it is intentionally never read.
/// Why the store lock could not be taken: contention is retryable, an
/// unwritable store is not - the messages must differ.
#[derive(Debug)]
pub enum LockError {
    Busy,
    Unwritable(String),
}

pub struct LockGuard(#[allow(dead_code)] fs::File);

/// chmod 0700/0600 everything under `dir` (dirs/files), best-effort.
fn tighten_tree(dir: &std::path::Path) {
    let Ok(rd) = fs::read_dir(dir) else { return };
    for e in rd.flatten() {
        let p = e.path();
        // NEVER follow a symlink: chmod/recurse would touch a target OUTSIDE
        // the 0700 store. Use the entry's own file type (lstat), and skip any
        // symlink outright - a real snapshot part is a plain file/dir.
        let is_symlink = e
            .file_type()
            .map(|t| t.is_symlink())
            .or_else(|_| fs::symlink_metadata(&p).map(|m| m.file_type().is_symlink()))
            .unwrap_or(true);
        if is_symlink {
            continue;
        }
        if fs::symlink_metadata(&p)
            .map(|m| m.is_dir())
            .unwrap_or(false)
        {
            fs::set_permissions(&p, fs::Permissions::from_mode(0o700)).ok();
            tighten_tree(&p);
        } else {
            fs::set_permissions(&p, fs::Permissions::from_mode(0o600)).ok();
        }
    }
}

impl Store {
    pub fn open(paths: &Paths) -> Result<Store> {
        let dir = paths.store_dir();
        fs::create_dir_all(&dir).with_context(|| format!("create store {}", dir.display()))?;
        // 0700 explicitly - do not rely on inherited perms.
        fs::set_permissions(&dir, fs::Permissions::from_mode(0o700)).ok();
        for sub in ["accounts", "backups"] {
            let d = dir.join(sub);
            fs::create_dir_all(&d).ok();
            fs::set_permissions(&d, fs::Permissions::from_mode(0o700)).ok();
            // Snapshots ARE tokens: tighten everything under them too. cp -r,
            // backup tools, or a loose umask can widen modes after the fact,
            // and doctor's top-level check would miss it. Best-effort, tiny
            // tree (profiles x tools), runs on every open.
            tighten_tree(&d);
        }
        Ok(Store { dir })
    }

    /// Exclusive lock around the read-current -> backup -> apply compound; refuse
    /// (rather than block) if another swapdex is mid-switch.
    pub fn lock(&self) -> std::result::Result<LockGuard, LockError> {
        let path = self.dir.join(".lock");
        let f = fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(false)
            .mode(0o600)
            .open(&path)
            .map_err(|e| LockError::Unwritable(format!("{e}")))?;
        f.try_lock_exclusive().map_err(|_| LockError::Busy)?;
        Ok(LockGuard(f))
    }

    fn account_tool_dir(&self, name: &str, tool: &str) -> PathBuf {
        self.dir.join("accounts").join(name).join(tool)
    }

    pub fn save(&self, name: &str, snap: &Snapshot) -> Result<()> {
        let d = self.account_tool_dir(name, snap.tool);
        fs::create_dir_all(&d).ok();
        fs::set_permissions(
            self.dir.join("accounts").join(name),
            fs::Permissions::from_mode(0o700),
        )
        .ok();
        fs::set_permissions(&d, fs::Permissions::from_mode(0o700)).ok();
        for (part, secret) in &snap.blobs {
            let dest = d.join(part);
            crate::atomic::refuse_symlink_below(&self.dir, &dest)?;
            crate::atomic::write_secret(&dest, secret.expose())?;
        }
        Ok(())
    }

    pub fn load(&self, name: &str, tool: &str) -> Result<Option<Snapshot>> {
        let d = self.account_tool_dir(name, tool);
        if !d.exists() {
            return Ok(None);
        }
        let tool_static: &'static str = match tool {
            "claude-code" => "claude-code",
            "codex" => "codex",
            "gemini" => "gemini",
            "antigravity" => "antigravity",
            _ => return Ok(None),
        };
        let mut blobs = Vec::new();
        for e in fs::read_dir(&d)?.flatten() {
            let part = e.file_name().to_string_lossy().into_owned();
            // Skip a transient ".<name>.swapdex.tmp" from a concurrent write so
            // it is never mistaken for a snapshot part.
            if e.path().is_file() && !part.starts_with('.') {
                crate::atomic::refuse_symlink_below(&self.dir, &e.path())?;
                let bytes = crate::atomic::read_regular(&e.path())?;
                blobs.push((part, Secret::new(bytes)));
            }
        }
        Ok(Some(Snapshot {
            tool: tool_static,
            blobs,
        }))
    }

    pub fn list(&self) -> Vec<ProfileInfo> {
        let mut out = Vec::new();
        let accounts = self.dir.join("accounts");
        if let Ok(rd) = fs::read_dir(&accounts) {
            for e in rd.flatten() {
                if !e.path().is_dir() {
                    continue;
                }
                let name = e.file_name().to_string_lossy().into_owned();
                let mut tools = Vec::new();
                if let Ok(td) = fs::read_dir(e.path()) {
                    for t in td.flatten() {
                        let tname = t.file_name().to_string_lossy().into_owned();
                        // Only KNOWN tools count - a stray subdir (crash
                        // debris, manual poking) must not render as a tool.
                        if t.path().is_dir() && KNOWN_TOOLS.contains(&tname.as_str()) {
                            tools.push(tname);
                        }
                    }
                }
                tools.sort();
                // An empty dir is not a profile: `use` would refuse it, so
                // `ls` showing it is a lie.
                if tools.is_empty() {
                    continue;
                }
                out.push(ProfileInfo { name, tools });
            }
        }
        out.sort_by(|a, b| a.name.cmp(&b.name));
        out
    }

    pub fn remove(&self, name: &str) -> Result<bool> {
        let d = self.dir.join("accounts").join(name);
        if !d.exists() {
            return Ok(false);
        }
        // Best-effort overwrite of snapshot bytes before unlinking (CoW caveat
        // documented in the README).
        overwrite_tree(&d);
        fs::remove_dir_all(&d).with_context(|| format!("remove profile {name}"))?;
        Ok(true)
    }

    /// Rename a profile. Returns false if `old` does not exist; errors if `new`
    /// already exists.
    /// Whether ANY directory (even a ghost one hidden from `list()`) claims
    /// this name - the collision test for rename targets.
    pub fn profile_dir_exists(&self, name: &str) -> bool {
        self.dir.join("accounts").join(name).exists()
    }

    pub fn rename(&self, old: &str, new: &str) -> Result<bool> {
        let from = self.dir.join("accounts").join(old);
        let to = self.dir.join("accounts").join(new);
        if !from.exists() {
            return Ok(false);
        }
        if to.exists() {
            anyhow::bail!("a profile named '{new}' already exists");
        }
        fs::rename(&from, &to).with_context(|| format!("rename profile {old} -> {new}"))?;
        // The timeline attributes sessions/usage by profile NAME - leaving the
        // old name there makes `usage`/`sessions` report a profile that no
        // longer exists, forever. Rewrite events in place (atomic).
        let tl = self.dir.join("timeline.jsonl");
        if let Ok(text) = fs::read_to_string(&tl) {
            let mut changed = false;
            let rewritten: Vec<String> = text
                .lines()
                .map(
                    |line| match serde_json::from_str::<serde_json::Value>(line) {
                        Ok(mut v) if v["account"] == old => {
                            v["account"] = serde_json::Value::String(new.to_string());
                            changed = true;
                            serde_json::to_string(&v).unwrap_or_else(|_| line.to_string())
                        }
                        _ => line.to_string(),
                    },
                )
                .collect();
            if changed {
                let mut out = rewritten.join("\n");
                out.push('\n');
                crate::atomic::refuse_symlink_below(&self.dir, &tl)?;
                crate::atomic::write_secret(&tl, out.as_bytes())?;
            }
        }
        Ok(true)
    }

    /// Back up a live snapshot before a switch; keep only the newest 2 per tool.
    pub fn backup(&self, snap: &Snapshot) -> Result<()> {
        let base = self.dir.join("backups").join(snap.tool);
        fs::create_dir_all(&base).ok();
        fs::set_permissions(&base, fs::Permissions::from_mode(0o700)).ok();
        let stamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let d = base.join(stamp.to_string());
        fs::create_dir_all(&d).ok();
        fs::set_permissions(&d, fs::Permissions::from_mode(0o700)).ok();
        for (part, secret) in &snap.blobs {
            let dest = d.join(part);
            crate::atomic::refuse_symlink_below(&self.dir, &dest)?;
            crate::atomic::write_secret(&dest, secret.expose())?;
        }
        // Prune to newest 2.
        let mut stamps: Vec<PathBuf> = fs::read_dir(&base)
            .into_iter()
            .flatten()
            .flatten()
            .map(|e| e.path())
            .filter(|p| p.is_dir())
            .collect();
        // Sort by the numeric stamp, not lexically, so pruning always drops the
        // genuinely-oldest backup (lexical sort would misorder across a digit-
        // length change).
        stamps.sort_by_key(|p| {
            backup_order_key(
                p.file_name()
                    .and_then(|n| n.to_str())
                    .and_then(|s| s.parse::<u128>().ok())
                    .unwrap_or(0),
            )
        });
        while stamps.len() > 2 {
            let old = stamps.remove(0);
            overwrite_tree(&old);
            let _ = fs::remove_dir_all(&old);
        }
        Ok(())
    }

    /// The newest backup snapshot for a tool (taken by `use` before each switch),
    /// with its unix-nanos stamp. `None` when no backup exists.
    pub fn load_backup(&self, tool: &str) -> Result<Option<(u128, Snapshot)>> {
        let tool_static: &'static str = match tool {
            "claude-code" => "claude-code",
            "codex" => "codex",
            "gemini" => "gemini",
            "antigravity" => "antigravity",
            _ => return Ok(None),
        };
        let base = self.dir.join("backups").join(tool);
        let mut stamps: Vec<(u128, PathBuf)> = fs::read_dir(&base)
            .into_iter()
            .flatten()
            .flatten()
            .map(|e| e.path())
            .filter(|p| p.is_dir())
            .filter_map(|p| {
                let s = p.file_name()?.to_str()?.parse::<u128>().ok()?;
                Some((s, p))
            })
            .collect();
        stamps.sort_by_key(|(s, _)| backup_order_key(*s));
        // Newest first, but skip a torn candidate (a crash between mkdir and
        // the blob writes leaves an empty/partial dir) - an older intact backup
        // is better than "no backup".
        while let Some((stamp, d)) = stamps.pop() {
            let mut blobs = Vec::new();
            for e in fs::read_dir(&d)?.flatten() {
                let part = e.file_name().to_string_lossy().into_owned();
                if e.path().is_file() && !part.starts_with('.') {
                    crate::atomic::refuse_symlink_below(&self.dir, &e.path())?;
                    let bytes = crate::atomic::read_regular(&e.path())?;
                    blobs.push((part, Secret::new(bytes)));
                }
            }
            let complete = match tool_static {
                // A claude backup needs both parts or apply() will refuse it.
                "claude-code" => {
                    blobs.iter().any(|(n, _)| n == "credentials")
                        && blobs.iter().any(|(n, _)| n == "oauth_account")
                }
                _ => !blobs.is_empty(),
            };
            if !complete {
                continue;
            }
            return Ok(Some((
                stamp,
                Snapshot {
                    tool: tool_static,
                    blobs,
                },
            )));
        }
        Ok(None)
    }

    pub fn append_timeline(&self, tool: &str, account: &str, action: &str) -> Result<()> {
        let ts = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        self.append_timeline_at(tool, account, action, ts)
    }

    /// Append with an explicit timestamp so every tool touched by ONE `use` /
    /// `restore` invocation shares the same ts - that shared ts is what lets a
    /// bare `restore` scope itself to exactly the last switch.
    pub fn append_timeline_at(
        &self,
        tool: &str,
        account: &str,
        action: &str,
        ts: u64,
    ) -> Result<()> {
        self.append_timeline_inv(tool, account, action, ts, 0)
    }

    /// `inv` is a per-INVOCATION discriminator (nanos): whole-second `ts`
    /// alone collides when two separate invocations run inside one second,
    /// and bare `restore` scopes to "the last invocation's tools" by it.
    /// 0 = legacy/unknown (grouping falls back to ts equality).
    pub fn append_timeline_inv(
        &self,
        tool: &str,
        account: &str,
        action: &str,
        ts: u64,
        inv: u128,
    ) -> Result<()> {
        let path = self.dir.join("timeline.jsonl");
        let line = if inv > 0 {
            serde_json::json!({"ts": ts, "tool": tool, "account": account, "action": action, "inv": inv.to_string()})
        } else {
            serde_json::json!({"ts": ts, "tool": tool, "account": account, "action": action})
        };
        let mut buf = if path.exists() {
            {
                crate::atomic::refuse_symlink_below(&self.dir, &path)?;
                crate::atomic::read_regular(&path)?
            }
        } else {
            Vec::new()
        };
        buf.extend_from_slice(serde_json::to_string(&line)?.as_bytes());
        buf.push(b'\n');
        // Bound the file: session attribution only needs recent history, so
        // compact to the newest TIMELINE_KEEP events once it doubles that.
        const TIMELINE_KEEP: usize = 1000;
        let lines = buf.iter().filter(|&&b| b == b'\n').count();
        if lines > TIMELINE_KEEP * 2 {
            let text = String::from_utf8_lossy(&buf).into_owned();
            let tail: Vec<&str> = text
                .lines()
                .rev()
                .take(TIMELINE_KEEP)
                .collect::<Vec<_>>()
                .into_iter()
                .rev()
                .collect();
            buf = (tail.join("\n") + "\n").into_bytes();
        }
        crate::atomic::refuse_symlink_below(&self.dir, &path)?;
        crate::atomic::write_secret(&path, &buf)
    }
}

/// A profile name must be a single safe path component - reject anything that
/// could escape the store (`/`, `\`, `..`, a leading `.`, control chars, empty,
/// or absurdly long). Guards `add`/`use`/`rm`/`rename` against path traversal.
/// Ordering key for backup stamps: a stamp more than an hour in the FUTURE
/// (clock skew during one switch - NTP jump, VM resume) sorts as the OLDEST,
/// so a ghost can neither shadow real backups in load_backup nor survive
/// pruning forever.
fn backup_order_key(stamp: u128) -> u128 {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    if stamp > now + 3_600_000_000_000 {
        0
    } else {
        stamp
    }
}

pub const KNOWN_TOOLS: [&str; 4] = ["claude-code", "codex", "gemini", "antigravity"];

pub fn valid_profile_name(name: &str) -> bool {
    // NOTE: "-" is reserved at CREATION time (add/rename reject it) because
    // `use -` toggles - but it stays valid here so a legacy profile named "-"
    // can still be rm'd/renamed after an upgrade.
    !name.is_empty()
        && name.len() <= 64
        && !name.starts_with('.')
        && !name.contains(['/', '\\'])
        && !name.chars().any(|c| c.is_control())
}

fn overwrite_tree(dir: &std::path::Path) {
    if let Ok(rd) = fs::read_dir(dir) {
        for e in rd.flatten() {
            let p = e.path();
            // Use lstat, never follow a symlink: `fs::write` through a symlink
            // would zero a file OUTSIDE the store. Unlink (in remove_dir_all
            // afterwards) drops the link itself; we never write through it.
            let Ok(meta) = fs::symlink_metadata(&p) else {
                continue;
            };
            if meta.file_type().is_symlink() {
                continue;
            }
            if meta.is_dir() {
                overwrite_tree(&p);
            } else if meta.is_file() {
                let _ = fs::write(&p, vec![0u8; meta.len() as usize]);
            }
        }
    }
}

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

    fn snap() -> Snapshot {
        Snapshot {
            tool: "codex",
            blobs: vec![("auth".into(), Secret::new(b"{\"k\":\"SENTINEL\"}".to_vec()))],
        }
    }

    // A symlink planted inside the store must never be FOLLOWED when tightening
    // perms or securely zeroing on `rm`: chmod/overwrite would escape to a file
    // outside the 0700 store. remove() must delete the profile without touching
    // the symlink target.
    #[test]
    fn destructive_traversal_does_not_follow_symlinks_out_of_the_store() {
        use std::os::unix::fs::symlink;
        let d = tempfile::tempdir().unwrap();
        let p = Paths::rooted(d.path());
        let s = Store::open(&p).unwrap();
        s.save("work", &snap()).unwrap();
        // An important external file, and a symlink to it inside the profile.
        let outside = d.path().join("important.txt");
        fs::write(&outside, b"DO-NOT-TOUCH").unwrap();
        let mode_before = fs::symlink_metadata(&outside).unwrap().permissions().mode();
        let link = p
            .store_dir()
            .join("accounts")
            .join("work")
            .join("codex")
            .join("evil");
        symlink(&outside, &link).unwrap();
        // Re-open (runs tighten_tree over the symlink) and remove (overwrite_tree).
        let s = Store::open(&p).unwrap();
        assert!(s.remove("work").unwrap());
        assert_eq!(
            fs::read(&outside).unwrap(),
            b"DO-NOT-TOUCH",
            "the external target was neither zeroed nor chmod-ed"
        );
        assert_eq!(
            fs::symlink_metadata(&outside).unwrap().permissions().mode(),
            mode_before,
            "external file's mode is untouched (never chmod-ed through the symlink)"
        );
    }

    fn walk_files(dir: &std::path::Path) -> Vec<PathBuf> {
        let mut out = vec![];
        if let Ok(rd) = fs::read_dir(dir) {
            for e in rd.flatten() {
                let p = e.path();
                if p.is_dir() {
                    out.extend(walk_files(&p));
                } else {
                    out.push(p);
                }
            }
        }
        out
    }

    #[test]
    fn store_dir_is_0700_and_roundtrips_a_snapshot() {
        let d = tempfile::tempdir().unwrap();
        let p = Paths::rooted(d.path());
        let s = Store::open(&p).unwrap();
        assert_eq!(
            fs::metadata(p.store_dir()).unwrap().permissions().mode() & 0o777,
            0o700
        );
        s.save("work", &snap()).unwrap();
        let back = s.load("work", "codex").unwrap().unwrap();
        assert_eq!(back.part("auth").unwrap().expose(), b"{\"k\":\"SENTINEL\"}");
        for f in walk_files(&p.store_dir().join("accounts/work")) {
            assert_eq!(
                fs::metadata(&f).unwrap().permissions().mode() & 0o777,
                0o600,
                "{f:?}"
            );
        }
    }

    #[test]
    fn timeline_holds_no_secret() {
        let d = tempfile::tempdir().unwrap();
        let p = Paths::rooted(d.path());
        let s = Store::open(&p).unwrap();
        s.append_timeline("codex", "work", "use").unwrap();
        let tl = fs::read_to_string(p.store_dir().join("timeline.jsonl")).unwrap();
        assert!(!tl.contains("SENTINEL"));
        assert!(tl.contains("work") && tl.contains("codex"));
    }

    #[test]
    fn lock_is_exclusive() {
        let d = tempfile::tempdir().unwrap();
        let p = Paths::rooted(d.path());
        let s = Store::open(&p).unwrap();
        let _g = s.lock().unwrap();
        assert!(s.lock().is_err(), "second lock must fail while held");
    }
}