Skip to content

fix(runtime): a device registry save never resurrects a device removed on disk - #35483

Merged
nwparker merged 2 commits into
mainfrom
nwparker/device-registry-merge
Oct 29, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/device-registry-merge

Conversation

@nwparker

@nwparker nwparker commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​173 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​172
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​89 $\color{#cf222e}{\Huge{\mathbf{−}}}$​27 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​62

ELI5

orcad stores the devices allowed to connect in orca-devices.json on the host. An admin can revoke a desktop or phone by removing its row from that file. But orcad also kept its own copy of the list in memory and rewrote the whole file from that copy on routine bookkeeping saves ("last seen" times, written about 250 ms after any connection and again on shutdown). If one of those saves landed after the admin's edit, the revoked device came back, silently. This makes every save re-read the file and apply only orcad's own change, so a removed device stays removed.

What Changed

  • DeviceRegistry.save now writes through writeMergedDeviceRegistry (new device-registry-disk-merge.ts). It re-reads the file and writes the in-memory change merged over what is on disk:

    • a row this process knew of that is gone from disk stays gone, and is dropped from memory too;
    • rows another writer added to the file are kept;
    • this save's own adds, removals and row updates apply.
  • Every save returns what it wrote, and memory takes that result. All write paths go through save, so all of them are covered: device add, pending-offer rotate and reach change, delegated mobile children, remove, key fork, idle ephemeral prune, relay binding, push registration, connection mode, first-sighting lastSeen, the deferred lastSeen flush, and the shutdown flush (runtime-rpc-shutdown).

  • The load-time cleanup that drops the previous run's session-only rows passes the raw file as "before", so those rows are removed rather than re-added from disk.

  • Removal tombstones (review). DeviceRegistryWriter remembers every id this process removes. That covers any save's removals, and the load-time session-only cleanup, recorded even if that save fails. Those ids are never adopted from disk again. Without this, a stale writer could put a revoked row back (an old orcad's flush during an SSH relaunch or upgrade overlap, or an external tool), and the next save would treat it as new on disk and let it authenticate.

  • replaceRow returns false when the merge dropped the row because it was removed on disk. Callers already treat false as "device gone":

    • relay binding: no demand-state change;
    • push registration: not_mobile;
    • connection mode: the pairing is refused and the relay revoke is queued.

    getOrCreatePendingDevice mints a fresh offer instead of handing out a revoked pending one.

  • If the file has become unreadable or corrupt since load, the save is written as before. That case proves nothing about removals, and the existing unreadable and corrupt guards still apply.

  • The write is still the secure-file atomic path: a restricted temp file, then a rename, durable where it was.

  • tests/e2e/ssh-orcad-pairing-repair.spec.ts logs the registry's device ids, never tokens, right after the server is killed and after the reconnect, so a resurrected row shows up in CI logs.

Why

This is a security bug. A host admin's device revoke could be undone without any trace, depending on timing. It surfaced as the intermittent ssh-orcad-pairing-repair failure: the pane answered, but no re-pair happened because the revoked row had been written back. #35341 was suspected; its change (the daemon spawn order) doesn't touch the registry.

Semantics to note:

  • Deleting orca-devices.json now revokes every device this process knew of at its next save. Removal wins, as intended.
  • An in-place external edit of a row's fields, such as renaming a device, is last-writer-wins: orcad's next save writes its own version of the rows it knows.

What remains: memory picks up an external removal at its next save, not instantly. Authentication from a removed device can still pass until then, which at most is the next lastSeen flush, 250 ms after any connection. Watching the file is a possible follow-up.

Flag-off: this changes behavior with ORCA_INTERNAL_WSL_HOSTS unset too. The registry is used by orcad on SSH hosts, by the desktop runtime and by mobile pairing.
User-risk: low. Each registry save now reads the file first, a small JSON file, at the existing write points only. Devices revoked outside Orca stay revoked; nothing else changes for paired devices. Two reviewers, please.

Linked Issue

Internal WSL-via-orcad tracker; the ssh-orcad-pairing-repair sweep failure.

Visual Proof

