Commit graph

61 commits

Author SHA1 Message Date
Jason Monk
6abe11ef1d Add thread safety to TlsInputStream and TlsOutputStream with ReentrantLocks
SSLEngine's internal state can corrupt if concurrent threads call wrap/unwrap
simultaneously. Add separate read and write locks so each operation is
serialized independently, which SSLEngine supports.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 10:32:17 -04:00
Jason Monk
4cd183ae5e Fix onboarding flow: shared ViewModel, step progress, already-onboarded guard
The WELCOME and ONBOARDING routes each created separate OnboardingViewModel
instances via koinViewModel(), so startOnboarding() called on the WELCOME
screen's instance was never observed by the ONBOARDING screen's instance.

Collapse into a single ONBOARDING route that shows WelcomeScreen for
NotOnboarded state and SettingUpScreen/ErrorScreen for other states.
Add OnboardingStep enum with step-level progress (auth, registration,
cert issuance) shown on SettingUpScreen. Guard startOnboarding() against
InProgress and Onboarded states. Add onRegistered callback to
OnboardingFlow.execute() so the ViewModel can track cert issuance start.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 10:29:55 -04:00
Jason Monk
91ae7e07d4 Fix ktlint violations from MCP SDK upgrade
Line length and import ordering issues in core:bridge test providers
and core:tunnel integration tests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 10:10:48 -04:00
Jason Monk
6403c38af6 Upgrade MCP Kotlin SDK to 0.10.0 for protocol version 2025-11-25
Claude's client sends protocolVersion "2025-11-25" in its initialize
request. SDK 0.4.0 only supported 2024-11-05 and fell back to that
version, which modern clients may reject. SDK 0.10.0 advertises
2025-11-25 and negotiates down to 2025-06-18 / 2025-03-26 / 2024-11-05.

Breaking changes from the SDK upgrade:
- Types moved from io.modelcontextprotocol.kotlin.sdk to .sdk.types
- Tool.Input renamed to ToolSchema
- CallToolRequest.arguments moved to CallToolRequest.params.arguments
  (now nullable JsonObject?)
- Transport.send gains TransportSendOptions? parameter
- Server.connect() renamed to Server.createSession()
- addTool/addResource handlers receive ClientConnection receiver

Also bumps Kotlin 2.1.10 -> 2.2.21, AGP 8.8.2 -> 8.10.0, and
KSP 2.1.10-1.0.31 -> 2.2.21-2.0.5 to satisfy SDK metadata version
requirements.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 09:58:16 -04:00
Jason Monk
0acd98b920 Track active streams for CONNECTED↔ACTIVE state transitions, fix idle timeout
TunnelClientImpl now transitions to ACTIVE when the first mux stream
opens and back to CONNECTED when the last closes. StreamCloseTracker
wraps each stream to detect close. This fixes the idle timeout which
was never firing because the state never reached ACTIVE.

Verified: full FCM wake flow works end-to-end — device idles out after
30s (test) of no streams, AI client connects, relay sends FCM, device
wakes and serves the request in ~1 second.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 09:57:44 -04:00
Jason Monk
91fd2ce357 Add end-to-end OAuth authorization code flow test through real relay
Exercises the full AI client -> relay -> device -> MCP data path with
OAuth PKCE: 401 on unauthenticated request, OAuth metadata discovery,
dynamic client registration, authorize with PKCE challenge, programmatic
approval, status polling, token exchange, then authenticated MCP
initialize/tools-list/tools-call through the TLS tunnel.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 09:33:12 -04:00
Jason Monk
5135be0073 Add OAuth refresh token support with token expiration
Access tokens now expire after 1 hour and refresh tokens after 30 days.
TokenStore.createToken is replaced by createTokenPair which returns both
an access token and a refresh token. The /token endpoint handles
grant_type=refresh_token with token rotation (old refresh token is
invalidated on use). OAuth metadata advertises refresh_token in
grant_types_supported. Room schema bumped to v2 with destructive
migration since this is pre-release.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 09:22:58 -04:00
Jason Monk
4f8ecf1e54 Audit token grants, add notification action toggle, log audit failures
- Add TokenGrantEvent and onTokenGranted() to AuditListener so token
  creation is logged for both authorization code and device code flows
