Skip to content

feat(capture): extension trust surface — automatic UX, spool health, pairing (polylogue-yyvg.7 + 3v1 + gnie) - #3260

Merged
Sinity merged 2 commits into
masterfrom
feature/capture/extension-trust-surface
Jul 21, 2026
Merged

Sinity merged 2 commits into
masterfrom
feature/capture/extension-trust-surface

Conversation

@Sinity

@Sinity Sinity commented Jul 21, 2026

Copy link
Copy Markdown
Owner

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

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 refactor: split CLI into command modules and add HTML preview output #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 refactor: split CLI into command modules and add HTML preview output #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 Gemini AI Studio exports need one reproducible archive path #1/refactor: split CLI into command modules and add HTML preview output #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).

Sinity added 2 commits July 22, 2026 01:33
…etry

Problem: polylogue-gnie's remaining defect was token adoption -- a fresh
extension install had to view/copy/paste the receiver's long-lived bearer
token. polylogue-3v1's capture-gap/error telemetry design ask ("extension
failures land nowhere the daemon can report") was also unimplemented.

What changed:
- polylogue/browser_capture/pairing.py: a short-lived (default 180s),
  single-use, rate-limited (5 wrong guesses) pairing code, minted via
  `polylogued browser-capture pairing start` and exchanged for the current
  bearer token via `POST /v1/pairing/redeem`. Only the code's SHA-256 hash
  is ever persisted; the plaintext code and the token are never both in the
  same place except the in-flight loopback response.
- polylogue/browser_capture/server.py: `/v1/pairing/redeem` is
  origin-checked but deliberately unauthenticated (its purpose is
  bootstrapping the token an unpaired caller does not have yet).
  `/v1/capture-health` (POST report, GET list) is bearer-gated like every
  other route and stores events 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.
- polylogue/daemon/browser_capture.py: `pairing start` and `capture-health`
  CLI commands.
- polylogue/browser_capture/route_contracts.py: contract entries for the
  three new routes, including a new `unauthenticated_pairing_exchange` auth
  policy value.

Not attempted (see PR body AC matrix): the design's *recommended*
installer-managed native-messaging bootstrap (needs an OS-level host
manifest and stable extension identity this repo cannot install or test
headlessly) and automatic token-rotation recovery, which the design
associates with that native-messaging path specifically.

Verification: `devtools test tests/unit/browser_capture/` (146 passed,
including 18 new pairing/capture-health tests exercising real HTTP against
the threaded receiver server); `mypy` clean on touched files; `ruff check`/
`format` clean; `devtools render all --check` exit 0 (new pairing.py module
required a topology-projection regen).
Problem: the popup's only pairing path was a manual "Bearer token" field --
the operator had to run `token show` and paste the receiver's long-lived
secret. The receiver's new `POST /v1/pairing/redeem` route (this branch,
prior commit) exists specifically so a fresh install never needs that.

What changed:
- background.js: `redeemPairingCode(baseUrl, code)` posts to
  `/v1/pairing/redeem` with no Authorization header (mirrors
  `probeReceiverStatus`'s debug-log/timeout/abort pattern, but cannot reuse
  `postJson` -- that requires an already-trusted receiver, circular for an
  unpaired install). `pairWithCode(code)` saves the returned token via the
  existing `saveReceiverSettings` path and confirms health without
  canonical-endpoint auto-recovery (same posture as an explicit settings
  save). New `polylogue.pairWithCode` runtime message.
- popup.html/popup.js: a "Pairing code" field + Pair button inside the
  existing collapsed `<details id="diagnostics">` receiver-settings
  section, next to the manual bearer-token field it complements (does not
  replace manual entry, which remains the break-glass path). Lives inside
  diagnostics, so the yyvg.7 always-visible DOM/action budget test is
  unaffected.

Verification: `npx vitest run` (347 passed; the 1 failing
build.test.js service-worker-fixture-timing test is pre-existing --
reproduced identically on the pre-change tree via `git stash`); `npm run
lint`/`validate` clean.
@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: 18 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: 72c9b1e3-ae4c-4b04-b916-f23c855d7318

📥 Commits

Reviewing files that changed from the base of the PR and between 6b2574d and 74b74eb.

