Skip to content

fix(claude-accounts): preserve shared MCP OAuth credentials across an account switch - #21931

Merged
nwparker merged 7 commits into
stablyai:mainfrom
tomarai85:fix/preserve-mcpoauth-on-account-switch
Oct 6, 2026
Merged

nwparker merged 7 commits into
stablyai:mainfrom
tomarai85:fix/preserve-mcpoauth-on-account-switch

Conversation

@tomarai85

@tomarai85 tomarai85 commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Switching Claude accounts currently signs users out of OAuth MCP servers. This change keeps the live MCP authorizations while changing the Claude account.

What Changed

Before each runtime credential write, carry the live connector fields into the selected account's credentials. The runtime file and both macOS Keychain items receive the same value. Account capture and refresh read-back exclude connector secrets, so saved accounts cannot restore stale MCP tokens.

Compare each live store against Orca's last successful write to preserve additions, rotations, and revocations made by Claude. Before the first write, combine independent grants from the live stores. Keep each server's access and refresh tokens together. Stop before writing if a store cannot be read, contains malformed data, or conflicts with another update whose freshness cannot be established. Claude account-token expiry does not determine MCP-token freshness.

Advance the comparison baseline only after every runtime store is written successfully. Keep it through partial-write rollback so a retry cannot lose a grant or mistake an unwritten store for a revocation. Returning to the system default also carries the live grants, including signed-out defaults.

Why

MCP authorizations belong to the connector account, independently of the Claude subscription. Preserving them at the existing write boundaries avoids duplicating rotating secrets in saved accounts. Combining independent updates and rejecting ambiguous conflicts is safer than choosing a store by priority or guessing freshness. No new on-disk credential snapshots or remote protocol changes are introduced.

Linked Issue

Fixes #16098

Visual Proof

N/A — credential persistence only; no rendered UI changes.

Testing

  • Live Linear browser authentication and read-only list_teams calls verified before switching, after A → B → A, after a service restart, and after returning to default. Each stage checked the runtime file and both native macOS Keychain items, plus managed-account secret exclusion. The test used an isolated config and synthetic Claude account records; it did not exercise two live Claude subscription logins or the account-selector UI. Temporary test entries were removed.
  • Regression tests cover capture, repeated sync, restart, defaults, token rotation, revocation, stale snapshots, malformed inputs, read failures, independent updates, conflicting token pairs, partial writes, rollback, and retry. Linux and Windows branches and WSL isolation are covered by the account suite.
  • Account and credential tests pass: ORCA_BACKGROUND_LAUNCH=1 pnpm test src/main/claude-accounts src/main/rate-limits/claude-fetcher-managed-account-usage.test.ts src/main/rate-limits/claude-fetcher-keychain-credentials.test.ts src/main/macos-keychain src/main/ipc/preflight-host-cli-status.test.ts src/main/ipc/preflight-command-exec.test.ts
  • 455 total tests pass across 40 files, including the following startup, directory-check, and journal suites: ORCA_BACKGROUND_LAUNCH=1 pnpm test src/shared/startup-line-prompt-carry.test.ts src/shared/tui-agent-startup.test.ts config/scripts/check-runtime-electron-ratchet.test.mjs src/main/native-chat/agent-session-journal/journal-submission-positions.test.ts
  • All 114 cross-version compatibility tests pass across 20 files: ORCA_BACKGROUND_LAUNCH=1 pnpm test tests/e2e/cross-version-wire/ --maxWorkers=2. The prior missing released-source dependency is present on main.
  • pnpm tc, pnpm run audit:code-quality:native, pnpm run check:code-quality:changed a47e0f56578b, and pnpm run verify:localization-extraction
  • ORCA_BACKGROUND_LAUNCH=1 pnpm run build:electron-vite
  • Commit hooks: oxlint, React Doctor lint, and formatting
  • Current-head GitHub Actions CI passed: all five unit-test shards, relay integration, both packaging jobs, static analysis/typecheck, guards, final verification, test-selection evidence, Headless Node, and LoC.

AI Disclosure

The community patch was drafted with Claude (Anthropic, via Claude Code) under the author's direction; the author reproduced the bug, ran tests, and reviewed the diff before submitting.

Review