- Add allowActions toggle to NotificationMcpProvider that gates
  perform_notification_action and dismiss_notification behind a user
  preference, returning an error when disabled
- Log audit emit failures instead of silently swallowing them

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 09:14:11 -04:00
Jason Monk
d87c342d6a Fix 4 critical security findings from audit
1. redirect_uri validation: Validate http/https scheme at registration
   and authorization time. Store registered redirect_uris per client
   and verify match in /authorize. HTML-escape redirect_uri before
   embedding in JavaScript (prevents XSS via crafted URIs).

2. PKCE format validation per RFC 7636: code_challenge must be 43-128
   chars base64url charset, code_verifier must be 43-128 chars
   unreserved charset. Validated in createRequest() and exchangeCode().

3. Encrypted notification storage: Add FieldEncryptor using AES-GCM
   with Android Keystore-derived key. Encrypt notification title/text
   before Room insert, decrypt on read. Wire encryptor through
   RoomAuditListener for audit data.

4. Encrypted private key storage: FileCertificateStore now encrypts
   the PEM key file using AES-GCM with a Keystore-derived key.
   MtlsWebSocketFactory reads encrypted format with plaintext fallback
   for migration from existing installs.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 09:02:42 -04:00
Jason Monk
cd40f32dff Fix high-severity security findings from audit (5-12)
- Validate redirect_uris at /register: reject non-http/https schemes and
  registrations with no valid URIs (Finding 5)
- Use per-integration rate limiter keys (e.g. "health/register") instead of
  global keys to prevent cross-integration interference (Finding 6)
- Validate integration path parameter against ^[a-zA-Z0-9_-]{1,64}$ regex
  at all route handlers to prevent path traversal (Finding 7)
- Finding 8 (SQLCipher for token DB) deferred: no SQLCipher dependency yet,
  tokens already hashed
- Add security headers (X-Frame-Options, CSP, nosniff, HSTS) to the
  /authorize HTML response (Finding 9)
- Add per-integration rate limiting to /mcp endpoint via separate
  mcpRateLimiter parameter (Finding 10)
- Increase display/user code entropy from ~41 bits (4+4 chars) to ~61 bits
  (6+6 chars) and switch from kotlin.random.Random to java.security.SecureRandom
  in both AuthorizationCodeManager and DeviceCodeManager (Finding 11)
- Finding 12 (origin validation in device code approval) confirmed mitigated
  by phone-side approval UI requiring physical user interaction

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 08:56:55 -04:00
Jason Monk
4d7090457a Refactor EndToEndSessionTest to exercise TunnelClientImpl production code path
Scenarios 5-10, 17-20 now use TunnelClientImpl + MtlsWebSocketFactory instead
of manually constructing WebSocket connections and pumping mux frames. This
ensures the production incomingSessions flow and MuxDemux wiring are tested
end-to-end against the real relay binary.

Extract shared test utilities into TestRelayFixture.kt:
- TestCertificateAuthority: generates CA, relay, and device certs via keytool
- TestRelayManager: starts/stops relay subprocess, waits for ready
- TestSslContexts: factory methods for mTLS, device server, AI client contexts
- buildSyntheticClientHello / findFreePort / findRelayBinary: shared helpers

Add MtlsWebSocketFactory: a WebSocketFactory backed by Java's HttpClient that
properly presents client certificates (unlike Ktor CIO).

Add new test scenarios:
- Scenario 19: multiple sequential TLS messages through tunnel
- Scenario 20: full session lifecycle (connect, stream, disconnect, reconnect)

Net effect: -638 lines of duplicated cert/relay/SSL code across the two test
files, replaced with shared utilities. Both test classes now import from
TestRelayFixture instead of maintaining their own copies.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 18:42:09 -04:00
Jason Monk
a304432de7 Add phone-side OAuth approval UI with notifications and broadcast actions
Wire the full authorization request approval flow:
- AuthorizationCodeManager.onNewRequest callback fires on new requests
- High-importance notification channel for auth requests
- AuthorizationApprovalViewModel polls pending requests every 2s
- AuthorizationApprovalScreen shows cards with display code, approve/deny
- AuthApprovalReceiver handles approve/deny from notification actions
- Dashboard shows pending request count banner with navigation
- Navigation route and Koin wiring for the new screen

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 18:23:22 -04:00
Jason Monk
ea480467b5 UI fixes: hide debug connection state, clarify audit notifications, store client names
- Wrap connection status indicator in BuildConfig.DEBUG so it only shows
  in debug builds
