Skip to content

fix(browser-capture): stable receiver identity survives token rotation - #3245

Merged
Sinity merged 3 commits into
masterfrom
fix/daemon/receiver-pairing-stable-identity
Jul 21, 2026
Merged

Sinity merged 3 commits into
masterfrom
fix/daemon/receiver-pairing-stable-identity

Conversation

@Sinity

@Sinity Sinity commented Jul 21, 2026

Copy link
Copy Markdown
Owner

Summary

Fixes the polylogue-jlme.5 receiver-pairing architecture defect: the browser-capture receiver's stable pairing identity was derived by hashing the bearer token, so an ordinary token rotation silently changed a paired extension's trusted identity. Also adds a deliberate dev-override pairing state so an operator-pinned dev-loop receiver never silently self-heals to the canonical endpoint.

Problem

receiver_identity(config) (polylogue/browser_capture/receiver.py) hashed config.auth_token (or, in no-auth mode, the resolved spool path) to derive the rx-<hash> identity extensions treat as the pairing trust anchor. This meant:

  • Every bearer-token rotation minted a different receiver identity, forcing every already-paired browser profile through an unnecessary re-pair -- directly blocking gnie's automatic credential-refresh design (AC2: "token rotation is automatic when stable identity matches").
  • The existing unit test suite encoded this as expected behavior (test_receiver_identity_changes_on_token_rotation), which the bead's 2026-07-16 note explicitly flags as the architecture correction still owed: "stable receiver identity must not be derived from the bearer token."

Separately, the already-shipped bounded canonical-endpoint recovery (checkReceiverHealth in browser-extension/src/background.js) treats every non-canonical, identity-matching pairing the same way: a stale receiver silently swaps the extension over to the canonical endpoint. That is the correct fix for the original 2026-07-15 incident (an extension retaining a dead dev-loop endpoint while the packaged receiver ran at the canonical port), but wrong for a profile an operator has deliberately pinned to a dev-loop receiver for active testing -- today it would silently jump away from the dev receiver mid-session.

Solution

Python (receiver-side identity):

  • polylogue/paths/_roots.py: new browser_capture_receiver_identity_path(), archive-root-scoped like the existing token path but a separate file (browser-capture-receiver-id).
  • polylogue/browser_capture/receiver.py: new load_or_mint_receiver_identity() mints a non-secret rx-<20 hex> value once and persists it via the same mkstemp + os.replace pattern as the token minter (no fchmod needed -- nothing secret). receiver_identity(config) now reads/mints from that file instead of hashing config.auth_token/config.spool_path.
  • Rewrote the three affected unit tests in tests/unit/browser_capture/test_receiver.py to assert the corrected invariant (identity survives token rotation and spool relocation, both scoped to archive root) instead of the old, now-wrong, expectation.
  • tests/unit/core/test_paths.py: added the new path symbol to the polylogue.paths public-boundary allowlist.

JS (deliberate dev-override, browser-extension/src/):

  • background.js: saveReceiverSettings now marks dev_override: true on the stored pairing whenever an operator explicitly configures a non-canonical receiverBaseUrl via the settings UI (and clears it when they repoint at the canonical endpoint -- both are equally explicit acts). checkReceiverHealth's canonical-recovery gate now skips entirely when pairingBefore.dev_override is set. markReceiverPairingUnavailable marks such a pairing state: "dev_override_stale" (distinct from the calm "offline" state used for ordinary receiver-asleep framing). observeReceiverIdentity's two branches that previously rebuilt the pairing object from scratch now preserve dev_override across every state transition.
  • operator_status.js / popup.js: added a distinct, loud presentation for dev_override_stale in receiverPairingPresentation, computeAttention, operatorStatusForState, and operatorPresentationForState, at the same priority tier as an identity mismatch.

