Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(accounts): shared types + pure core for managed Claude accounts

enes2a1727c32def
diff --git a/src/main/claude-accounts-core.test.ts b/src/main/claude-accounts-core.test.ts
new file mode 100644
index 000000000..3acca9ffc
--- /dev/null
+++ b/src/main/claude-accounts-core.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest'
+import {
+ accountConfigDir,
+ claudeKeychainService,
+ AUTH_ENV_STRIP,
+ accountTmuxEnvArgs,
+ parseLoginCapture,
+ isSupportedClaudeVersion
+} from './claude-accounts-core'
+
+describe('accountConfigDir', () => {
+ it('maps an account id under userData/claude-accounts', () => {
+ expect(accountConfigDir('/Users/x/Library/Application Support/nodeterm', 'a1')).toBe(
+ '/Users/x/Library/Application Support/nodeterm/claude-accounts/a1'
+ )
+ })
+ it('rejects ids that could traverse out of the root', () => {
+ expect(() => accountConfigDir('/ud', '../evil')).toThrow()
+ expect(() => accountConfigDir('/ud', 'a/b')).toThrow()
+ expect(() => accountConfigDir('/ud', '')).toThrow()
+ })
+})
+
+describe('claudeKeychainService', () => {
+ // Claude Code ≥ 2.1 scopes the macOS Keychain service per config dir:
+ // 'Claude Code-credentials-' + first 8 hex chars of sha256(configDir).
+ it('appends the first 8 hex of sha256(configDir)', () => {
+ const svc = claudeKeychainService('/ud/claude-accounts/a1')
+ expect(svc).toMatch(/^Claude Code-credentials-[0-9a-f]{8}$/)
+ })
+ it('is deterministic per dir and differs across dirs', () => {
+ expect(claudeKeychainService('/a')).toBe(claudeKeychainService('/a'))
+ expect(claudeKeychainService('/a')).not.toBe(claudeKeychainService('/b'))
+ })
+})
+
+describe('AUTH_ENV_STRIP', () => {
+ it('covers the env vars that would shadow the account OAuth login', () => {
+ expect(AUTH_ENV_STRIP).toEqual(
+ expect.arrayContaining(['ANTHROPIC_API_KEY', 'ANTHROPIC_AUTH_TOKEN', 'CLAUDE_CODE_OAUTH_TOKEN'])
+ )
+ })
+})
+
+describe('accountTmuxEnvArgs', () => {
+ it('emits one -e pair for CLAUDE_CONFIG_DIR', () => {
+ expect(accountTmuxEnvArgs('/ud/claude-accounts/a1')).toEqual([
+ '-e',
+ 'CLAUDE_CONFIG_DIR=/ud/claude-accounts/a1'
+ ])
+ })
+})
+
+describe('parseLoginCapture', () => {
+ it('extracts the email from oauthAccount', () => {
+ const raw = JSON.stringify({ oauthAccount: { emailAddress: '[email protected]' } })
+ expect(parseLoginCapture(raw)).toEqual({ email: '[email protected]' })
+ })
+ it('accepts the alternate `email` key', () => {
+ const raw = JSON.stringify({ oauthAccount: { email: '[email protected]' } })
+ expect(parseLoginCapture(raw)).toEqual({ email: '[email protected]' })
+ })
+ it('returns null while login has not completed', () => {
+ expect(parseLoginCapture('{}')).toBeNull()
+ expect(parseLoginCapture('not json')).toBeNull()
+ expect(parseLoginCapture(JSON.stringify({ oauthAccount: {} }))).toBeNull()
+ })
+})
+
+describe('isSupportedClaudeVersion', () => {
+ it('accepts 2.1+ and rejects older', () => {
+ expect(isSupportedClaudeVersion('2.1.0 (Claude Code)')).toBe(true)
+ expect(isSupportedClaudeVersion('2.10.3 (Claude Code)')).toBe(true)
+ expect(isSupportedClaudeVersion('3.0.0')).toBe(true)
+ expect(isSupportedClaudeVersion('2.0.14 (Claude Code)')).toBe(false)
+ expect(isSupportedClaudeVersion('1.0.44')).toBe(false)
+ expect(isSupportedClaudeVersion('garbage')).toBe(false) // unparseable → unsupported (warn)
+ })
+})
diff --git a/src/main/claude-accounts-core.ts b/src/main/claude-accounts-core.ts
new file mode 100644
index 000000000..afe63723d
--- /dev/null
+++ b/src/main/claude-accounts-core.ts
@@ -0,0 +1,57 @@
+// Pure logic for managed Claude accounts (config-dir isolation). No fs/electron imports —
+// everything here is unit-tested; the impure lifecycle lives in claude-accounts.ts.
+import { createHash } from 'crypto'
+import path from 'path'
+
+/** Root-relative config dir for a managed account. Rejects ids that could escape the root. */
+export function accountConfigDir(userDataPath: string, accountId: string): string {
+ if (!/^[A-Za-z0-9_-]+$/.test(accountId)) {
+ throw new Error(`invalid account id: ${JSON.stringify(accountId)}`)
+ }
+ return path.join(userDataPath, 'claude-accounts', accountId)
+}
+
+/**
+ * Claude Code ≥ 2.1 scopes its macOS Keychain service name per config dir:
+ * 'Claude Code-credentials-' + first 8 hex chars of sha256(CLAUDE_CONFIG_DIR).
+ * (Learned from REF's claude-accounts/keychain.ts — undocumented CLI behavior.)
+ */
+export function claudeKeychainService(configDir: string): string {
+ const suffix = createHash('sha256').update(configDir).digest('hex').slice(0, 8)
+ return `Claude Code-credentials-${suffix}`
+}
+
+/** Env vars that would silently shadow the selected account's OAuth login. Stripped at spawn. */
+export const AUTH_ENV_STRIP = [
+ 'ANTHROPIC_API_KEY',
+ 'ANTHROPIC_AUTH_TOKEN',
+ 'CLAUDE_CODE_OAUTH_TOKEN'
+] as const
+
+/** tmux `-e` pair injecting the account config dir (shared server → per-session env). */
+export function accountTmuxEnvArgs(configDir: string): string[] {
+ return ['-e', `CLAUDE_CONFIG_DIR=${configDir}`]
+}
+
+/** Parse `{configDir}/.claude.json` for a completed login's identity. Null until login lands. */
+export function parseLoginCapture(rawClaudeJson: string): { email: string } | null {
+ try {
+ const j = JSON.parse(rawClaudeJson) as Record<string, any>
+ const acct = j.oauthAccount as Record<string, any> | undefined
+ const email =
+ (acct && typeof acct.emailAddress === 'string' && acct.emailAddress) ||
+ (acct && typeof acct.email === 'string' && acct.email) ||
+ null
+ return email ? { email } : null
+ } catch {
+ return null
+ }
+}
+
+/** Claude Code < 2.1 uses one unscoped Keychain service for every config dir → accounts collide. */
+export function isSupportedClaudeVersion(versionOutput: string): boolean {
+ const m = versionOutput.match(/(\d+)\.(\d+)\./)
+ if (!m) return false
+ const [major, minor] = [Number(m[1]), Number(m[2])]
+ return major > 2 || (major === 2 && minor >= 1)
+}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 5aaf2c1f7..03048ffdc 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -23,6 +23,8 @@ export interface PtyCreateOptions {
* real value in a later phase.
*/
agentId?: AgentId
+ /** Managed Claude account: inject CLAUDE_CONFIG_DIR for this account into the session env. */
+ accountId?: string
/** When set, this PTY runs on a remote host over the project's ssh ControlMaster, in remote tmux. */
sshRemote?: { controlPath: string; conn: import('./ssh').SshConnection; remoteCwd: string; hookEndpointPath?: string; tmuxConfPath?: string }
}
@@ -67,6 +69,12 @@ export interface CanvasNodeState {
cwd?: string
/** Which agent runs in this terminal node (claude/codex/gemini/custom). */
agentId?: AgentId
+ /**
+ * Claude-only: managed account this node runs on (CLAUDE_CONFIG_DIR injection).
+ * Resolved once at node creation (explicit pick → project default → system default)
+ * and immutable for the node's lifetime. Undefined = system default (~/.claude).
+ */
+ accountId?: string
/** When set, the terminal runs `ssh` to this host on the local PTY; persisted (auto-reconnects). */
ssh?: import('./ssh').SshConnection
/** When true (SSH-project terminals), the node runs in REMOTE tmux on `ssh` rather than `ssh`-on-local-PTY. */
@@ -132,6 +140,8 @@ export interface Project {
ssh?: { server: import('./ssh').SshConnection; remoteCwd: string }
viewport: Viewport
nodes: CanvasNodeState[]
+ /** Default managed Claude account for new Claude/chat nodes in this project. */
+ defaultAccountId?: string
/** Bridge links between Claude nodes (optional; absent in pre-bridge files). */
bridges?: BridgeLink[]
/**
@@ -274,6 +284,24 @@ export interface CustomAgent {
promptInjectionMode: PromptInjectionMode
}
+/**
+ * A managed Claude account. Its credentials/config live in a private config dir
+ * ({userData}/claude-accounts/<id>, or `~/.nodeterm/claude-accounts/<id>` on `host` for
+ * remote accounts) injected as CLAUDE_CONFIG_DIR at spawn. The claude CLI owns login,
+ * credential storage, and token refresh inside that dir — we never write credentials.
+ */
+export interface ClaudeAccount {
+ id: string
+ /** Display label; defaults to the captured email. */
+ label: string
+ email?: string
+ /** Set only for remote (SSH) accounts: the ssh host this account's config dir lives on. */
+ host?: string
+ /** True until `claude /login` completes in the account dir and the email is captured. */
+ pending?: boolean
+ createdAt: number
+}
+
/** User-configurable application settings (settings.json). */
export interface Settings {
fontSize: number
@@ -309,6 +337,8 @@ export interface Settings {
notifyConsentAsked: boolean
/** User-defined agents (BYO CLI) appended to the Add menus. */
customAgents: CustomAgent[]
+ /** Managed Claude accounts (config-dir isolated). See ClaudeAccount. */
+ claudeAccounts: ClaudeAccount[]
/** Agent ids hidden from the Add menus. */
disabledAgents: AgentId[]
/** Which agent the ⌘⇧C shortcut / quick-add launches. Always a launchable builtin. */
@@ -339,6 +369,7 @@ export const DEFAULT_SETTINGS: Settings = {
gitAutoFetch: true,
notifyConsentAsked: false,
customAgents: [],
+ claudeAccounts: [],
// New users see only Claude in the Add menus; Codex/Gemini are opt-in (re-enable in Settings).
// Existing users keep whatever they've saved (their persisted disabledAgents overrides this).
disabledAgents: ['codex', 'gemini'],