- Rename "Notifications" settings section to "Audit Notifications" with
  a description explaining what it controls
- Add clientName parameter to TokenStore.createToken so authorized
  clients list shows human-readable names instead of UUIDs
- Store client_id to client_name mapping in AuthorizationCodeManager
  during /register, pass through when issuing tokens

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 17:40:39 -04:00
Jason Monk
1f1208c5ab Fix UI padding inconsistencies and add empty state placeholders
Standardize spacing across all screens:
- 16dp horizontal screen edge padding (already present)
- 16dp vertical spacing between sections, 8dp within sections
- 16dp from header to first content element
- Card internal padding 16dp (already present)

Add empty state cards with icons for:
- Empty recent activity on dashboard and integration manage screen
- Empty authorized clients on integration manage screen
- Updated audit history empty text to "No tool calls recorded yet"

Use semi-transparent surfaceVariant for Settings section cards to
improve dark mode blending.

Also includes ktlintFormat auto-fixes for OnboardingViewModel and
RelayApiClient.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 17:34:48 -04:00
Jason Monk
ba27cfee0e Add expired auth cleanup, rate limiting, and MCP error response tests
- AuthorizationCodeManager: lazily clean up expired requests on
  createRequest() and getStatus() calls to prevent unbounded growth
- DeviceCodeManager: same pattern, cleanup on authorize() calls
- RateLimiter: new class for global per-endpoint rate limiting with
  configurable window and max requests
- McpRouting: wire rate limiter into /register, /authorize, /token
  endpoints (optional, null = no limiting)
- Tests for all three features: cleanup behavior, JSON-RPC error
  responses (-32700 parse error, -32603 internal error), and rate
  limiter unit + integration tests

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 17:33:54 -04:00
Jason Monk
f5a21a40d0 Send FCM token to relay after WebSocket connect for push wakeups
The relay accepts {"type":"fcm_token","token":"..."} as a text WebSocket
message to register a device's FCM token. This adds:

- sendText() to WebSocketHandle for text frame support
- sendFcmToken() to TunnelClient interface and TunnelClientImpl
- FCM token sending in TunnelForegroundService after connect and reconnect
- Tests verifying token JSON is sent and no-op behavior before connect

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 17:30:09 -04:00
Jason Monk
cf47b2f699 Harden TLS bridge, MuxDemux thread safety, and error handling
- MuxDemux: synchronize stream map access with Mutex, add stream limit
  (100 max) rejecting excess OPEN frames with ERROR
- MuxStreamImpl: add closeQuietly() for error cleanup without sending
  CLOSE frames over a broken transport
- TlsInputStream: fix BUFFER_OVERFLOW to retry unwrap immediately after
  resizing, add 30s read timeout
- TlsOutputStream: wrap stream.write() in try-catch, throw IOException
- TunnelClientImpl: log frame-after-disconnect and disconnect errors,
  use quiet cleanup in error path to avoid sending on broken connection
- HttpTransport: add 30s timeout on handleRequest, catch handler errors
- McpRouting: add withTimeout on /mcp POST body read

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 17:28:32 -04:00
Jason Monk
c97a25d555 Wire AuditListener into MCP tool call dispatch path
The auditListener parameter in configureMcpRouting was marked
@Suppress("UNUSED_PARAMETER") and never invoked, so tool calls
through MCP produced no audit history. Now emitAuditEvent intercepts
tools/call JSON-RPC requests, times the dispatch, extracts tool name
and arguments from the request, parses success/error from the response,
and fires AuditListener.onToolCall with a complete ToolCallEvent.

Also fixes pre-existing ktlint violations in the /register error path.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 17:20:11 -04:00
Jason Monk
d8c4b6454d Fix MCP tool invocation: notification handling, TLS multi-record, idle timeout
- HttpTransport: add handleNotification() for fire-and-forget JSON-RPC
  messages (no response expected). Without this, notifications/initialized
  hung forever waiting for a response that never came.