Verification

  • devtools test tests/unit/browser_capture/ tests/unit/core/test_paths.py -- 151 passed
  • mypy --strict polylogue/browser_capture/receiver.py polylogue/paths/_roots.py polylogue/paths/__init__.py tests/unit/browser_capture/test_receiver.py tests/unit/core/test_paths.py -- clean
  • cd browser-extension && npx eslint src/ tests/ -- clean
  • cd browser-extension && npx vitest run -- 342 passed, 1 pre-existing failure (build.test.js packaged service-worker fixture, a vi.waitFor timing flake) confirmed present on master before this change via git stash; untouched by this PR
  • devtools verify --quick -- 16/16 steps green (run id 20260721T155909Z-quick-121970-01cf1062)
  • devtools render all --check -- exit 0, no out of sync surfaces

Acceptance criteria matrix (polylogue-jlme.5)

  1. Stale-pairing → canonical recovery on identity+schema match -- already shipped (2026-07-16 partial implementation); covered by pre-existing tests recovers only at the canonical endpoint when the paired identity matches / does not adopt the canonical endpoint when its receiver identity differs; both still pass unmodified. Not touched by this PR.
  2. Identity persisted independently of the bearer token; token rotation preserves identity; gnie's automatic refresh; different identity/schema never auto-adopts -- satisfied by this PR for the identity/token-rotation half (test_receiver_identity_survives_token_rotation, test_receiver_identity_is_minted_once_and_persisted_on_disk). The extension-side identity-mismatch refusal was already shipped and is unchanged. gnie's own automatic-bootstrap wiring is that bead's separate scope (noted on jlme.5 as an explicit dependent, not owned here).
  3. Re-pair preserves capture queue, backfill jobs, receipts, extension instance identity -- already shipped (polylogue.receiverPairing.reset only clears the one pairing key); unchanged, covered by pre-existing test resets only the pairing key and preserves pending work.
  4. Popup/status show endpoint, identity, schema, last contact, current state without leaking credentials -- already shipped via receiverPairingPresentation; this PR adds the missing dev_override_stale presentation branch so a deliberately pinned pairing reports loudly rather than falling into the calm offline framing.
  5. No arbitrary port scan / token disclosure / unauthenticated fallback / browser-profile special case -- unaffected; this PR's recovery gate only restricts the existing bounded canonical probe (adds a !dev_override condition), it does not add any new endpoint discovery.
  6. Packaged two-authenticated-profile / dev-isolated-profile / canonical-failover / token-rotation / identity-mismatch proof -- not covered by this PR. This sandboxed lane has no live browser harness (repo-documented constraint); the notes on jlme.5 already flag this as the standing residual requiring a real packaged-extension fixture. New fixture tests here (test_receiver_identity_survives_token_rotation, does not auto-recover a deliberate dev-override pairing even when the canonical identity would match, marks a manually configured non-canonical endpoint as a deliberate dev override) prove the underlying mechanics at the unit level, not the packaged end-to-end proof AC6 asks for.

Residual risk

  • capture_jobs.py's per-lease HMAC proof (CaptureJobRegistry._proof) uses receiver_id as its HMAC key. This was already effectively non-secret before this PR (the identity is exposed via the authenticated /v1/status route to any bearer-token holder), so this change does not weaken that boundary, but it is worth a reader's attention if receiver_id is ever repurposed as an actual secret.
  • AC6's packaged multi-profile proof remains open, as it was before this PR; no code claim is made against it here.

Ref polylogue-jlme.5

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jul 21, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 7 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 466cc010-9623-4325-bab0-eb66ed67cc1c

📥 Commits

Reviewing files that changed from the base of the PR and between 5fdd4d1 and 36db592.

📒 Files selected for processing (10)
  • browser-extension/src/background.js
  • browser-extension/src/operator_status.js
  • browser-extension/src/popup.js
  • browser-extension/tests/background.test.js
  • browser-extension/tests/operator_status.test.js
  • polylogue/browser_capture/receiver.py
  • polylogue/paths/__init__.py
  • polylogue/paths/_roots.py
  • tests/unit/browser_capture/test_receiver.py
  • tests/unit/core/test_paths.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/daemon/receiver-pairing-stable-identity

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.

