Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(desktop): read Claude Code's Keychain item by account, not just by service

Kelvin747e3cbecad3
diff --git a/desktop/lib/usage/usage_credentials.dart b/desktop/lib/usage/usage_credentials.dart
index ae5351165..b76945f5d 100644
--- a/desktop/lib/usage/usage_credentials.dart
+++ b/desktop/lib/usage/usage_credentials.dart
@@ -13,6 +13,8 @@ library;
import 'dart:convert';
import 'dart:io';
+import 'package:cryptography/dart.dart';
+
/// A token, and when it stops working.
class UsageToken {
const UsageToken({required this.accessToken, this.expiresAt});
@@ -34,15 +36,59 @@ class UsageToken {
/// Reads the tokens the usage endpoints need, from wherever each CLI put them.
class UsageCredentials {
- const UsageCredentials({this.home, this.runProcess});
+ const UsageCredentials({this.home, this.runProcess, this.environment});
/// Overridden by tests. Null means this machine's real home.
final String? home;
+ /// Overridden by tests. Null means this process's real environment — the same one Claude Code
+ /// reads `USER` and `CLAUDE_CONFIG_DIR` from when it names its Keychain item.
+ final Map<String, String>? environment;
+
/// Overridden by tests so nothing shells out to the real `security`.
final Future<ProcessResult> Function(String, List<String>)? runProcess;
String? get _home => home ?? Platform.environment['HOME'];
+ Map<String, String> get _env => environment ?? Platform.environment;
+
+ /// The Keychain SERVICE Claude Code writes its OAuth token under — its own rule, read off
+ /// Claude Code 2.1.272: `Claude Code-credentials`, plus `-<sha256(configDir)[0..8]>` when
+ /// `CLAUDE_CONFIG_DIR` is set, so profiles kept in different directories get different items.
+ /// (`CLAUDE_SECURESTORAGE_CONFIG_DIR` overrides the directory that is hashed; empty means the
+ /// plain name even with a config dir set.)
+ static String keychainService(Map<String, String> env) {
+ final secure = env['CLAUDE_SECURESTORAGE_CONFIG_DIR'];
+ final configDir = env['CLAUDE_CONFIG_DIR'];
+ final plain = secure != null
+ ? secure.isEmpty
+ : configDir == null || configDir.isEmpty;
+ if (plain) return _claudeKeychainService;
+ final hashed = secure ?? configDir!;
+ final digest = const DartSha256().hashSync(utf8.encode(hashed)).bytes;
+ final prefix = digest
+ .take(4)
+ .map((b) => b.toRadixString(16).padLeft(2, '0'))
+ .join();
+ return '$_claudeKeychainService-$prefix';
+ }
+
+ /// The Keychain ACCOUNT Claude Code writes under — again its own rule: `USER`, else the OS
+ /// username, and a fixed placeholder when that is not a plain account name.
+ ///
+ /// ⚠️ This is the half that was missing. `security find-generic-password -s <service>` alone
+ /// returns whichever item matches the service FIRST, and a Keychain that has seen more than one
+ /// account (a stale item under another user name, say) answered with the stale one — an expired
+ /// token, so the menu said "Not signed in" beside a Claude Code that was signed in and working.
+ static String keychainAccount(
+ Map<String, String> env, {
+ required String username,
+ }) {
+ final name = env['USER'] ?? username;
+ return _claudeAccountPattern.hasMatch(name) ? name : 'claude-code-user';
+ }
+
+ static const _claudeKeychainService = 'Claude Code-credentials';
+ static final _claudeAccountPattern = RegExp(r'^[a-zA-Z0-9._-]+$');
/// Claude Code's OAuth token.
///
@@ -128,19 +174,25 @@ class UsageCredentials {
}
}
- /// The macOS Keychain item Claude Code writes.
+ /// The macOS Keychain item Claude Code writes — looked up by service AND account, exactly the
+ /// way Claude Code reads it back ([keychainService], [keychainAccount]), so this app and the
+ /// CLI that signed in cannot be reading two different items.
///
/// `security` is used rather than a plugin because the item is a plain
/// generic password and this is one read on a timer — a native channel would
/// be a second thing to keep in step across two platforms for it.
Future<String?> _readKeychain() async {
- if (!Platform.isMacOS) return null;
+ if (!Platform.isMacOS && runProcess == null) return null;
final run = runProcess ?? Process.run;
+ final env = _env;
try {
- final result = await run('security', const [
+ final result = await run('security', [
'find-generic-password',
+ '-a',
+ // Claude Code falls back to `os.userInfo().username`; the nearest thing here is LOGNAME.
+ keychainAccount(env, username: env['LOGNAME'] ?? 'claude-code-user'),
'-s',
- 'Claude Code-credentials',
+ keychainService(env),
'-w',
]);
if (result.exitCode != 0) return null;
diff --git a/desktop/test/usage_credentials_test.dart b/desktop/test/usage_credentials_test.dart
new file mode 100644
index 000000000..ca67d9c77
--- /dev/null
+++ b/desktop/test/usage_credentials_test.dart
@@ -0,0 +1,101 @@
+// How the app finds Claude Code's OAuth token in the macOS Keychain — the same lookup Claude Code
+// itself performs, or it reads a different item than the CLI that is signed in.
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/usage/usage_credentials.dart';
+
+/// A Keychain holding several `Claude Code-credentials` items, the way a real one does after a
+/// few years of use: the first item `security` returns for the bare service name is a stale one
+/// under another account, and the live one is keyed by THIS user's account.
+class _Keychain {
+ _Keychain({required this.user});
+ final String user;
+ final calls = <List<String>>[];
+
+ static String _item(int expiresAt) =>
+ '{"claudeAiOauth":{"accessToken":"tok-$expiresAt","refreshToken":"r","expiresAt":$expiresAt}}';
+
+ Future<ProcessResult> run(String executable, List<String> args) async {
+ calls.add([executable, ...args]);
+ if (executable != 'security') {
+ return ProcessResult(0, 1, '', 'no such command');
+ }
+ final service = args[args.indexOf('-s') + 1];
+ final account = args.contains('-a') ? args[args.indexOf('-a') + 1] : null;
+ // Only the plain service, the way current Claude Code names it without CLAUDE_CONFIG_DIR.
+ if (service != 'Claude Code-credentials') {
+ return ProcessResult(0, 44, '', 'not found');
+ }
+ // The stale first match — what `security` answers for the bare service name.
+ if (account == null) return ProcessResult(0, 0, _item(1000), '');
+ // 2100-01-01: the live item, under this user's account.
+ if (account == user) return ProcessResult(0, 0, _item(4102444800000), '');
+ return ProcessResult(0, 44, '', 'not found');
+ }
+}
+
+void main() {
+ test(
+ 'reads the item Claude Code itself reads: service AND this user\'s account',
+ () async {
+ final keychain = _Keychain(user: 'macbookpro');
+ final credentials = UsageCredentials(
+ home: Directory.systemTemp.path,
+ environment: const {'USER': 'macbookpro'},
+ runProcess: keychain.run,
+ );
+
+ final token = await credentials.claude();
+
+ expect(token?.accessToken, 'tok-4102444800000');
+ expect(token?.isExpired, isFalse);
+ final security = keychain.calls.singleWhere((c) => c.first == 'security');
+ expect(security, containsAllInOrder(['-a', 'macbookpro']));
+ expect(security, containsAllInOrder(['-s', 'Claude Code-credentials']));
+ },
+ );
+
+ test('falls back to the OS username when USER is unset, and to Claude Code\'s placeholder when it is unusable', () {
+ expect(
+ UsageCredentials.keychainAccount(const {}, username: 'macbookpro'),
+ 'macbookpro',
+ );
+ // Claude Code refuses an account name outside `[a-zA-Z0-9._-]` and uses a fixed one instead,
+ // so the same name has to be looked up here or the item is simply never found.
+ expect(
+ UsageCredentials.keychainAccount(const {
+ 'USER': 'mac book',
+ }, username: 'ignored'),
+ 'claude-code-user',
+ );
+ expect(
+ UsageCredentials.keychainAccount(const {
+ 'USER': 'kelvin.dev',
+ }, username: 'ignored'),
+ 'kelvin.dev',
+ );
+ });
+
+ test('names the per-profile item when CLAUDE_CONFIG_DIR is set, as Claude Code does', () {
+ expect(
+ UsageCredentials.keychainService(const {}),
+ 'Claude Code-credentials',
+ );
+ // sha256('/Users/macbookpro/.claude-work').substring(0, 8) — a worked example, not recomputed
+ // here, so a drift in the hashing would be caught rather than mirrored.
+ expect(
+ UsageCredentials.keychainService(const {
+ 'CLAUDE_CONFIG_DIR': '/Users/macbookpro/.claude-work',
+ }),
+ 'Claude Code-credentials-${_sha256Prefix('/Users/macbookpro/.claude-work')}',
+ );
+ });
+}
+
+/// The known-good prefix for the profile-dir example above, computed once with
+/// `printf '%s' '/Users/macbookpro/.claude-work' | shasum -a 256 | cut -c1-8`.
+String _sha256Prefix(String dir) {
+ const known = {'/Users/macbookpro/.claude-work': '138c714b'};
+ return known[dir]!;
+}