N/A: no UI.

Testing

  • New device-registry-external-edit.test.ts:
    • a removal on disk survives a pending lastSeen flush (fake timers);
    • it survives the shutdown flush (flushPendingLastSeen);
    • it survives this process adding a device meanwhile;
    • another writer's add survives this process removing a different device;
    • the previous run's session-only rows are still dropped at load.
    • a device this process removed stays removed when a stale writer puts it back: fix-reviewer's repro;
    • a session-only row stays removed when its load-time cleanup save failed;
    • a row update (connection mode) on a row removed on disk returns false and keeps it removed.
  • The first four fail on main, and the last three fail on the previous head 9c77824.
  • src/main/runtime: 15024 pass. One failure, runtime-failed-local-worktree-removal, also fails on main without this change. The registry consumers in wsl, orcad, ipc/mobile and managed-server pass.
  • pnpm tc, typecheck:ci, code-quality, anti-slop and ast-grep pass.
  • Automated tests added/updated

Status

Ready for two reviewers.

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • N/A for visuals with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote impact considered (orcad-wide; same atomic secure write)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (CI runs the rest)

…d on disk

Every DeviceRegistry save wrote orcad's whole in-memory list. A lastSeen flush (250 ms after any
socket auth, and again at shutdown) could therefore write back a device an admin had just removed
from orca-devices.json on the host, silently undoing the revoke; it also dropped rows another
writer had added. Saves now re-read the file and write the in-memory change merged over it: rows
this process knew of that are gone from disk stay gone (in memory too), rows added on disk are
kept, and this save's own adds and removals apply. The write stays the secure-file atomic rename.
The pairing-repair e2e logs the registry's device ids after the kill and after the reconnect.
@nwparker

Copy link
Copy Markdown
Contributor Author

STATUS: ready for two reviewers. Head 9c77824.

Checks run: pnpm tc, typecheck:ci, code-quality:changed, anti-slop, oxlint, ast-grep. The new external-edit tests pass 5/5, and 4 of them fail on main. src/main/runtime has 15024 passing; the one failure there also fails on main. The registry consumer suites pass.

Open question: an external removal still takes effect in memory only at the next save (at most 250 ms after any connection). Watching the file would close that gap; I'd treat it as a follow-up.

@greptile-apps

greptile-apps Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

RetriggerView in GreptileConfidence Score: 2/5

[High impact] The shared device registry reaches SSH hosts, desktop runtime, and mobile pairing.

The PR is not ready to merge: valid credentials can still disappear after quarantine, and a save can still overwrite a concurrent revocation.

Findings

  1. P1 Valid devices disappear after quarantine ▶
  2. P1 Security A revocation can be reversed ▶

Summary

The latest changes remember device IDs removed by this process and report when a row update loses to a removal on disk.

  • Device registry saves keep removed devices out of the file.

Reviews (2) · Last reviewed commit: "fix(runtime): tombstone devices this pro..." · Reviewed by Greptile

Comment thread src/main/runtime/device-registry.ts Outdated
this.assertReadable()
const write = options.durable ? writeDurableSecureJsonFile : writeSecureJsonFile
write(this.registryPath, devices)
const written = writeMergedDeviceRegistry(this.registryPath, before, devices, options)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Valid devices disappear after quarantine

If the registry contains valid devices alongside one malformed row at startup, assertReadable quarantines the file before this new read. The read then reports a missing file with no devices. The merge treats every previously loaded device as externally removed, so the first save deletes all valid credentials from memory and the active file.

Preserve the loaded valid rows when this process itself quarantined the file. Add a test that checks they survive the next save.

Comment on lines +37 to +43
const disk = readDeviceRegistryFile(registryPath)
const merged =
disk.unreadable || disk.corruptFilePending
? [...next]
: mergeDeviceRegistrySave(before, next, disk)
const write = options.durable ? writeDurableSecureJsonFile : writeSecureJsonFile
write(registryPath, merged)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 security A revocation can be reversed

