Commit graph

14 commits

Author SHA1 Message Date
Jason Monk
3d7b9e1f30 Gate tunnel service and cert renewal on having enabled integrations
Skip FCM wake (tunnel service start) and cert renewal when no
integrations are enabled. This avoids wasting the 50/week ACME cert
quota and unnecessary foreground service starts when the device has
nothing to serve.

Checks are in FcmReceiver (primary gate) and TunnelForegroundService
onStartCommand (defensive fallback).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 18:35:34 -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
dfe01c8d48 Fix idle timeout to wait for first client, add auto-reconnect and WebSocket pings
The idle timer previously started on any CONNECTED transition, including
initial connect --- disconnecting the tunnel before any client had a chance
to arrive. Now it only starts after a stream has been ACTIVE and returns
to CONNECTED (i.e. all clients left).

Also adds exponential-backoff reconnect (1s-30s, give up after 5min) for
unexpected disconnects, 15-second OkHttp WebSocket ping interval for dead
connection detection, and restores the 5-minute idle timeout from the
testing value of 30 minutes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 17:22:41 -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
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
6de98373b9 Fix all 3 device tests: manifest declarations, TestWakeReceiver, cleartext debug config 2026-04-05 17:34:49 -04:00
Jason Monk
b7e2e4f3c1 Add FCM token registration to Firestore on startup and onNewToken 2026-04-05 17:34:32 -04:00
Jason Monk
1850a085f3 Fix device integration tests: manifest, permissions, and plain-HTTP relay
Three root causes prevented the wake flow test from passing:

1. TunnelForegroundService and FcmReceiver were not declared in the work
   module's AndroidManifest.xml, so Android couldn't find or start them.

2. ADB broadcasts to FirebaseInstanceIdReceiver require the C2DM sender
   permission, which the ADB shell (uid 2000) lacks. Added a debug-only
   TestWakeReceiver that starts TunnelForegroundService without requiring
   any sender permission.

3. The relay URL was hardcoded to wss:// but the test relay runs without
   TLS. Added configurable relay.scheme build property (defaults to wss,
   tests pass ws). The relay now injects a test DeviceIdentity when running
   without TLS so /ws accepts connections. Added cleartext network security
   config for debug builds.

Also fixed: TunnelForegroundService now catches connection errors instead
of crashing, and installApk() auto-uninstalls on signature mismatch.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 17:31:54 -04:00
Jason Monk
33e442c03f Fix TunnelForegroundService crash: inject dependencies via Koin
The service had lateinit var fields that were never set, causing a crash
on FCM wake. Convert to Koin by inject() delegation and register
TunnelClient, WakelockManager, IdleTimeoutManager, and relayUrl in AppModule.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 17:12:56 -04:00
Jason Monk
05edbd6198 Add SecurityCheckWorker for periodic cert and CT log verification
Wire SelfCertVerifier and CtLogMonitor into a WorkManager periodic task
that runs every 4 hours. Results are persisted to SharedPreferences for
UI consumption, and alerts/warnings trigger appropriate notifications.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 15:28:11 -04:00
Jason Monk
687586e832 Harden FCM payload: remove relay_host/relay_port, use BuildConfig for relay URL
Security: the device no longer reads relay host/port from the FCM message
payload, preventing a spoofed message from redirecting connections. The relay
URL is baked into the APK via BuildConfig at compile time.

- FCM payload now only contains {"type": "wake"} or {"type": "renew"}
- Relay URL configurable via Gradle properties: -Prelay.host=x -Prelay.port=y
- Defaults to relay.rousecontext.com:443 if no property set
- TunnelForegroundService.relayUrl injected by :app module

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 15:16:50 -04:00
Jason Monk
8e317ab191 Fix cross-module integration: resolve merge conflicts and API mismatches
- Resolve stacked merge conflicts in core/tunnel/ from T-5, T-9, T-11
- Fix notifications module: add missing project deps, update ToolCallEvent
  field references (provider->providerId, timestampMillis->timestamp, etc.)
- Fix RoomAuditListener: wrap suspend DAO call in coroutine scope
- Fix TunnelForegroundService: pass url parameter to connect()
- Add androidx.test:core dependency for AuditDaoTest

All tests pass:
- core:tunnel jvmTest (85 tests)
- core:mcp jvmTest (32 tests)
- notifications testDebugUnitTest
- work testDebugUnitTest
- api testDebugUnitTest
- health testDebugUnitTest
- relay cargo test (74 tests)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 09:00:19 -04:00
Jason Monk
c060145eb5 Implement work module: foreground service, FCM receiver, WorkManager, wakelock
Add the Android service lifecycle layer that bridges FCM wakeups to
TunnelClient, manages wakelocks based on tunnel state, enforces idle
timeouts, and schedules certificate renewal via WorkManager.

Components:
- FcmDispatch/FcmReceiver: route FCM messages to service start or cert renewal
- WakelockManager: acquire during CONNECTING/ACTIVE, release otherwise
- IdleTimeoutManager: disconnect after idle period, respects battery exemption
- CertRenewalWorker: WorkManager worker, renews certs expiring within 14 days
- TunnelForegroundService: lifecycle service wiring it all together

21 unit tests covering all four test scenarios from the task spec.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 07:53:39 -04:00
Jason Monk
65d71fba10 Restructure Gradle modules: flat layout to nested architecture
Rename modules to match target architecture:
- mcp-core/ -> core/mcp/ (MCP session, providers, audit)
- tunnel/ -> core/tunnel/ (mux protocol, TLS, CertificateStore)
- mcp-health/ -> health/ (Health Connect integration)

Create new empty modules:
- api/ (integration contract layer, depends on core:mcp)
- notifications/ (notification state machine + audit persistence)
- work/ (foreground service, FCM, WorkManager)

Update all module references in settings.gradle.kts, app/build.gradle.kts,
health/build.gradle.kts. Update .claude/CLAUDE.md with Java 21 and new
module paths. Fix .gitignore to cover all build/ directories.

Verified: ./gradlew assemble, :core:mcp:testDebugUnitTest, ktlintCheck
all pass with JAVA_HOME=/usr/lib/jvm/java-21-openjdk.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-05 07:18:03 -04:00