Commit graph

81 commits

Author SHA1 Message Date
monkopedia-coder
96aeeeb872
Cap HTTP framing buffers and make refresh-token rotation atomic (F-Droid audit) (#750)
* fix(bridge): cap HTTP framing so one stream cannot OOM the service

HttpHeaderInjector buffered a request's whole header block with no cap on
total bytes, per-line length or line count, and emitted nothing downstream
until the \r\n\r\n terminator arrived. A peer that never sends the terminator
therefore grows headerBuf without bound while the local Ktor server -- which
has its own limits -- receives zero bytes and so can never fire them.
Measured on the unfixed tree: 16 793 629 bytes buffered, 0 forwarded.
chunkSizeBuf had the same shape.

Reachability is what makes this a blocker. The injector runs on the first
plaintext byte after the TLS handshake, ahead of HTTP parsing, ahead of the
X-Internal-Token guard and ahead of OAuth, and the device does not request
client auth, so the integration secret from the MCP URL is the whole
prerequisite. Up to 32 streams share the process, and the resulting
OutOfMemoryError is an Error, so it walked past every `catch (Exception)` on
the path and took the foreground service down rather than one session.

Caps are matched to ktor-http-cio 3.4.2 so that nothing this layer accepts on
size is something Ktor would then reject on size: 8192 bytes per header line
(HTTP_LINE_LIMIT) and 128 bytes per chunk-size line (MAX_CHUNK_SIZE_LENGTH).
The 64 KiB header-block cap undercuts rather than matches, because Ktor CIO
has no block-level cap at all and a per-line limit bounds nothing against a
peer sending limitless well-formed lines.

Exceeding a cap enters a terminal failed state, releases both buffers and
throws. Deliberately NOT a fall-through to PASSTHROUGH, the injector's
existing escape hatch for malformed framing: passthrough would forward the
request without the internal token, which fails closed at the Ktor guard only
after the bytes have already been consumed and copied.

HttpFramingLimitExceededException is an IOException so classifyTunnelFailure
files it as PeerOrTransport -- INFO, rate visible, no non-fatal. A remotely
triggerable crash report would be a spam channel.

Separately, and regardless of the caps: collectIncomingSessions now catches
Throwable rather than Exception, so an Error raised while serving one session
costs one session instead of the service. An explicit CancellationException
clause is stated first so cancellation still propagates -- reportTunnelFailure
rethrew it anyway, but relying on that left the site reading as a swallow to
both the #674 gate and to anyone else. That retires its backlog row.

Found by @andrewpozdnakov7 reviewing 1.0.10 for F-Droid (fdroiddata!42096).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

* fix(token): rotate refresh tokens with a compare-and-swap

RoomTokenStore.refreshToken was read -> check -> write with no transaction, no
CAS and no lock, over an unconditional `UPDATE tokens SET rotatedAt WHERE id`.
Two concurrent redemptions of one refresh token both read `rotatedAt IS NULL`,
both wrote, and both minted a descendant. Both then looked legitimate, so the
family was never revoked, OAuth 2.1 §4.14 reuse detection never fired, and a
stolen refresh token survived indefinitely. Measured on the unfixed tree: 199
of 200 unassisted rounds minted two descendants.

InMemoryTokenStore already does this correctly -- consumeRefreshToken calls
itself "Atomically validates and consumes" and holds a synchronized block. The
Room implementation, the one that ships, did not get that treatment.

markRotatedIfUnrotated adds `AND rotatedAt IS NULL` and returns the affected
row count, so the predicate and the write cannot be separated; a child is
minted only on 1. A single SQLite UPDATE is atomic, so no surrounding
transaction is needed. A 0 return collapses "replayed minutes later" and
"raced us just now" into one answer: revoke the family, mint nothing. The
expiry check is now guarded on `rotatedAt == null`, because an already-rotated
token presented again is reuse whatever the clock says and must reach the CAS
rather than return early.

BEHAVIOUR CHANGE, flagged for the owner and deliberately not softened here: a
well-behaved client that fires two refreshes concurrently -- 401 storms do
this -- goes from "both succeed" to "one succeeds, family revoked, user
re-authenticates". The spec-clean alternative is a short grace window in which
the immediately-preceding token returns the child already minted for it. That
is a product decision, so it is written down rather than taken.

Both tests assert exactly one descendant, not at most one: "at most" is
satisfied by a store that rejects every refresh, and the lower bound is what
keeps an ordinary single refresh working.

Found by @andrewpozdnakov7 reviewing 1.0.10 for F-Droid (fdroiddata!42096).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

---------

Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 14:42:16 -04:00
monkopedia-coder
a8b0dbf329
Let the user stop the security check entirely (#740) (#741)
Some checks are pending
Android CI / test (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build & Test (push) Waiting to run
Deploy docs to GitHub Pages / build (push) Waiting to run
Deploy docs to GitHub Pages / deploy (push) Blocked by required conditions
* Let the user stop the security check entirely (#740)

An F-Droid reviewer on fdroiddata!42096 found the app queries public CT logs
on a schedule with no way to turn it off: HttpCtLogFetcher (crt.sh) and
CertspotterCtLogFetcher, both in the shipped dex, with the per-device hostname
as the query value. Settings offered only cadence choices.

Add `Never` to the existing check-interval control. The interval already
governs the whole feature -- SelfCertVerifier and CtLogMonitor are each
reachable only via SecurityCheckSources -> SecurityCheckWorker, with no other
caller and no other scheduler -- so `Never` completes that control rather than
carving a second one into it. Default is unchanged; nothing becomes opt-in.

It stops the work, it does not hide the result. Enforced in two places, both
load-bearing:

  - SecurityCheckScheduler.cancelPeriodic removes the scheduled work.
  - SecurityCheckWorker re-checks the flag before touching either source.

The second is not redundant. TunnelForegroundService enqueues a *one-time*
run on connect, in a different unique-work slot the scheduler cannot cancel,
and it fires whenever the last check is stale. Under `Never` the last-check
time stops advancing, so scheduler-only cancellation would have made the CT
queries more frequent -- one per tunnel connect -- not fewer.

Persisted as its own boolean rather than a sentinel hour count.
forHours() snaps unrecognised values to HOURS_12, so a "never" encoded in the
interval key would sit one stale read away from decoding back into a live
12-hour cadence and silently resuming the egress the user switched off.
NEVER.hours is null, so no integer can name it. The stored cadence is left
untouched while checks are off, so switching back restores it.

Tests assert at the CtLogFetcher boundary -- the frame that opens the socket --
over a real CtLogMonitor, not a stubbed source: a gate that suppressed only the
result would still reach the fetcher and fail. Both directions are covered, so
an implementation that disabled everything, or that could never be turned back
on, does not pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

* Cite the approval provenance instead of flagging it unverified (#740)

The ux-decisions entry shipped with its Approved by line reading "NOT
independently verified" and asking Jason to confirm it. That was the honest
state at the time -- the approval reached the implementing agent relayed, and
writing an owner's name against a quote it had not witnessed is what #735 did
wrong. But an entry that merges in that state leaves a permanent open question
in the file that is supposed to be the record.

The repo agent has since posted the verbatim provenance on #741
(issuecomment-5604042230). Cite it, and attribute the witnessing to the repo
agent rather than to this agent -- that distinction is the reason the line was
flagged in the first place, so collapsing it now would defeat the point.

Jason proposed the design himself: offered a separate CT-specific toggle, he
asked for "a different value in the interval? like never" instead. The
approval covers the mechanism and the order of work. It does not cover the
reply to fdroiddata!42096, which he reserved for his own sign-off; the entry
now says so.

Also records that the entry is voluntary. Adding an option to an existing
Settings control is a pure addition behind an existing entry point, which
.claude/rules/ux-changes.md lists under "does NOT require approval". Without
that note a future reader would read this as a mandatory gate that was nearly
missed.

Docs only -- no code, tests or goldens touched.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

---------

Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 12:03:07 -04:00
monkopedia-coder
e0fa82f7a4
Remove TunnelSessionManager from jvmMain (#671) (#684)
Some checks are pending
Android CI / test (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build & Test (push) Waiting to run
Closes #671

`TunnelSessionManager` was test infrastructure living in `jvmMain`. Nothing in
any `main` source set ever constructed it, it never had a Koin binding, and the
collector that actually ships is
`TunnelForegroundService.collectIncomingSessions`. Sitting in a production
source set it read as a second, competing collector one wiring change away from
being used, and its comments argued production error-reporting policy for a
code path that never ran.

The class is deleted. The collect-into-handler helper its tests needed moves to
`core/bridge/src/jvmTest/.../SessionCollection.kt`, next to its only callers,
where it makes no claims about production; `:app`'s integration test collects
inline instead, because `:core:bridge`'s test source set is not on `:app`'s
unit-test compile classpath.

Not a coverage regression, despite how the diff reads. This removes
`TunnelError.UnhandledTlsState` escape-pinning *from the manager* only.
`SessionHandlerDefectVisibilityTest` still pins exactly that property, in the
same module, for `SessionHandler` -- the class that does ship -- and it is
pinned end-to-end at four shipped layers: thrown in `TlsAcceptor`, surviving to
the handler boundary, rethrown by `SessionHandler`, and becoming a crash report
in `TunnelBoundaryFailureReportingTest`. What is deleted was a fifth, parallel
pin on a class nothing constructed. Please do not revert this as a lost guard.

The one property that needed migrating is now better covered than before. "One
bad session must not take the collector down" was pinned only against the
manager, so it was not actually covered on the path that ships. It moves to
`TunnelBoundaryFailureReportingTest` as `an ordinary session failure does not
stop the collector`, driving the real service through the real Koin graph.
Every pre-existing test there delivers exactly one stream and so stays green on
a boundary that handles its first failure and then stops collecting forever;
only a second stream can tell the difference, which is why the new test emits
two. Verified by ablation, not by reading: removing the per-stream `launch` and
the `catch` turns it red.

`ToolCallViaSniPassthroughTest`'s kdoc claimed the manager came "from the
production Koin graph" while it was hand-constructed, because no binding
existed. The kdoc now enumerates precisely which pieces are production
(`SessionHandler`, `CertificateStore`) and which are scaffolding
(`TunnelClientImpl`, built with a fixture websocket factory).

`TunnelSessionManagerTest` is deleted for free: its 103-line helper block was
byte-identical to `ClientPassthroughTest`'s and its sole test a variable-rename
clone. Its two extra `initialize should succeed` assertions are folded into the
survivor, and its three detekt baseline entries go with it.

Docs: four references updated in `docs/design/android-app.md` (20, 33, 321) and
`docs/test-coverage-audit.md:79`. That last one credited "✓ Good" coverage to a
class that ships nowhere -- one instance of the pattern issue #654 tracks. This
removes that instance only; #654 is a broader audit and stays open.

No `docs/ux-decisions.md` entry: `.claude/rules/ux-changes.md:21` exempts
documentation updates that describe already-shipped behaviour.

Reviewed-by: reviewerbot
2026-09-02 07:06:24 -04:00
monkopedia-coder
c081ce3feb
Discriminate three ways at the tunnel service boundary (#642) (#650)
* Discriminate three ways at the tunnel service boundary (#642)

TunnelForegroundService funnelled every exception escaping handleStream
into crashReporter.logCaughtException, so a peer aborting mid-handshake,
a genuine TunnelError.UnhandledTlsState and plain cancellation were
indistinguishable in the crash channel. That is the mirror image of the
discrimination #616/#626/#630/#639/#643/#647 built inside the TLS layer:
UnhandledTlsState exists precisely so the copy loops can stay quiet about
ordinary disconnects while surfacing real defects, and this boundary
discarded it.

CancellationException extends IllegalStateException, so it was being
swallowed into a crash report too -- the remaining half of #644, whose
first half (#647) made cancellation arrive recognisable out of accept.

Classify in three, not two, reusing the existing type vocabulary:
cancellation propagates silently, peer/transport events (TlsHandshakeFailed,
ConnectionFailed, WebSocketClosed, StreamRefused, StreamReset, plain
IOException) get Log.i so the abort rate stays measurable, and everything
else -- UnhandledTlsState and anything unanticipated -- stays loud on
Log.e + logCaughtException. The quiet set is a closed allowlist and the
else arm is Defect, so "report nothing" cannot creep in.

Applied at both reporting sites (handleStream and connect), plus a
cancellation-propagation sweep of every other catch in work/src/main.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

* Inspect ConnectionFailed's cause before classifying it quiet

TunnelClientImpl.connect wraps anything non-TunnelError escaping it into
a TunnelError.ConnectionFailed. Classifying that type blanket-quiet at the
boundary would silence every defect that broad wrap had laundered -- the
"report nothing" failure this change exists to avoid.

A ConnectionFailed caused by an IOException, or with no cause at all
(our own code stating that the link is gone), stays routine. One wrapping
an NPE or an IllegalStateException is a laundered defect and stays loud.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-30 22:48:31 -04:00
Jason Monk
cee47059e5
Defensively reconcile foreground notification against live tunnel state (#510) (#513)
#506 fixed the root cause of the stuck "Connecting…" foreground notification
(the foss UnifiedPush wake no longer ANRs the main thread, so the lifecycleScope
`tunnelClient.state` collector in observeStateChanges runs normally and
reconciles to "Connected"). This adds a belt-and-suspenders reconcile so a
tunnel whose socket is genuinely ESTABLISHED can never be left showing
"Connecting…", independent of whether that Main-dispatcher collector was
momentarily starved.

reconcileNotification() re-renders the foreground notification from
`tunnelClient.state.value` (ground truth), reusing updateNotification() so the
copy is identical. It is called from two hooks that can't be missed:
- in onStartCommand's coroutine right after awaitReady(), on every wake;
- immediately after a successful connect() returns (socket established).

StateFlow replays its current value to new collectors, so a transition is not
normally dropped — the collector is not a true single point of failure. This
reconcile is purely defensive hardening; no user-facing flow changes.

Co-authored-by: monkopedia-coder <monkopedia+coder@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 17:12:41 -04:00
Jason Monk
11c9825942
feat(foss): "Ignore daily time limit" toggle runs the tunnel FGS as specialUse (#509)
Android 15 caps dataSync foreground services at 6h cumulative per 24h. A foss
user who keeps the tunnel connected for long interactive MCP sessions can hit
that ceiling on a genuinely active day and have the service killed mid-use.

Add a foss-only, opt-in "Ignore daily time limit" setting. When ON, the tunnel
foreground service enters the foreground as specialUse instead of dataSync,
which has no 6h/24h cap. This ONLY changes the FGS type: the adaptive
idle-timeout / quick-disconnect teardown still governs when the tunnel drops,
so the type swap merely removes the hard ceiling.

It is foss-only because declaring specialUse triggers Google Play review, and
Play steers persistent-connection use cases to FCM (which the google build
already uses). The Play build stays dataSync-only and never declares the
specialUse type or the FOREGROUND_SERVICE_SPECIAL_USE permission.

Implementation:
- New FgsTypeSelector seam in :work, injected into TunnelForegroundService so
  startForeground() asks for the type instead of hardcoding DATA_SYNC. Bound
  per-distribution: GoogleFgsTypeSelector (constant dataSync) vs
  FossFgsTypeSelector (specialUse when opted in AND API 34+, else dataSync).
- foss reads a synchronously-cached IgnoreDailyTimeLimitState mirror of the
  persisted flag, since startForeground() can't suspend on a DataStore read.
- Setting persisted via AppStatePreferences.ignoreDailyTimeLimit (default OFF),
  threaded through SettingsViewModel state + setter. The Settings row is gated
  on an injected canIgnoreDailyLimit capability flag (true in foss
  DistributionModule, false on google) — no BuildConfig.FLAVOR checks in UI.
- foss manifest overlay sets foregroundServiceType="dataSync|specialUse" and
  adds PROPERTY_SPECIAL_USE_FGS_SUBTYPE; google merged manifest stays dataSync.
- Existing onTimeout / ForegroundServiceStartNotAllowedException dataSync-budget
  handling is unchanged; it simply won't fire while running as specialUse.

UX decision logged in docs/ux-decisions.md (owner-approved in-session).

Co-authored-by: monkopedia-coder <monkopedia+coder@gmail.com>
2026-06-23 12:49:08 -04:00
Jason Monk
e631751a9e
feat(work): adaptive idle timeout to protect the Android 15 dataSync budget (#508)
Android 15 caps dataSync foreground services at 6h cumulative per 24h. A
lightweight wake (an MCP client that only lists tools/resources then idles)
previously held the tunnel CONNECTED for the full idle timeout, burning the
budget for ~1s of real work.

Make the post-session teardown adaptive: a wake cycle is "substantive" only if
its MCP stream issued at least one tools/call. The session layer flags this via
the existing AuditListener.onToolCall (SessionActivityAuditListener ->
SessionActivityTracker); IdleTimeoutManager reads it when arming and resets it
on DISCONNECTED. Substantive cycles keep the existing "Idle timeout" (minutes);
discovery-only or spurious wakes get the new, shorter "Quick disconnect"
timeout (seconds).

Add the "Quick disconnect" setting (15s/30s/1min, default 30s) below "Idle
timeout" in the Connection settings cluster, persisted via the same DataStore
mechanism. The existing "Disable timeout" switch is unchanged.

Co-authored-by: monkopedia-coder <monkopedia+coder@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-23 11:54:30 -04:00
monkopedia-coder
c2f910e791
FOSS #476: move Firebase out of :work so the foss APK links zero firebase-* (#477)
The foss runtime classpath still pulled firebase-auth + firebase-messaging
transitively via the shared :work module, even though foss runs keypair +
UnifiedPush at runtime. F-Droid rejects APKs that link proprietary deps, so
:work must be Firebase-free.

Relocate the Firebase-coupled classes from :work into the :app `google`
source set, leaving the Firebase-free seams/interfaces in :work:

- FirebaseRenewalAuthProvider -> app/src/google (com.rousecontext.app.auth),
  behind the existing RenewalAuthProvider seam (foss already binds
  KeypairRenewalAuthProvider).
- FcmReceiver (FirebaseMessagingService) -> app/src/google
  (com.rousecontext.app.push); its manifest entry already lived in
  app/src/google. It delegates to the Firebase-free WakeDispatcher /
  FcmTokenRegistrar, which stay in :work.
- TunnelForegroundService's per-connect FCM-token push (the last
  FirebaseMessaging usage) now goes through a new ConnectPushReporter seam in
  :work. google binds FcmConnectPushReporter (fetches the FCM token via the
  existing FcmTokenProvider seam and forwards it); foss binds a no-op (its
  UnifiedPush endpoint is reported by UnifiedPushBackgroundDelivery).

Drop firebase-auth/messaging from :work's build.gradle.kts; they remain
googleImplementation in :app. Moved tests to app/src/testGoogle.

google behavior is unchanged — same Firebase auth + FCM paths, just relocated.

Classpath evidence:
  fossDebugRuntimeClasspath  | grep firebase -> (nothing)
  googleDebugRuntimeClasspath | grep firebase -> firebase-auth, firebase-messaging, firebase-crashlytics

Part of #460. Fixes #476.

Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-14 12:51:06 -04:00
monkopedia-coder
94b7fb4946
FOSS #463: UnifiedPush wake path (app/UX half, deferred activation) (#473)
Adds the foss-flavor UnifiedPush on-demand wake path — the Firebase-free
counterpart of the FCM wake path — behind a flavor-agnostic BackgroundDelivery
seam so all UnifiedPush API use stays out of the shared source set.

Option A (deferred activation): a foss device has no push endpoint until a
distributor is chosen, and the merged relay (#472) requires a push target to
register. So foss onboarding completes WITHOUT registering — a skipped device
lands on a degraded Home with a "set up a delivery app" banner; registration
fires later when a distributor reports its endpoint, which activates the device.

- core/tunnel: RegisterRequest.push_endpoint + TunnelClient.sendPushEndpoint
  ({"type":"push_endpoint",...}); threaded through OnboardingFlow/register.
- foss UnifiedPushReceiver routes wake/renew through a shared WakeDispatcher
  (extracted from FcmReceiver) and reports endpoints via UnifiedPushBackgroundDelivery.
- "Background delivery" picker (after Welcome; foss-only nav), ON_RESUME rescan,
  ntfy-only-when-empty, Settings row, degraded Home banner.
- Home gate relaxed for foss (onboarding-complete flag, not subdomain).
- Roborazzi goldens for the shipping picker/banner/Settings-row.
- docs/ux-decisions entry (deferred-activation correction).

Fixes #463.

Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-14 10:05:52 -04:00
monkopedia-coder
e635e73393
Keypair device identity for foss flavor (#462) (#468)
* Keypair device identity for foss flavor (#462)

Replace Firebase Anonymous Auth with a hardware-keypair identity for the
`foss` flavor, while the relay accepts BOTH Firebase (google) and keypair
(foss) auth simultaneously.

Relay:
- DeviceRecord gains an optional key_thumbprint (base64 SHA-256 of SPKI DER);
  find_device_by_thumbprint mirrors find_device_by_uid.
- New keypair_auth module: canonical proof message, bounded-timestamp replay
  check, signature verify, thumbprint derivation (+ unit tests).
- POST /register, /register/certs, /renew accept a keypair variant alongside
  the unchanged Firebase path.

App (foss only):
- Real keypair DeviceCredentialProvider + RenewalAuthProvider replace the
  stub auth bindings; google keeps its Firebase impls.
- Flows thread a flavor-agnostic DeviceCredential.

Part of #460. Fixes #462.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* cargo fmt the keypair_auth relay code (#462)

CI Format check (rustfmt) flagged the new keypair_auth/register/renew
Rust code. Pure formatting; no logic change.

---------

Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 15:17:12 -04:00
monkopedia-coder
f163bd586a
Add google/foss product flavors (#461) (#466)
* Add google/foss product flavors (#461)

Introduce a `distribution` flavor dimension on `:app` with two flavors:

- `google` — the unchanged shipping build (Firebase/FCM/Crashlytics).
- `foss`   — compiles with zero firebase-*/google-services/Play-Services
  dependencies; google-services.json is not required to assemble it.

The google-services and firebase-crashlytics Gradle plugins are now applied
conditionally (skipped for a foss-only build, detected by requested task name),
and the Firebase deps are scoped to `googleImplementation`. The three runtime
seams get flavor-specific Koin bindings via a new `distributionModule`:
CrashReporter, AnonymousAuthClient/FcmTokenProvider/DeviceAuthTokenProvider, and
RenewalAuthProvider. The foss flavor binds NoOp/stub placeholders — real impls
land in #462-#464; #461 only needs both flavors to assemble.

Two direct FirebaseAuth call sites in shared `:app`/debug code
(IntegrationSetupViewModel, AddIntegrationDestination, TestCommandProvider) are
moved behind the seams so `main`/`debug`/`foss` compile Firebase-free.

The shared `:work` module keeps its Firebase types for now; only the FCM
`FcmReceiver` manifest entry moves to the google-flavor manifest so it is absent
from the foss build's merged manifest.

CI/task renames: assembleDebug -> assembleGoogle/FossDebug, testDebugUnitTest ->
testGoogleDebugUnitTest, release builds the google flavor only (dual-flavor
release is #465). Kover excludes the foss debug + flavored release test tasks.

Part of #460. Fixes #461.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Load flavor distributionModule in integration test harness

PR #461 moved CrashReporter, AnonymousAuthClient, FcmTokenProvider,
DeviceAuthTokenProvider, and RenewalAuthProvider out of the base appModule
into per-flavor distributionModule. RouseApplication registers both, but the
integration-test Koin bootstrap (AppIntegrationTestHarness.bootKoin) only
loaded appModule, so those five definitions were missing and every
com.rousecontext.app.integration.* test failed with NoDefinitionFoundException.

Add distributionModule (google variant on the integrationTest classpath) to
the startKoin module list, between appModule and the test overrides so any
harness fake still wins. Mirrors RouseApplication's base + distribution
composition.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Fix stale variant-task references missed in the flavor rename (#461)

- docs/self-hosting.md: :app:compileDebugKotlin -> :app:compileGoogleDebugKotlin
- app/build.gradle.kts comment: testDebugUnitTest -> testGoogleDebugUnitTest

Flagged by reviewer on PR #466.

---------

Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-13 08:55:11 -04:00
monkopedia-coder
080cdf0987
Deduplicate graceful-shutdown sequence (#455) (#458)
The #446 teardown sequence (withTimeoutOrNull { mcpSession.shutdown() }
then tunnelClient.disconnect()) was duplicated in two modules:
TunnelForegroundService.onDestroy (:work) and the IdleTimeoutManager
onTimeout lambda wired in AppModule (:app), each with its own copy of the
GRACEFUL_SHUTDOWN_TIMEOUT_MS = 5_000L constant. Tuning one (timeout,
ordering, an added step) would silently drift the other across modules.

Factor the sequence into a single `suspend fun gracefulTunnelShutdown`
plus one GRACEFUL_SHUTDOWN_TIMEOUT_MS constant in :work (the lowest module
that already depends on both :core:mcp and :core:tunnel, and is depended on
by :app). Both call sites now invoke it. Pure refactor: ordering, the 5s
value, and the onDestroy lifecycleScope.launch structure are unchanged.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-07 23:41:09 -04:00
monkopedia-coder
d9deb85106
Wire the dormant Connection settings cluster (#453) (#456)
The entire "Connection" settings group was built as UI but never connected
to the ViewModel/destination, so four controls were silently inert:

- the idle-timeout dropdown discarded its selection (`setIdleTimeout` threw
  away its argument; the displayed value was a hardcoded 5);
- the "Disable timeout" switch's callback was unwired and it was gated on a
  `batteryOptimizationExempt` flag hardcoded to false (permanently greyed);
- the battery-optimization warning's `showBatteryWarning` was hardcoded true,
  so every user saw a permanent, non-actionable warning;
- the "Fix this" button's callback was unwired.

Wire all four to behave as their labels promise:
- persist idle-timeout minutes + the disable flag in AppStatePreferences;
- IdleTimeoutManager now reads its timeout from a `suspend () -> Long?`
  provider each CONNECTED cycle (null = disabled => timer never arms), so a
  settings change takes effect on the next wake without a service restart;
- derive batteryOptimizationExempt + showBatteryWarning from the real
  PowerManager status via a shared BatteryOptimization helper (lifted from
  BugReportUriBuilder), re-read on Settings resume;
- "Fix this" opens ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS (no
  Play-restricted permission, unlike the direct-request intent).

Tests cover the prefs round-trip, the dynamic/disabled timeout provider, the
battery helper, and the ViewModel persist + state-reflection paths. Verified
on a Pixel 6 Pro (Android 17): selecting 10 min updates live and survives a
process restart. docs/ux-decisions.md records activating the battery-opt
system screen via the existing "Fix this" button.

With the timeout disabled the tunnel stays foregrounded until the 6h dataSync
FGS cap stops it (the #452 path) — intended semantics.

Fixes #453

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-02 08:31:04 -04:00
monkopedia-coder
4b2ec2fd68
Stop FGS gracefully on dataSync run-time timeout (#450) (#452)
Android 15+ enforces a cumulative ~6h/24h limit on dataSync foreground
services. When the budget is exhausted while the service is running, the
system calls Service.onTimeout() and requires a prompt stop; otherwise it
force-kills the process with ForegroundServiceDidNotStopInTimeException
(#450, #451).

TunnelForegroundService handled the symmetric start-time case
(ForegroundServiceStartNotAllowedException -> notify + stopSelf) but never
overrode onTimeout, so a budget that ran out mid-session crashed silently.
v1.0.2's keep-Ktor-alive-across-idle change made the service stay
foregrounded longer, accelerating accumulation toward the cap.

Override onTimeout to mirror the start-time path: suppress reconnect, post
the existing FgsLimitNotifier, and stopSelf. Add a Robolectric test
(@Config sdk=35) covering the handler, and a docs/ux-decisions.md entry for
the new lifecycle moment at which the budget notification can appear.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 16:13:24 -04:00
Jason Monk
dcfda5e92d
Cancel stale security-check notifications on Verified or Skipped (#449)
Previously, when a security check (CT log or self-cert) crossed the
warning threshold and posted an info/alert notification, a subsequent
Verified or Skipped run reset the in-prefs streak counter but never
cleared the notification from the shade. Users were left with stale
warnings indicating an outage that had already recovered.

Add SecurityCheckNotifier.cancel(check), implement in
AndroidSecurityCheckNotifier by cancelling both the alert and info
notification ids for the given check, and call it from
SecurityCheckWorker's Verified and Skipped branches alongside
prefs.resetWarningStreak(). NotificationManager.cancel is idempotent,
so cancelling an absent id is a no-op.

Closes #448
2026-05-05 12:23:50 -04:00
Jason Monk
1ed99f350d
Add graceful MCP session shutdown before tunnel disconnect (#446) (#447)
When the phone's idle timeout fires, abrupt tunnel teardown kills active
SSE streams. Claude Code counts each disconnect as a terminal error and
after 3 sleep/wake cycles marks the server as permanently dead.

Add McpRoutes.shutdown() that cleanly closes all session transports
before the tunnel is torn down. SSE handlers exit their keepalive loop
normally so the client sees a server-initiated close instead of a reset.

Wire the shutdown into both IdleTimeoutManager.onTimeout and
TunnelForegroundService.onDestroy with a 5-second timeout guard.

Closes #446

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-03 10:46:21 -04:00
Jason Monk
497ed796c7
Deduplicate warning-streak increments within 6-hour window (#439)
Each tunnel reconnect triggers an opportunistic security check if >6h
stale (TunnelForegroundService:217). During heavy testing (100+ e2e
iterations, cold-start probes), this fires constantly, inflating the
warning streak far faster than the intended "12h periodic × 3 threshold
= 36h before notification" cadence.

Fix: incrementWarningStreak now records a per-source timestamp. If
<6h have passed since the last increment for that source, the call
is a no-op (returns the existing streak, doesn't bump). Rapid
reconnects within the window are deduplicated into a single logical
failure.

The interval is injectable via constructor (tests pass 0 to disable
dedup and preserve existing test timing). Production uses the 6h
default via Koin.
2026-04-30 12:53:31 -04:00
Jason Monk
1a12fd12ac
Fix #429: Suppress security-check re-notifications for ongoing warning streak (#430)
Once a Warning streak crossed the 3-run notification threshold (#256), the
SecurityCheckWorker fired a fresh notification every scheduled interval as
long as the streak persisted, because nothing tracked "we already told
the user". User report: crt.sh has been flaky and the phone has been
posting 502 notifications every interval for hours.

Fix: per-source `notifiedForStreak` flag set on first notification past
threshold, cleared when the streak resets via Verified or Skipped (same
hook as the existing streak counter reset). Subsequent Warning runs in
the same streak log silently.

If the streak breaks (a Verified or Skipped result lands) and a new
3-run streak builds, the next notification fires normally.

Tests:
- `continued warning past threshold does not re-notify until streak breaks`
- `verified after notified streak resets state and next streak fires again`
2026-04-27 11:47:16 -04:00
Jason Monk
ec389786d9
Fix #414: Await IntegrationProviderRegistry first emission before checking enabledPaths() (#416)
On a cold-start FCM wake, FcmReceiver and TunnelForegroundService both read
ProviderRegistry.enabledPaths() synchronously to decide whether to honor the
wake. The app-side IntegrationProviderRegistry is DataStore-backed: its
_enabledIds StateFlow starts at emptySet() and only populates after the first
async combine() emission lands. In a freshly-spawned process the FCM message
arrives before that emission, the synchronous read returns emptySet(), and the
wake is silently dropped — every subsequent AI-client request EOFs after the
relay's 20s wakeup timeout.

This fix introduces ProviderRegistry.awaitReady()/awaitReadyBlocking() and
routes the three production callers through it before checking enabledPaths():

- FcmReceiver.onMessageReceived blocks the FCM worker thread (NOT main) on a
  CountDownLatch with a 2s timeout, then runs the empty-check and dispatches.
- TunnelForegroundService.onStartCommand defers the empty-check into a
  lifecycleScope coroutine that suspends on awaitReady() first.
- The state-store collector signals readiness on its first emission (which is
  emptySet() if nothing is enabled on disk — still a valid loaded state).

Empty integrations list → registry is trivially ready (no flow to wait on).
On timeout, drop the wake rather than spin up the tunnel against unknown state.

Reproduced via /tmp/probe-fresh and /tmp/probe-warm1: relay sends FCM, device
logs "Ignoring wake: no integrations enabled" and returns, relay's 20s timer
fires, client gets TLS EOF. The new FcmReceiverTest.`wake dispatches to
startService once registry becomes ready with enabled state` regression test
fails on the pre-fix code (verified) and passes here.

Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
2026-04-26 11:38:58 -04:00
Jason Monk
7ddd98c3e6
Fix #381: Privacy page + debug-only Renew Cert button in Settings (#382)
- Add a Privacy row in the Settings About section that opens
  `https://rousecontext.com/privacy` via `ACTION_VIEW`. The docs page
  itself already lives at `docs/user/privacy.md`; this PR wires the
  in-app link and adds the label string.
- Add a debug-only Developer section with a "Renew cert now" button
  that enqueues a one-shot cert renewal through a new
  `CertRenewalScheduler.enqueueOneShot` entrypoint (distinct unique-work
  slot, REPLACE policy so spammed taps collapse to a single pending
  request). Gated on `BuildConfig.DEBUG` so the section is not rendered
  for release users.
- Extract a `renewalConstraints()` helper in `CertRenewalScheduler` so
  the periodic, delayed, expiring-immediate, and one-shot paths all
  share the same `NetworkType.CONNECTED + requiresBatteryNotLow`
  constraints instead of duplicating the builder three times.
- Force `showDeveloperSection = false` in the Settings Roborazzi
  screenshot tests so the recorded goldens match what release users
  see, regardless of `BuildConfig.DEBUG` in the test variant. The
  Privacy row is visible in release builds so it does appear in the
  goldens (though the Settings layout happens to render it below the
  800dp test viewport, so the existing PNGs remain pixel-identical).

Tests:
- `CertRenewalSchedulerTest` covers the new one-shot path: enqueue,
  REPLACE-on-re-enqueue, and slot distinctness from the periodic and
  immediate slots.
- `SettingsPrivacyRowTest` (new) asserts the Privacy row renders and
  fires its callback, that the Developer section is hidden when
  `showDeveloperSection = false`, and that tapping "Renew cert now"
  fires the callback and surfaces the "Renewal enqueued" confirmation.

Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
2026-04-23 14:56:36 -04:00
Jason Monk
30f63b2155
Fix #330: Add network constraint to SecurityCheckWorker (#351)
The periodic SecurityCheckWorker was enqueued with no Constraints, so it
fired while offline or behind a captive portal. Captive portals respond
to the crt.sh lookup with an HTML interstitial, which the worker reported
as "crt.sh returned HTTP 404 body=<!DOCTYPE H..." — a false-positive
notification every time a user walked into a hotel lobby, cafe, or metro.

Extract the scheduling into a new SecurityCheckScheduler object under
:work (mirroring CertRenewalScheduler) and apply the same constraints
the cert-renewal worker already uses:

  - NetworkType.CONNECTED — the whole point: don't fire when the only
    reachable host is a captive-portal interstitial.
  - requiresBatteryNotLow=true — consistent with renewal; no reason to
    spend the last 10% on a monitoring check.

Extracting to a scheduler object makes the constraints unit-testable in
:work without needing to drive the Application subclass through
Robolectric — the same pattern CertRenewalScheduler established for #277.

Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
2026-04-21 22:29:11 -04:00
Jason Monk
a2aa589b77
Fix #325: Eliminate foreground-service startup race on cold-start FCM wake (#328)
On cold-start FCM wakes, Application.onCreate (Koin graph, Firebase,
notification channels) consumed most of the 5-second FGS timer budget,
leaving almost no margin for TunnelForegroundService.startForeground().
When the budget was exceeded, Android killed the process with
ForegroundServiceDidNotStartInTimeException, closing the WebSocket ~4s
after connection.

Two changes eliminate the race:

1. TunnelForegroundService.onCreate now calls startForeground() as its
   very first action after super.onCreate(), before
   NotificationChannels.createAll() or any coroutine work. The
   notification channel already exists from Application.onCreate; the
   defensive createAll() is moved after startForeground.

2. RouseApplication.onCreate defers non-critical init (crash reporting,
   security-check scheduling, cert renewal scheduling) to a posted
   Handler message. This lets the service's onCreate run sooner after
   Application.onCreate returns.

A new Robolectric test verifies that the foreground notification is set
synchronously in onCreate, before the main looper drains any coroutines.

Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
2026-04-20 12:55:54 -04:00
Jason Monk
68be0f457a
Fix #289: Force-immediate cert renewal check on app start (#294)
Before this change, `RouseApplication.onCreate` only scheduled the 24h
periodic `CertRenewalWorker`. A user who opens the app with an already-
expired cert would sit stuck for up to 24h before the first periodic
tick. The tunnel's mTLS handshake fails on an expired cert, so there
was no in-band recovery path.

Add `CertRenewalScheduler.enqueueImmediateIfExpiring` which reads the
stored cert's expiry, compares it to a configurable threshold (default:
the worker's own 21-day renewal window), and enqueues a one-time
`CertRenewalWorker` under a dedicated unique-work slot
(`cert_renewal_immediate`) when the cert is near-or-past expiry.
`ExistingWorkPolicy.KEEP` avoids resetting run attempts on repeated app
restarts.

Wire this into `RouseApplication.onCreate` after the existing
`enqueuePeriodic` call. The new unique-work slot is distinct from the
periodic slot so the 24h schedule is preserved as the long-running
safety net.

Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
2026-04-19 16:11:25 -04:00
Jason Monk
1fb30338d5
Fix #285 (part 2): auto-push integration secrets on state-store flip (#288)
* Fix #285 (part 2): auto-push integration secrets on state-store flip

Part 1 (PR #286) made the relay's /rotate-secret replace-wholesale so a
shorter integrations list actually drops the removed entries from the
valid-secrets cache. Part 2 closes the device side: without a listener
on IntegrationStateStore, disabling an integration from Settings flipped
a local DataStore flag but never told the relay, so the disabled
integration's secret stayed live for any AI client with the URL.

IntegrationSecretsSynchronizer observes every configured integration's
observeUserEnabled() flow, combines them into the current enabled set,
debounces rapid flips (500ms), and POSTs /rotate-secret with the
current enabled set. Retries transient failures with the same
exponential backoff IntegrationSetupViewModel uses. Wired as a
createdAtStart Koin single so the observer is running before any UI
touches the state store.

Coexists with IntegrationSetupViewModel's onboarding-time push: the
synchronizer's collect loop peeks at certStore.getIntegrationSecrets()
and skips the push when the stored set already matches the enabled
set — that's the "VM just pushed and we'd only duplicate" case.

Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>

* Fix #285 (part 2): tighten integration-test timing for CI

Drop the `state-store-only enable flip` test added to
EnableSecondIntegrationTest — its coverage duplicates the
DisableIntegrationTest state-store flip case and the
IntegrationSecretsSynchronizer unit tests, and the extra relay
subprocess pushed the `:app:integrationTest` suite past the 10-minute
CI budget. Reduce the SYNC_QUIESCE wait in DisableIntegrationTest from
1.5s to 800ms (debounce is 500ms, so 800ms keeps a safe margin).

Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
2026-04-19 15:05:01 -04:00
Jason Monk
ece9639d0f
Fix #233: Wire up Firebase Crashlytics for release builds (#261)
Post-ship crashes now surface in the Firebase console so we can react to
regressions without waiting for users to file manual bug reports. Debug
builds skip collection so local repros don't pollute the dashboard.

- Add Crashlytics Gradle plugin + dependency (piggybacks on the existing
  google-services.json already shipped for FCM, so no new secrets).
- Release builds upload R8 mapping files via the plugin so stack traces
  in the console stay deobfuscated; debug builds skip that slow step.
- Add a thin CrashReporter interface in :api so :app, :work, and other
  feature modules can log caught exceptions without taking a direct
  dependency on Firebase. Production impl (FirebaseCrashReporter) lives
  in :app; all other modules see only the contract plus CrashReporter.NoOp.
- Initialize collection state in RouseApplication.configureCrashReporting
  gated on BuildConfig.DEBUG — release builds collect by default, debug
  builds stay silent.
- Surface previously-swallowed failures at the sites called out in the
  issue: cert provisioning storage/key-gen failures in IntegrationSetup,
  tunnel connect/session-handler errors in TunnelForegroundService,
  terminal KeyGenerationFailed + CnMismatch outcomes in CertRenewalWorker,
  and KeyInfo inspection failures in AndroidKeystoreDeviceKeyManager.
  Uncaught exceptions are still handled automatically by Crashlytics'
  default UncaughtExceptionHandler, so these explicit reports only cover
  the paths we'd otherwise lose.

Privacy note: enabling Crashlytics collects crash stacks + Firebase
installation IDs, which will change the Play Store data-safety
declaration when we list. A user-facing opt-out toggle was scoped out
of this PR (see follow-up candidates) — current behaviour is on-by-
default for release builds.

Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
2026-04-18 21:46:22 -04:00
Jason Monk
133240efa7
Fix #256: Retry transient 5xx in HttpCtLogFetcher and debounce Warning notifications (#257)
crt.sh routinely 502s under load, and before this change a single hiccup
surfaced directly as a user notification. Two complementary fixes:

1. HttpCtLogFetcher retries 5xx and network IOExceptions with exponential
   backoff (1s/3s/9s, ~13s total wall, under the 30s security-check budget).
   4xx still fails fast -- a bad query will never succeed on retry. Uses
   kotlinx.coroutines.delay so cancellation is respected.

2. SecurityCheckWorker debounces Warning notifications: a user notification
   fires only after the same source returns Warning on N=3 consecutive runs.
   Any non-Warning result (Verified/Alert/Skipped) resets the counter. Alerts
   still fire immediately; debouncing applies only to Warning. Counter
   persisted per source in SecurityCheckPreferences.

Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
2026-04-18 20:20:23 -04:00
Jason Monk
b12928c7f3
Fix #243: Always reconnect on FCM wake, never trust stale tunnel state (#245)
An FCM wake from the relay proves it needs a fresh WebSocket -- it would
not have sent the push if it already had one. The previous WakeAction.Skip
path trusted a passing mux-level health check, but a half-open TCP socket
can sit in ACTIVE while the relay has already dropped its WebSocket mapping
(idle timeout, restart, NAT timeout). Every inbound MCP call then fails
until the user force-stops the app.

Remove WakeAction.Skip entirely. The decider now always returns Reconnect
on FCM wake. The health check ping is still performed for diagnostics:
wasStale=true means the tunnel was confirmed dead, false means it looked
alive but the relay disagrees.

Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
2026-04-18 12:49:39 -04:00
Jason Monk
6d5b82cc20
Fix #227, #228: classify pre-onboarding as Skipped, check CT HTTP status (#229)
Two related bugs in the security-check pipeline that produced noisy
and misleading notifications for a freshly-installed device:

#227: HttpCtLogFetcher passed the response body straight to the JSON
parser without checking the HTTP status. crt.sh's transient 502/503
HTML error pages got surfaced as "Malformed CT log response" -- wording
that reads as "the CT log itself is corrupt" when the actual cause is
a Sectigo outage. Now throw IOException on non-2xx so CtLogMonitor
classifies as "Could not reach CT log service" instead.

#228: Pre-onboarding devices (no cert, no subdomain) fired "Security
Check" warning notifications describing a state that is just "not set
up yet." Introduce SecurityCheckResult.Skipped for "not applicable"
cases and route it through the worker without firing a notification.
The Settings screen renders "Waiting for onboarding" in muted colours
so the audit trail is still visible for users who look.

Constraints preserved:
- Alert path unchanged -- real issuer mismatches still fire loudly.
- Genuine network / I/O failures still produce Warning notifications.
- Only pre-onboarding classifications were reclassified to Skipped.

Closes #227
Closes #228

Co-authored-by: Claude Opus 4 (1M context) <noreply@anthropic.com>
2026-04-18 06:24:34 -04:00
Jason Monk
e4583516c4 Fix #200: generate device identity key in Android Keystore (TEE/StrongBox)
Before: CsrGenerator minted ECDSA P-256 keys via KeyPairGenerator.getInstance("EC")
and FileCertificateStore persisted them as encrypted PEM on disk. Any root-level
process could read them.

Now: the device identity keypair is owned by a new DeviceKeyManager interface
(in :core:tunnel), implemented on Android by AndroidKeystoreDeviceKeyManager
(in :app) which provisions the key under alias `rouse_device_key` in the
hardware-backed Android Keystore. StrongBox is preferred with a TEE fallback on
StrongBoxUnavailableException. Private key bytes never enter app memory:
SHA256withECDSA signing is driven through the Keystore provider.

CsrGenerator.generate(cn, keyPair) now takes a caller-owned KeyPair; the PEM-key
parsing path (generateWithExistingKey) and CsrResult.privateKeyPem are gone.
CertProvisioningFlow and CertRenewalFlow take a DeviceKeyManager; the deprecated
CertificateStore.storePrivateKey / getPrivateKey hooks are silent no-op / null
defaults. CertStoreTlsCertProvider and MtlsWebSocketFactory build their
SSLContexts from DeviceKeyManager.getOrCreateKeyPair().private plus the PEM cert
chain already on disk. LazyWebSocketFactory carries the key manager forward.

Upgrade migration: on startup FileCertificateStore.migrateLegacyPrivateKeyFileIfNeeded
detects a legacy rouse_key.pem with no Keystore alias and calls clearCertificates(),
which triggers a fresh cert re-provision under the new hardware key. Subdomain and
integration-secrets files survive so the user is not bounced back to onboarding
(regression guard for issue #163). clearCertificates() no longer deletes the
Keystore alias; only clear() (full reset) does, because the relay pins the
registration public key and rollback must preserve it.

Tests:
- CsrGeneratorTest asserts the CSR carries exactly the caller-supplied public
  key DER and verifies under SHA256withECDSA.
- AndroidKeystoreDeviceKeyManagerTest (Robolectric) covers the first-call/
  second-call idempotency contract and a SHA256withECDSA round-trip; guarded by
  Assume.assumeTrue when the Robolectric runtime lacks the AndroidKeyStore
  provider.
- CertRenewalTest covers reuse of the keypair across consecutive renewals.
- FileCertificateStoreTest adds the legacy-PEM migration test (PEM present,
  alias missing -> cert state wiped, onboarding state preserved) and drops the
  obsolete encrypted-PEM round-trip tests.
- RelayApiClientIntegrationTest and CertRotationIntegrationTest rework registration
  and renewal helpers to pass a locally-generated KeyPair through the new
  CsrGenerator.generate(cn, keyPair) signature.

Adolin smoke-test (debug APK, 84TY004PW) confirms the startup migration fires on
an upgraded install -- log: "Legacy software-key PEM detected with no Keystore
alias; clearing cert state so issue #200 onboarding re-runs with a hardware-
backed key." Full re-registration plus StrongBox KeyInfo confirmation requires UI
interaction and is left to the user to verify.

Co-Authored-By: Claude Opus 4 (1M context) <noreply@anthropic.com>
2026-04-17 16:15:58 -04:00
Jason Monk
2d02e8253c Fix #210: one-shot guard for SelfCertVerifier TOFU backfill
The pre-#111 migration backfill in SelfCertVerifier.verify() was permanent:
an empty knownFingerprints set caused the presented leaf to be silently
trusted and recorded. If the fingerprints file was ever corrupted/emptied
after the migration fired (disk error, partial-snapshot restore, buggy
cleanup), the verifier would re-backfill whatever cert was presented --
defeating pinning.

Gate the backfill behind a one-shot sidecar marker stored alongside the
fingerprints file:

  - Marker absent + fingerprints empty  -> legitimate migration: backfill,
    write marker, return Verified.
  - Marker present + fingerprints empty -> corruption detected: Alert
    (no backfill, no state mutation).
  - Non-empty set                       -> normal match/mismatch path,
    marker has no effect.

On FileCertificateStore the marker lives at
filesDir/rouse_fingerprint_bootstrapped. clearCertificates() deletes it
so a full provisioning rollback can legitimately one-shot again.

Added CertificateStore methods hasFingerprintBootstrapMarker() and
writeFingerprintBootstrapMarker(); all implementations updated.

New tests:
  - SelfCertVerifierTest: marker-absent backfill writes marker; marker +
    empty -> Alert; marker doesn't affect non-empty match/mismatch.
  - FileCertificateStoreTest: marker absent on fresh store; marker
    persists across store instances; clearCertificates deletes marker.
2026-04-17 14:56:57 -04:00
Jason Monk
f0922ea002 Fix #197: add Robolectric tests for TunnelForegroundService lifecycle transitions
Five tests covering the service's state-flow decision tree:
- ACTIVE -> CONNECTED -> idle timeout -> DISCONNECTED stops service
- FCM wake when ACTIVE with healthy probe skips reconnect
- FCM wake when ACTIVE with failing probe forces reconnect
- onStartCommand stopSelf when no integrations enabled
- intentionalDisconnect flag suppresses reconnect on disconnect

Uses a FakeTunnelClient with MutableStateFlow to drive state transitions,
mockkObject for ForegroundNotifier/NotificationChannels (resources from :api
are not available in :work Robolectric tests), and reflection to set
IdleTimeoutManager.timeoutFired (private setter).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 17:16:56 -04:00
Jason Monk
c89a2d53cc Fix #178: poll for terminal WorkInfo state instead of assuming SynchronousExecutor drains DataStore
After #116 migrated SecurityCheckPreferences from SharedPreferences to
DataStore, SecurityCheckWorker's doWork() now awaits suspend calls that
SynchronousExecutor can't drain synchronously from the enqueue path. The
test asserted WorkInfo.State immediately after enqueue().result.get()
and saw RUNNING instead of SUCCEEDED.

Switch to a bounded poll (50ms interval, 5s timeout) for a terminal
state before asserting. No production code changes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 16:28:39 -04:00
Jason Monk
17a7b855fb Fix #179: mux ping/pong keepalive + liveness probe to detect dead tunnel sockets
The tunnel client declared "active" whenever the WebSocket handshake had
completed and at least one stream was open, with no application-layer
liveness check. Under half-open socket conditions (Doze, NAT rebind,
Wi-Fi -> cellular), the device would sit in ACTIVE forever while the
relay knew the connection was dead. Every FCM wake got "skipping
reconnect" and Claude requests never reached the phone.

Four compounding bugs are addressed together:

1. No mux-layer keepalive. Added MuxFrame.Ping / MuxFrame.Pong (frame
   types 0x04 / 0x05, stream_id reserved 0, 8-byte u64 BE nonce
   payload). The peer that receives a Ping must echo the nonce back
   verbatim as a Pong. Implemented symmetrically in the Rust relay
   (mux/frame.rs, mux/lifecycle.rs dispatch_incoming) and the Kotlin
   client (MuxFrame, MuxCodec, MuxDemux).

2. Stream-count tracking leaked through a wrapper that peer-initiated
   CLOSE frames bypassed. Moved activeStreamCount into MuxDemux as a
   StateFlow; incremented on peer Open, decremented on peer Close /
   Error and on locally-initiated MuxStreamImpl.close(). Deleted
   StreamCloseTracker. TunnelClientImpl now observes the StateFlow
   for CONNECTED <-> ACTIVE transitions, so the back-transition fires
   on peer Close (the bug case), not just on local close.

3. activeStreamCount never reset across reconnects. cleanupRefs() now
   nulls the MuxDemux reference; the next connect() allocates a fresh
   one whose counter starts at 0. Verified by the new "reconnect after
   ACTIVE resets activeStreamCount" test.

4. No service-side liveness probe. Added
   TunnelClient.healthCheck(timeout): sends a mux Ping and suspends
   until the matching Pong arrives or the deadline passes. Extracted
   WakeReconnectDecider as a testable pure helper; when state is
   ACTIVE the service now probes with a 2s Ping before trusting the
   state flag, falling through to reconnect on failure.

Also added a periodic 30s keepalive loop in TunnelClientImpl: after
three consecutive missed Pongs it flips the tunnel to DISCONNECTED so
the service reconnects autonomously, even in the absence of an FCM
wake.

Tests:
 - relay: mux_frame_test adds Ping/Pong encode/decode round-trips;
   mux_lifecycle_test asserts the relay echoes Ping as Pong without
   opening a stream.
 - tunnel jvmTest: MuxFrameTest adds Ping/Pong codec coverage;
   MuxDemuxTest adds activeStreamCount tracking (peer open/close/error,
   local close) and Ping/Pong handling; TunnelClientImplTest covers
   healthCheck against live and dead peers, the ACTIVE -> CONNECTED
   back-transition on peer Close, activeStreamCount reset across
   reconnects, and the periodic-keepalive teardown path.
 - tunnel integrationTest: two new scenarios hit the real Rust relay
   to validate healthCheck end-to-end (success while relay is up,
   failure + state flip when relay is killed).
 - work: WakeReconnectDeciderTest covers the wake decision table
   including the healthCheck-throws branch.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 14:16:19 -04:00
Jason Monk
4c442a8f48 Fix #170: align /renew request/response shapes between client and relay
The Android RelayApiClient and the relay's POST /renew endpoint had drifted
apart on both request and response shapes: the client was sending
{ csrPem, authMethod, currentCertPem } while the relay required
{ csr, subdomain, firebase_token, signature }, and the client expected
{ certificatePem } in the response while the relay returned
{ server_cert, client_cert, relay_ca_cert }. Neither side had integration
coverage on the renew path, so /renew returned 422 unconditionally in
production and cert renewal was quietly broken until devices approached
expiry.

This change keeps the relay's response shape (it already matched
/register/certs) and aligns the client to the relay side, plus a small
relay-side simplification so both auth paths are body-driven:

Request (both paths):
  { csr, subdomain, signature, firebase_token? }

Path A ("mTLS-equivalent", cert still valid): omit firebase_token.
Path B (cert expired): include firebase_token.
The relay verifies the signature against the public key it registered
earlier, and additionally verifies firebase_token (+ UID match) on Path B.

Response (matches /register/certs):
  { server_cert, client_cert, relay_ca_cert }

Wire-contract tests pin both sides:
- relay/tests/api_renew_test.rs gains a Path A signature-only success case
  and a bad-signature-on-Path-A case; pre-existing tests were adjusted
  for the new "signature always required" rule.
- core/tunnel CertRenewalTest gains serializer tests that assert the
  snake_case field names on both the request and the response, so a
  future rename on either side fails loudly here first.

CertRenewalFlow now routes the signature through a CsrSigner (parallel to
the existing FirebaseRenewalCredentialsProvider) so both paths sign over
the freshly-generated CSR DER rather than accepting a pre-computed value,
and stores all three cert bundle fields (mirroring CertProvisioningFlow).
RenewalAuthProvider in :work gains a signCsr hook to match.

docs/design/relay-api.md is updated to the new shape; the old stale
"Path A uses TLS client cert" language no longer reflects reality and
would have slowly misled future work.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 19:41:25 -04:00
Jason Monk
db30a284d2 Fix #163: Preserve onboarding state across cert-provisioning failures
Root cause: `CertProvisioningFlow` called `CertificateStore.clear()` on any
storage failure after attempting to persist a cert bundle. That method nuked
*everything* -- including the subdomain file that records completed device
onboarding -- so a single failed provisioning attempt reset the user to the
Welcome screen on next launch even though the device already had an assigned
subdomain. Issue #163 surfaced this after `adb install -r`, but it also fires
any time cert provisioning hits a storage hiccup.

Three changes, each narrowly scoped:

1. Split CertificateStore.clear() into two methods. The new
   clearCertificates() drops only cert/key/fingerprint state; clear() keeps
   its full-wipe semantics for onboarding-level rollback (OnboardingFlow).
   CertProvisioningFlow now uses clearCertificates() so the onboarding state
   survives.

2. FileCertificateStore.storeSubdomain and storeIntegrationSecrets now write
   atomically via tmp-file + rename. `File.writeText` truncates first, so a
   process kill between truncate and write leaves a zero-byte file -- a
   second failure mode that masqueraded as "subdomain disappeared".

3. FileCertificateStore.getSubdomain defensively returns null for blank
   content (empty or whitespace-only file), so any corrupt-file artifact
   triggers a clean re-onboarding retry instead of handing an empty string
   to downstream URL builders.

Tests:
- CertProvisioningFlowTest: new test asserts subdomain survives cert-store
  throw during provisioning (regression for the bug).
- FileCertificateStoreTest: round-trip, cross-instance persistence (process
  restart simulation), empty/whitespace file, overwrite, and
  truncate-then-read scenarios.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 15:31:55 -04:00
Jason Monk
0a0e914a2a Fix #116: Migrate all SharedPreferences usage to DataStore
Drop the last SharedPreferences call sites and replace them with typed
Preferences DataStore accessors:

- SecurityCheckPreferences: last-check time, self-cert / CT-log results,
  cert fingerprint (written by SecurityCheckWorker, read by
  TunnelForegroundService and SettingsViewModel)
- CertRenewalPreferences: last-attempt time, last outcome (written by
  CertRenewalWorker, observed by CertRenewalBannerFlow as a live Flow)
- SpuriousWakePreferences: wake counters and timestamp ring buffer,
  with the SpuriousWakeRecorder interface now suspend; the backing
  class is renamed DataStoreSpuriousWakeRecorder
- AppStatePreferences: first-launch marker and security-check interval
  (replaces the legacy rouse_settings prefs file)

Workers access their preferences through `by inject()` from Koin;
SettingsViewModel takes nullable accessor classes instead of raw
SharedPreferences. The McpSession alert gate reads from a
StateFlow-materialized view so the `() -> Boolean` contract is preserved
without reintroducing runBlocking.

Pre-release so no migration shim: legacy SharedPreferences files are
simply abandoned on upgrade. Only comments retain the SharedPreferences
word (pointing at this commit / the issue).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 21:24:08 -04:00
Jason Monk
46b398f943 Fix #135: Consolidate SessionHandler — delete :app/McpSessionBridge and :work/SessionHandler
Three things with overlapping concerns and a name collision collapse into
one: the :work/SessionHandler interface, the :app/McpSessionBridge that
implemented it, and :core:bridge.SessionHandler (previously test-only).

The :core:bridge class was always the better-factored design — it takes
TlsCertProvider and McpSessionFactory abstractions instead of concrete
CertificateStore and McpSession — and had the correct "wait for either
copy direction" lifecycle (CompletableDeferred) that #128 wanted
production to adopt. Now production uses it directly and the test and
production code paths are the same class.

- Delete :app/McpSessionBridge.kt (162 LOC) — its byte-copy, TLS accept,
  and socket-bridging logic now lives in :core:bridge.SessionHandler.
  The invalidateTlsAcceptor() hook it exposed was dead code.
- Delete :work/SessionHandler.kt (the interface) — replaced by depending
  on :core:bridge.SessionHandler directly.
- TunnelForegroundService imports :core:bridge.SessionHandler and calls
  handleStream(stream) instead of handle(stream) — same symbol name,
  different package.
- AppModule wires TlsCertProvider via CertStoreTlsCertProvider, McpSessionFactory
  via SharedMcpSessionFactory, and SessionHandler via the :core:bridge
  constructor that takes both.

Closes #128 — the lifecycle bug it targeted lived only in the deleted
:app.McpSessionBridge. The consolidated implementation already had the
correct semantics.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 20:59:53 -04:00
Jason Monk
96b2f97873 Fix #149: Rethrow CancellationException in FcmTokenRegistrar
The broad catch(Exception) around sendFcmToken swallowed CancellationException
(which inherits from IllegalStateException on JVM), breaking structured
concurrency. Rethrow CancellationException before the general handler so
callers tied to a cancellable scope observe cancellation correctly.

Added a test that cancels the calling scope mid-send and asserts the
CancellationException propagates out of registerToken.
2026-04-14 20:01:47 -04:00
Jason Monk
15df1b6eba Fix #112: Push refreshed FCM tokens to relay when tunnel is connected
FcmTokenRegistrar.registerToken was a no-op that only logged. When FCM
rotated the device token mid-session, the relay kept the stale token
until the next reconnect (could be hours). The pull-on-connect path in
TunnelForegroundService covered the disconnected case but not the
live-session case.

Inject TunnelClient into FcmTokenRegistrar; on token refresh, push via
TunnelClient.sendFcmToken when state is CONNECTED or ACTIVE. Treat
CONNECTING as disconnected to avoid racing a half-open connection.
Swallow send exceptions so a racing disconnect can't crash the FCM
service thread — the next wake's pull will re-sync.

Drop registerCurrentToken() and the RouseApplication.onCreate call site.
It was pure overhead: the tunnel already pulls a fresh token on every
connect, so a startup push adds nothing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:52:32 -04:00
Jason Monk
21e459cfad Extract SecurityCheckNotifier interface + AndroidSecurityCheckNotifier impl (#147)
SecurityCheckNotifier was declared as open class with open methods purely
so test fakes could subclass it. Convert to a proper interface + concrete
AndroidSecurityCheckNotifier implementation. Test fake now implements the
interface directly -- no more open keyword, no surprise overrides.

Koin binding updated to single<SecurityCheckNotifier> { AndroidSecurityCheckNotifier(...) }.
Worker's notifier field type stays the interface.

Id scheme (4210-4213) unchanged; SecurityCheck enum remains nested on the
interface so existing callers need no import changes.
2026-04-14 19:45:03 -04:00
Jason Monk
7a54bdce4b Delete NotificationAdapter and NotificationAction dead code (#125)
Completes the notifier-pattern cleanup. NotificationAdapter and
NotificationAction had no production call sites — they were exercised
only by their own tests and NotificationIconTest. Their private
buildSessionNotification / buildErrorNotification / buildAlertNotification
helpers were the last classes in :notifications that built-and-returned
a Notification without the startForeground justification.

Every :notifications class now either posts-via-postX (all notifiers) or
is the single documented exception (ForegroundNotifier). Rule satisfied.

NotificationIconTest is rewritten to exercise live notifiers
(ForegroundNotifier, FgsLimitNotifier, SecurityCheckNotifier,
AuthRequestNotifier) instead of the dead adapter. Icon coverage is now
routed through real production code paths.

TunnelForegroundService.updateNotification() still calls
NotificationManager.notify() with the FGS id — Android treats that as an
in-place update of the ongoing foreground notification, so this is an
intentional extension of the startForeground contract. A comment on the
method documents the rationale.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:37:53 -04:00
Jason Monk
8fecf94646 Rename SessionSummaryPoster -> SessionSummaryNotifier (#125)
Aligns the session-summary class with the :notifications Notifier naming
convention from issue #125. The class already exposed postSummary(...),
so no method changes are required — only the type name, the file name,
and the test file name. Also updates the KDoc cross-reference in
PerToolCallNotifier and the Koin binding in AppModule.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:37:53 -04:00
Jason Monk
4c1098f7b4 Rename ForegroundNotification -> ForegroundNotifier, method -> build (#125)
Aligns the foreground-service notification with the :notifications
notifier naming convention. Since the FGS notification MUST be returned
(to pass to startForeground), the class is documented as the ONE
exception to the 'postX builds and posts' rule.

Renames the top-level createForegroundNotification(...) function into an
object ForegroundNotifier with a build(...) method, and updates the two
call sites (TunnelForegroundService, NotificationAdapter) plus the
Roborazzi screenshot test and icon test.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:37:53 -04:00
Jason Monk
0f3f36bb2e Fix #117: Extract SecurityCheckNotifier and fix id clobbering
Move notification posting out of SecurityCheckWorker into a new
SecurityCheckNotifier in :notifications, matching the pattern used by
FgsLimitNotifier. Replace the per-worker-instance nextNotificationId
counter (which started at 200 on every run and silently overwrote prior
runs' alerts) with four stable, semantic ids keyed by (check, severity).

Same-check same-severity reposts now replace the existing notification
(desired for persistent alerts), and different-check alerts no longer
clobber each other. The worker keeps orchestration and SharedPreferences
writes; the notifier is injected via KoinWorkerFactory.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:24:21 -04:00
Jason Monk
f4e1852e08 Fix #118: Add grace period after CONNECTED in WakelockManager
Hold the wakelock for 3s after the tunnel transitions to CONNECTED before
releasing. This closes the CONNECTED->ACTIVE window where the relay's first
request frame could be deferred by Doze on non-battery-exempt devices.

- ACTIVE within grace: cancel the pending release, wakelock stays held
- DISCONNECTING/DISCONNECTED within grace: cancel pending release AND release
  immediately (no point holding)
- Duplicate CONNECTED emissions reset the timer, never double-release

Tests use runTest + virtual time (advanceTimeBy/advanceUntilIdle) rather
than real delays.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:21:48 -04:00
Jason Monk
e61e1c9c14 Fix #113: Rename FgsLimitHandler to FgsLimitNotifier in :notifications
Move completes the refactor: notification-posting logic no longer crosses
the :work -> :notifications boundary. FgsLimitNotifier now follows the
*Notifier convention alongside AuthRequestNotifier, LaunchRequestNotifier,
PerToolCallNotifier, and SessionSummaryPoster.

No behavior change.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:09:52 -04:00
Jason Monk
4a2c7de14b Move FgsLimitHandler files to :notifications (preserve blame)
Part of #113. Pure file rename via git mv; package and class name
updates follow in the next commit.
2026-04-14 19:09:52 -04:00
Jason Monk
9bb64e02de Fix #115: Remove dead batteryExempt flag from IdleTimeoutManager
Production DI always passed batteryExempt = false, so the short-circuit
branch was unreachable. The mental model was also wrong: battery
exemption excuses Doze restrictions but does not excuse the FGS 6h/24h
cap on dataSync (issue #110), so the flag would have made things worse
if ever enabled.

Removed the constructor parameter, the short-circuit in observe(), the
hardcoded argument in AppModule, and the single test exercising the
removed branch. Idle timeout is now unconditionally on.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:09:11 -04:00
Jason Monk
a2be40e67f Replace fully qualified names with imports across production code
Audit of production Kotlin sources for inline `java.*`, `kotlinx.*`,
`io.ktor.*`, and `android.*` FQNs. Replaced with proper imports in:

- core/mcp: McpRouting.kt (RoutingCall, JsonArray, JsonElement,
  JsonPrimitive, URI, UUID), AuthorizationCodeManager.kt (URI, UUID),
  McpSession.kt (EmbeddedServer)
- outreach: OutreachMcpProvider.kt (JsonArray, PackageManager)
- usage: UsageMcpProvider.kt (JsonArray)
- work: IdleTimeoutManager.kt (StateFlow)
- app: AppModule.kt (Context, PowerManager), MainActivity.kt (Color),
  RouseContextApp.kt (Color), AppNavigation.kt (Uri),
  FileCertificateStore.kt (Base64), MtlsWebSocketFactory.kt (Base64)

No behavior change. ktlintFormat applied.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 15:56:28 -04:00
Jason Monk
67f60bf1ec Fix #110: Handle FGS 6h limit gracefully — notify + stopSelf instead of crash
Before this fix, when `startForeground(...)` was called after the
cumulative `dataSync` foreground-service budget had been exhausted
(6h / 24h on Android 14+), the resulting
`ForegroundServiceStartNotAllowedException` propagated out of
`TunnelForegroundService.onCreate` and crashed the process. Every
subsequent FCM wake re-crashed until the rolling 24h window reset,
producing a crash loop for affected users.

Keep `foregroundServiceType=dataSync` — masking the cap via specialUse
would hide a real signal. Instead, catch the exception, post a
user-visible HIGH-importance notification on a new `rouse_fgs_limit`
channel explaining the situation, and call `stopSelf()`. No retry is
scheduled: the next FCM wake naturally re-attempts `startForeground`,
and once the rolling window gives budget back, the service starts
normally.

A fixed notification id is used so repeated exhausted wakes update the
same notification rather than spamming the shade.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 06:20:44 -04:00