- McpRouting: detect JSON-RPC notifications (no "id" field) and return
  202 Accepted immediately instead of dispatching through handleRequest.
  Also add 5s timeout on receiveText() for /register to prevent hangs.

- TlsInputStream: same multi-record fix as TlsAcceptor handshake —
  check netIn.position() before reading from stream. HTTP headers and
  body arriving in the same mux DATA frame caused the body read to block.

- TunnelClientImpl: catch ClosedSendChannelException in onBinaryMessage
  to prevent crash when WebSocket frames arrive after disconnect.

- TunnelForegroundService: handle double-wake by disconnecting stale
  connection before reconnecting.

- Increase idle timeout to 30 minutes for testing (was 5 minutes, which
  caused the connection to drop right when Claude tried tool calls).

Verified: Claude connected via OAuth, called echo and device_info tools
successfully through the full relay → device → MCP pipeline.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:41:22 -04:00
Jason Monk
9737a2d3ea Add OAuth authorization code flow with PKCE for MCP client auth
Replace device code flow as the primary auth method for Claude's MCP
client, which supports the standard authorization code flow with PKCE.
Device code flow remains as a fallback for other clients.

The flow: Claude opens GET /authorize in a browser, sees a display code
and spinner. The phone shows the same code for user approval. On
approval, the browser JS polls /authorize/status, gets the auth code,
redirects to the callback URI. Claude then exchanges the code + PKCE
verifier at POST /token for an access token.

Key changes:
- AuthorizationCodeManager: manages pending auth requests, PKCE S256
  validation, single-use authorization codes, 10-minute expiry
- OAuthMetadata: adds authorization_endpoint, authorization_code grant
  type, S256 code challenge method
- McpRouting: GET /authorize (HTML page), GET /authorize/status (JSON
  polling), POST /token now handles both grant types and form-encoded
  bodies
- McpSession: exposes authorizationCodeManager for phone-side approval
- TestWakeReceiver: approve_auth type for ADB testing

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:07:19 -04:00
Jason Monk
b426128c18 Add OAuth discovery endpoints for MCP client compatibility
- RFC 9728 protected resource metadata at /.well-known/oauth-protected-resource/{path}
- RFC 8414 path-based auth server metadata at /.well-known/oauth-authorization-server/{path}
- Root-level fallback for /.well-known/oauth-authorization-server
- Dynamic client registration at /{integration}/register (RFC 7591)
- Add registration_endpoint to OAuthMetadata
- Temporary request/response logging in McpSessionBridge

Claude's MCP client discovers OAuth via these endpoints but requires
authorization_code + PKCE flow (not device_code). Next step: implement
the authorization code flow with phone-side approval.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 15:58:50 -04:00
Jason Monk
2a03cc7046 Fix TLS handshake appOut buffer, add debug device code approval
- TlsAcceptor: allocate empty appOut buffer (size 0) during handshake.
  The previous 16384-byte buffer was being wrapped as application data,
  sending 16KB of null bytes before the actual HTTP response.

- McpSession: expose deviceCodeManager for programmatic approval.

- TestWakeReceiver: add "approve" type to approve device codes via ADB
  broadcast for e2e testing without needing the UI.

- McpSessionBridge: remove temporary debug logging.

Full MCP e2e verified: AI client → relay → device → OAuth device code →
approve → token → initialize → tools/list → tools/call → echo response.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 15:28:02 -04:00
Jason Monk
da28a140b0 Fix TLS handshake: handle multi-record mux DATA frames, use Channel.receive()
Two bugs prevented the TLS handshake from completing:

1. TlsAcceptor NEED_UNWRAP always called stream.read() even when netIn
   already had data from a previous read. When the client sends
   ClientKeyExchange + ChangeCipherSpec + Finished in a single mux DATA
   frame, the first unwrap consumed part of it, the loop hit NEED_UNWRAP
   again and blocked on stream.read() forever. Fix: only read from the
   stream when netIn is empty.

2. MuxStreamImpl.read() used flow.first() which throws
   NoSuchElementException on empty flow completion. Changed to
   Channel.receive() which throws ClosedReceiveChannelException with a
   clearer error message.

Verified: full TLS handshake completes end-to-end through the relay
passthrough to the device (CN=main-board.rousecontext.com, TLSv1.2).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 15:15:56 -04:00
Jason Monk
3071f15989 Fix integration tests: seed InMemoryFirestore, update tests to two-round-trip API
- Seed test-device record in InMemoryFirestore so mTLS WebSocket passes
  the Firestore check without calling POST /register