Sinity added 3 commits July 21, 2026 18:04
…bearer token

Problem: receiver_identity() hashed config.auth_token directly, so every
ordinary token rotation minted a different rx-<hash> id. Paired browser
extensions treat receiver_id as the pairing trust anchor, so a rotation
silently changed the trusted identity and forced an unnecessary re-pair --
the exact architecture defect flagged on polylogue-jlme.5 (gnie's automatic
credential-rotation refresh depends on identity surviving rotation).

Solution: add browser_capture_receiver_identity_path() (paths/_roots.py),
archive-root-scoped like the existing token path but a separate file, and
load_or_mint_receiver_identity() (browser_capture/receiver.py) that mints a
non-secret rx-<20 hex> value once and persists it via the same
mkstemp+os.replace pattern as the token minter (no fchmod needed -- nothing
secret to protect). receiver_identity(config) now reads/mints from that file
instead of hashing config.auth_token or config.spool_path; the no-auth
escape hatch's previous spool-derived identity is superseded by the same
persisted-per-archive-root value.

Ref polylogue-jlme.5

Verification: devtools test tests/unit/browser_capture/test_receiver.py -k identity (7 passed);
mypy --strict polylogue/browser_capture/receiver.py polylogue/paths/_roots.py polylogue/paths/__init__.py (clean)
…self-heal

Problem: checkReceiverHealth's bounded canonical-endpoint recovery treats
every non-canonical, identity-matching pairing the same way -- a stale
receiver silently swaps to the canonical endpoint whenever identity/schema
match. That is correct for a profile that drifted onto a dev endpoint by
accident (the polylogue-jlme.5 incident), but wrong for a profile the
operator deliberately pinned to a dev-loop receiver: today it would silently
jump away from the dev receiver the operator is actively testing against.

Solution: saveReceiverSettings (background.js) marks the pairing
dev_override: true whenever an operator explicitly configures a
non-canonical receiverBaseUrl via the settings UI, and clears it when they
point settings back at the canonical endpoint -- both are equally explicit
acts. checkReceiverHealth's canonical-recovery gate now skips entirely when
pairingBefore.dev_override is set; markReceiverPairingUnavailable marks such
a pairing state: "dev_override_stale" instead of the calm "offline" so it is
never confused with ordinary receiver-asleep framing. operator_status.js
(receiverPairingPresentation, computeAttention, operatorStatusForState,
operatorPresentationForState) and popup.js gained a distinct loud
presentation for the new state, at the same priority tier as an identity
mismatch. observeReceiverIdentity's two branches that previously rebuilt the
pairing object from scratch now preserve dev_override across every state
transition.

Ref polylogue-jlme.5

Verification: npx eslint src/ tests/ (clean); npx vitest run (342 passed, 1
pre-existing failure in build.test.js's packaged service-worker fixture,
confirmed present on master before this change and unrelated -- a timing
flake in the backfill page-transport waitFor, untouched by this PR)
The paths public-boundary allowlist test enumerates every symbol
polylogue.paths exports; the new browser_capture_receiver_identity_path
(polylogue-jlme.5) needed adding alongside the existing token-path entry.

Ref polylogue-jlme.5

Verification: devtools test tests/unit/browser_capture/ tests/unit/core/test_paths.py (151 passed)
@Sinity
Sinity force-pushed the fix/daemon/receiver-pairing-stable-identity branch from 0f94621 to 36db592 Compare July 21, 2026 16:05
@Sinity

Sinity commented Jul 21, 2026

Copy link
Copy Markdown
Owner Author