A removal can still be undone if it lands after readDeviceRegistryFile but before the secure writer renames its temporary file. The merge uses the earlier snapshot, and the rename overwrites the admin's newer file with the revoked row included. Atomic rename protects the file contents, not this read-and-merge sequence.

Detect intervening changes and retry or coordinate writers. Add a test that removes a device during the write stage.

How this was verified: The save reads the registry once, then publishes that snapshot through a later rename without checking whether the registry changed.

Comment thread src/main/runtime/device-registry.ts Resolved
@coderabbitai

coderabbitai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 10 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: c11d7fef-f534-4428-a5da-cc3e44eb1983
Commits

Reviewing files that changed from the base of the PR and between 9c77824 and 9550aca.

Files selected for processing: 3
  • src/main/runtime/device-registry-disk-merge.ts
  • src/main/runtime/device-registry-external-edit.test.ts
  • src/main/runtime/device-registry.ts
Walkthrough

Registry saves now reread disk and merge proposed rows with current entries. DeviceRegistry assigns the rows returned by the merged write to its in-memory state. New tests cover external registry edits and session-only rows. Pairing repair diagnostics now record device IDs instead of full device records.

Priority: Normal

Merge Risk: Moderate · previous review 9c778

If a registry file contains a partially invalid entry, the first save after startup can wipe the remaining valid paired devices. Removing a parent device on disk can also leave its delegated mobile child able to authenticate. Fix both before merging.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Description check Warning The description clearly explains the problem, implementation, security impact, testing, visual proof, and checklist status. It does not satisfy the required Linked Issue section because it provides no… Add a valid linked issue reference in the required Fixes #... section. Complete or explicitly mark the Review, Agent skill upstream boundary, and Notes sections. Confirm the required lint, typecheck, test, and build checks, or state that …
Passed Passed checks: 4 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: preventing registry saves from restoring devices removed from disk.
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 1 functions across 4 files.

Full details: Description check

Explanation

The description clearly explains the problem, implementation, security impact, testing, visual proof, and checklist status. It does not satisfy the required Linked Issue section because it provides no actual issue link or issue reference, and it omits the Review, Agent skill upstream boundary, and Notes sections from the template.

Resolution

Add a valid linked issue reference in the required Fixes #... section. Complete or explicitly mark the Review, Agent skill upstream boundary, and Notes sections. Confirm the required lint, typecheck, test, and build checks, or state that CI will cover them.

Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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
src/main/runtime/device-registry-disk-merge.ts: 1

37-43: Trivial · Data Integrity & Integration

Do not raise this as a major issue.

writeMergedDeviceRegistry can overwrite a manual edit made after its read and before renameSync. Synchronous calls do not prevent another process from editing the file. However, the production pairing mutations use the runtime registry, and the PR treats manual edits as best effort. The repository has no registry-specific lock convention, so requiring coordination for arbitrary admin edits is not a supported fix for this PR.

Consider a lock or compare-and-swap design only if the project later requires a stronger guarantee for coordinated external writers.


Review info
Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: a0f30ac2-cf52-405e-b500-2e8abff4047c
Commits

Reviewing files that changed from the base of the PR and between 79dbada and 9c77824.

Files selected for processing: 4
  • src/main/runtime/device-registry-disk-merge.ts
  • src/main/runtime/device-registry-external-edit.test.ts
  • src/main/runtime/device-registry.ts
  • tests/e2e/ssh-orcad-pairing-repair.spec.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 1 remain after this review.

Comment on lines +21 to +22
...next.filter((device) => onDisk.has(device.deviceId) || !known.has(device.deviceId)),
...disk.devices.filter((device) => !known.has(device.deviceId) && !saving.has(device.deviceId))

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.

Major · Security & Privacy · Heavy lift

Remove delegated children when their parent is removed.

If an admin removes a parent device from disk but leaves its delegated child row, this merge drops the parent and retains the child. DeviceRegistry.validateToken and resolveAuthenticatedPrincipal can still accept that child without checking its parent. Remove children of a removed parent during the merge, or enforce the parent relationship at authentication. (raw.githubusercontent.com)