- Update MockRelayServer to serve two-round-trip registration
  (/register + /register/certs)
- Update OnboardingFlowTest to match current OnboardingFlow.execute()
  signature and two-cert response model

All 105 tunnel tests now pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 15:00:53 -04:00
Jason Monk
1445f872e9 Extract core:bridge module for TLS accept + MCP session bridging
The bridge between incoming mux streams and MCP sessions was duplicated
across integration tests and would be duplicated again in the Android
service. This extracts the shared logic into a new core:bridge KMP module.

SessionHandler accepts a MuxStream, performs TLS server-side accept using
TlsCertProvider, then bridges plaintext HTTP to a local MCP session via
McpSessionFactory. TunnelSessionManager collects incoming sessions from
TunnelClient and dispatches each to SessionHandler in its own coroutine.

Tests cover: TLS+MCP round-trip, full tool call flow, multiple providers
routed by path, OAuth device code flow, concurrent independent sessions,
and error handling when no cert is available.

Refactors TunnelMcpIntegrationTest to use SessionHandler instead of
inline TLS accept + bridge code. Adds core:bridge as a dependency to
:app and :work modules for production wiring.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 14:22:37 -04:00
Jason Monk
a711abfd54 Fix race in TunnelClientImpl where incomingSessions returns dead flow
The incomingSessions property was a computed get() accessor that
re-evaluated on each access. When connect() and incomingSessions.collect
were launched concurrently (as in TunnelForegroundService), the collect
would evaluate before connect() assigned muxDemux, receiving an orphaned
MutableSharedFlow that never emits.

Replace the computed property with a stable Channel<MuxStream> that
exists for the lifetime of the TunnelClientImpl instance. In connect(),
a forwarding coroutine bridges MuxDemux.incomingStreams to the channel.
The channel intentionally survives across reconnects so collectors
are not disrupted.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 14:21:03 -04:00
Jason Monk
dc3b374b44 Wire mux OPEN frames to TLS accept and MCP HTTP server
When the relay sends an OPEN frame (AI client connected), the device now:
1. Performs TLS server-side accept using the ACME cert/key
2. Bridges the plaintext I/O to the local Ktor MCP HTTP server
3. Routes MCP JSON-RPC requests to the registered integration tools

Key changes:
- SessionHandler interface in :work for the foreground service to dispatch streams
- McpSessionBridge in :app implements TLS accept + TCP bridge to MCP
- TlsAcceptor.fromPem() factory for PEM-based cert/key loading
- McpSession.resolvePort() to get the ephemeral port after start
- Koin wiring for McpSession singleton and SessionHandler

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 13:51:35 -04:00
Jason Monk
5725f872f3 Include relay CA cert in mTLS client cert chain for OkHttp KeyManager
The relay's rustls CertificateRequest advertises its self-signed CA as
an acceptable issuer. Without the CA cert in the KeyStore chain entry,
JSSE's KeyManager cannot match the client cert's issuer to the relay's
acceptable CAs list, so it silently omits the client cert from the
handshake.

Three changes:
1. CertificateStore gains storeRelayCaCert/getRelayCaCert; OnboardingFlow
   persists the relay CA cert returned by /register/certs
2. MtlsWebSocketFactory builds the cert chain as [leaf, issuerCA] so the
   KeyManager can present the full chain
3. TrustManager includes the relay CA alongside system CAs so the relay's
   server cert verification and client cert issuer matching both work

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 13:24:03 -04:00
Jason Monk
3234fd623a Two-cert mTLS: device keeps keypair, relay issues ACME server cert + relay CA client cert, two-round-trip registration 2026-04-06 12:48:30 -04:00
Jason Monk
d00e0cf50e Switch tunnel WebSocket from Ktor CIO to OkHttp for mTLS support
Ktor CIO engine silently drops client certificates during TLS handshake,
causing 401 from the relay even when certs are correctly loaded. OkHttp
uses JSSE which properly presents client certs via SSLContext/KeyManager.

- Add WebSocketFactory/WebSocketHandle/WebSocketListener abstractions to
  core:tunnel so TunnelClientImpl is decoupled from any WebSocket library
