Commit graph

238 commits

Author SHA1 Message Date
monkopedia-coder
bad1b7ea72
Generate new address did not rotate secrets (#836)
Some checks failed
Android CI / test (push) Waiting to run
CI / Build & Test (push) Waiting to run
CI / Lint (push) Waiting to run
Deploy docs to GitHub Pages / build (push) Has been cancelled
Relay CI / relay-test (push) Has been cancelled
Deploy docs to GitHub Pages / deploy (push) Has been cancelled
* relay: add rotate_all to /rotate-secret for forced secret rotation

Generate new address did not rotate secrets: /rotate-secret preserves
every existing secret. rotate_all=true mints a fresh secret for each
requested integration; replaced secrets become stale. Absent keeps the
preserve behaviour for deployed clients.

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

* Generate new address did not rotate secrets

Settings rotate now sends rotate_all with only the enabled integration
ids and stores the relay's fresh secrets. The setup-time push also stops
sending disabled ids. Subtitle copy says old URLs stop working; design
docs describe the shipped per-integration rotation.

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

---------

Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 18:33:48 -05:00
monkopedia-coder
3ed5639d90
relay: treat an empty secret set as nothing valid (#810) (#817)
Some checks failed
CI / Lint (push) Waiting to run
CI / Build & Test (push) Waiting to run
Relay CI / relay-test (push) Waiting to run
Android CI / test (push) Has been cancelled
* relay: add failing regression tests for empty-secret-set fail-open (#810)

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

* relay: treat an empty secret set as nothing valid (#810)

Disabling the last integration rotates valid_secrets to []. The cache
evicted the entry on empty, and the Firestore fallback then treated a
record with neither valid_secrets nor secret_prefix as 'skip validation',
so any first label passed the relay check and triggered a wake.

Cache the empty set explicitly and drop the skip branch: valid_secrets is
authoritative unless the record only has a legacy secret_prefix.
Production check: 0/117 device records use secret_prefix; the 12 with
neither field are all post-rotate-to-empty (11) or a dead May record.

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

* Seed fixture device secrets via a test-mode admin endpoint (#810)

The Kotlin integration fixtures auto-create devices on /ws with an empty
secret set and then route AI clients with a fixed SNI label. That only
worked through the removed skip-validation branch. Add a test-mode-only
POST /test/seed-secrets (compiled out without the test-mode feature) and
a TestRelayManager.seedValidSecrets helper that re-applies on restart;
seed the label in the four affected suites.

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

---------

Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 07:32:41 -04:00
monkopedia-coder
b27709ec10
Run SessionHandler's session work off the caller's thread (#800)
1.0.13 crashed every incoming session with NetworkOnMainThreadException.
#781 replaced a java.net.Socket connected under withContext(Dispatchers.IO)
with a Ktor socket, whose connect calls SocketChannel.connect synchronously
on the calling thread -- and handleStream is called from lifecycleScope,
i.e. the Android main thread.

serveStream now runs under an injected ioDispatcher (default
Dispatchers.IO): cert/Keystore loading, TLS accept, MCP session
create/stop, the loopback connect, the copy loops and the socket close.
closeStream hops to it too, outside serveStream's hop so a caller
cancelled before it still sends CLOSE (#796). Suspending on IO holds no
thread while a session idles, so #781's behaviour is unchanged.

SessionHandlerCallerThreadTest calls handleStream from a single-thread
stand-in for the main thread and records the thread of each seam,
observing the connect via a recording SelectorProvider.


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 20:29:25 -04:00
monkopedia-coder
0f7da38317
Close the mux stream whenever a device-side session ends (#780) (#796)
SessionHandler never closed its MuxStream, so when a session ended on
the device (the #778 idle bound, an error, the local server closing
the connection, cancellation, or a failed TLS accept) no CLOSE frame
reached the relay. The relay then kept the client's connection open,
so the client saw no bytes and no EOF until its own timeout. The relay
also kept holding the device's stream slot.

handleStream now closes the stream in a finally under NonCancellable.
When the relay closed the stream first (the client hung up),
MuxStreamImpl.close is a no-op, so no duplicate CLOSE goes out.

Fixes #780


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:59:46 -04:00
monkopedia-coder
94a9b8b410
Stop abandoned bridge sessions from pinning IO threads (#778) (#781)
* Add failing gate: abandoned bridge sessions hold IO threads (#778)

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

* Stop abandoned bridge sessions from pinning IO threads (#778)

Each bridged session read the loopback socket with a blocking
Socket.InputStream.read on Dispatchers.IO, so every live session held one
IO worker. A client that went silent mid-request (no more bytes, no CLOSE)
was never timed out by Ktor, so its worker was held forever; 64 of them
fill the shared IO pool and every withContext(Dispatchers.IO) in the app
queues behind them.

The loopback socket is now a Ktor selector-backed socket, so a waiting
session parks a coroutine instead of a thread. Sessions are also bounded
by inactivity (5 min with no bytes in either direction), which ends the
abandoned ones that nothing else would.

The removed socket-close catch was a #674 backlog entry; its row goes too.

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

---------

Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 10:06:18 -04:00
monkopedia-coder
625329436b
Test the read timeout, the other half of #761 (#767)
Some checks failed
Android CI / test (push) Has been cancelled
CI / Lint (push) Has been cancelled
CI / Build & Test (push) Has been cancelled
Review on #763 found the cap half of that fix pinned six ways and the timeout
half implemented but untested -- the "fix the half that is easier to test"
shape. #763 merged before this landed, so it follows here.

A cap without a timeout still admits a slowloris: a client that declares a
body comfortably UNDER the cap and then stops sending holds the request
coroutine open indefinitely, and the cap cannot catch it because by
construction the body is small.

Adds a raw-socket test that declares `Content-Length: 200` (under the cap, so
the cheap pre-check cannot fire), sends 20 bytes and goes silent. The only
thing that can end that request is the 5s read timeout. It asserts both that
the server answered and that the answer took at least three quarters of the
timeout -- the elapsed time is what separates "the timeout fired" from "the
body parsed instantly and the status means something unrelated".

Paired with a control sending the same declared body in full, which must be
answered in well under the timeout. Without it, a server that simply waited
5s before answering everything would pass.

Pinned by mutation rather than asserted: raising TOKEN_BODY_TIMEOUT_MS from
5s to 600s fails the stall test with `java.net.SocketTimeoutException: Read
timed out` -- the server hanging, which is the slowloris the timeout exists
to prevent.

Tests only; no production change.


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 10:49:19 -04:00
monkopedia-coder
498e6560fe
Bound the /token request body (#761) (#763)
`POST /token` read its request body with no size cap and no read timeout.
It was the only body-reading endpoint in McpRouting.kt with no protection
at all -- `/register` wraps its read in `withTimeout(5000)` and rate-limits
it, `/mcp` wraps its read in `withTimeout(MCP_REQUEST_TIMEOUT_MS)`, and
`/device/authorize` and `/authorize` read no body. That contrast is what
makes this an oversight rather than a deliberate exemption.

For Ktor CIO, `receiveText()` and `receiveParameters()` read the remaining
request channel fully into memory before decoding, so a client that can
already reach an integration's endpoint could stream a large fixed-length or
chunked body and make the Android process accumulate it before JSON or form
parsing rejected anything.

The cap is 4096 bytes, derived from what this codebase actually sends rather
than picked round: every OAuth credential here is 32 random bytes rendered
base64url (43 chars) and `client_id` is a UUID (36 chars), so the largest
request the specs permit -- an authorization_code grant with a `code_verifier`
at RFC 7636's 128-char maximum -- measures 268 bytes before `redirect_uri`.
TokenBodyLimitTest measures that against the real generators instead of
trusting the comment. 4096 also sits below the 8192 bytes Ktor CIO already
accepts unconditionally for a single request header line, so a /token body
can never be the largest thing this endpoint has agreed to buffer.

Applied to BOTH branches. The form branch now parses the bounded text with
`parseUrlEncodedParameters` instead of calling `receiveParameters()`, which
reads the channel itself and would defeat the cap; form-encoded is the
default for OAuth clients, so a JSON-only cap would have left the common
path open.

Two guards, each pinned by a test that fails when only that guard is removed:

  - a `Content-Length` already over the cap is refused before the body is
    touched (a request declaring 4 MB and sending nothing gets an immediate
    413, not a 400 after the read timeout);
  - `readBounded` then takes exactly `maxBytes + 1` bytes off the channel, so
    a chunked body cannot make the process accumulate more. This is invisible
    over HTTP -- CIO drains the rest of the body after the handler answers, so
    both a bounded and an unbounded reader look identical from the client --
    so it is asserted directly on `readBounded` by the bytes it leaves unread.

Read timeout is 5s, matching /register; /mcp keeps 30s because its body is a
tool call rather than a credential exchange.

Deliberately NOT added: a rate limiter on /token. Its absence is a product
decision (the device-code flow legitimately polls it), documented above
`handleToken` and pinned by `RateLimiterTest`.

Also removes the `parseTokenRequestParams` row from the #674 cancellation
backlog: the old `catch (_: Exception)` swallowed `CancellationException`,
and the new chain rethrows it.

Fixes #761


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-15 09:54:42 -04:00
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
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
9e6f5e11f6
Bound the core/tunnel spin case with per-test ceiling evidence (#600) (#681)
A `SAME_THREAD` `@Timeout` is checked only after the test method returns, so
against a CPU spin -- the failure this module has actually produced (#563's
`BUFFER_UNDERFLOW` loop) -- it yields an unbounded hang rather than a red.

The `SEPARATE_THREAD` hazard from #501/#504 is per-test, not module-wide: it
needs output reaching Gradle's per-test output store from a path still running
after the ceiling abandons the test. So the predicate is "can this test still
emit output after its ceiling fires?", not "is SEPARATE_THREAD dangerous?".

Measured that predicate per class from the system-out/system-err in the JUnit
XML of a full green integrationTest run. Seven classes emit zero bytes and
contain no print statement; they take SEPARATE_THREAD: EndToEndSessionTest,
TunnelMcpIntegrationTest, OAuthEndToEndTest, MultiClientConcurrencyTest,
TestRelayAdminSmokeTest, RealRelayIntegrationTest and
StreamFailureDoesNotKillTunnelTest.

Two method-level ceilings inside converted classes were converted too -- a
method-level `@Timeout` replaces the class one, so leaving them SAME_THREAD
would have quietly exempted those methods from the bound.

The five that do emit keep SAME_THREAD, each with its named emitter recorded
rather than a blanket rule: CertRotationIntegrationTest (~15 KB) and
RelayApiClientIntegrationTest (~76 KB) dump the relay's captured output in
teardown; AbruptDisconnectTest and HalfOpenDetectionTest println timings from
the test body; ClaudeFullFlowEndToEndTest shares @BeforeAll collectors across
eight ordered tests, a structural hazard independent of logging.

The comments that stated the blanket rule are rewritten to state the predicate
and the measurement. ClaudeFullFlowEndToEndTest's note in particular claimed
collector logging spanning all eight tests; the class's entire 74 bytes of
output is kotlin-logging's one-time init banner, so the note named the wrong
mechanism for a conclusion that still holds for a different reason.

Verified the bound fires BECAUSE of this change, by planting a non-yielding CPU
spin in TestRelayAdminSmokeTest, whose class ceiling this commit converts, and
running it at both revisions:

  this commit  120s SEPARATE_THREAD  RED at 123.954s, XML written
                                     (tests=2 failures=1), sibling reported at
                                     4.353s, zero corruption markers
  base 0b2d81a6  120s SAME_THREAD    never fired, killed at 420s, ZERO XML

A measurement is evidence about the runs observed, not a property of the code,
and TWO paths escaped it. First, TunnelClientImpl stores the caller's scope raw
-- no re-wrap, no SupervisorJob -- and a bare `CoroutineScope(Dispatchers.IO)`
is a ROOT scope, so an uncaught throw out of any of its eight `scope.launch`
sites ends at the default handler, which writes to System.err from a background
thread, on the failure path, exactly when a ceiling fires. The converted classes
now build that scope through IntegrationScope, whose handler is in context for
all eight sites and routes such throws to a recorded list; no SupervisorJob and
no production change, so sibling propagation is unchanged and only the
throwable's destination moves. A new test pins this, with a control proving a
bare root scope does reach the default handler so the diversion is not vacuous.

Second, TestRelayFixture.stop() prints ~100 bytes to System.err if the relay
subprocess survives destroyForcibly() plus a 3s wait, and EndToEndSessionTest
calls stop() from inside a test body, so an abandoned thread can reach it. Left
unguarded deliberately: it needs a kernel-level stall AND the ceiling to fire in
the same window, and what it replaces is the unbounded hang that loses the whole
run. Recorded rather than fixed.

IntegrationHttpSupport is the hub every converted class's note points at, so it
now states which part of the claim is closed by construction (slf4j-api with no
provider), which by IntegrationScope, and which remains coverage-dependent --
rather than the flat "nothing exists to race the store" it carried, which the
rest of this change had already outgrown.

Counts: jvmTest 260/41 -> 262/42 (the two new handler tests), bridge 23/6
unchanged, integrationTest 50/12 unchanged, all green, with repeat integration
runs showing no output-store corruption markers.

Closes #600

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK
2026-09-02 05:56:58 -04:00
monkopedia-coder
9a83c845a1
Scope the close_notify NEED_WRAP claim to TLS 1.3 (#668) (#675)
classifyEngineRequest's KDoc said, unqualified, that a server unwrap of the
peer's close_notify "does not reproduce" as NEED_WRAP -- always CLOSED with
NOT_HANDSHAKING. That was measured, and true of the connection it was measured
on, which was TLS 1.3. The protocol was never varied.

Re-measured on JDK 21.0.12.1, two SunJSSE engines over an in-memory transport,
varying only setEnabledProtocols and asserting session.protocol afterwards
rather than trusting the call took:

  TLSv1.3  unwrap(close_notify) -> CLOSED / NOT_HANDSHAKING, holds nothing
           wrap after that      -> OK,     produced 0
  TLSv1.2  unwrap(close_notify) -> CLOSED / NEED_WRAP,       holds a record
           wrap after that      -> CLOSED, produced 31

TLS 1.2 is in scope because nothing pins the acceptor to 1.3: fromCertAndKey
and fromPem build SSLContext.getInstance("TLS") and createServerEngine sets
only useClientMode and applicationProtocols, so the enabled set is the platform
default -- measured as [TLSv1.3, TLSv1.2].

No behaviour change. Every changed line in TlsAcceptor.kt is a comment.

Two corrections recorded beside the measurement. 664 under-claims itself: on
TLS 1.2 the second trigger reproduces exactly as 617 described, so it repaired
that too. And classifyEmitStatus's answer is NOT what stops the pump on this
path, which is the tempting thing to write -- the branch is reached, but
returning RECORD_EMITTED instead changes nothing, because the engine has
dropped to NOT_HANDSHAKING and pumpEngineOutput's loop guard ends it anyway.
Both mutations were run; only the NEED_WRAP branch is load-bearing here.

"Do not re-derive it from the issue text" is gone. That instruction is what
locked the error in -- it marked an unvaried claim as settled. What replaces it
names the protocol as the variable and says to vary it.

Adds TlsAcceptorTls12CloseNotifyTest so the claim fails when it stops being
true instead of sitting in a comment: one test pins the JDK premise on both
protocols with a protocol-in-force control, the other drives the shipped
acceptor against a TLS-1.2-only client and asserts the responding close_notify
reaches the mux stream. Red on mutation -- routing NEED_WRAP to NOTHING_TO_DO
leaves the read() -> -1 assertion passing and fails only the response
assertion, which is how 617 stayed invisible.

Closes #668

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


Reviewed by monkopedia-reviewer at e6032a30. Comment-only in TlsAcceptor.kt
confirmed two ways (comment-stripped revisions are byte-identical, 491 lines
each). Mutation table re-run independently: NEED_WRAP -> NOTHING_TO_DO red (2
failures), classifyEmitStatus CLOSED -> throw red (1 failure), CLOSED ->
RECORD_EMITTED green (0 failures) -- so the branch is reached but its answer is
not load-bearing, and the PR was right to decline the issue's suggested
wording. Under the first mutation the read() -> -1 assertion still passes and
only the response assertion fails. :core:tunnel:jvmTest 41 classes / 260 tests
/ 0 failures counted from JUnit XML; ktlintCheck and detekt clean; all three
CI checks green by step list.
2026-09-02 01:39:41 -04:00
monkopedia-coder
01a9159d8a
Stop TunnelSessionManager swallowing the TLS defect (#638) (#672)
`catch (_: Exception)` around `handleStream` ate `TunnelError.UnhandledTlsState`,
reproducing the clean-EOF outcome #615/#616/#626/#630 spent four issues
eliminating. Apply the same three-way split the copy loops in `SessionHandler`
use (`SessionHandler.kt:185`, `:221`): rethrow cancellation, rethrow the defect,
keep swallowing routine disconnects so one bad session still cannot take the
collector down.

The old comment justified the swallow with "errors are logged at the session
level". That was never true of this exception -- `SessionHandler` deliberately
rethrows it because `:core:bridge` is a KMP jvm target with no `Log` or
`CrashReporter` on its classpath, so leaving the coroutine IS the report. A
stale justification is what let this survive four issues, so the comment is
rewritten along with the code.

Two tests, because either alone is insufficient: the defect test catches a
dropped or mis-ordered rethrow, and the swallow test catches a wrongly widened
one (a guard rethrowing a supertype still rethrows the subtype, so the defect
test stays green on it).

The cancellation clause is deliberately not claimed as pinned. Ablation shows
deleting it leaves the suite green, because the handler call is last in its
coroutine and an already-cancelled job ends cancelled either way. Manufacturing
an assertion would mean adding a production seam that exists only for the test.
The clause stays for consistency with `SessionHandler` and the site says plainly
what is and is not covered.

Ordering is load-bearing throughout: `CancellationException` extends
`IllegalStateException` on the JVM and `TunnelError` extends `Exception`, so both
specific clauses must precede the broad one -- and Kotlin diagnoses neither an
unreachable catch clause nor a mis-ordered one.

This disarms the trap. Removing the class from `jvmMain` altogether -- it has
never had a production construction site -- is tracked separately in issue #671,
which is not addressed here.

Reviewed by monkopedia-reviewer at e29d5c1d. Both ablations re-derived
independently in a clean worktree (`:core:bridge:jvmTest`, `--rerun-tasks`,
`test-results/` deleted per run, counts from XML):

  as merged                                     23 tests, 0 failures
  drop the UnhandledTlsState clause             defect test red (1)
  catch (e: Exception) { throw e }              swallow test red (1), defect test GREEN
  broad clause widened to { throw e }           swallow test red (1), defect test GREEN
  drop the cancellation clause                  suite green (the disclosed non-pin)

The two widened shapes were run 3x each, 6/6 identical -- the swallow test is
race-free under repetition, because the throw is the statement after the signal
the assertion waits on. No test-only production seam: `SessionHandler.tlsAccept`,
`TlsCertProvider` and `McpSessionFactory` all pre-exist on the base and
`SessionHandler.kt` is not in this diff.

Closes #638

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK
2026-09-02 00:46:19 -04:00
monkopedia-coder
2526f630a5
Emit the record a post-handshake NEED_WRAP asks for (#617) (#664)
Some checks are pending
Android CI / test (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build & Test (push) Waiting to run
`SuspendTlsSession.read` serviced the engine through an `if` on `NEED_TASK`, so
the other five `SSLEngineResult.HandshakeStatus` members were a silent residual
reached without ever writing a `when` -- the one shape an audit that greps for
`else` cannot see. Four were harmless. `NEED_WRAP` was not: the engine holds a
record for the peer and nothing emitted it.

Reachable on a healthy TLS 1.3 connection, measured rather than argued. Two
JDK 21 engines over an in-memory transport with `jdk.tls.keyLimits` lowered
report `Status.OK` + `handshakeStatus = NEED_WRAP` from a post-handshake server
`unwrap`; the pending record is the `KeyUpdate{update_not_requested}` that
RFC 8446 4.6.3 requires in answer to the peer's `key_update{update_requested}`.

The severity is narrower than the issue claimed, and the same measurement says
so. Against a SunJSSE peer this does not hang -- 2 MB went through with every
response dropped and no error, because the peer does not gate on the answer.
What is lost is conformance: a mandatory response never sent and our write key
never rotated, so the record limit is silently exceeded. A peer that does gate
parks the read in `pullNetData()`.

The issue's second named trigger, the responding `close_notify`, is
PROTOCOL-SCOPED, and the KDoc landing with this commit states it without the
scope. Reviewer measurement on JDK 21, protocol the only variable: on TLS 1.3 a
server `unwrap` of the peer's `close_notify` reports `CLOSED` /
`NOT_HANDSHAKING` holding nothing, as the KDoc says; on TLS 1.2 it reports
`CLOSED` / `NEED_WRAP` and the next `wrap` produces the 31-byte responding
`close_notify`. The acceptor sets no `enabledProtocols`, so TLS 1.2 is live and
that trigger does reproduce there -- this commit repairs it too, which the KDoc
does not claim. `classifyEmitStatus`'s `CLOSED` branch is written for exactly
that path. Documentation defect only; tracked separately, and the KDoc's "do
not re-derive it from the issue text" should not be trusted on this point.

The fix takes `writeMutex` from inside `read`, which is the deadlock the issue
parked on. Re-enumerated at review: `readMutex` is acquired only in `read`,
`writeMutex` only in `write` and the new `pumpEngineOutput`, whose sole call
chain is `read` -> `serviceEngineRequest` -> `pumpEngineOutput`. Both are
`private val`s of a `private class` in one file, `close()` takes neither, and no
path takes `readMutex` while holding `writeMutex`. Read-then-write is the only
ordering and there is no cycle. The lock is also not optional: `SSLEngine`
permits one concurrent `wrap`, and `netOut` is `writeMutex`'s buffer. `write`
needs no matching pump. That is the one place this does LESS than #617 asked
for, so it was confirmed by measurement rather than by reasoning, twice
independently: with `NEED_WRAP` pending, wrapping application data gives
`consumed=0 produced=43` (the pending record, zero application bytes) and the
next `wrap` gives `consumed=19 produced=57` (the data), leaving the engine
holding nothing. `write`'s existing `while (appOut.hasRemaining())` loop already
drains it.

Two new classifiers in the file's shape, no `else`. `classifyEngineRequest` is
the first over `HandshakeStatus`, so its counterfactual was re-run rather than
inherited from the `Status` matrix, and re-run again at review on a different
member: dropping `NEED_UNWRAP_AGAIN` with no `else` is a hard compilation error
naming it; the same deletion with an `else` compiles with no error and no
warning.

The four members grouped into `NOTHING_TO_DO` were verified rather than
inherited. `TransportContext.getHandshakeStatus()` returns `NEED_WRAP` before
every other test whenever `outputRecord` is non-empty, so no other member can
co-occur with a held record; `NEED_UNWRAP_AGAIN` is gated on `isDTLS()` and the
acceptor builds `SSLContext.getInstance("TLS")`, so it is unreachable here
rather than merely unobserved. 3059 instrumented server unwraps across TLS 1.3
and TLS 1.2 produced zero cases of a `NOTHING_TO_DO` status while the engine
held a record. Reachability on TLS 1.3 was also reproduced independently --
note for anyone re-running it that `jdk.tls.keyLimits` is a SECURITY property:
setting it with `-D` is silently ignored and yields a clean-looking null result.

`TlsAcceptorNeedWrapTest` pins both directions -- the record reaches the mux
stream, and the four no-ops stay no-ops. Red on the base commit with the
expected message; the two passing tests ablated per change.

`:core:tunnel:jvmTest` 255 -> 258 tests, 39 -> 40 classes, 0 failures, baseline
re-measured independently at review. `:core:bridge:jvmTest` 20, 0 failures.
`ktlintCheck` and `detekt` clean.

Reviewer-filed follow-up on the KDoc's unqualified close_notify claim: #668

Closes #617

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-01 23:02:35 -04:00
monkopedia-coder
a6f96c0fe1
Stop AddIntegrationDestination swallowing cancellation (#662) (#665)
#660 made CertProvisioningFlow.execute propagate CancellationException instead
of reporting StorageFailed. AddIntegrationDestination's bare `catch (_:
Exception)` converted it straight back one frame above that guard -- the shape
#616 found on #615. The comment was the tell: "best-effort; integrationSetup
will retry" is an argument about a provisioning FAILURE, not about cancellation,
because a cancelled screen is gone and will not retry.

The launch body is extracted to `provisionCertsInBackground` so the contract is
unit-testable, and a CancellationException rethrow goes above the broad catch,
matching SessionHandler:185/:221 and CertProvisioningFlow's own #646 guard.
AddIntegrationProvisioningTest pins both directions in one run; dropping only
the rethrow reproduces exactly one failure ("expected:<[threw
CancellationException]> but was:<[returned normally (cancellation swallowed)]>")
with the other three cases green.

Also records why OnboardingFlow's storeSubdomain/storeIntegrationSecrets pair is
safe without a cancellation rollback. That safety is a property of
FileCertificateStore in another module (non-suspend atomicWrite, no
withContext), and OnboardingFlow does not self-heal -- its onboarded gate is
`getSubdomain() != null`, so nothing repairs "subdomain present, secrets
absent". OnboardingHalfWriteWindowTest pins the property so an ordinary move of
atomicWrite to Dispatchers.IO fails loudly instead of silently opening the
window.

The app/src/main sweep enumerated 29 catch clauses across 15 files plus 3
Flow.catch operators. Six further deliverable-and-swallowed sites reach a
user-visible surface and were deliberately left untouched as error-surface
changes under .claude/rules/ux-changes.md; they are tracked in #667, and
the flavor-source-set reporters in #666. Neither is resolved by this
change.

Reviewed by monkopedia-reviewer at fd92a1c2: both ablations reproduced, the
`withContext` absence re-run with /usr/bin/grep, the Flow.catch bytecode claim
confirmed against the resolved kotlinx-coroutines 1.10.2 artifact, and the
composite tree with PR #664 verified green (:app 638/0, :core:tunnel 258/0).

Closes #662

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK
2026-09-01 22:52:03 -04:00
monkopedia-coder
e4e27434d6
Make TlsAcceptor read as one design again (#649) (#663)
Some checks are pending
Android CI / test (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build & Test (push) Waiting to run
Five locally-correct edits in a week -- #563, #615, #639, #643, #647 -- left
three drifts that no diff-scoped review was positioned to see.

1. CLOSED mapped four ways. The handshake/data-phase split is principled and
   stays; so does "peer behaviour is never UnhandledTlsState". The read/write
   split inside the data phase was not: two PRs classified the same event a day
   apart. It is now one decision in two forms -- read returns -1, write throws
   TlsStreamClosed, an IOException subtype that names the event at the throw
   site instead of leaving its meaning to the consumer's broad catch. The class
   kdoc carries the four-row table and says which distinctions are load-bearing.

2. Two residual policies coexisted. Three classifiers were exhaustive `when`
   expressions with no `else`; SuspendTlsSession.read used an inline `when`
   with a runtime `else` that nothing could reach. Extracting
   classifyDataUnwrapStatus makes it four out of four.

   What buys the compile-time check is dropping the `else`, and nothing else.
   Measured on Kotlin 2.2.21, holding form, subject and branch count constant
   and varying only the `else`:

     statement,  platform subject, 3 of 4, no else -> ERROR, names CLOSED
     statement,  platform subject, 3 of 4, + else  -> compiles, no warning
     expression, platform subject, 3 of 4, no else -> ERROR, names CLOSED
     expression, platform subject, 3 of 4, + else  -> compiles, no warning
     expression, declared non-null, 3 of 4, + else -> compiles, no warning
     statement,  platform subject, 4 of 4, no else -> compiles

   An `else` absorbs the residual silently in every shape; statement versus
   expression, and platform versus declared non-null, are both irrelevant. So
   read()'s dead `else` is the entire reason its missing residual went
   unreported for five PRs, and removing it is the entire fix. The extraction
   buys uniformity across the four sites -- legibility, not safety.

3. close() swallowed cancellation on a suspend stream.close(), losing the
   cancellation AND skipping the CLOSE frame. It now uses
   withContext(NonCancellable), the same idiom SessionHandler uses for the same
   intent and the one .claude/rules/coroutines.md prescribes. Note no production
   caller invokes TlsSession.close() today, so this is correctness for the first
   real caller rather than an observable fix.

Behaviour is unchanged apart from (3). Three new tests: the data-phase CLOSED
pair asserted side by side at both the unit and the SessionHandler boundary --
the coupling that made read and write agree was previously untested -- and one
pinning that close() finishes its cleanup under a cancelled caller.

Review history worth keeping: the reason given for (2) was stated wrongly twice
before anyone measured it, each time printed beside real compiler output that
confirmed only the outcome and said nothing about the mechanism. The kdoc now
tells the next editor to build the counterfactual for the reason and not just
for the result, because that is the step all three attempts skipped.

Closes #649

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-01 00:41:24 -04:00
monkopedia-coder
8479cf563b
Propagate cancellation out of the tunnel's returned results (#646) (#660)
Twelve broad `catch (Exception)` clauses in :core:tunnel wrapped a suspend
call and converted cancellation into a *returned* value -- a Warning, a
StorageFailed with a rollback, a NetworkError, `false` -- instead of letting
it propagate. `.claude/rules/coroutines.md` requires propagation; the
consequence is work performed after cancellation.

Fixed, lowest frame first:

  MuxDemux.sendPingAwaitPong          `false`  -> propagate
  TunnelClientImpl.runKeepaliveLoop   `false`  -> propagate
  TunnelClientImpl.healthCheck        `false`  -> propagate
  CtLogMonitor.check x2               Warning  -> propagate
  SelfCertVerifier x3                 Warning  -> propagate
  OnboardingFlow (clear())            StorageFailed + rollback -> propagate
  CertProvisioningFlow (clearCerts()) StorageFailed + rollback -> propagate
  RelayApiClient.executeRequest       NetworkError -> propagate
  KtorWebSocketFactory.connect        onFailure/onClosing -> silent teardown

The keepalive stack is the reason for the ordering. #650 added a cancellation
rethrow at WakeReconnectDecider:56 that could not fire, because both frames
below it swallowed cancellation into `false` first. A guard above an
already-swallowing callee is dead code that looks identical in a diff to one
that works, so the swallow is fixed at the lowest frame that performs it and
each guard above is covered by a test that reddens when it alone is reverted.

MuxDemux and KtorWebSocketFactory discriminate on the *job* rather than the
exception type. Not every CancellationException at those frames is the
caller's: MuxDemux.closeAllQuietly deliberately cancels each pending ping
waiter when the transport dies (#230), and that must keep reading as a failed
health check. A blanket rethrow there hangs
MuxDemuxTest.awaitPongReturnsFalseWhenTransportClosedQuietly.
KtorWebSocketFactory still fails the bind on the teardown path so an awaiter
parked in sendBinary is released (#420 finding #4); only the listener
notification is dropped.

Four sites listed in the issue are documented in place rather than guarded,
because cancellation cannot reach them:

  CertProvisioningFlow:76, CertRenewalFlow:105/159/200 -- both guarded calls
    (DeviceKeyManager.getOrCreateKeyPair, CsrGenerator.generate) are declared
    non-suspend on their interfaces, so no implementation can suspend.
  CtLogMonitor:68 -- json.decodeFromString is not a suspend function.
  RelayApiClient:281 -- Ktor 3's SaveBody plugin drains the body inside
    block(), so bodyAsText() reads an in-memory buffer; a body that fails
    mid-read surfaces at the outer catch instead. Pinned by a test.

Two sites are deliberately untouched: SecurityCheckSources.kt:25, whose
Warning reaches a user-visible notification and so needs a ux-changes.md
decision, and TunnelSessionManager, which is #638's subject.

27 tests added, two directions per fixed site. All 12 cancellation-direction
tests are red against 54fdcd46; the 15 ordinary-direction tests pass against
it unchanged.


Closes #646

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK
2026-08-31 23:17:13 -04:00
monkopedia-coder
0e3ab5663f
Propagate cancellation out of TlsAcceptor.accept (#644) (#647)
Some checks are pending
Android CI / test (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build & Test (push) Waiting to run
* Propagate cancellation out of TlsAcceptor.accept (#644)

`accept` ended in a broad `catch (e: Exception)` that refiled whatever it
caught as `TunnelError.TlsHandshakeFailed`. On the JVM that clause catches
cancellation too -- `java.util.concurrent.CancellationException` extends
`IllegalStateException` -- so every ordinary teardown came back out of
`accept` as a domain failure, and `TunnelForegroundService`'s untyped
`catch (e: Exception)` filed it via `crashReporter.logCaughtException`.
A routine cancelled handshake was landing as a non-fatal crash report, in
exactly the channel #616/#626/#630/#643 spent a week making meaningful.
It also left a `withTimeout` around `accept` unable to see its own timeout.

`TunnelClientImpl.connect` had the identical shape: a cancellation while
`opened.await()` was suspended became a `TunnelError.ConnectionFailed`,
both thrown to the crash-reporting boundary and published on `errors`,
which the app surfaces to the user. Its three failure paths now share
`abandonConnect`, so the cancellation path still closes the inbound queue
and moves the state machine to DISCONNECTED -- only the error report is
dropped.

The two existing correct sites in TlsAcceptor used the fully-qualified
`kotlinx.coroutines.CancellationException`, so a grep for the short form
found neither and the pattern looked absent. All three now use the
imported name.

#643's cancellation test asserts only that a CancellationException is
somewhere in the `cause` chain, which was already true of the wrapped
`TlsHandshakeFailed` -- the new tests assert the thrown **type**, and both
directions run together so a fix that turned real handshake failures into
cancellation would fail too. Ablation: reverting either production change
reddens exactly its own two tests and nothing else.

The boundary half -- `TunnelForegroundService` must not crash-report a
CancellationException it now receives -- remains open as #642. The sweep's
swallowed-into-a-returned-result findings are filed as #646.

Closes #644

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

* Correct the claim that `errors` reaches the user (#644)

Both kdocs added by the previous commit asserted that a cancelled connect's
`TunnelError.ConnectionFailed` was "published on `errors`, which the app
surfaces to the user". Measured, that is false: `TunnelClient.errors` is
declared at TunnelClient.kt:19 and emitted at TunnelClientImpl.kt:200,205,
and nothing in the repo collects it. Positive control in the same sweep --
`incomingSessions` returns three production references, so the empty result
for `errors` is a real read rather than a broken search.

The behaviour is unchanged; only the stated reason for it is. The crash
report at the service boundary is the consequence that actually lands, and
the suppressed `errors` publication is a contract property rather than a
user-visible surface. Recording the measurement here so the next reader does
not re-derive it from the same wrong starting point.

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 02:40:21 -04:00
monkopedia-coder
88de3ddfee
Classify every handshake engine-result status in TlsAcceptor (#618) (#643)
Some checks are pending
Android CI / test (push) Waiting to run
CI / Build & Test (push) Waiting to run
CI / Lint (push) Waiting to run
The handshake pump read `result.status` through two `if`s after `unwrap`,
leaving `{OK, CLOSED}` unhandled, and never read it at all after `wrap`
(residual 0 of 4). A peer's mid-handshake `close_notify` therefore exited
the `while` guard normally and `accept` returned a `SuspendTlsSession`
over an already-closed engine -- a half-open session indistinguishable
from a good one, whose first `read` degrades to a clean EOF.

Both branches are now expression-position `when`s with no `else`, per the
`classifyWrapStatus` template from #639, so a future JDK enum member is a
compile error rather than a silent no-op. Verified by deleting a branch:
"'when' expression must be exhaustive", FAILURE, not a warning.

Classification is argued per direction rather than copied. On the
handshake `unwrap`, both buffer statuses stay ordinary: `BUFFER_UNDERFLOW`
is the everyday split-record case (#558) and `BUFFER_OVERFLOW` targets
`appIn`, sized from a hint, so growing is real recovery (#565). On the
handshake `wrap` both are defects and get `TunnelError.UnhandledTlsState`:
`netOut` is private, `clear()`ed every call and sized to the engine's own
`packetBufferSize`, and `wrap` has no minimum input at all (`appOut` is
deliberately zero-capacity). `CLOSED` on either side is peer behaviour,
not a defect in this layer, so it fails the handshake as
`TunnelError.TlsHandshakeFailed` and never as a crash-reported defect.

The wrap status is classified after the transport write, deliberately: a
record the engine did produce still reaches the peer, and a cancellation
raised by that write wins over the classification instead of being
laundered into a tunnel defect.

Branch D (`runTasksIfRequested`) is deliberately NOT converted -- see the
PR body and #617.


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-30 01:23:38 -04:00
monkopedia-coder
5505087f90
fix(tunnel): classify the wrap status so a defect stops looking like a hang-up (#630) (#639)
Some checks are pending
Android CI / test (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build & Test (push) Waiting to run
`SuspendTlsSession.write` collapsed every non-OK `wrap` status into one
`IOException("TLS wrap failed: $status")`. That put an ordinary `CLOSED`
-- a peer that hung up, routine on a bridge -- and a genuine defect in
this layer under the same type, and `SessionHandler.copyStreamToTls` has
to keep swallowing disconnect `IOException`s, so the defect ended the
copy loop as a clean EOF. Exactly the hole #616 closed on the read side.

#626 gave `copyStreamToTls` a `catch (TunnelError.UnhandledTlsState)`
clause ahead of its broad catch, but nothing on the write path ever threw
that type, so the clause was inert.

`SSLEngineResult.Status` is a closed four-member enum (verified with
`javap` against the JDK in use), so the split is decidable:

  OK               ordinary -- continue draining
  CLOSED           ordinary -- plain IOException, quiet loop end
  BUFFER_OVERFLOW  defect   -- TunnelError.UnhandledTlsState
  BUFFER_UNDERFLOW defect   -- TunnelError.UnhandledTlsState

`netOut` is allocated at `session.packetBufferSize` and cleared before
every wrap, so the destination always offers the engine's own advertised
maximum for one record: overflow means that bound broke, not that we
under-allocated. `BUFFER_UNDERFLOW` is an unwrap concept; `wrap` has no
minimum input at all. The read path classifies both as ordinary for
reasons that do not survive the trip to the write side -- the asymmetry
is deliberate and argued in the kdoc. The `when` is an expression with no
`else`, so a future fifth enum member fails the build rather than being
silently treated as success.

Tests, both directions:

  - `TlsAcceptorWrapStatusTest` pins the per-status classification on the
    real session, plus that cancellation still propagates as itself.
  - `WrapDefectReachesSessionHandlerTest` drives the production stack end
    to end (scripted SSLEngine behind a real TlsAcceptor, reached through
    SessionHandler's own default `tlsAccept`) and asserts a wrap defect
    escapes `handleStream` while an ordinary CLOSED returns normally.

Reverting only the production hunk turns the three defect assertions red
and leaves both quiet-path tests green; removing #626's clause instead
reddens only the boundary test.

Closes #630


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-28 22:49:01 -04:00
monkopedia-coder
7b09dd1a69
fix(bridge): let a TLS-layer defect out of the session copy loops (#616) (#626)
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
`SessionHandler.copyTlsToStream`'s bare `catch (_: Exception)` swallowed the
`IOException` that #615 added to `SuspendTlsSession.read`'s residual `else`,
converting it back into a clean EOF -- bit for bit the outcome of the `return
-1` that #615 replaced. The signal existed and could not be heard.

The catch is not simply wrong: a peer disconnecting mid-copy is normal and
frequent, and those exceptions genuinely should end the loop quietly. Making
them noisy would train whoever reads the logs to ignore them, which is the same
failure one level up. So the fix needs a discriminator, and `IOException` is not
it -- `SuspendTlsSession.write` reports an ordinary dead peer as
`IOException("TLS write failed: stream closed")`.

Give the defect its own type in the module's existing sealed hierarchy,
`TunnelError.UnhandledTlsState`, throw that from the residual `else`, and catch
it ahead of the broad catch in both copy loops so it propagates. It lands in
`TunnelForegroundService.collectIncomingSessions`, which already does `Log.e` +
`crashReporter.logCaughtException` per stream -- so the defect reaches
Crashlytics and one bad session still cannot take the tunnel down.
`:core:bridge` is a KMP jvm target with no Android logging or `CrashReporter` on
its classpath, so propagating to that existing handler is how it becomes
observable from here.

Unreachable today: `SSLEngineResult.Status` is a closed 4-member enum and
`read`'s `when` handles all four, so the residual set is empty and nothing can
throw it. This restores an invariant; it does not fix a live crash.

`tlsAccept` is a defaulted constructor parameter so tests can drive the copy
loops with a stub `TlsSession`. Production wiring is unchanged.


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-27 23:21:19 -04:00
monkopedia-coder
b2e8d130b8
fix(tunnel): handle the three unhandled SSLEngine states in TlsAcceptor (#565) (#615)
Some checks are pending
Android CI / test (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build & Test (push) Waiting to run
All three are the #558/#563 family: an engine result the loop does not
handle, where the fallback quietly loops or exits instead of failing.

- BUFFER_OVERFLOW in the handshake pump grew nothing and consumed
  nothing, so the loop re-unwrapped the same bytes forever. It now grows
  appIn and retries, matching what SuspendTlsSession.read has always
  done; both call the same growBuffer helper so the two paths can no
  longer disagree about whether the case is possible.
- NEED_UNWRAP_AGAIN fell into `else -> break`, abandoning a handshake
  that was still progressing while the caller saw an ordinary return. It
  now shares the NEED_UNWRAP branch but never pulls another DATA frame,
  which is exactly what the status means.
- SuspendTlsSession.read never ran delegated tasks, so an engine that
  defers work after the handshake could not be advanced at all.
  runDelegatedTasks is now a shared top-level helper, on Dispatchers.IO
  since a delegated task is blocking work.

The residual `else` in both loops now throws instead of `break`/`-1`:
TunnelError.TlsHandshakeFailed in the pump (the documented failure of
accept) and IOException in read (what write already throws). An unknown
engine state is a bug, and a loop that reports it as a completed
handshake or a clean EOF is how #558 stayed open across four filings.

Both loops also check ensureActive(). The defect in #563 was an
uncancellable spin, invisible to withTimeout because no iteration
suspended.

Tests script an SSLEngine directly (ScriptedSslEngine + a pluggable
SSLContextSpi) because SunJSSE does not produce any of these states on a
healthy TLS 1.3 exchange -- that is the point of the issue. Each test was
verified to go red on its own production change and green on the other
two.


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 23:01:12 -04:00
monkopedia-coder
535276a16f
Post the approval notification for the device-code flow (#606) (#608)
`onNewRequest` existed only on `AuthorizationCodeManager` and was wired in
`AppModule`. `DeviceCodeManager.authorize()` minted a user code and returned
with no hook, so an RFC 8628 request — the path a headless client takes —
never prompted the user. It polled `authorization_pending` until the 600s
expiry with nothing on screen.

Mirror the existing pattern:

- `DeviceCodeManager.onNewRequest`, invoked from `authorize()` with the
  `integrationId` that was passed in. `McpRouting.handleDeviceAuthorize()`
  passes `resolveIntegration()` (Host-header derived), so the notification
  names the integration the request was made against — NOT the session's
  `integration`, which `AppModule` sets to `integrations.firstOrNull()`
  under its one-session-for-now TODO.
- `AppModule` wires it beside the auth-code hook.

Two follow-on gaps the hook alone would have left:

- `AuthApprovalReceiver` only ever asked the auth-code manager, so the
  notification's Approve/Deny would have been dead buttons for a device
  code. It now falls through to the device-code manager.
- The approval screen (the notification's tap destination) never listed
  device codes, so it would have opened empty. `DeviceCodeManager` gains a
  `pendingCodesFlow` mirroring `pendingRequestsFlow`, and the view-model
  combines both sources.

No new entry point and no manual code-entry UI: reaching the approval
screen without a notification is still unresolved, as is whether
`device_code` should stay in the advertised `grant_types_supported`.

Tests, all demonstrated red before the fix:
- `DeviceCodeFlowTest`: callback fires exactly once with the right user
  code and integration; per-integration ids; `pendingCodesFlow` lifecycle.
- `HttpRoutingTest`: end-to-end over `/device/authorize` with a
  non-first-integration Host header, pinning the id that reaches the hook.
- `AuthApprovalReceiverTest` / `AuthorizationApprovalViewModelTest`:
  device-code fall-through for approve and deny.

Fixes #606


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 11:10:45 -04:00
monkopedia-coder
9d50167eba
fix(mcp): advertise the build version in the MCP handshake (#603) (#604)
`AppModule` built its `McpSession` with named arguments and simply omitted
`serverVersion`, so the `core:mcp` default won and every MCP client that
completed `initialize` was told the server was `0.1.0` -- true of every
release so far, and the first thing an AI client learns about the app.

`core:mcp` is KMP and cannot read the app's `BuildConfig`, so there is no
correct default it could hold. The next best thing is no default at all:
`serverVersion` is now required on both `McpSession` and
`configureMcpRouting`, which turns "a caller forgot" into a compile error,
and `AppModule` passes `BuildConfig.VERSION_NAME`. Both `"0.1.0"` literals
are gone.

Tests pass an obviously-fake `0.0.0-test` so a real version can never be
mistaken for one that came from a build. `McpEndToEndTest` now asserts the
advertised `serverInfo.version` equals the versionName of the package
installed on the device; against the pre-fix build it reports
`expected: <1.0.9> but was: <0.1.0>`. `McpSessionTest` covers the same
plumbing at the unit level.

`McpProtocolTest`'s inline notifications provider moved out to a private
class so the one added argument does not push that test over detekt's
LongMethod limit.

Closes #603


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-23 16:18:34 -04:00
monkopedia-coder
a1fb3c120b
test(tunnel): bound the TlsAcceptor tests so a spin reports red (#566) (#599)
Some checks failed
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) Has been cancelled
Deploy docs to GitHub Pages / deploy (push) Has been cancelled
TlsAcceptorSplitRecordTest, TlsAcceptorTest and TlsAcceptTest all drive
TlsAcceptor.accept in a `launch(Dispatchers.IO)` child of the test's
`runBlocking`. The handshake pump has a demonstrated uncancellable-spin
failure mode (#563; #565 covers three more unhandled SSLEngine states), and
the in-test `withTimeout` bounds cannot turn that into a failure: they bound
the `await`, but a child that never reaches a suspension point ignores the
cancellation `runBlocking` sends it, so `runBlocking` parks forever. Measured
on #563 against pre-fix production code: killed at the 300 s job bound, zero
tests executed, no JUnit XML written -- which the repo's executed-count check
reads as "the build never ran".

Add a class-level JUnit 5 ceiling with `ThreadMode.SEPARATE_THREAD`, the only
mode that does not need the wedged thread to cooperate. Same mechanism and
reasoning as MultiClientConcurrencyTest's method-level ceiling (#504). 60 s
sits above the in-test `withTimeout` sums (45 s worst case) -- so a
merely-slow run still fails with the more specific message -- and >100x above
the measured per-test runtime (<0.6 s).

Verified by reintroducing the spin: all 7 tests fail with
`TimeoutException: ... timed out after 60 seconds` at exactly 60 s each, and
JUnit XML IS written.

No assertion changed; no production code touched.


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-20 01:35:23 -04:00
monkopedia-coder
088683dd67
test(tunnel): pin the inbound consumer's tolerant ClosedSendChannelException clause (#591)
The tolerant clause in TunnelClientImpl.consumeInboundFrames was unpinned:
deleting it left the whole :core:tunnel suite green, so a refactor that
collapsed the three catches into one would have landed clean while funnelling
benign per-stream/demux teardown races into whole-tunnel teardown.

The new test provokes the exception from production code rather than a test
double. disconnect() closes the demux -- and with it the channel behind
MuxDemux.incomingStreams -- before cleanupRefs() closes the frame queue and
cancels the consumer. Holding the transport close mid-flight keeps that window
open, so an OPEN frame already on the ordered queue makes MuxDemux.handleOpen
throw ClosedSendChannelException out of incomingChannel.send.

The load-bearing assertion is that the Ping queued behind that OPEN is still
echoed: both frames ride the one ordered queue, so the Pong can only appear if
the consumer survived the throw.

Test-only; no production behaviour moves.

Closes #576


Claude-Session: https://claude.ai/code/session_01YYSPuh9bZEJkrzvnEpY1QK

Co-authored-by: monkopedia-coder <coder@monkopedia.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 23:50:48 -04:00
monkopedia-coder
3ea4bf2acb
refactor(mcp): give required tool params a non-null delegate (#581)
Some checks are pending
Android CI / test (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build & Test (push) Waiting to run
Every param declared `val period by stringParam(...)` read back as
`String?`, even though `McpTool.invoke()` answers with an error before
`execute()` runs when a required param is missing. So the nullability was
fictional and 19 call sites across the four providers wrote `period!!`.

`.required()` now returns a `RequiredParam`, whose `provideDelegate`
overload hands back a `ReadOnlyProperty<McpTool, T>`. `.optional()` and
`.default(v)` are unchanged and still read back as `T?`, which is honest —
those really can be absent. The one assertion left lives in
`RequiredBinding.getValue`, at the boundary where `invoke()` enforces the
invariant.

`.required()` after `.optional()`/`.default()` throws, since it would
promise a non-null value the extractor cannot deliver.

`ParamDef.required` is renamed `isRequired`: a Boolean property named
`required` shadows a `required()` call badly enough that the compiler
resolves `param.required()` to `DeepRecursiveFunction.invoke`.

Closes #539

Co-authored-by: monkopedia-coder <monkopedia-coder@users.noreply.github.com>
2026-08-19 18:24:52 -04:00
monkopedia-coder
3ade148a65
test(mcp): make shutdown closes transports observe a real close (#580)
`McpShutdownTest.shutdown closes transports` had no assertions — it called
`shutdown()` and stopped, so it passed whenever `shutdown()` didn't throw,
which two other tests already cover. It promised coverage of transport
closing that nothing in `core:mcp` provided.

Nothing could provide it: `SessionEntry` and the session map are private,
and transports come from `createIntegrationServer`, which builds a fresh
`HttpTransport` per call. So this adds the minimum seam that makes a close
observable — an `internal var McpRoutes.transportFactory`, defaulting to
`{ HttpTransport() }`, threaded through `createIntegrationServer`, plus
`HttpTransport` becoming `open` so a test can subclass it. No public API
changes; `configureMcpRouting`'s signature is untouched.

The test now creates two sessions through a recording transport and asserts
`shutdown()` closes each exactly once, and that the close reaches the SDK
(each per-session `Server.sessions` goes 1 -> 0).

Contrary to the note on #571, `HttpTransport.close()` is not a no-op in
production. `closeHandler` is null only until `Server.createSession` runs;
the SDK's `Protocol.connect` registers a close handler, so `close()` does
tear the SDK session down. Measured on kotlin-sdk 0.11.1, and now guarded.

Both assertions verified by mutation: dropping `entry.transport.close()`
from `shutdown()` fails the first; having the test transport swallow
`super.close()` fails the second. `core:mcp` stays at 262 tests, 0 failures.

Closes #571

Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-19 18:22:41 -04:00
monkopedia-coder
3fb3dde7f6
test(mcp): guard the session keep-alive touch against mutation (#578)
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
`McpRoutes.resolveOrCreateSession` refreshes `lastAccessedAt` whenever an
existing session is reused. Deleting that line left all 261 `:core:mcp:jvmTest`
tests green: the existing idle-timeout test only covers the forward direction
(an *idle* session is evicted), and eviction is transparent — an evicted
session is recreated under the same id and answers 200 — so neither the status
nor the echoed `Mcp-Session-Id` can distinguish "kept alive" from "rebuilt".

Adds `active session survives past the idle timeout without being rebuilt`,
which drives the clock 20 minutes, issues a request, drives it 20 more (past
SESSION_IDLE_TIMEOUT_MS since creation, but not since the last request) and
asserts on session *identity* rather than on the request succeeding: a counting
provider records how many SDK `Server` instances were built, which is exactly
once iff the session was never evicted.

Mutation round-trip, counts read from the JUnit XML with
`core/mcp/build/test-results` removed before each run:

| run | result |
|---|---|
| test added, production untouched | `XMLFILES=34 TESTS=262 FAILURES=0` |
| `lastAccessedAt` touch deleted | `XMLFILES=34 TESTS=262 FAILURES=1` |
| touch restored | `XMLFILES=34 TESTS=262 FAILURES=0` |

The single failure under mutation was the new test, on the identity assertion
(`expected:<1> but was:<2>`). Nothing else went red, confirming it is the only
guard on that line.

Test-only: `McpRouting.kt` is byte-identical to origin/main.

Closes #555

Co-authored-by: Jason Monk <monkopedia@gmail.com>
2026-08-18 23:52:50 -04:00
monkopedia-coder
576ed0432f
fix(tunnel): demultiplex inbound mux frames off the main thread (#575)
#567 serialised inbound mux frames onto a single consumer coroutine
launched on the injected scope. In production that scope is
`SupervisorJob() + Dispatchers.Main`, so every inbound frame in the app
was demultiplexed on the main thread, one at a time — anything else
occupying Main stalled the whole tunnel, and a long enough stall
overflows the bounded queue and reports it as a stalled stream reader,
naming the wrong subsystem.

Launch the consumer on Dispatchers.Default explicitly. Ordering is
untouched: it comes from there being exactly one consumer draining the
queue, not from the dispatcher being single-threaded, and
MuxFrameOrderingTest already asserts wire order under multi-threaded
dispatchers.

Closes #569

Co-authored-by: Monkopedia <monkopedia@gmail.com>
2026-08-18 23:50:06 -04:00
monkopedia-coder
078e95eefe
fix(tunnel): tear the tunnel down when the inbound frame consumer throws (#572)
Some checks failed
Android CI / test (push) Has been cancelled
CI / Lint (push) Has been cancelled
CI / Build & Test (push) Has been cancelled
#567 serialised inbound mux frames onto a single consumer coroutine to fix
the ordering bug in #562. That made the consumer a single point of failure:
it is the only caller of MuxDemux.handleFrame, and it caught only
ClosedSendChannelException. Any other throw killed it silently -- the socket
stayed up, the reader kept draining it, the state machine stayed CONNECTED,
no TunnelError was emitted, and every later frame went nowhere. Nothing would
ever trigger a reconnect. That is indistinguishable from the #558 symptom.

Before #567 each frame ran in its own coroutine, so the same throw cost one
frame. Serialising is correct for ordering; it also converted a per-frame
failure into a whole-tunnel one, so the tunnel-level failure now has to be
reported as one.

Broaden the catch and treat an unexpected throw the way the queue-overflow
path added by #567 already does: close the queue, then hand teardown to a
sibling coroutine that transitions to DISCONNECTED and emits a named
TunnelError.ConnectionFailed. Teardown cannot run inline because
handleDisconnect cancels this very job via cleanupRefs.

CancellationException is caught and rethrown ahead of the broad clause. It is
an Exception, so catching Exception without that clause would swallow every
cooperative teardown and report it as a tunnel error -- a worse bug than the
one being fixed. A test pins that: disconnect() while the consumer is parked
inside handleFrame must produce no error.

Ordering behaviour is unchanged; the single-consumer design from #567 is
untouched.

Co-authored-by: Monkopedia <monkopedia@gmail.com>
2026-08-13 01:09:28 -04:00
monkopedia-coder
a36d939fe0
fix(mcp): close swept session transports outside sessionsMutex (#570)
sweepExpiredSessions() removed expired entries and closed their
transports in the same loop, inside sessionsMutex.withLock. shutdown()
does the opposite by design -- collect under the lock, close after
releasing it -- and #559 wrote that rationale into its kdoc.

The sweep is the site where it matters more. It runs inline on every
/mcp request, and sessionsMutex guards five other request-path
acquisitions (session create/evict, the handleMcp lookup, and
handleMcpDelete's remove/restore pair), so a close that stalls would
stall every concurrent MCP request for that integration.

Latent, not live: HttpTransport.close() is closeHandler?.invoke(),
which holds no socket and is fast. This removes the hazard before a
future close() acquires a lock, does I/O, or suspends.

Behaviour-preserving -- eviction stays atomic with respect to the map,
only the close moves out. Matches the shape already used by shutdown()
and the evictOldestIfNeeded cap eviction.

Fixes #560


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-08-13 00:42:54 -04:00
monkopedia-coder
795fbb95fa
fix(tunnel): serialise inbound mux frames so DATA keeps wire order (#567)
Some checks failed
Android CI / test (push) Has been cancelled
CI / Build & Test (push) Has been cancelled
CI / Lint (push) Has been cancelled
Deploy docs to GitHub Pages / build (push) Has been cancelled
Deploy docs to GitHub Pages / deploy (push) Has been cancelled
TunnelClientImpl.onBinaryMessage started a coroutine per inbound WebSocket
message with nothing serialising them, so under a multi-threaded scope the
launches raced to MuxDemux.handleFrame -> MuxStreamImpl.receiveData and
delivered DATA frames to the stream out of wire order.

The mux protocol has no sequence numbers, so nothing downstream can repair
that. A swapped pair of TLS records fails SSLEngine.unwrap with
bad_record_mac, SessionHandler swallows the failure as EOF and tears the
bridge down without closing the TLS session -- a dead tunnel with nothing in
any log naming the cause.

Production was safe only by accident: appScope is Dispatchers.Main, a
single-threaded event loop, so the launches happened to run FIFO. The
correctness of the whole mux data path rested on an undocumented property of
a scope injected from AppModule. Pinning the dispatcher would have preserved
the accident rather than removed it.

Decode on the callback, then hand frames to a single consumer coroutine over
a bounded queue. Ordering is now a property of the tunnel, not of the
caller's dispatcher.

Ordering is global rather than per-stream. The protocol only needs per-stream
ordering, but every stream rides one WebSocket over one TCP connection, so a
stalled stream already stalls its peers once the receive window closes.
Per-stream queues would buy decoupling the transport does not provide, at the
cost of a queue and coroutine per stream.

Neither of the other obvious shapes works. A Mutex around handleFrame
serialises execution, not arrival -- the per-frame coroutines still race to
reach the lock. limitedParallelism(1) caps parallelism, not concurrency: the
moment handleFrame suspends on a full stream buffer the next frame starts and
the two interleave.

The queue is bounded (512) rather than UNLIMITED so ordering is not bought
with an OOM. The reader cannot suspend to apply backpressure (OkHttp delivers
on its own thread), and silently dropping a frame would be indistinguishable
from reordering downstream, so overflow tears the tunnel down with a named
error and the service layer reconnects.

MuxStream's kdoc now states the wire-order contract and MuxDemux.handleFrame
documents its single-caller requirement.

Fixes #562


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-08-10 01:15:54 -04:00
monkopedia-coder
a68a8c9efe
fix(tunnel): read more when a TLS record spans two mux DATA frames (#563)
TlsAcceptor gated its stream read on `netIn.position() == 0` in both the
handshake pump and SuspendTlsSession.read. That guard (da28a140, d8c4b645)
exists so several TLS records coalesced into ONE mux DATA frame are all
consumed before reading again. It creates the inverse defect: ONE record
SPLIT across TWO frames leaves a partial record in netIn, so position() != 0,
so the remainder was never read -- unwrap returned BUFFER_UNDERFLOW consuming
zero bytes, compact() restored the same bytes, and the loop ran forever at
100% CPU with no suspension point (so it was not cancellable either). The
peer was left on a socket that never spoke again and failed on its own read
timeout, with nothing in any log pointing at the cause.

Reachable in production: the relay splices client bytes with a 16 KiB read
buffer while a TLS record can be ~16.4 KiB on the wire, so any client burst
over 16 KiB splits a record deterministically.

Track whether the previous unwrap underflowed and read another frame when it
did. Behaviour-preserving otherwise -- the flag is only ever set by an
underflow, so the multi-record-per-frame path is untouched.

The extractions (pumpHandshake, runDelegatedTasks, takeFromAppIn,
pullNetData, appendTo, drain) are mechanical: the two added branches pushed
accept and read past detekt's LongMethod/CyclomaticComplexMethod limits.

New TlsAcceptorSplitRecordTest covers both call sites; both cases hang
forever on main and pass in ~1.5s here.

Found while investigating #558. Does not close it -- see #562.


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-08-10 00:09:20 -04:00
monkopedia-coder
fbde32e6a2
docs(mcp): remove the last two GET /mcp claims, including one #556 missed (#559)
Some checks are pending
Android CI / test (push) Waiting to run
CI / Lint (push) Waiting to run
CI / Build & Test (push) Waiting to run
* docs(mcp): remove the last two GET /mcp claims, including one #556 missed

Follow-up to #556, which corrected the "POST, GET and DELETE" attribution but
left two instances of the same falsehood in the file.

McpRouting.kt:1011 — "GET/DELETE without the header keeps returning 400 rather
than 401". Introduced by #551 (absent from fc86afd4^), three lines from a
correction #556 did make, and missed because #556 was written from the review's
list rather than from a fresh sweep of the file. Now DELETE-only, which is
accurate: handleMcpDelete is authenticateAndLookupSession's sole caller.

McpRouting.kt:256 — "SSE streams (GET /mcp) exit their keepalive loop". Genuinely
pre-existing, and the likely origin of the whole family: it is the oldest GET
/mcp reference in the file. SSE is not a route, it is a response FORM of POST
/mcp, selected in respondMcpResponse when the client sends
Accept: text/event-stream. Reworded to say that, and to state outright that no
GET /mcp route exists, so the next reader cannot re-derive the same wrong
inference from a nearby comment.

The full route table is three get("/.well-known/..."), post("/register"),
post("/device/authorize"), get("/authorize"), get("/authorize/status"),
post("/token"), post("/mcp"), delete("/mcp"). No GET on /mcp anywhere.

Documentation only; no behaviour change.

Found by the independent reviewer on #556, which verified all three of that
PR's corrections against source and then swept for survivors rather than
stopping at what it had been asked to check.

* docs(mcp): describe shutdown from the code, not from the sentence it replaced

Review of #559 found my rewrite fixed one half of a two-part claim and made
the other half worse by aiming it at a concrete function.

The original read "SSE streams (GET /mcp) exit their keepalive loop cleanly".
I corrected the route half and kept "exit their keepalive loop", then pointed
it at respondMcpResponse — turning a vague falsehood into a specific one.

There is no keepalive loop on that path. respondMcpResponse writes ONE frame
with respondText, not respondTextWriter, so the response completes before the
handler returns. HttpTransport is pure request/response and its close() is
just closeHandler?.invoke(), holding no socket. A repo-wide keepalive grep
finds only mux/tunnel WebSocket Ping/Pong, a different layer. Both halves
arrived together in 1ed99f35 (#447); they were always one claim.

Rewritten from what shutdown() does: takes the session map under its mutex,
clears it, closes each transport. No claim about streams, keepalives, or what
the client observes — none of which I can support from the code.

Also fixes the same family in McpSession.kt, which the review found and which
no previous sweep had reached: its kdoc said shutdown "then stops the HTTP
server", contradicted by its own body four lines below — "Do NOT call stop()
here. The Ktor server must stay alive so subsequent FCM wakes can bridge new
connections to it."

Verified after: no keepalive / SSE-stream / stops-the-HTTP-server claims
remain anywhere in :core:mcp, and none elsewhere in the tree.

Documentation only; no behaviour change.

* docs(mcp): drop the false onDestroy clause, and say the closes are outside the lock

Third instance of the same failure in this chain, and the same mechanism each
time: a claim inherited from a neighbouring comment rather than read off the
code.

The body comment says "Only stop() when the service is being destroyed
(onDestroy path)". That reads fine as a rule about when calling stop WOULD be
appropriate. I promoted it into kdoc as a statement of where stop runs, which
is false:

  TunnelForegroundService.onDestroy -> gracefulTunnelShutdown(mcpSession, ...)
  GracefulTunnelShutdown.kt:24      -> withTimeoutOrNull { mcpSession.shutdown() }

onDestroy reaches shutdown(), the function this kdoc is attached to, and never
stop(). Worse, it pointed readers at onDestroy expecting to find stop() there.

McpSession.stop() has no production caller at all. The only .stop() in any
production sourceset is mcpHandle.stop() in SessionHandler.kt:62, which is a
lambda field on McpSessionHandle, and in production that lambda is
SharedMcpSessionFactory.kt:25 -- `{ /* shared session survives individual
streams */ }` -- deliberately a no-op because the Ktor server is a singleton
shared across streams. The kdoc now records that rather than implying a caller
exists.

Also addresses the reviewer's non-blocking nit on McpRouting.shutdown: the
transport closes happen OUTSIDE the mutex, and the previous wording could be
read as bundling them under it. Now says so, and why -- a slow close must not
block other session traffic.

Documentation only; no behaviour change.
2026-08-09 02:26:17 -04:00
monkopedia-coder
2338ebc0bd
docs(mcp): correct three claims in the #551 kdoc that review falsified (#556)
Review of #551 found three statements in the merged kdoc that are not true.
All three are documentation-only; no behaviour changes.

1. There is no GET /mcp route. Only post("/mcp") and delete("/mcp") are
   registered (McpRouting.kt:159-160). The respondUnauthorized kdoc I added
   said the four inline 401 blocks were "across POST, GET and DELETE". The
   count of four is right; the GET attribution was wrong, inherited from a
   pre-existing stale kdoc on authenticateAndLookupSession which said "Common
   auth + session lookup for GET and DELETE /mcp". Both corrected — the
   extraction is now described by where the call sites actually are.

2. "each step is independently testable" is false. Every extracted helper is
   private, so jvmTest still reaches them only through a full request. The
   extraction bought reviewability, not direct unit-testability. #541 asked
   for both; this delivered one, and the kdoc now says so rather than claiming
   the half it did not.

3. Reworded rather than deleted, because the reason the helpers exist is still
   accurate — what was wrong was the claim about what that buys.

Found by the independent reviewer on #551, which also ran five mutations
against the extracted paths and confirmed the "no new tests needed" defence
holds for the #206 ownership check, the no-leak 404, the #345 label migration
and the initialize guard. The one mutation nothing caught — the lastAccessedAt
touch — is pre-existing and is filed separately as #555.
2026-08-09 01:42:18 -04:00
monkopedia-coder
fc86afd4fd
refactor(mcp): extract the POST /mcp prologue from handleMcp (Fixes #541) (#551)
handleMcp() was ~298 lines carrying @Suppress("LongMethod", "ReturnCount",
"CyclomaticComplexMethod") and mixing roughly ten concerns: security-alert
gate, integration resolution, rate limiting, bearer auth, client identity,
label resolution with the #345 lazy migration, body read and parse, session
sweep, session create/lookup/evict with the #206 ownership check, and JSON-RPC
dispatch.

It is now orchestration over focused helpers: respondUnauthorized,
authenticateBearer, resolveCallerClientId, resolveClientLabel,
readJsonRpcBody, resolveOrCreateSession, and newSessionEntry for the
create-and-evict block that appeared twice.

No functional change intended.

The WWW-Authenticate + 401 challenge was written inline four times — twice in
handleMcp, twice in authenticateAndLookupSession. It is now one function.
authenticateAndLookupSession composes the same auth helpers, so POST, GET and
DELETE authenticate through identical code; previously an auth fix could land
on one verb and miss the others.

Two orderings are load-bearing and are preserved with comments:

- authenticateAndLookupSession reports the missing-session-id 400 BEFORE the
  client-id 401, opposite to handleMcp. A GET/DELETE without the header still
  returns 400.
- resolveClientLabel is called before session routing rather than inside the
  initialize branch. It performs a write (upgradeClientLabel) as part of the
  #345 lazy migration, and that write previously happened even on requests
  that then failed with 400.

One reorder: resolveClientId now runs before resolveClientName. Both are pure
reads under the store lock, so the only observable difference is that the
failure path skips a lookup it used to perform and discard.

LongMethod and CyclomaticComplexMethod are gone from handleMcp. ReturnCount
stays: the prologue is a chain of guard clauses, and satisfying the limit of 4
requires nesting them into a pyramid. #541 expected all three to come off;
detekt says otherwise, and the rationale is now in the kdoc.

No new tests. The invariants named in the issue already have dedicated
coverage — McpSessionClientBindingTest (4 tests, #206),
UnknownClientLabelerRoutingTest (5 tests, #345), McpSessionRoutingTest (7
tests). Parallel unit tests for the same rules would be duplicate coverage
that drifts.

Verified: 261 test executions, 0 failures, counted from the JUnit XML with
the results directory deleted beforehand so attribution is unambiguous.
2026-08-09 00:58:24 -04:00
Jason Monk
56f661a3f5
test(fixtures): frame integration HTTP byte-exactly to close socket-read desync (#523) (#524)
`IntegrationHttpSupport.readResponse` read the status line, headers, AND
body through one char-oriented `BufferedReader` (reused per stream since
#522). But `Content-Length` counts BYTES while a `BufferedReader` counts
CHARS, and `readFixedBody` read `Content-Length` *chars* off a UTF-8
decoder. Whenever a body was non-ASCII the char and byte counts diverged,
the decoder's 8 KiB block reads pulled bytes belonging to the next
response into its internal buffer, and the keep-alive socket desynced ->
every subsequent read blocked until `SOCKET_READ_TIMEOUT_MS` and surfaced
as the cascading `SocketTimeoutException` in `ClaudeFullFlowEndToEndTest`.
#522's reader-reuse narrowed the window; the char/byte unit mismatch kept
it open.

Rewrite the read path to be byte-exact on one reused `BufferedInputStream`
per underlying stream (identity-keyed, mirroring #522 but bytes not chars):

- Read status + header lines as BYTES up to each CRLF, decoded ISO-8859-1
  (byte-exact 1:1 for HTTP framing).
- Read the body as EXACTLY `Content-Length` BYTES, or decode chunked by
  exact byte reads of each hex-sized chunk. Decode to String as UTF-8 only
  after the exact bytes are in hand.
- Keep per-stream reuse so bytes buffered ahead from a coalesced TCP
  segment carry to the next call. `applyReadTimeout`/`exchange`/
  `HttpResponse`/`SOCKET_READ_TIMEOUT_MS` public API unchanged, so call
  sites need no changes.

Add `IntegrationHttpSupportTest` (no relay/device; a fake stream feeds
canned bytes) pinning the property the de-flake hinges on: a multi-byte
UTF-8 body does not over-read into the next response, coalesced responses
both parse, and chunked decodes byte-exactly. The old char path would
over-read past a non-ASCII body and desync the following response.

Also migrate the two app-side hand-rolled char `readResponse`
implementations (`McpSessionTestHarness`, `OAuthDeviceFlowIntegrationTest`)
onto the shared byte-exact helper so none of the char/byte-desync-prone
readers are left behind.

Closes #523

Co-authored-by: rouse-context-bot <bot@rousecontext.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 03:25:51 -04:00
Jason Monk
bcd3ed8551
test(tunnel): de-flake OAuthEndToEndTest by reusing one socket reader (#518) (#522)
OAuthEndToEndTest intermittently failed with `SocketTimeoutException: Read
timed out` while reading a relay response (the issue saw it 2/6 in CI, and
it reproduced locally). The cause was not a too-tight timeout — the suite
already shares the generous 60s `SOCKET_READ_TIMEOUT_MS` from #501/#504 —
but a lost-bytes desync in `IntegrationHttpSupport.readResponse`.

The tests fire a dozen sequential requests over one keep-alive socket.
`readResponse` built a fresh `BufferedReader`/`InputStreamReader` on every
call. That reader fills from the socket in 8 KiB blocks, so when the relay
coalesces two responses into one TCP segment (or the next response arrives
before we finish parsing the current one) it buffers bytes belonging to the
*next* response. Discarding the reader after each call dropped those bytes;
the next call's brand-new reader then blocked on a status line that had
already been consumed, and only unblocked when the 60s read timeout fired —
surfacing as the flake. OAuthEndToEndTest is the most exposed because it
makes the most sequential requests on a single socket.

Fix: keep exactly one reader per underlying `InputStream` (identity-keyed,
synchronized so concurrent test classes stay isolated), so buffered-ahead
bytes carry over instead of being dropped. Tests may call the new
`release(input)` on teardown to drop the cached reader; OAuthEndToEndTest
does so when it closes its socket.

Verification (no Gradle test-retry on the `integrationTest` task, so each
pass is a single unretried attempt):
- `*OAuthEndToEndTest*` alone, `--rerun-tasks`: 30/30 clean, 0 retries.
- full `:core:tunnel:integrationTest` (50 tests), `--rerun-tasks`: 5/5 clean.

Co-authored-by: monkopedia-coder <monkopedia+coder@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-25 00:19:20 -04:00
monkopedia-coder
a74fb962c1
test(tunnel): de-flake MultiClientConcurrencyTest (#501) (#504)
* test(tunnel): de-flake MultiClientConcurrencyTest (#501)

The relay-backed multi-client test was flaky and hang-prone in CI: it
failed with a SocketTimeoutException on one PR and wedged for ~35 min on
another, burning the "Integration tests (relay)" job on unrelated changes.

Two root causes, both test-timing (relay passthrough is fine in prod):

1. The class-level `@Timeout(180s)` runs in the default SAME_THREAD mode,
   which only checks elapsed time *after* the test method returns. A thread
   blocked in a `Socket` `read()` is never interrupted, so a wedged run
   hangs indefinitely instead of failing. Add a method-level
   `@Timeout(120s, threadMode = SEPARATE_THREAD)` so a stuck run is
   preempted and FAILS FAST (~2 min) instead of hanging the CI job.

2. The phase transitions waited on fixed `delay(...)`s ("let the stream
   register", "let handlers spin up", "let the CLOSE propagate") that race
   a wall clock and the 30s socket read timeout under load. Replace them
   with deterministic readiness signals: the device-side session collector
   now emits on per-stream open/close Channels, and the test awaits the
   actual lifecycle events (stream surfaced / handler returned) with bounded
   `withTimeout`. The test now tracks real events, so it can neither
   flake-timeout nor wedge.

Test-only change; no production tunnel/relay behavior touched. Verified
green and ~2.3s across 5 repeated runs, plus the full :core:tunnel
integration suite (50 tests) with no regression.

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

* De-flake relay integration suite: shared IntegrationHttpSupport helper + SEPARATE_THREAD timeouts

Extract the duplicated socket-HTTP request/response helper (the readLine()-racing-soTimeout source of the SocketTimeoutException flakes) into a shared core/testfixtures IntegrationHttpSupport, and convert ClaudeFullFlowEndToEndTest, OAuthEndToEndTest, TunnelMcpIntegrationTest, EndToEndSessionTest, and MultiClientConcurrencyTest to it. Robust read backed by a SEPARATE_THREAD hard @Timeout ceiling rather than racing per-read soTimeout. Test infra only. #501

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

* De-flake: rely on generous socket read timeout, drop broad SEPARATE_THREAD

The class-level @Timeout(threadMode = SEPARATE_THREAD) added across the
end-to-end integration classes intermittently corrupted Gradle's per-test
output store ("Could not write XML test results ... EOFException / Kryo
buffer underflow"): these tests run long-lived background coroutines whose
logging races the per-method separate-thread boundaries.

Revert to the default SAME_THREAD class timeout and rely on the generous
shared socket read timeout (IntegrationHttpSupport.SOCKET_READ_TIMEOUT_MS,
60s) as the fail-fast mechanism: every blocking read is bounded, so a stuck
relay round trip raises SocketTimeoutException in ~60s instead of hanging,
while normal CI slowness never trips it. MultiClientConcurrencyTest keeps
its method-level SEPARATE_THREAD ceiling on its single test (#504), where
the output-store interaction does not arise.

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

---------

Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 15:53:59 -04:00
monkopedia-coder
0257d0375f
Wire real CertInspector and reach the CN-mismatch path (#495) (#499)
* Wire real CertInspector and reach the CN-mismatch path (#495)

The CN-mismatch safety net and the expiry guard in CertRenewalFlow were
both inert in production. CertInspector was a no-op stub returning an
empty CertInfo, so isExpired was always false and the old-vs-new CN
comparison was always null == null. The downstream banner chain
(RenewalResult.CnMismatch -> CertRenewalWorker.handleCnMismatch ->
CertRenewalBannerFlow -> dashboard banner) could therefore never fire.

Implement the default CertInspector for real: parse the PEM via
CertificateFactory into an X509Certificate and populate commonName (from
the subject X500 principal, parsed with LdapName) and isExpired (notAfter
< now). A malformed/unparseable cert degrades safely to an empty CertInfo
rather than throwing inside the renewal flow.

Also pass the current stored cert into handleRenewResponse on the
Firebase and renewExpired paths (the mTLS path already did) so the
CN-mismatch check runs end-to-end on every renewal path. The expired
cert still carries a valid subject CN, so the comparison is meaningful
there too.

Tests use real openssl-generated self-signed fixtures so CN + expiry
extraction is exercised against the production code path, not a fake.

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

* Parse cert CN without JNDI (LdapName absent on Android) — #499 review

CertInspector.inspect() extracted the subject CN via javax.naming.ldap.LdapName,
but JNDI is not in the Android runtime: on-device the LdapName(...) call throws
NoClassDefFoundError, which the surrounding runCatching{} swallowed, so commonName
was permanently null and the CN-mismatch safety net (#495) was inert in production.

Parse the X500Principal RFC 2253 subject string directly instead — split on
unescaped commas, take the first CN= component. No new dependency, no JNDI.

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

* ci: re-trigger checks (prior integration run wedged; see #501 flake)

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

---------

Co-authored-by: Jason Monk <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-18 17:44:18 -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
4a2ebd98f2
Extract shared ReadinessGate (#454) (#457)
Four classes independently hand-rolled the identical "suspend/block until
the backing flow has emitted at least once" primitive — a
CompletableDeferred<Unit> + CountDownLatch(1) pair with byte-for-byte
identical signalReady()/awaitReady()/awaitReadyBlocking(timeoutMs) bodies.
This gate is load-bearing on the cold-start FCM-wake path (#414/#416), so
the duplicated correctness logic (idempotent signal, deferred + latch kept
in sync) should live in one tested place.

Add ReadinessGate to :core:mcp, alongside the ProviderRegistry interface
that already documents this awaitReady/awaitReadyBlocking contract. :app
already depends on :core:mcp, so all four consumers can import it without a
new dependency edge. Each class now delegates to the gate; observable
behavior is unchanged (pure refactor).

Add a focused unit test on the helper (idempotent signal; awaitReady
suspends until signalled then resumes; awaitReadyBlocking false before /
true after; double-signal is safe).

Migrated:
- IntegrationProviderRegistry
- DeviceRegistrationStatus
- SecurityAlertGate
- OutreachIntegration

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-08 10:40:17 -04:00
monkopedia-coder
25966d3006
Add Certspotter fallback for CT-log checks (#459)
crt.sh (community-run, maintained by Sectigo) returns 502/503 for minutes
at a time, longer than HttpCtLogFetcher's 1s/3s/9s retry window (#256) and
the cross-run debounce (#256/#429). The residual user-facing "Could not
reach CT log service" warnings were crt.sh outages, not real reachability
problems.

Add a second, independent CT source (Certspotter) consulted only after
crt.sh has already failed, so a crt.sh outage becomes a silent successful
check instead of a warning -- while preserving real security coverage.

- CertspotterCtLogFetcher: GET api.certspotter.com/v1/issuances and translate
  each issuance's issuer.name into a crt.sh-shaped CtLogEntry. Certspotter's
  issuer.name is byte-identical to crt.sh's issuer_name (verified against live
  data: same C=US, O=..., CN=... DN order + comma-space), so no normalization
  is needed and there is zero false-Alert risk. Non-2xx throws IOException.
- CompositeCtLogFetcher(primary, fallback): try crt.sh; on any failure try
  certspotter; if both fail, rethrow the PRIMARY error so the monitor's
  warning text stays meaningful. CancellationException is rethrown.
- Wire AppModule's CtLogFetcher to the composite.

CtLogMonitor, HttpCtLogFetcher, SecurityCheckWorker, and the notification
path are unchanged -- this only makes the underlying fetch succeed more
often, so there is no UX/error-surface change.

Co-authored-by: Monkopedia <monkopedia@gmail.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-06-08 10:12:37 -04:00
Jason Monk
a4116532f7 SSE response support and auto-recreate unknown sessions
Two fixes that together restore claude.ai connector functionality
through Anthropic's Streamable HTTP proxy:

1. Respect the client's Accept header. The proxy sends
   `Accept: application/json, text/event-stream` and rejects plain
   JSON responses as "Invalid content from server" because it expects
   the SSE form. When the client accepts text/event-stream, wrap the
   JSON-RPC response as `event: message\ndata: <json>\n\n` and respond
   with Content-Type: text/event-stream.

2. Auto-recreate sessions for unknown session IDs. When the device
   restarts (process kill, app reinstall, idle eviction) the in-memory
   sessions map is empty, but the proxy / client still holds the old
   session ID and sends tools/call without re-initializing. Returning
   404 surfaces "Invalid content from server" through the proxy.
   Instead, recreate the session under the requested id and bind it to
   the caller's clientId. Security is unchanged: the caller's OAuth
   token is what gates access, and the SDK Server starts fresh — there
   is no leftover state from the previous session.

Tests for the previous "unknown session = 404" behaviour are updated
to assert the auto-recreate behaviour, including matching session id
echo on the response.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 10:01:30 -04:00
Jason Monk
9950fb88d1 Remove GET /mcp SSE handler; keep server alive across idle timeout
Two related fixes for Claude Code outreach connection stability:

1. Remove GET /mcp (SSE stream). The persistent SSE stream dies every
   time the phone goes idle, and Claude Code counts each disconnect as
   a "terminal connection error." After 3 strikes the server is marked
   dead in Claude Code's session. Without GET /mcp, there's no
   persistent stream to disconnect — POST and DELETE are sufficient
   for our request/response architecture.

2. Don't call stop() in McpSession.shutdown(). The graceful shutdown
   added in #447 was killing the Ktor server permanently. After the
   first idle timeout, no subsequent FCM wake could bridge connections
   to a dead server. Keep the server alive across shutdowns; only
   stop() in the destruction path.

Refactor TlsAcceptor.accept() to extract createServerEngine() so the
ALPN setup doesn't push it over the LongMethod threshold.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 08:23:27 -04:00
Jason Monk
ec55b400c5 Advertise HTTP/1.1 via ALPN in TLS server handshake
Some HTTP clients require ALPN negotiation during TLS before sending
requests. Without this, they complete the handshake but never send
HTTP data because no application protocol was agreed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-03 11:05:17 -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
6702193bd4
Add GET /mcp (SSE) and DELETE /mcp (session teardown) for Streamable HTTP (#440) (#441)
Claude Code's MCP client expects GET /mcp to open an SSE stream and
DELETE /mcp to tear down sessions. Without these, the client gets 405s
and cannot connect. GET holds the connection with periodic keepalive
comments; DELETE removes the session and closes its transport.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-02 21:22:18 -04:00
Jason Monk
1fc93e4d55
Fix #437: Add test- prefix to subdomains for debug builds (#438)
Debug builds now send prefix: "test" in /request-subdomain requests,
producing subdomains like test-cliff instead of cliff. This stops
testing from burning the finite single-word pool.

Relay: accept optional prefix field (validated: alphanumeric+hyphen,
max 10 chars), prepend to single-word candidates only.
Android: pass subdomainPrefix through RelayApiClient constructor,
wired from BuildConfig.DEBUG in AppModule.

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-28 22:11:33 -04:00