Coordinator stand-in review (CodeRabbit rate-limited): read the full 539-line diff. The root cause (receiver identity hashed from the bearer token, so rotation minted a new rx-id and broke pairing — with the old behavior actually pinned by a test as expected) is a real find; mint-once persisted non-secret identity is the correct fix, and the dev_override flag turns deliberate dev pairings into loud failures instead of silent canonical failover — matching the bead's incident semantics. Receiver-side + extension-side both covered by fixtures; 151 py tests + 342 vitest green, mypy strict + eslint clean. The lease-HMAC key-material note is accurate (receiver_id was already non-secret pre-change — no regression). Merging; AC6 packaged two-profile proof remains the documented open gap.

@Sinity
Sinity merged commit 59752ec into master Jul 21, 2026
2 of 3 checks passed
@Sinity
Sinity deleted the fix/daemon/receiver-pairing-stable-identity branch July 21, 2026 16:10
Sinity added a commit that referenced this pull request Jul 21, 2026
…pairing (polylogue-yyvg.7 + 3v1 + gnie) (#3260)

## Summary

Delivers the browser-capture receiver+extension pairing-bootstrap and
capture-health-telemetry slice of the extension trust-surface cluster
(Ref polylogue-yyvg.7, Ref polylogue-3v1, Ref polylogue-gnie). Two
commits:
receiver/CLI infrastructure (Python), then the extension-side pairing UI
that consumes it (JS).

## Problem

- **polylogue-gnie**: a fresh extension install had no way to adopt the
  receiver's auto-minted bearer token except the operator running
  `polylogued browser-capture token show` and pasting the 43-character
secret into the popup. The bead's own notes call this out explicitly as
  the still-open defect after the underlying auth machinery (PR #3245,
jlme.5) shipped: "the prior close treated CLI copy/paste as equivalent
to
  automatic token adoption. It is not."
- **polylogue-3v1**: the design explicitly asks for capture-health
  telemetry ("extension errors post to the receiver as capture-health
events -> ops.db -> daemon /metrics + status ... the extension becomes
an
observable component") so that capture gaps/errors are queryable archive
history rather than only visible transiently in the popup. This did not
  exist.
- **polylogue-yyvg.7**: per the bead's extensive existing notes
(2026-07-16
through 2026-07-19), the popup/badge/attention-model redesign is already
substantially shipped across five prior merged PRs (#2928, #3098, #3126,
  #3137, #3139). What remains open per the bead's own AC-by-AC record is
  either blocked on a data model that does not exist yet (explicit-
  approval/destructive-conflict attention categories) or requires live
  installed-browser proof the bead's notes say was already attempted and
  partially completed by a prior session.

## Solution

**polylogue-gnie — one-time pairing code (compatibility fallback per the
bead's own design text)**: the bead's recommended primary design is an
installer-managed native-messaging host; this repo cannot install an
OS-level
native-messaging manifest or exercise a real, stable
`chrome-extension://`
identity headlessly, so that path is genuinely out of scope for an
unattended session. The design text names an explicit fallback instead —
"a user-presence one-time pairing approval/code that transfers the
secret
without copy/paste" — and that is what this PR implements:

- `polylogue/browser_capture/pairing.py` (new): mints an 8-character,
40-bit-entropy, single-use, 180s-default-TTL code; only its SHA-256 hash
  is ever persisted (`browser-capture-pairing` file under the archive
  root, same 0600-atomic-write pattern as the bearer token). 5 wrong
  guesses burn the pending code even before its TTL expires.
- `POST /v1/pairing/redeem` (new route,
`polylogue/browser_capture/server.py`):
deliberately unauthenticated — bootstrapping the token *is* its job —
but
still origin-checked (`_reject_origin`), so an arbitrary webpage cannot
  forge the extension's `chrome-extension://` origin to redeem a code it
  somehow observed.
- `polylogued browser-capture pairing start [--ttl-seconds]` CLI prints
the
code; the extension's new popup "Pairing code" field (inside the
existing
collapsed diagnostics section, next to the manual bearer-token field it
  complements rather than replaces) exchanges it automatically via
  `background.js`'s new `pairWithCode`/`redeemPairingCode`.
- **Not attempted**: automatic token-rotation recovery (AC #4) — the
design explicitly ties that behavior to the native-messaging host path,
  which is out of scope here. Manual re-pairing (paste the token, or run
  `pairing start` again) remains the break-glass/recovery route.

**polylogue-3v1 — capture-health telemetry, producer side deferred**:

- `POST /v1/capture-health` (bearer-gated like every other route) and
`GET /v1/capture-health` (new routes): events are stored in the existing
  ops.db `daemon_events` ledger under `kind="browser_capture_health"`,
reusing
`polylogue.daemon.events.emit_daemon_event`/`query_daemon_events`
  rather than adding a new table (`ops.db` is a freeform-additive
  disposable tier — see `fts_drift_samples` precedent).
- `polylogued browser-capture capture-health [--limit]` CLI lists recent
  events without an HTTP round trip.
- **Not attempted**: wiring the extension itself to detect a
completeness
  mismatch (page-visible vs. archived message count) and call this new
endpoint automatically. The receiver-side ledger, query surface, and CLI
are real and tested; the producer that would make gaps self-report is a
  distinct, still-open chunk of work (the extension has no existing
  visible-vs-captured comparison to hook — a genuine follow-up, not a
  trivial wire-up). Gemini bridge coverage (`gemini.google.com` host
  permission + content-script bridge) is likewise not attempted — a full
  new provider bridge is out of scope for this slice.

**polylogue-yyvg.7 — no additional code in this PR.** Verified the
bead's
own AC-by-AC record against current `main` (popup.js/operator_status.js/
popup.html) and confirmed the prior sessions' claims hold: compact
always-visible surface, single-attention-item model, shared status
module,
DOM/action budget test, and the F1/F6 visual convergence are all present
in the current tree. What the bead's notes list as still open —
explicit-
approval/destructive-conflict attention categories (blocked on a data
model ptx does not yet expose) and literal live-installed
offline-recovery
proof — are unchanged by this PR; both require capability or environment
this session does not have (a real backing data model for the former, a
disposable second receiver + real browser for the latter).

## Verification

- Python: `devtools test tests/unit/browser_capture/` — 146 passed
(18 new: `tests/unit/browser_capture/test_pairing.py`, real HTTP against
  the threaded `BrowserCaptureHTTPServer`, plus CLI round-trips via
  `CliRunner`). `mypy` clean on touched files. `devtools verify --quick`
  exit 0 (`.cache/verify/runs/20260721T234119Z-quick-765869-deca05d8`).
`devtools render all --check` exit 0 (new `pairing.py` module required a
  topology-projection regen, included).
- JS: `npx vitest run` — 347 passed / 1 failed. The 1 failure
  (`build.test.js` service-worker-fixture timing) is **pre-existing and
unrelated** — reproduced identically with this branch's diff stashed out
(`git stash && npx vitest run tests/build.test.js` fails the same way).
  `npm run lint` and `npm run validate` (manifest) both clean.
- **Anti-vacuity**:
`test_pairing_redeem_route_pairs_without_a_preexisting_token`
  exercises the real `write_capture_envelope`-adjacent HTTP stack end to
  end — mutating `redeem_pairing_code` to skip the origin check, or
  removing the `_reject_origin()` call ahead of the pairing route in
`server.py`, makes `test_pairing_redeem_route_rejects_disallowed_origin`
  fail; mutating the single-use clear-on-success behavior makes
`test_pairing_redeem_route_is_single_use_over_http` fail. On the JS
side,
  deleting the `polylogue.pairWithCode` handler or the `Content-Type`
  header in `redeemPairingCode` fails
`background.test.js`'s "exchanges a valid pairing code" test (asserts no
  `Authorization` header is sent and the body round-trips exactly).

## What only manual/live browser testing can prove

- The popup's new "Pairing code" field actually rendering and being
  reachable/styled correctly in a real installed Chrome/Firefox profile
(jsdom-based `popup.test.js` proves the click → message → storage
wiring,
  not visual layout).
- End-to-end pairing against a real `polylogued` daemon + real
  `chrome-extension://<id>` origin (the test fixtures use a synthetic
  `chrome-extension://polylogue-test` origin, which is the same pattern
  every other receiver-route test in this repo already uses).
- Token-rotation recovery UX and the native-messaging path — both
  explicitly out of scope for this PR (see Solution above).

## Per-bead AC matrix

**polylogue-gnie** ("Automate secure browser-to-receiver pairing"):
1. Fresh install pairs without viewing/copying/pasting a bearer secret —
**partially satisfied**: the one-time-code fallback delivers this; the
design's *primary* recommendation (native messaging) is not attempted.
2. Receiver stays deny-by-default; hostile origin/process can't retrieve
the token via pairing — **satisfied** for the origin axis (tested); the
short-lived/single-use/rate-limited code is the stated defense against a
   same-host process without native-messaging-grade isolation.
3. Pairing binds real extension+receiver identities, fails visibly on
   mismatch, logs no secret — **satisfied**: the response includes
`receiver_id`; rejections log only the exception type, never the code or
   token (verified by reading the log call sites).
4. Token rotation invalidates old token, extension recovers
automatically —
**deferred**: this AC clause is explicitly tied to the native-messaging
path in the bead's design text; manual re-pairing remains the recovery
   route with this fallback.
5. Real browser-extension-to-loopback fixture proving first pairing,
authenticated reads, rotation recovery, profile reseed, hostile-origin
   rejection, receiver-offline recovery — **partially satisfied**: first
pairing and hostile-origin rejection are proven over real HTTP; rotation
recovery, profile reseed, and receiver-offline recovery are not (need a
   live browser or are explicitly deferred per AC #4).

**polylogue-3v1** ("Capture extension reliability + status UX"):
- Badge shows current/spooled/error per tab — **unchanged by this PR**
  (already substantially shipped per the bead's prior-session notes;
  independently verified present in the current tree).
- Receiver-down spooling drains with no loss/dup — **unchanged by this
PR**
(prior sessions' notes claim this is already implemented; not
re-verified
  here — out of this slice's scope).
- `gemini.google.com` capture end-to-end — **not attempted** (full new
provider bridge, out of scope for this slice; named as residual above).
- Capture-gap events queryable in the archive — **satisfied for the
  receiver/CLI side** (`GET /v1/capture-health`,
  `polylogued browser-capture capture-health`); **not satisfied for the
  producer side** — the extension does not yet detect and report gaps
  automatically (residual, needs a follow-up bead for the visible-vs-
  captured comparison + wiring).
- Bridge DOM fixtures in CI — **unchanged by this PR**.

**polylogue-yyvg.7** ("Make extension UX automatic and
exception-driven"):
- AC1-AC7 — **no change from the bead's existing 2026-07-19 record**,
independently spot-checked against current `main` and found consistent.
Still-open items per that record (explicit-approval/destructive-conflict
  attention categories blocked on a missing data model; literal
  live-installed offline-recovery proof) are unchanged residuals, not
  addressed by this PR.

## Residuals (named follow-ups, not silently dropped)

1. Extension-side capture-health *producer* wiring (visible-vs-captured
   comparison → `POST /v1/capture-health` on detected gap/error/spool-
backlog/provider-auth-broken) — the receiver/CLI/query side landed here,
   the extension-side detection+call did not.
2. Gemini (`gemini.google.com`) capture bridge — not attempted.
3. Native-messaging installer bootstrap for gnie AC #1/#4's full
automatic
   path — not attempted (this repo cannot install/test it headlessly).
4. yyvg.7's explicit-approval/destructive-conflict attention categories
—
   blocked on a ptx-side data model that does not exist yet (per the
   bead's own notes, unchanged by this PR).
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