Comment thread src/main/runtime/device-registry.ts Outdated
this.assertReadable()
const write = options.durable ? writeDurableSecureJsonFile : writeSecureJsonFile
write(this.registryPath, devices)
const written = writeMergedDeviceRegistry(this.registryPath, before, devices, options)

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.

Major · Data Integrity & Integration · Quick win

Preserve valid rows after quarantining a corrupt registry.

If load drops an invalid row but retains valid rows, assertReadable() quarantines the file on the first save. The new writer then reads a missing file. The merge treats every previously loaded valid row as removed and writes them out of the registry. Carry the pre-quarantine rows into this save, or bypass the removal merge when this save quarantines the file. (raw.githubusercontent.com)

Comment on lines +25 to +26
`node -e 'console.log(JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))` +
`.map((d)=>d.deviceId).join(","))' ${DEVICES}`

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.

Minor · Stability & Availability · Quick win

Supported by static analysis

Script executed:

# Read the spec with line numbers to see DEVICES, DEVICE_IDS call sites, and whether they run in failure handling.
test -f tests/e2e/ssh-orcad-pairing-repair.spec.ts && cat -n tests/e2e/ssh-orcad-pairing-repair.spec.ts | sed -n '1,140p'

# Locate DEVICE_IDS uses within the file.
rg -n -F 'DEVICE_IDS' tests/e2e/ssh-orcad-pairing-repair.spec.ts || test "$?" -eq 1

# Locate the host.exec helper definition and any exec wrapper in the e2e tree.
rg -n -F -e 'exec!' -e 'exec(' -e 'exec:' -e 'exec =' -- tests/e2e || test "$?" -eq 1

Repository: stablyai/orca

Length of output: 17340


Keep the failure-path device read from replacing the original error.

In the catch block, host.exec!(DEVICE_IDS) runs before throw error. If /root/.orca/orca-devices.json is missing or malformed at that point, DEVICE_IDS exits non-zero and host.exec! throws. That error replaces the original failure, and the screenshot and the rest of the evidence object are not recorded. Wrap the read so the evidence falls back to a sentinel:

Suggested fix
 const DEVICE_IDS =
   `node -e 'console.log(JSON.parse(require("fs").readFileSync(process.argv[1],"utf8"))` +
   `.map((d)=>d.deviceId).join(","))' ${DEVICES}`
+
+function readDeviceIds(exec: (command: string) => string): string {
+  try {
+    return exec(DEVICE_IDS)
+  } catch {
+    return '<unavailable>'
+  }
+}
-          devices: host.exec!(DEVICE_IDS)
+          devices: readDeviceIds(host.exec!)

…r can't restore them

Review of #35483: after removeDevice(a), a stale writer (an old orcad's flush during an SSH
relaunch or upgrade overlap, an external tool) could write a back; the next save treated it as
new on disk, adopted it and let it authenticate. DeviceRegistryWriter now remembers every id
this process removed, recorded before the write so a failed load-time cleanup counts too, and
never adopts those from disk. replaceRow reports false when the merge dropped the row, and a
pending offer removed on disk is replaced instead of handed out.
@nwparker

Copy link
Copy Markdown
Contributor Author

STATUS: fix-reviewer's security finding and e9's three items are pushed. Head 9550aca.

Changes:

  • Tombstones: DeviceRegistryWriter remembers every id this process removed, including the ids the load-time cleanup strips, even when that save fails. It never re-adopts them from disk.
  • replaceRow returns false when the merge dropped the row. A pending offer removed on disk is replaced, not handed out.
  • The PR body now covers deleting the file (removal wins) and in-place field edits (last writer wins).

New tests: fix-reviewer's repro (revoke, stale write-back, later save: the device stays absent and its token is invalid), the failed load-cleanup variant, and replaceRow on a row removed on disk. All three fail on 9c77824. The external-edit suite passes 8/8.

Checks run: pnpm tc, typecheck:ci, code-quality:changed, anti-slop, oxlint, ast-grep. src/main/runtime has 15058 passing. Two tests fail: runtime-failed-local-worktree-removal also fails on main, and orca-runtime passes 1499/1499 when run on its own. The registry consumer suites pass.

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