Reviewed account ownership, refresh identity, partial-write rollback, and WSL isolation. Fault injection reproduced and verified fixes for grant loss during a partial first switch and a blocked retry after partial rollback of a rotated grant. Folder workspaces use the same host credential path. A live SSH host was not exercised.

External Claude processes can still race Orca between a read and write; this change does not add cross-process locking. Conflicting live grants after a cold start intentionally block switching while preserving existing authorizations.

Agent skill upstream boundary

  • Not applicable; no agent skill source or sharing behavior changes.

Notes

Pullfrog was manually disabled while its review was queued; the associated pending check is stale, and GitHub rejected its rerun as a disabled workflow. All active CI workflows passed.

Rebased onto main at a47e0f56578b, retaining all three community commits and four maintainer commits. Credential code is unchanged by the rebase. One unrelated Windows PATH test freezes its clock to remove a one-millisecond timeout assertion flake; production preflight behavior is unchanged. The earlier duplicate-import failure and missing required-directory declaration were already fixed on main. The Windows prompt control and missing journal import are now fixed upstream; their redundant maintainer commit was dropped. Main also retains the test-only dependency required by the released-source cross-version suite. No production launch, journal, or wire behavior changes are included here.

Checklist

  • This PR is focused on preserving shared connector credentials
  • I explained the user-facing change, mechanism, and approach
  • Visual proof marked N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and folder-workspace impact considered
  • Current-head CI test/build matrix passed; focused tests, full typecheck, native and changed-code lint, localization extraction, and Electron build passed locally

@coderabbitai

coderabbitai Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Understand this PR’s impact

Explore downstream dependencies and potential security impact with Blast Radius.

View blast radius →

📝 Walkthrough

Walkthrough

The macOS Claude account-switching path uses a best-effort active Keychain read before writing managed credentials. Successful reads merge five machine-shared fields from the live credential. Missing shared fields are removed, and account-scoped fields remain unchanged. Invalid inputs and semantic no-ops preserve the target string. A failed active Keychain read no longer aborts account switching. Tests cover these behaviors.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to 6a341