- Add KtorWebSocketFactory in jvmMain for test use
- Replace MtlsHttpClientFactory with MtlsWebSocketFactory backed by OkHttp
- Update AppModule DI wiring to use new factory
- Fix pre-existing test compile errors (missing privateKey in RegisterResponse)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 21:37:23 -04:00
Jason Monk
4f91d08fe5 Fix private key storage: store relay-generated PEM key, read from file for mTLS (not Android Keystore) 2026-04-05 21:11:46 -04:00
Jason Monk
aa29d620a4 Increase RelayApiClient timeout to 120s for ACME cert issuance 2026-04-05 20:41:23 -04:00
Jason Monk
1288ac7776 Regenerate screenshots and fix ktlint violations across modules
Add trust status variant screenshots (verified, warning, alert) and
fix pre-existing ktlint issues: discouraged inline comments in argument
lists, import ordering, and line length violations.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 20:12:34 -04:00
Jason Monk
2fdef14887 Fix onboarding: strip PEM headers from CSR, add logging to OnboardingViewModel and RelayApiClient 2026-04-05 18:31:14 -04:00
Jason Monk
7399007360 Fix /register request to match relay's expected format
The relay expects firebase_token, csr, and fcm_token fields but the app
was only sending csrPem. This caused 422 responses. Updated
RegisterRequest/RegisterResponse to use @SerialName annotations matching
the relay's snake_case field names, and updated OnboardingFlow and
OnboardingViewModel to obtain and pass Firebase auth and FCM tokens.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 18:21:25 -04:00
Jason Monk
fbb06d177d Add RealHealthConnectRepository with Health Connect SDK wrapper 2026-04-05 15:54:55 -04:00
Jason Monk
901f21a775 Add end-to-end session tests using real relay binary
Tests the full data path: relay startup, device mux WebSocket, AI client
TCP connection, and SNI-based passthrough routing. Covers 11 scenarios:
cold path full TLS tunnel (scenario 5), warm path instant OPEN (6),
concurrent clients with independent stream IDs (7), client disconnect
sends CLOSE (8), device disconnect drops client TCP (9), max streams
exceeded (10), unregistered device rejection (14), STREAM_REFUSED closes
client (15), DATA for unknown stream_id resilience (16), mux drop closes
all clients (17), and reconnect gets fresh stream IDs (18).

Scenario 5 proves the full architecture works end-to-end: AI client TLS
handshakes through the relay passthrough to the device's TLS accept over
a mux stream, with plaintext flowing bidirectionally.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 15:13:35 -04:00
Jason Monk
d3ccceb6ab Add MCP protocol test coverage for scenarios 109-113
Scenarios 105-108 were already covered by HttpRoutingTest and
McpSessionTest. This adds the missing tests:
- 109: tools/call with unknown tool name returns error
- 110: resources/list returns registered resources (and empty case)
- 111: resources/read returns content for valid URI
- 112: multiple sequential requests on same session all succeed
- 113: concurrent requests from different clients stay independent

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 13:55:18 -04:00
Jason Monk
8c1a079f80 Add cross-language integration test: Kotlin tunnel client vs real Rust relay
Starts the actual relay binary as a subprocess with mTLS (CA + relay cert +
device cert generated via keytool), then connects from Kotlin over WebSocket
using Java's HttpClient with a custom SSLContext. Four test scenarios:

1. Valid mTLS cert establishes WebSocket mux session
2. OPEN/DATA/CLOSE frame sequence processes without errors
3. No client cert is rejected at TLS handshake
4. Multiple concurrent connections are independent

Also fixes two relay issues discovered during integration:
- Add ring crypto provider install (rustls panics when both ring and
  aws-lc-rs features are transitively enabled)
- Resolve merge conflict in app/build.gradle.kts

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 11:55:10 -04:00
Jason Monk
535fb2e430 Merge T-16: Tunnel + relay integration tests with mock relay server 2026-04-05 10:00:46 -04:00
Jason Monk
e75e078a43 Add tunnel + MCP end-to-end integration tests (T-15)
Tests the full data path: MuxDemux OPEN frame -> TLS server-side accept ->
plaintext streams bridged to Ktor MCP HTTP server -> JSON-RPC responses
flow back through the same path.

