Skip to content

fix(browser-capture): scope receiver token + spool root under archive_root - #3137

Merged
Sinity merged 1 commit into
masterfrom
fix/browser-capture/archive-scope-token-and-spool
Jul 18, 2026
Merged

Sinity merged 1 commit into
masterfrom
fix/browser-capture/archive-scope-token-and-spool

Conversation

@Sinity

@Sinity Sinity commented Jul 18, 2026

Copy link
Copy Markdown
Owner

Summary

browser_capture_receiver_token_path() and browser_capture_spool_root()
resolved from XDG defaults (state_home()/data_home()) regardless of
POLYLOGUE_ARCHIVE_ROOT. Every archive root shared one auth token, and
since receiver_identity() hashes that token to derive the receiver's
stable id, every archive root shared one receiver identity too.

Problem

Discovered via a real incident during live browser-extension proof work
(polylogue-ptx / polylogue-yyvg.7): a scratch polylogued run --spool <scratch> on the default port crashed on startup (Address already in use) because the real polylogued.service was already bound there — but
because the token wasn't archive-scoped, the scratch instance's pairing
token authenticated successfully against the real running daemon instead
of failing loudly. Two real browser-action test conversations and their
captured content briefly landed in the production archive before being
caught and fully cleaned up. Separately, even a correctly-isolated
scratch instance on an alternate port got silently reconnected to the
canonical production endpoint by the extension's own
checkReceiverHealth({allowCanonicalRecovery:true}) self-heal, because
the two instances' receiver_id matched (same non-scoped token → same
hash).

Solution

Both path functions now resolve under archive_root(), matching every
other archive-tier path (index.db, source.db, blob/, render/,
etc). Also fixed the parallel (currently unconsumed by any live code path)
ResolvedRuntimeConfig construction in config.py for consistency, so it
doesn't silently diverge from the now-correct polylogue.paths behavior
once something starts reading it.

For the default/unconfigured case this is a no-op for the spool root
(archive_root() already equals data_home() when
POLYLOGUE_ARCHIVE_ROOT is unset — verified live) and a one-time
relocation for the token (~/.local/state/polylogue/browser-capture-receiver-token
→ ~/.local/share/polylogue/browser-capture-receiver-token).

New regression test (test_default_token_and_spool_paths_are_scoped_to_archive_root)
proves two POLYLOGUE_ARCHIVE_ROOT values never share a token, spool
root, or (by construction) receiver_id — the exact contract the incident
violated.

Migration note

Any already-running polylogued.service picks this up on its next
restart after deployment. Its receiver token relocates, so it auto-mints
a fresh one, and any currently-paired browser extension needs a one-time
re-pair (polylogued browser-capture token show, paste into the popup's
Receiver settings) — the extension's existing "Reset pairing"/Attention
flow already covers this; no new UI needed.

Verification

  • devtools test tests/unit/browser_capture/test_receiver_token.py → 8 passed
  • devtools test tests/unit/browser_capture/ tests/unit/daemon/test_daemon_cli.py tests/unit/sources/test_live_watcher.py → 304 passed
  • devtools test tests/unit/core/test_paths.py tests/unit/core/test_config.py → 115 passed, 1 pre-existing unrelated failure (test_external_active_pointer_changes_only_the_index_tier, confirmed failing identically on master without this change)
  • devtools verify --quick → exit 0
  • Live sanity check: two POLYLOGUE_ARCHIVE_ROOT values now mint genuinely distinct tokens; default (no override) spool path unchanged, token path intentionally relocated as documented above

Ref polylogue-x2q3

🤖 Generated with Claude Code

…_root

Ref polylogue-x2q3

Problem: browser_capture_receiver_token_path() and browser_capture_spool_root()
resolved from state_home()/data_home() (XDG defaults) regardless of
POLYLOGUE_ARCHIVE_ROOT. Every archive root shared one auth token file, and
since receiver_identity() hashes that token to derive the receiver's stable
id, every archive root also shared one receiver identity.

This caused a real incident: a scratch `polylogued run --spool <scratch>`
on the default port crashed on startup (Address already in use) because
the real polylogued.service was already bound there -- but because the
token wasn't archive-scoped, the scratch instance's pairing token
authenticated successfully against the real running daemon instead of
failing loudly. Real browser-action test traffic and its captured content
briefly landed in the production archive before being caught and cleaned
up (see polylogue-ptx/polylogue-yyvg.7 session notes). Separately, even a
correctly-isolated scratch instance on an alternate port got silently
reconnected to the canonical production endpoint by the extension's own
checkReceiverHealth({allowCanonicalRecovery:true}) self-heal, because the
two instances' receiver_id matched (same non-scoped token, same hash).

Fix: both path functions now resolve under archive_root(), matching every
other archive-tier path (index.db, source.db, blob/, render/, etc). For the
default/unconfigured case this is a no-op for the spool root (archive_root()
already equals data_home() when POLYLOGUE_ARCHIVE_ROOT is unset) and a
one-time relocation for the token (moves from
~/.local/state/polylogue/browser-capture-receiver-token to
~/.local/share/polylogue/browser-capture-receiver-token). Also fixed the
parallel (currently unconsumed) ResolvedRuntimeConfig construction in
config.py for consistency, so it doesn't silently diverge from the
now-correct polylogue.paths behavior once something starts reading it.

New regression test proves two POLYLOGUE_ARCHIVE_ROOT values never share a
token, spool root, or (by construction, since identity hashes the token)
receiver_id -- the exact contract the incident violated.

Migration note: any already-running polylogued.service picks this up on
its next restart after deployment. Its receiver token relocates, so it
auto-mints a fresh one and any currently-paired browser extension needs a
one-time re-pair (`polylogued browser-capture token show`, paste into the
popup's Receiver settings) -- the extension's existing "Reset pairing" /
Attention flow already covers this, no new UI needed.

Verification:
- devtools test tests/unit/browser_capture/test_receiver_token.py -> 8 passed
- devtools test tests/unit/browser_capture/ tests/unit/daemon/test_daemon_cli.py tests/unit/sources/test_live_watcher.py -> 304 passed
- devtools test tests/unit/core/test_paths.py tests/unit/core/test_config.py -> 115 passed, 1 pre-existing unrelated failure (test_external_active_pointer_changes_only_the_index_tier, confirmed failing identically on master before this change)
- devtools verify --quick -> exit 0
- Live sanity check: two POLYLOGUE_ARCHIVE_ROOT values now mint genuinely distinct tokens; default (no override) spool path unchanged, token path intentionally relocated as documented above

Ref polylogue-x2q3

Co-Authored-By: Claude <[email protected]>
@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.

@coderabbitai

coderabbitai Bot commented Jul 18, 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: 23 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: 7a4d9b99-8fb3-4a98-a61b-b98e7bd43560

📥 Commits

Reviewing files that changed from the base of the PR and between c39c254 and 5a2246a.

📒 Files selected for processing (3)
  • polylogue/config.py
  • polylogue/paths/_roots.py
  • tests/unit/browser_capture/test_receiver_token.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/browser-capture/archive-scope-token-and-spool

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
Sinity merged commit cdec148 into master Jul 18, 2026
3 checks passed
@Sinity
Sinity deleted the fix/browser-capture/archive-scope-token-and-spool branch July 18, 2026 23:03
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