Account switching can remove shared MCP credentials for malformed live data and may falsely detect unchanged credentials as refreshed. Fix both merge cases before merging.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning Issue [#16098] requires preservation of the active shared MCP credential state during account switching. mergeSharedClaudeCredentialFields correctly preserves live shared keys for the macOS Keychain… Read the live shared credentials before materializing the runtime credentials, then use the merged JSON for both writeRuntimeCredentials and the macOS Keychain write. Add a regression test that switches accounts and verifies that the runt…
✅ Passed checks (4 passed)
Check name Status Explanation
Out of Scope Changes check ✅ Passed The helper, Keychain integration, runtime-auth test changes, malformed-input tests, no-op tests, and read-failure test all support the shared-credential preservation objective in issue [#16098]. No un…
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 5 files.
Title check ✅ Passed The title clearly describes the main change: preserving shared MCP OAuth credentials when switching Claude accounts.
Description check ✅ Passed The description covers the required sections, links issue #16098, explains the change and rationale, and provides detailed testing, review, and checklist information. It also marks visual proof as not…
Full details: Linked Issues check

Explanation

Issue [#16098] requires preservation of the active shared MCP credential state during account switching. mergeSharedClaudeCredentialFields correctly preserves live shared keys for the macOS Keychain, including authoritative absence and malformed-input pass-through. However, doSyncForCurrentSelection calls writeRuntimeCredentials(credentialsJson) before it reads and merges the live Keychain values. The runtime credentials file therefore still receives the target snapshot without the live mcpOAuth state. The tests cover the Keychain path and read failures, but they do not establish preservation in the runtime credentials file.

Resolution

Read the live shared credentials before materializing the runtime credentials, then use the merged JSON for both writeRuntimeCredentials and the macOS Keychain write. Add a regression test that switches accounts and verifies that the runtime credentials file preserves live mcpOAuth and the other shared fields.

  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 8494688f-a6ed-4eaa-b184-7bbef6b8439f

📥 Commits

Reviewing files that changed from the base of the PR and between 8cf1c85 and 90b33d3dae4e13be63eec8cf510409e1edf82ab3.

📒 Files selected for processing (3)
  • src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts
  • src/main/claude-accounts/shared-credential-fields.test.ts
  • src/main/claude-accounts/shared-credential-fields.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

Comment on lines +274 to +277
const credentialsJsonForKeychain = mergeSharedClaudeCredentialFields(
credentialsJson,
liveCredentialsJson
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- target file outline ---'
ast-grep outline src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts
printf '%s\n' '--- target lines ---'
sed -n '230,295p' src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts
printf '%s\n' '--- writeRuntimeCredentials definitions and usages ---'
rg -n -C 5 'writeRuntimeCredentials' .

Repository: stablyai/orca

Length of output: 9730


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 19585


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- file storage implementation ---'
cat -n src/main/claude-accounts/runtime-auth/runtime-auth-file-storage.ts
printf '%s\n' '--- shared-field helper and related symbols ---'
rg -n -C 8 'mergeSharedClaudeCredentialFields|SharedClaudeCredential|MCP|mcp' src/main/claude-accounts/runtime-auth src/main | head -240
printf '%s\n' '--- runtime path and credential writer declarations ---'
rg -n -C 6 'getRuntimePaths|credentialsPath|writeActiveClaudeKeychainCredentialsForRuntime|readActiveClaudeKeychainCredentials' src/main/claude-accounts/runtime-auth

Repository: stablyai/orca

Length of output: 42306


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- helper ---'
cat -n src/main/claude-accounts/shared-credential-fields.ts
printf '%s\n' '--- helper references and tests ---'
rg -n -C 6 'mergeSharedClaudeCredentialFields|shared-credential-fields' src test tests 2>/dev/null || true

Repository: stablyai/orca

Length of output: 16751


Preserve shared fields in the file-backed write. writeRuntimeCredentials writes directly to paths.credentialsPath before the macOS Keychain merge. If the existing file contains mcpOAuth or another shared field, the account switch can overwrite it with the target account’s credential. Merge the current file credential before writeRuntimeCredentials, then use the merged value for the Keychain write as well.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — minor suggestions inline. The core fix is sound and its live-wins, absence-authoritative semantics match the claude-swap tool it cites.

Reviewed changes

  • shared-credential-fields.ts (new) — pure mergeSharedClaudeCredentialFields(target, live) plus SHARED_CLAUDE_CREDENTIAL_KEYS; overlays the live credential's mcpOAuth / mcpOAuthClientConfig / mcpXaaIdp / mcpXaaIdpConfig / pluginSecrets onto the target, live-wins including absence, and passes the target through unchanged when either side isn't a parseable claudeAiOauth object.
  • runtime-auth-sync.ts — reads the live active Keychain item immediately before the darwin write and merges its shared fields into the target credential, so an Orca-driven switch no longer drops MCP connector tokens.
  • shared-credential-fields.test.ts (new) — covers present / absent / malformed / raw-API-key inputs and non-shared siblings.

The shared-key classification and merge direction are correct: claude-swap's SHARED_CREDENTIAL_KEYS / merge_shared_credential_fields treat exactly these five keys as machine-shared and keep trustedDeviceToken account-scoped, which this diff matches. Two hygiene points and a broken reference are inline; nothing here blocks merge.

ℹ️ Nitpicks

  • The last test iterates SHARED_CLAUDE_CREDENTIAL_KEYS rather than asserting its contents, so removing a key from the constant would not fail any test. Pinning the five documented names would make the "covers every documented shared key" claim real.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ The follow-up commit is correct and covers what it claims. No new issues; the three suggestions from the previous review are unchanged, so this is comment-only rather than an approval.

Reviewed changes (since the previous review of 90b33d3)

  • No-op merge guard — mergeSharedClaudeCredentialFields now returns the target byte-for-byte when the serialized merge equals the target, so a no-op reformat (e.g. a dropped trailing newline) no longer looks like an external refresh downstream. Correct: merged is built by iterating the target's own entries in order and appending only live's shared keys, so the equality check fires exactly when live contributes no shared key.
  • New test — pins the trailing-newline no-op case against the guard.
  • Import reformat in the test file.

ℹ️ The no-op guard covers only the empty case

The guard returns early precisely when live carries no shared key, which is the case where the byte diff would have been formatting-only. When live does carry mcpOAuth / pluginSecrets, the written Keychain value still differs from lastWrittenCredentialsJson, so the read-back behavior flagged in the previous review is unchanged. This is not a correctness break — the merge still discards the target's copies and the persisted copy is never the source of truth — but the guard should not be read as a complete fix for that side effect.

Technical details
# No-op guard does not cover the non-empty merge

## Affected sites
- `src/main/claude-accounts/shared-credential-fields.ts:78-82` — early return only when `JSON.stringify(merged) === JSON.stringify(target)`.
- `src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts:264` — `writeRuntimeCredentials(credentialsJson)` sets `lastWrittenCredentialsJson` to the unmerged target.
- `src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts:278-281` — Keychain receives the merged value; `lastWrittenCredentialsJson` is not updated.
- `src/main/claude-accounts/runtime-auth/runtime-auth-readback.ts:21-26,95-98` — the merged Keychain candidate survives the filter and is persisted via `writeManagedCredentials`.

## Required outcome
- Only relevant if the maintainers want the shared fields kept out of per-account managed storage; the current behavior still copies them there on the first same-account sync after a switch that actually preserved MCP state.

## Open questions for the human
- Is persisting the shared fields into managed storage acceptable, or should read-back ignore the shared-key overlay when deciding whether the runtime credential changed?

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 102ea887-e65b-4b14-a254-27bc35e9c2dc

📥 Commits

Reviewing files that changed from the base of the PR and between 90b33d3dae4e13be63eec8cf510409e1edf82ab3 and a27b20600d1ce0a973253a935a030a180c987847.

📒 Files selected for processing (2)
  • src/main/claude-accounts/shared-credential-fields.test.ts
  • src/main/claude-accounts/shared-credential-fields.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 40943c1a-2a95-411b-910c-186c483bac7d

📥 Commits

Reviewing files that changed from the base of the PR and between a27b20600d1ce0a973253a935a030a180c987847 and 6a341bbd61738c0237b46e4d05a4cabbb7dbcbe5.

📒 Files selected for processing (5)
  • src/main/claude-accounts/runtime-auth-service-keychain-snapshots.test.ts
  • src/main/claude-accounts/runtime-auth-service-test-harness.ts
  • src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts
  • src/main/claude-accounts/shared-credential-fields.test.ts
  • src/main/claude-accounts/shared-credential-fields.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/claude-accounts/shared-credential-fields.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.

): string {
const target = parseCredentialObject(targetCredentialsJson)
const live = parseCredentialObject(liveCredentialsJson)
if (!target || !hasClaudeOauthObject(target) || !live) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '1,170p' src/main/claude-accounts/shared-credential-fields.ts
sed -n '1,180p' src/main/claude-accounts/shared-credential-fields.test.ts
sed -n '245,290p' src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts
rg -n 'claudeAiOauth|readAggregateClaudeKeychainCredentialsBestEffort|mergeSharedClaudeCredentialFields' src/main/claude-accounts

Repository: stablyai/orca

Length of output: 22905


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 29479


🏁 Script executed:

#!/bin/bash
printf '%s\n' '--- focused declarations and callers ---'
rg -n -A8 -B8 'mergeSharedClaudeCredentialFields|readAggregateClaudeKeychainCredentialsBestEffort|writeActiveClaudeKeychainCredentialsForRuntime|write.*Claude.*Credentials|credentialsJson' src/main/claude-accounts -g '*.ts' | head -n 520
printf '%s\n' '--- credential shape/parsing contracts ---'
sed -n '1,150p' src/main/claude-accounts/oauth-refresh.ts
sed -n '100,165p' src/main/claude-accounts/claude-auth-capture.ts
sed -n '1,145p' src/main/claude-accounts/runtime-auth/runtime-auth-keychain-snapshots.ts
printf '%s\n' '--- repository documentation and tests mentioning credential shape ---'
rg -n -i -g '*.md' -g '*.ts' -g '*.json' 'claudeAiOauth|mcpOAuth|malformed|Keychain|credential.*object|OAuth credential' . | head -n 420

Repository: stablyai/orca

Length of output: 42829


🏁 Script executed:

sed -n '80,125p' src/main/claude-accounts/runtime-auth/runtime-auth-keychain-snapshots.ts
sed -n '1,120p' src/main/claude-accounts/runtime-auth/runtime-auth-snapshot-capture.ts
rg -n -A12 -B12 'readAggregateClaudeKeychainCredentialsBestEffort|mergeSharedClaudeCredentialFields' src/main/claude-accounts/runtime-auth src/main/claude-accounts/*.test.ts
rg -n -i -g '*.md' -g '*.ts' 'claudeAiOauth|mcpOAuth|malformed|credential.*object|OAuth credential' . | head -n 300

Repository: stablyai/orca

Length of output: 42241


🏁 Script executed:

cat -n src/main/claude-accounts/runtime-auth/runtime-auth-keychain-snapshots.ts | sed -n '88,125p'
cat -n src/main/claude-accounts/runtime-auth/runtime-auth-snapshot-capture.ts | sed -n '45,65p'
cat -n src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts | sed -n '265,282p'
rg -n -A10 -B10 'readAggregateClaudeKeychainCredentialsBestEffort' src/main/claude-accounts

Repository: stablyai/orca

Length of output: 10999


🏁 Script executed:

rg -n -A45 -B12 'export async function readActiveClaudeKeychainCredentials|function readActiveClaudeKeychainCredentials|const readActiveClaudeKeychainCredentials' src/main/claude-accounts/keychain.ts
cat -n src/main/claude-accounts/keychain.ts | sed -n '1,125p'

Repository: stablyai/orca

Length of output: 7582


Validate the live credential OAuth shape before merging.

When live is {} or has claudeAiOauth: null, the current guard accepts it. The loop then treats every shared key as absent and deletes those keys from a valid target credential. This violates the malformed-input pass-through contract and can remove MCP credentials during account switching.

Require hasClaudeOauthObject(live) here. Add live cases for missing, null, and primitive OAuth values.

Proposed fix
-  if (!target || !hasClaudeOauthObject(target) || !live) {
+  if (!target || !hasClaudeOauthObject(target) || !live || !hasClaudeOauthObject(live)) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (!target || !hasClaudeOauthObject(target) || !live) {
if (!target || !hasClaudeOauthObject(target) || !live || !hasClaudeOauthObject(live)) {

for (const key of SHARED_CLAUDE_CREDENTIAL_KEYS) {
const targetHasKey = key in target
if (key in live) {
if (!targetHasKey || JSON.stringify(live[key]) !== JSON.stringify(target[key])) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '53,100p' src/main/claude-accounts/shared-credential-fields.ts
rg -n -C 6 'lastWrittenCredentialsJson|readBackRefreshedTokens|externally|refresh|JSON.stringify' src/main/claude-accounts/runtime-auth src/main/claude-accounts

Repository: stablyai/orca

Length of output: 45535


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- helper and direct callers ---'
rg -n -C 12 'mergeSharedClaudeCredentialFields' src/main/claude-accounts
printf '%s\n' '--- runtime state relevant methods ---'
sed -n '1,150p' src/main/claude-accounts/runtime-auth/runtime-auth-runtime-state.ts
printf '%s\n' '--- focused helper tests and shared-field references ---'
rg -n -C 10 'shared-credential-fields|mcpOAuth|mcpOAuthClientConfig|hasUnchangedRuntimeCredentials|lastWrittenCredentialsJson' src/main/claude-accounts --glob '*test.ts' --glob '*.ts' | head -n 700

Repository: stablyai/orca

Length of output: 42782


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- sync write path ---'
sed -n '240,292p' src/main/claude-accounts/runtime-auth/runtime-auth-sync.ts
printf '%s\n' '--- keychain writer and readers ---'
rg -n -C 12 'function writeActiveClaudeKeychainCredentialsForRuntime|const writeActiveClaudeKeychainCredentialsForRuntime|writeActiveClaudeKeychainCredentialsForRuntime|readActiveClaudeKeychainCredentialsBestEffort|readAggregateClaudeKeychainCredentialsBestEffort' src/main/claude-accounts

Repository: stablyai/orca

Length of output: 38420


Compare shared JSON values structurally.

When a shared value has identical object content but a different nested key order, JSON.stringify reports a difference. The helper then rewrites the target with changed = true. The read-back path compares credential strings exactly, so this formatting-only rewrite can be treated as an external refresh. Compare parsed JSON values structurally, ignoring object key order while preserving array order, and add a no-op test for reordered nested keys.

🧰 Tools
🪛 ast-grep (0.45.3)

[error] 76-87: Recursive/iterative merge copies attacker-controllable keys from a source object into a target via a computed property assignment without rejecting dangerous keys, allowing prototype pollution. Skip or block "proto", "constructor", and "prototype" keys (e.g. if (key === "__proto__" || key === "constructor" || key === "prototype") continue;), use a null-prototype object (Object.create(null)), or use a safe merge utility instead.
Context: for (const key of SHARED_CLAUDE_CREDENTIAL_KEYS) {
const targetHasKey = key in target
if (key in live) {
if (!targetHasKey || JSON.stringify(live[key]) !== JSON.stringify(target[key])) {
merged[key] = live[key]
changed = true
}
} else if (targetHasKey) {
delete merged[key]
changed = true
}
}
Note: [CWE-1321] Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution').

(prototype-pollution-recursive-merge-typescript)

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in this follow-up. The three changes land correctly, the two actionable threads from the prior review are addressed, and the known Keychain read-back divergence stays intentionally tracked (and its thread open), so this is comment-only rather than an approval.

Reviewed changes (since the prior pullfrog review of a27b206)

  • Key-order-preserving merge — mergeSharedClaudeCredentialFields now shallow-copies the target and reassigns only the per-key values that actually differ (or deletes shared keys absent from live), so a same-value shared key sitting before a target-only key no longer causes a formatting-only rewrite that read-back would misread as an external refresh.
  • claudeAiOauth shape check — hasClaudeOauthObject rejects a null/array/primitive claudeAiOauth on the target before merging, instead of only checking key presence.
  • Best-effort live read — the merge's live Keychain read now goes through readAggregateClaudeKeychainCredentialsBestEffort, so a transient security read failure skips the merge instead of aborting the account switch and restoring the system-default snapshot.
  • Tests — null/primitive claudeAiOauth, interleaved key order (unchanged and changed), a failed live read not aborting the switch, and assertion of the five shared key names. Both touched test files pass (32 tests).

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the fix/preserve-mcpoauth-on-account-switch branch 3 times, most recently from 83ccda3 to 5e4d6cd Compare October 5, 2026 09:00

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found. The expanded reconciliation is well-scoped and covered; the one prior open thread is now addressed.

Reviewed changes (since the prior pullfrog review of 6a341bb)

  • Cross-store reconciliation — shared-credential-fields.ts adds reconcileSharedClaudeCredentialFields, resolving mcpOAuth / mcpOAuthClientConfig per server (each server's access+refresh pair stays atomic) and the other three keys whole, against a committed baseline; conflicting changed values for the same server abort the switch rather than guessing freshness.
  • Applied at every write and restore boundary — runtime-auth-runtime-state.ts::mergeLiveRuntimeSharedCredentials is now used by sync, read-back, system-default snapshot restore, and account clear, not just the account-switch Keychain write.
  • Committed baseline — lastWrittenSharedCredentialsJson advances only after the file and (darwin) both Keychain stores succeed, so a partial rollback cannot turn a preserved grant into a revocation.
  • Managed-storage exclusion — shared fields are stripped on managed credential write/read and ignored in credential comparisons (accountCredentialFieldsEqual), so account snapshots neither freeze nor re-duplicate rotating connector tokens.
  • Failure hardening — strict Keychain reads and malformed or unreadable live credentials now stop the write before shared tokens are overwritten.
  • Tests — reconciliation, partial-write rollback/retry, and cross-platform switch/restart/restore coverage added; 70 focused tests pass locally.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the fix/preserve-mcpoauth-on-account-switch branch from 5e4d6cd to e1f1b53 Compare October 5, 2026 19:11

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

The delta since the prior Pullfrog review is a single test-only commit; no credential or production behavior changed.

  • Freeze Date.now in the Windows PATH probe test — preflight-host-cli-status.test.ts pins Date.now to 1_000 so probeRunnableLocalCommand's deadline - Date.now() timeout resolves to exactly 5000, removing the one-millisecond CI flake (a real-time gap can make it 4999).
  • Restore spies after each test — afterEach now calls vi.restoreAllMocks() so the new Date.now spy does not leak into later tests.

The clock-freeze is the correct fix: the assertion at preflight-host-cli-status.test.ts:610 expects timeout: 5000, which is only guaranteed when both Date.now() reads in preflight-command-exec.ts:167-169 see the same instant. The file is the only change in the range, and the suite passes (25 tests).

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the fix/preserve-mcpoauth-on-account-switch branch 2 times, most recently from 0c16da7 to 40b1b4c Compare October 6, 2026 00:39

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

The delta since the prior Pullfrog review is test-only; no credential or production behavior changed.

  • Corrected the Windows prompt-carry expectations — startup-line-prompt-carry.test.ts now asserts a short multi-line prompt is carried on a PowerShell host that can prove the agent is in front, and pins hasControlByte(launchCommand) false. This matches quotePowerShellLiteral → quotePowerShellMultilineLiteral (src/shared/powershell-native-argument.ts:15), which collapses \n→`n / \r→`r onto one physical line, so the line is 210 bytes with no control byte and startupLineCarriesPrompt returns true; the previous blanket false expectation was wrong.
  • Restored the missing journal-test import — journal-submission-positions.test.ts imports codexProviderHandle, which the fixture already used for IDENTITY.providerHandle. Base main carried the usage without the import; this repairs it.

Both files pass (34 tests). All prior Pullfrog threads are resolved.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

tomarai85 and others added 7 commits October 5, 2026 18:46
… account switch

Orca's account switch writes the target managed account's own stored credential
verbatim to the global "Claude Code-credentials" Keychain item. That credential
never carries mcpOAuth/mcpOAuthClientConfig/mcpXaaIdp/mcpXaaIdpConfig/pluginSecrets
(they are machine-shared MCP connector state, not per-account), so every switch
silently drops any MCP connections the previous session had.

Merge the live credential's copy of these shared fields into the target credential
right before the Keychain write, live-wins (absence included), mirroring how the
third-party claude-swap tool already treats this exact shared Keychain item.

Fixes stablyai#16098
…nothing changed

mergeSharedClaudeCredentialFields always re-serialized via JSON.stringify, even when
the shared-key set was identical on both sides. The reformatted-but-semantically-equal
JSON (e.g. missing the original trailing newline) then read as an external Claude Code
refresh to the read-back byte-equality check in runtime-auth-sync, causing every
subsequent sync to wrongly adopt it into managed credential storage.

Return the original string when the merge changes nothing.
…egrade Keychain read failures

Address CodeRabbit/pullfrog follow-up review on the shared-credential merge:

- parseCredentialObject accepted claudeAiOauth as null or a primitive; the merge would
  then serialize the malformed target instead of passing it through unchanged. Validate
  it is a non-null object (hasClaudeOauthObject) before merging.
- The no-op guard compared whole-object JSON.stringify output, so an existing shared key
  interleaved among target-only keys got moved to the end of the rebuilt object even when
  its value did not change, producing a formatting-only rewrite. Compare per shared key
  and keep the target's own key order via object spread instead.
- runtime-auth-sync read the live Keychain credential for the merge with the raw
  (non-best-effort) function, so a transient Keychain read error aborted the whole
  account switch instead of just skipping the merge. Use the inherited
  readAggregateClaudeKeychainCredentialsBestEffort, matching every other Keychain read
  in this subsystem.
- Fixed a dead citation URL (scaryghost/claude-swap 404s; the real repo is
  realiti4/claude-swap, verified to contain the cited SHARED_CREDENTIAL_KEYS /
  merge_shared_credential_fields).
- Added docstrings to every function touched by this change.

Tests: 5 new cases (null/primitive claudeAiOauth, interleaved shared key no-op and
update, Keychain read failure does not abort the switch).
…dential writes

Keep live MCP grants in both runtime files and keychain items, excluding shared secrets from managed account capture and refresh read-back. Preserve rotations and revocations through default restoration and reject unreadable live state before destructive writes.
Before Orca has a last-written baseline, a missing shared field in one store cannot prove revocation. Carry present fields from the other live stores, prioritizing a proved newer refresh candidate when available.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Switching Claude accounts wipes MCP OAuth tokens (they live in the same keychain blob)

2 participants