Three test scenarios:
- initialize request through TLS tunnel returns valid MCP response
- full tool call flow: initialize -> tools/list -> tools/call with echo tool
- two concurrent mux streams serve independent MCP sessions simultaneously

Adds test-only dependency from :core:tunnel jvmTest on :core:mcp (no
production dependency, tunnel still has zero MCP knowledge).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 09:10:50 -04:00
Jason Monk
a9a8988e76 Resolve merge conflicts in core/tunnel from T-5, T-9, T-11 feature merges
Three feature branches (WebSocket+TLS, onboarding+renewal, security
monitoring) left stacked conflict markers in 9 files. Resolved by
unifying on the T-1 sealed-class MuxFrame protocol with MuxCodec,
enum TunnelState with expanded valid transitions, and a combined
CertificateStore interface covering all three feature sets.

Key decisions:
- MuxFrame: kept sealed class (Data/Open/Close/Error) with MuxCodec
  encode/decode, adapted TunnelClientImpl to use MuxCodec directly
- TunnelState: kept enum with ACTIVE/DISCONNECTING states, added
  CONNECTED->DISCONNECTED and ACTIVE->DISCONNECTED for error paths
- MuxStream: unified interface with both Flow-based (incoming/send)
  and imperative (read/write) APIs via default method delegation
- CertificateStore: merged all methods; renamed binary getPrivateKey
  to getPrivateKeyBytes to avoid clash with PEM version
- TunnelError: sealed class extending Exception (needed by TlsAcceptor)
  with all error types from both branches
- build.gradle.kts: combined all deps (ktor WS, content-negotiation,
  serialization, server-netty for tests)

Also updated non-conflicted files whose APIs changed: TunnelClientImpl,
MuxStreamImpl (added read()), test stores, and all WebSocket/TLS tests.

All 85 tests pass, module assembles cleanly.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 08:53:40 -04:00
Jason Monk
2483fdb92f Merge T-9: Onboarding flow, cert renewal, CSR generation, RelayApiClient 2026-04-05 07:53:19 -04:00
Jason Monk
83af60b234 Remove build artifacts from tracking, fix .gitignore for subprojects
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 07:52:53 -04:00
Jason Monk
1d5dcb7e9b Add onboarding + cert renewal flows for core:tunnel KMP module
Introduce the core:tunnel KMP module with onboarding (keypair gen, CSR,
/register) and certificate renewal (/renew via mTLS or Firebase+signature).
Includes RelayApiClient (Ktor), CsrGenerator (expect/actual with JVM ASN.1
builder), CertificateStore interface, CertInspector, and full retry/backoff
logic. All 12 jvmTest scenarios pass: success paths, network errors, rate
limiting, partial failure rollback, CN mismatch rejection, and expired cert
handling.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 07:52:29 -04:00
Jason Monk
980ac93226 Merge T-11: Self-cert verification and CT log monitoring with tests 2026-04-05 07:49:48 -04:00
Jason Monk
68437be352 Add security monitoring: self-cert verification and CT log checking
Implements two security monitoring mechanisms in the core:tunnel KMP module:

- SelfCertVerifier: SHA-256 fingerprint comparison of presented certificates
  against known fingerprints in CertificateStore. Supports renewal windows
  where both old and new fingerprints are accepted. Checks leaf cert only.

- CtLogMonitor: Queries crt.sh CT logs for the device's subdomain and
  verifies all logged certificates come from expected issuers. Uses
  injectable CtLogFetcher interface for testability.

Both return SecurityCheckResult (Verified/Warning/Alert) where transient
errors (network, storage) produce Warning rather than Alert.

Sets up core:tunnel as a KMP module with JVM target, kotlinx.serialization,
and the CertificateStore interface (prerequisite from T-9/T-10).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 07:49:19 -04:00
Jason Monk
97a712a6ea Merge T-5: WebSocket client, TLS accept, TunnelClientImpl 2026-04-05 07:41:17 -04:00
Jason Monk
12dd855316 Merge T-2: HTTP server, OAuth device code flow, token management, auth middleware 2026-04-05 07:40:36 -04:00
Jason Monk
bf972aafc0 Fix .gitignore to exclude all build directories, remove committed artifacts
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 07:40:32 -04:00