📒 Files selected for processing (15)
  • browser-extension/src/background.js
  • browser-extension/src/popup.html
  • browser-extension/src/popup.js
  • browser-extension/tests/background.test.js
  • browser-extension/tests/popup.test.js
  • docs/plans/topology-target.yaml
  • docs/topology-status.md
  • polylogue/browser_capture/models.py
  • polylogue/browser_capture/pairing.py
  • polylogue/browser_capture/route_contracts.py
  • polylogue/browser_capture/server.py
  • polylogue/daemon/browser_capture.py
  • polylogue/paths/__init__.py
  • polylogue/paths/_roots.py
  • tests/unit/browser_capture/test_pairing.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/capture/extension-trust-surface

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 74b74ebe98

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +745 to +746
try:
token = redeem_pairing_code(request.code)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Return the receiver's configured token during redemption

When the receiver is started with an explicit token through --auth-token or daemon.browser_capture.auth_token, this call loads or mints the archive token file instead of returning self.server.config.auth_token. Redemption therefore reports success but gives the extension a token the running receiver will reject on every authenticated request, breaking pairing for a documented configuration.

Useful? React with 👍 / 👎.

Comment on lines +965 to +966
const health = await checkReceiverHealth({ allowCanonicalRecovery: false });
return { ok: true, health, pairing: health.pairing || (await storedReceiverPairing()) };

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Adopt the redeemed receiver identity when re-pairing

When an extension with an existing pairing uses a code after the receiver identity changes, such as after an archive/profile reseed, checkReceiverHealth compares the new identity with the retained old one and returns pairing_mismatch. This code nevertheless returns ok: true, so the popup says “Paired,” clears the now-consumed code, and never adopts result.receiverId; an explicit code redemption should authorize replacing the old identity and should not report success while health remains mismatched or unauthorized.

Useful? React with 👍 / 👎.

Comment on lines +801 to +803
self._send_json(
HTTPStatus.ACCEPTED,
BrowserCaptureHealthEventAcceptedPayload(event_id=get_latest_event_id()).model_dump(mode="json"),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Return the inserted capture-health event ID

Under concurrent reports handled by ThreadingHTTPServer, another request can insert an event after this request commits but before get_latest_event_id() runs. The response will then identify the other request's row, and multiple callers can receive the same event_id; the insert operation should return its own SQLite lastrowid rather than querying the global maximum afterward.

Useful? React with 👍 / 👎.

@Sinity
Sinity merged commit 5f061e8 into master Jul 21, 2026
3 checks passed
@Sinity
Sinity deleted the feature/capture/extension-trust-surface branch July 21, 2026 23:54
Sinity added a commit that referenced this pull request Jul 29, 2026
Problem:
- tests/unit/daemon/test_daemon_http_security.py::TestNoTokenLogging::test_no_token_in_log_or_print_calls:
  the AST-based token-output scanner flagged two legitimate call sites its
  name-based taint tracking can't distinguish from real secret leaks:
  `_handle_query_units` (polylogue/daemon/http.py) echoes decoded query
  results, not the client-supplied `continuation_token` pagination cursor
  itself, back via `_send_json`; `_pairing_redeem`
  (polylogue/browser_capture/server.py, #3260) deliberately returns a
  freshly-issued `auth_token` to the client that just redeemed its one-time
  pairing code -- that disclosure IS the endpoint's whole purpose.
- tests/unit/daemon/test_route_contracts.py::test_rebuild_index_handler_forwards_resumable_pass_options_through_writer_bridge:
  the handler (polylogue/daemon/http.py:_handle_rebuild_index, polylogue-ogn1)
  calls `write_bridge.run_sync_with_timeout(...)` (a longer-timeout variant
  sized for a bounded rebuild pass) instead of the bridge's default-timeout
  `run_sync`; the test still mocked/asserted on `run_sync`, so
  `call_args` was `None` and unpacking it raised `AttributeError` before the
  test's own assertions ran.
- tests/unit/daemon/test_health_contract.py::TestTierInventoryContract::test_medium_tier_inventory_pinned:
  #3362 ("add provider format-drift sentinel over live ingest") added a new
  MEDIUM-tier health check (`_check_schema_drift_medium`,
  polylogue/daemon/health.py) that was never added to this test's pinned
  `EXPECTED_MEDIUM_CHECKS` inventory.

What changed:
- test_daemon_http_security.py: added both call sites to
  `intentional_secret_outputs` with rationale comments.
- test_route_contracts.py: updated the mock/assertion to
  `run_sync_with_timeout` (actor, timeout, function, request) instead of
  `run_sync` (actor, function, request).
- test_health_contract.py: added `"schema_drift"` to `EXPECTED_MEDIUM_CHECKS`.

Verification:
- devtools test tests/unit/daemon/test_daemon_http_security.py
  tests/unit/daemon/test_route_contracts.py
  tests/unit/daemon/test_health_contract.py -> 679 passed.

Ref polylogue-c66i

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