Skip to content

refactor(host): route secret storage through a SecretStore port - #15916

Merged
nwparker merged 5 commits into
mainfrom
nwparker/secret-store-port
Aug 22, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/secret-store-port

Conversation

@nwparker

@nwparker nwparker commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​252 $\color{#cf222e}{\Huge{\mathbf{−}}}$​107 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​145
Prod 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​172 $\color{#cf222e}{\Huge{\mathbf{−}}}$​33 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​139

ELI5

Orca stores secrets (Linear tokens, Jira credentials, your OpenAI speech key) encrypted on disk. Today the code asks Electron to do that encryption, by calling safeStorage directly in five different places.

That works fine on the desktop — but it means those five files can only ever run inside Electron. And we want the Orca runtime to also run as a small plain-Node server on a remote machine, where there is no Electron.

This PR puts a thin interface in the middle. The code now asks for "the secret store" instead of asking Electron specifically. On the desktop we hand it an implementation that is a direct pass-through to safeStorage — same behaviour, same bytes on disk. Later, a Node server can hand it a different one.

Nothing changes for users today. This is the plumbing that makes a Node-only backend possible.

What changed

File Why
src/shared/secret-store.ts The port: isEncryptionAvailable / encryptString / decryptString, mirroring safeStorage exactly, plus a settable registry.
src/main/host/electron-secret-store.ts The desktop adapter — a pass-through to safeStorage.
src/main/index.ts Installs the adapter at the top of the pre-ready bootstrap.
5 production modules safeStorage.x() → getSecretStore().x().
config/scripts/vitest-secret-store-setup.ts Installs an in-memory store before each test.
12 test files Suites that drive encryption availability now install their own fake.

Two deliberate design decisions

1. getSecretStore() throws until installed — it does not fall back.
A silent default would report "encryption unavailable" and write real credentials in plaintext before anyone noticed. Failing at the first read makes a missing setSecretStore() obvious at startup instead of silently downgrading a security posture. Verified that no other entrypoint reaches these modules (checked daemon-entry, relay, cli/index, and every worker/forked entry by bundling each and inspecting the metafile — all clean), so installing in src/main/index.ts alone is sufficient.

2. The port stays free of node: imports.
src/shared/** is in the web build graph (config/tsconfig.tc.web.json includes ../src/shared/**/*, and 3,701 renderer files import from it). A require('node:os') here would ship Node into the renderer bundle. The Node-flavoured test default lives in the vitest setup file instead, which is not in that graph.

One small piece of new surface

describeUnavailable(): string | null. Today, when sealing is unavailable, the only signal is a console.warn nobody reads — the credential silently lands in plaintext. This returns a user-safe, platform-specific sentence ("The OS keyring is unavailable… install and unlock gnome-keyring or kwallet") so a later PR can actually surface it. Not wired to UI yet; no behaviour change.

Proof of no regressions

Check Result
CI, full sharded run 47/47 checks pass
Full local suite, whole stack 6,070 files / 57,140 tests pass, 0 failures
Baseline: full local suite on main 57,173 tests pass, 0 failures — same shape
All suites touching secret storage 68 files / 822 tests pass
pnpm typecheck (node + web + cli projects) clean
oxlint (full repo) clean
A note on local full-suite noise, since it is worth being precise about

An early local full-suite run of this branch showed 1 failure (pty-login-shell-startup-commands), and a re-run showed 6 different failures with no overlap — while two suites were competing for the same machine. That test depends on LOGIN_PREFLIGHT_TIMEOUT_MS = 500 (src/main/providers/macos-tcc-login-shell.ts:17), a real wall-clock deadline that a saturated 16-worker run can blow. Run alone, the suite is clean, and CI — sharded across dedicated runners — is 47/47. The load-contended runs were measuring the machine, not the diff.

| Pre-commit hooks (oxlint, react-doctor, oxfmt) | clean |

Why the desktop cannot behave differently: ElectronSecretStore is a pass-through with no added logic, installed before any code path can read a credential. The plaintext-fallback branches are untouched. Ciphertext format is unchanged, so existing sealed credentials keep decrypting.

Test-wiring honesty: 55 of the 67 suites that mocked electron.safeStorage pass untouched — the global setup satisfies them. The 12 that actually assert on availability were migrated to install their own fake with identical behaviour (same encrypted: prefix, same toggle variable), so no assertion was weakened. That 55/12 split is itself evidence: the suites that broke are exactly the ones that were genuinely exercising this behaviour.

User-facing trade-offs

None. No UI, no wire format, no on-disk format, no CLI surface changes. This is a pure refactor plus one unused accessor.

Review loops

Round Reviewer Outcome
1 Grok 4.6 (adversarial, design-level) 3 blockers + 4 serious against the parent design doc. All independently verified; 2 adopted as written, 1 downgraded with evidence (see below). None applied to this PR's diff.
2 Grok 4.6 (adversarial, this diff) Requested: init-order hazards, missed entrypoints, vi.resetModules interaction, whether the global test default hides real bugs.

Verdict: ready to merge. The diff is mechanical, the behaviour is provably identical, and the risky part (an uninstalled store) fails loudly rather than silently.

Design-review findings that shaped this PR

Review correctly caught that an earlier draft of the parent design doc overclaimed its spike ("serves runtime RPC" when it had only proven load-and-bind), and that the Node floor claim was wrong. Both are now corrected in the design doc. The finding that did shape this PR: do not ship a bundler-level electron shim — it makes every call site look fine while silently returning a lie. That is why this PR uses a real typed port with a throwing registry instead.

Follow-ups (not in this PR)

  • AppEnvironment port — the same treatment for app.getPath('userData') (37 call sites across 17 files). Branch ready.
  • Surfacing describeUnavailable() through the runtime's degradation contract.

Every at-rest secret in the main process went through `electron.safeStorage`
directly, which is one of the couplings that stops the Orca runtime from
booting on plain Node. Introduce `SecretStore` as the seam.

- `src/shared/secret-store.ts` — the port plus a settable registry. `getSecretStore()`
  throws until an entrypoint installs one: a silent default would answer
  "encryption unavailable" and write real credentials in plaintext before anyone
  noticed. Kept free of `node:` imports because `src/shared/**` is in the web
  build graph.
- `src/main/host/electron-secret-store.ts` — the desktop adapter, a pass-through
  to `safeStorage`. Installed at the top of the pre-ready bootstrap, before any
  step can touch a credential; constructing it does not call `safeStorage`, so it
  stays clear of the pre-ready Keychain service-name resolution below it.
- `describeUnavailable()` is new surface, not a port of existing behaviour. When
  sealing is unavailable today the only signal is a console warning; this returns
  a user-safe, platform-specific sentence so the degradation can be surfaced.

No behaviour change on the desktop: the adapter is a pass-through and the
plaintext-fallback paths are untouched.

Test wiring: a vitest setup file installs an in-memory store before each test, so
55 of the 67 suites that mocked `electron.safeStorage` pass untouched. The 12
that actually drive availability now install their own fake, which wins because
it registers later.

Verified: 68 files / 822 tests pass; `tsc -p tsconfig.node.json` and
`tsconfig.tc.web.json` clean; `oxlint` clean.
@coderabbitai

coderabbitai Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b4b63f95-4e32-4962-899b-f895bad81804

📥 Commits

Reviewing files that changed from the base of the PR and between 1badde9 and 3e92d73.

📒 Files selected for processing (1)
  • src/shared/secret-store.ts

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


📝 Walkthrough

Walkthrough

The pull request adds a shared SecretStore abstraction with registry functions and tests. It adds an Electron-backed implementation with platform-specific unavailable-encryption messages. Startup registers this implementation before credential-dependent initialization. Credential, token, API-key, and protected-secret persistence modules now use the shared store. Vitest setup and individual tests inject shared in-memory or configurable secret stores instead of mocking Electron’s safeStorage API.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the implementation and validation well, but it omits required sections such as Linked Issue, Visual Proof/N/A, Notes, and Checklist. Add the missing template sections, including a linked issue, visual-proof status, notes, checklist, and required testing confirmations.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring check was indeterminate for this PR — some files could not be analyzed in time. Not blocking.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: routing host secret storage through a SecretStore port.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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: 3

🧹 Nitpick comments (1)
config/scripts/vitest-secret-store-setup.ts (1)

4-13: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten this block comment.

The comment explains implementation details across ten lines. Keep only the non-obvious test contract.

As per coding guidelines, “Comments must be concise, non-obvious, and brief—prefer one line; do not explain obvious behavior or walk through code.”

Proposed change
-/**
- * Why: `getSecretStore()` throws until an entrypoint installs a store, which is the
- * right production behaviour but would fail ~67 suites that only ever cared that
- * *some* store existed. Install a reversible in-memory one before every test so
- * those suites stay unchanged; a suite that asserts on sealing behaviour calls
- * `setSecretStore()` itself and wins, because this runs first.
- *
- * Deliberately not a plaintext passthrough: encryptString must return something a
- * test can tell apart from the input, or a test that forgot to seal would pass.
- */
+// Install a reversible store before each test. Local test setup can replace it.
+// Prefix ciphertext so tests can detect unsealed values.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b1641b6b-7922-4dbc-b5cc-3091abda998f

📥 Commits

Reviewing files that changed from the base of the PR and between 6b51ef4 and 4c4ea6b.

📒 Files selected for processing (23)
  • config/scripts/vitest-secret-store-setup.ts
  • config/vitest.config.ts
  • src/main/bitbucket/credential-connection.test.ts
  • src/main/bitbucket/credential-store.test.ts
  • src/main/bitbucket/status-no-decrypt.test.ts
  • src/main/host/electron-secret-store.ts
  • src/main/index.ts
  • src/main/integration-credential-file.ts
  • src/main/jira/client.test.ts
  • src/main/jira/site-credential-store.ts
  • src/main/linear/client.test.ts
  • src/main/linear/linear-token-store.ts
  • src/main/persistence-protected-secret-fail-closed.test.ts
  • src/main/persistence-protected-secret-write-race.test.ts
  • src/main/persistence-proxy-secret-recovery.test.ts
  • src/main/persistence-single-serialize.test.ts
  • src/main/persistence-ui-state.test.ts
  • src/main/protected-secret-persistence.test.ts
  • src/main/protected-secret-persistence.ts
  • src/main/speech/openai-api-key-store.test.ts
  • src/main/speech/openai-api-key-store.ts
  • src/shared/secret-store.test.ts
  • src/shared/secret-store.ts

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

Comment on lines +9 to +10
isEncryptionAvailable(): boolean {
return safeStorage.isEncryptionAvailable()

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- Electron declarations ---'
rg -n --hidden \
  --glob 'package.json' \
  --glob 'package-lock.json' \
  --glob 'pnpm-lock.yaml' \
  --glob 'yarn.lock' \
  '"electron"' .

printf '%s\n' '--- Secret store implementation ---'
cat -n src/main/host/electron-secret-store.ts

printf '%s\n' '--- Relevant tests and consumers ---'
rg -n -C 5 \
  --glob '*.{test,spec}.{ts,tsx,js,jsx}' \
  'ElectronSecretStore|safeStorage|getSelectedStorageBackend|basic_text|describeUnavailable|isEncryptionAvailable' \
  src

Repository: stablyai/orca

Length of output: 50370


🌐 Web query:

Electron 43.1.0 safeStorage getSelectedStorageBackend basic_text API

💡 Result:

In Electron, the safeStorage.getSelectedStorageBackend() API is a Linux-specific method used to identify the underlying password management system being utilized for encryption [1][2]. The value basic_text is returned when the desktop environment is not recognized or when the command-line flag --password-store="basic" is explicitly provided [1][3]. When safeStorage reports basic_text as the backend, it indicates that a secure system secret store (such as GNOME Libsecret or KWallet) is not available or not configured, and items stored via the safeStorage API are encrypted using a hardcoded plaintext password, meaning they are essentially unprotected [1][3]. This API is only available on Linux [1][4]. If called before the Electron application has emitted the ready event, it will return unknown [1][3]. Other possible return values include gnome_libsecret, kwallet, kwallet5, and kwallet6, depending on the desktop environment and configuration [1][3].

Citations:


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- package metadata ---'
sed -n '195,220p' package.json
rg -n --hidden \
  --glob 'package-lock.json' \
  --glob 'pnpm-lock.yaml' \
  --glob 'yarn.lock' \
  'electron(@|":|:)' . | head -80

printf '%s\n' '--- secret-store consumers and default wiring ---'
rg -n -C 4 \
  'ElectronSecretStore|describeUnavailable\(\)|getSecretStore\(\)\.isEncryptionAvailable|isEncryptionAvailable\(\)' \
  src/main src/shared \
  --glob '*.{ts,tsx}' | head -240

printf '%s\n' '--- focused test file candidates ---'
git ls-files 'src/main/*secret*' 'src/shared/*secret*' '*electron-secret-store*' '*secret-store*'

Repository: stablyai/orca

Length of output: 18398


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- Electron 43.1.0 safe-storage documentation ---'
curl -fsSL \
  https://raw.githubusercontent.com/electron/electron/v43.1.0/docs/api/safe-storage.md |
  rg -n -C 5 \
  'getSelectedStorageBackend|basic_text|isEncryptionAvailable|ready'

printf '%s\n' '--- Electron 43.1.0 type declaration ---'
curl -fsSL \
  https://raw.githubusercontent.com/electron/electron/v43.1.0/electron.d.ts |
  rg -n -C 3 'getSelectedStorageBackend|isEncryptionAvailable'

printf '%s\n' '--- initialization context ---'
sed -n '820,885p' src/main/index.ts
rg -n -C 5 \
  'app\.whenReady|whenReady\(|ready|describeUnavailable|setSecretStore' \
  src/main/index.ts src/main src/shared \
  --glob '*.{ts,tsx}' | head -260

Repository: stablyai/orca

Length of output: 4144


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- bootstrap and readiness context ---'
sed -n '1,80p' src/main/index.ts
sed -n '780,875p' src/main/index.ts
rg -n -C 8 \
  'bootstrap|app\.whenReady|whenReady\(|setSecretStore|describeUnavailable' \
  src/main/index.ts src/main \
  --glob '*.{ts,tsx}' | head -320

printf '%s\n' '--- all direct availability descriptions ---'
rg -n -C 6 \
  'describeUnavailable\(' \
  src/main src/shared \
  --glob '*.{ts,tsx}'

Repository: stablyai/orca

Length of output: 36802


Treat Linux basic_text as unavailable.

On Linux, safeStorage.isEncryptionAvailable() can return true for the unprotected basic_text backend. Check safeStorage.getSelectedStorageBackend() and return false for basic_text. Make describeUnavailable() use the same availability predicate, and add Linux backend coverage for both methods.

Comment thread src/shared/secret-store.ts Resolved
The safety argument for this refactor is that the desktop byte path did not
change. That only holds if the adapter forwards without re-encoding, so assert it
directly: same argument in, same buffer/string back out, availability read live
rather than cached, and a round trip through the real safeStorage pair standing in
for a previously sealed credential.

A live OS-keychain round trip was attempted against the built app and blocked on a
macOS keychain prompt that cannot be answered from a headless shell; this covers
the same contract deterministically.

@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

🧹 Nitpick comments (1)
src/main/host/electron-secret-store.test.ts (1)

19-21: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Shorten the explanatory comment.

Keep the contract note to one brief line. For example: // Verify that the adapter preserves safeStorage bytes verbatim.

Proposed comment change
-  // Why this shape: the whole safety argument for the SecretStore refactor is that the
-  // desktop byte path did not change. That is only true if this adapter forwards
-  // verbatim — same argument, same return value, no re-encoding.
+  // Verify that the adapter preserves safeStorage bytes verbatim.

Source: Coding guidelines


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 42da15e7-bab1-4a67-acac-8d7ec659a0d2

📥 Commits

Reviewing files that changed from the base of the PR and between 4c4ea6b and 2e76692.

📒 Files selected for processing (1)
  • src/main/host/electron-secret-store.test.ts

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

@nwparker

Copy link
Copy Markdown
Contributor Author

CI note: one shard failed once on orca-runtime.test.ts > fences provider resume and reveals one exact live legacy worker without stealing focus, then passed on rerun.

Classified as flake, not a regression:

  • That file is untouched by this PR (git diff origin/main..HEAD -- src/main/runtime/orca-runtime.test.ts is empty).
  • It passes 3/3 locally on this branch.
  • An earlier CI run of this same branch was 47/47 green.
  • The rerun is green.

Flagging rather than burying it, since "rerun until green" is how real regressions get shipped.

…rading

Review caught that encryptionAvailable() wrapped getSecretStore() in the same
try that absorbs a keyring probe failure. The two are not the same: a missing
setSecretStore() is a startup bug, and swallowing it made encrypt() hand back an
empty blob while decryptWithStatus() reported 'unavailable' — a real secret
silently not stored, which is the outcome the port throws to prevent.

Regression test verified in both directions: it fails against the old code.

Also from review: the contract comment claimed every caller degrades by storing
plaintext, but persistence retains the prior sealed blob; and an adapter test
claimed to prove previously sealed credentials still open while safeStorage is
mocked, which it cannot. Both now say what is actually true.
@nwparker

Copy link
Copy Markdown
Contributor Author

Review feedback applied

Three of the four inline comments were correct and are fixed. One is a real finding but out of scope for this PR — flagged below rather than silently changed.

Fixed — fail-fast regression (the important one)

encryptionAvailable() wrapped getSecretStore() in the same try that absorbs a keyring probe failure. Those are not the same failure. On main the try only ever caught safeStorage.isEncryptionAvailable() throwing — a genuine OS keyring failure, where false is the right answer. Moving the port call inside it meant a missing setSecretStore() — a startup bug — also became false, so encrypt() returned an empty blob and decryptWithStatus() reported unavailable: a real secret silently not stored. That is precisely the outcome the port throws to prevent, so this was a regression I introduced.

getSecretStore() now sits outside the try; only the backend probe may fail softly.

The regression test is verified in both directions — restoring the old code makes it fail with expected [Function] to throw an error.

I also audited the other call sites for the same shape. integration-credential-file.ts:114 calls isEncryptionAvailable() outside its try, and the two remaining getSecretStore() calls in this file run only after that check has already succeeded. This was the only instance.

Fixed — contract comment was factually wrong

It claimed every caller degrades by storing plaintext. protected-secret-persistence.ts:57-68 retains the prior sealed blob instead. Corrected to say degradation is consumer-specific, and shortened per the comment guideline.

Fixed — test claimed more than it proved

round-trips through the real safeStorage pair, so previously sealed credentials still open runs against a mocked safeStorage, so it cannot prove legacy-ciphertext compatibility. Renamed to pairs encryptString and decryptString without altering the payload, with a comment noting real compatibility needs a captured fixture.

Not fixed — Linux basic_text (valid, but pre-existing and out of scope)

The point is correct: on Linux safeStorage.isEncryptionAvailable() returns true for the basic_text backend, which is obfuscation, not encryption — so Orca reports secrets as sealed when they effectively are not.

But getSelectedStorageBackend appears nowhere in this repo, and main already calls bare safeStorage.isEncryptionAvailable(). This adapter is a deliberate pass-through, and this PR claims zero behaviour change. Adding the backend check would flip existing Linux users from sealed to degraded and change how their stored secrets are persisted — a security-posture change that deserves its own PR, its own migration thinking, and its own review, not a quiet inclusion in a refactor.

Worth doing. Not here.

vi.resetModules() hands the re-imported graph a fresh copy of this module, so a
store installed before the reset read back as uninstalled. That was survivable
while the getter degraded silently; now that it throws, it is a hard failure in
any suite that resets modules.
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.

1 participant