From 69d3414814a2b1e3a039ba61cce58363a78cc9cf Mon Sep 17 00:00:00 2001 From: shakibuzzaman Date: Mon, 24 Aug 2026 16:52:57 +0600 Subject: [PATCH] feat: improve DevConsole server startup and permissions - prefer port 8080 and fall back when occupied externally - restart the SDK-owned server before rebinding - bind immediately and hydrate persisted timeline asynchronously - request required LAN permissions before server startup - keep notification permission optional - default browser access to open mode with same-origin protection - synchronize notification stop actions with SDK UI state - keep no-op release artifacts permission-free - add tests and documentation for server lifecycle behavior --- README.md | 76 ++- docs/BACKGROUND_KEEPALIVE.md | 90 ++-- docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md | 22 +- docs/COMPOSER_AND_MOCKS.md | 7 +- docs/DATA_INSPECTORS_AND_EXPORTS.md | 8 +- docs/DESIGN_SPEC.md | 4 +- docs/FAQ_TROUBLESHOOTING.md | 13 +- docs/GETTING_STARTED_COMPOSE.md | 24 +- docs/GETTING_STARTED_XML_JAVA.md | 10 +- docs/GETTING_STARTED_XML_KOTLIN.md | 17 +- docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md | 53 ++- docs/PROTOCOL_REFERENCE.md | 37 +- docs/README.md | 6 +- docs/THREAT_MODEL.md | 28 +- .../NoopRuntimeExcludesFullModulesTest.kt | 23 +- .../compose-app/src/debug/AndroidManifest.xml | 20 +- .../devconsole/sample/compose/MainActivity.kt | 21 +- .../src/debug/AndroidManifest.xml | 20 +- .../io/devconsole/sample/MainActivity.kt | 25 +- .../src/debug/AndroidManifest.xml | 20 +- .../sample/viewsjava/MainActivity.java | 17 +- sdk/api/api/api.api | 11 + .../io/devconsole/api/DevConsoleConfig.kt | 15 + .../api/DevConsoleFacadeProvider.kt | 2 +- .../io/devconsole/api/DevConsoleResult.kt | 4 +- .../io/devconsole/api/FocusedPolicies.kt | 24 +- .../kotlin/io/devconsole/api/StartRequest.kt | 16 +- .../devconsole/api/DevConsoleContractTest.kt | 13 + .../api/FocusedConfigurationTest.kt | 17 + .../main/kotlin/io/devconsole/DevConsole.kt | 3 +- sdk/full/src/main/AndroidManifest.xml | 23 +- .../main/kotlin/io/devconsole/AutoBinding.kt | 6 +- .../io/devconsole/FullInspectorDataSource.kt | 8 +- .../kotlin/io/devconsole/KeepAliveGate.kt | 27 +- .../devconsole/KeepAliveServiceController.kt | 7 +- .../io/devconsole/LanPermissionPolicy.kt | 26 + .../io/devconsole/PersistentTimeline.kt | 66 ++- .../io/devconsole/PlatformFacadeProvider.kt | 448 ++++++++++++------ .../kotlin/io/devconsole/AutoBindingTest.kt | 6 +- .../kotlin/io/devconsole/FullFacadeTest.kt | 60 ++- ...ullInspectorDataSourceServerControlTest.kt | 13 + .../kotlin/io/devconsole/KeepAliveGateTest.kt | 2 + .../io/devconsole/LanPermissionPolicyTest.kt | 58 +++ .../io/devconsole/PersistentTimelineTest.kt | 67 ++- .../PlatformFacadeProviderAutoBindingTest.kt | 9 + ...latformFacadeProviderBrowserBindingTest.kt | 9 + ...formFacadeProviderMoreScreenBindingTest.kt | 9 + .../PlatformFacadeProviderScreenshotTest.kt | 7 +- sdk/server-api/api/server-api.api | 3 + .../server/api/LocalServerEngine.kt | 49 +- .../server/api/StartRequestDefaultsTest.kt | 11 + sdk/server-ktor/api/server-ktor.api | 3 + .../server/ktor/DevConsoleKtorModule.kt | 194 +++++--- .../resources/devconsole-web/dashboard.js | 114 +++-- .../main/resources/devconsole-web/index.html | 34 +- .../server/ktor/DevConsoleKtorModuleTest.kt | 57 ++- sdk/ui-compose/api/ui-compose.api | 18 + .../devconsole/ui/compose/InspectorAction.kt | 5 + .../ui/compose/InspectorDataSource.kt | 22 +- .../ui/compose/InspectorMoreScreen.kt | 72 ++- .../InspectorServerStartPermissionProvider.kt | 17 + .../ui/compose/InspectorViewModel.kt | 56 ++- .../ui/compose/KeepAliveNotificationPrompt.kt | 10 +- .../compose/LocalNetworkPermissionPrompt.kt | 149 ++++++ .../ui/compose/InspectorViewModelTest.kt | 140 +++++- 65 files changed, 1872 insertions(+), 579 deletions(-) create mode 100644 sdk/full/src/main/kotlin/io/devconsole/LanPermissionPolicy.kt create mode 100644 sdk/full/src/test/kotlin/io/devconsole/LanPermissionPolicyTest.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorServerStartPermissionProvider.kt create mode 100644 sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/LocalNetworkPermissionPrompt.kt diff --git a/README.md b/README.md index c7b4422..becf7be 100644 --- a/README.md +++ b/README.md @@ -91,10 +91,20 @@ way your manifest needs `INTERNET`, which most apps already declare: lifecycleScope.launch { // startBrowser is a suspend function; the server never starts on its own val result = DevConsole.startBrowser(StartRequest()) val connectUrl = (result as? StartResult.Started)?.access?.connectUrl - // e.g. http://192.168.0.15:8080/#code=B7KQ2XWZ — surface this in your debug UI + // e.g. http://192.168.0.15:8080 — surface this in your debug UI } ``` +Browser authentication is off by default for local development, so opening that URL does not +require a new key after each build. To restore the single-use session-code flow, opt in explicitly: + +```kotlin +DevConsole.initialize( + application, + DevConsoleConfig.default().withBrowserSecurity(BrowserSecurity.SESSION_CODE), +) +``` + The default binding is `BindingMode.AUTO`: it binds your device's network address when there is one, so the URL opens from any machine on the same Wi-Fi, and falls back to `127.0.0.1` when there isn't. If it fell back — or if you passed `BindingMode.LOOPBACK` to keep it off the network on purpose — @@ -104,8 +114,8 @@ forward the port first: adb forward tcp:8080 tcp:8080 # use the port from the loopback start's log line ``` -Then open the **whole URL**. The `#code=` fragment is the credential, so a bare `http://host:port/` -gets you nothing. +Then open the URL. With the default `BrowserSecurity.NONE`, the bare address is enough. With +`BrowserSecurity.SESSION_CODE`, open the full `#code=` URL because that fragment is the credential. > **The dashboard speaks plaintext HTTP.** On a network address, everything it shows — headers, > tokens, bodies — is readable by anyone who can see your traffic. That is fine on a home or office @@ -128,7 +138,7 @@ gets you nothing. | **Remote Config inspector** | Every Remote Config value active on the device, and where each one came from — server, in-app default, static fallback, or a local override — plus last fetch time and status. Read-only. The Firebase adapter uses reflection — no compile-time Firebase dependency. | | **Data inspectors** | Browse SharedPreferences, SQLite (incl. a SQL console), and app files. Read-only by default; every edit surface is opt-in. | | **Evidence tray & exports** | Flag anything, attach it to a bug report bundle or Markdown/Jira/GitHub clipboard text. Export HAR, Postman Collection, or a full session ZIP. | -| **Background keep-alive** | Opt-in foreground service that keeps the server alive while your app is backgrounded. Manifest-only opt-in, zero SDK-declared permissions. | +| **Background keep-alive** | Default foreground service that keeps the server alive while your app is backgrounded. Enabled by the debug-only full runtime; the no-op runtime contributes no service or permissions. | Capture is category-scoped. `DevConsoleConfig.withCaptureCategories(...)` narrows what gets recorded to any of `NETWORK`, `SOCKET`, `MQTT`, `PUSH`, `LOGS`, `CRASHES`, `STATE`, `INSPECTION`, @@ -221,7 +231,7 @@ when (result) { is StartResult.Started -> { result.endpoint // host + port actually bound; bindingMode is LOOPBACK or LAN, // never AUTO — it reports the socket, not the request - result.access.connectUrl // the full credential URL — treat as a secret + result.access.connectUrl // bare URL by default; a #code= credential URL when opted in } is StartResult.PermissionRequired -> { /* explicit LAN only: request result.permission */ } else -> { /* NoEligibleNetwork, ServerUnavailable, ... */ } @@ -230,6 +240,16 @@ when (result) { DevConsole.stop(StopReason.UserRequested) ``` +For a shared or untrusted network, combine loopback with `adb forward`, or keep the reachable +binding and opt into the secure browser handshake: + +```kotlin +DevConsole.initialize( + application, + DevConsoleConfig.default().withBrowserSecurity(BrowserSecurity.SESSION_CODE), +) +``` + Java is fully supported via async variants and builders: ```java @@ -251,10 +271,12 @@ After `startBrowser`, filter Logcat on the `DevConsole` tag: I/DevConsole: Dashboard available at: http://192.168.0.15:8080/ (access link available through the DevConsole API/launcher; binding: LAN) ``` -**The session code is deliberately absent from Logcat.** The full URL, with its `#code=` credential fragment, comes from only three places: `StartResult.Started.access.connectUrl`, -`DevConsole.accessInfo()`, and the device's More screen as text or a QR code. The port is the first -free one in **8080–8099**, so read it from the log rather than assuming 8080. +The default open mode has no session code, so Logcat prints only the bare dashboard URL. In +`BrowserSecurity.SESSION_CODE` mode, the session code is deliberately absent from Logcat: the full +URL, with its `#code=` credential fragment, comes from only three places: +`StartResult.Started.access.connectUrl`, `DevConsole.accessInfo()`, and the device's More screen as +text or a QR code. The port is the first free one in **8080–8099**, so read it from the log rather +than assuming 8080. ### Connect from your browser @@ -273,9 +295,10 @@ free one in **8080–8099**, so read it from the log rather than assuming 8080. `StartResult.Started.endpoint.bindingMode` always tells you which one you actually got. -Open the **whole URL**. The `#code=` fragment is the credential. It is single-use, expires in five -minutes, and creates a session immediately with no approval step. A bare `http://host:port/` sits -unauthenticated forever. If a code lapses, issue a fresh one from the device. +In the default open mode, open the bare `http://host:port/` address. If you opted into +`BrowserSecurity.SESSION_CODE`, open the **whole URL**: its `#code=` fragment is single-use, expires +in five minutes, and creates a session immediately with no approval step. If that code lapses, issue +a fresh one from the device. ### Wire up your network stack @@ -452,10 +475,11 @@ none at all. | Permission | Declared by | Why it exists | In your release build? | |---|---|---|---| -| `ACCESS_LOCAL_NETWORK` | **DevConsole** (`devconsole`) | Android 17 (API 37) gates local-network access. Without it a LAN-bound dashboard binds and then silently serves nobody — see [LAN permission](docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md). Requested at runtime only when you start in LAN mode. | **No** | +| `ACCESS_LOCAL_NETWORK` | **DevConsole** (`devconsole`) | Android 17 (API 37) gates local-network access. Without it a LAN-bound dashboard binds and then silently serves nobody — see [LAN permission](docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md). Declared by the full runtime and requested at runtime when needed. | **No** | | `ACCESS_NETWORK_STATE` | **DevConsole** (`devconsole`) | Normal (non-runtime) permission, used only to record connectivity-change markers on the timeline. | **No** | -| `FOREGROUND_SERVICE` + `FOREGROUND_SERVICE_SPECIAL_USE` | **You**, in `src/debug` | Opt-in only. Lets the dashboard server survive your app being backgrounded — [keep-alive](docs/BACKGROUND_KEEPALIVE.md). Omit them and you simply don't get the feature; DevConsole declares neither. | **No** (you put them in the debug manifest) | -| `POST_NOTIFICATIONS` | **You**, in `src/debug` | Optional. Only decides whether the keep-alive notification is *visible* — the service runs either way. DevConsole never requests it unprompted; the inspector offers it. | **No** (same) | +| `NEARBY_WIFI_DEVICES` | **DevConsole** (`devconsole`) | Nearby-devices permission used by Android 13–16's local-network compatibility path. The SDK declares `neverForLocation`; it does not read location. | **No** | +| `FOREGROUND_SERVICE` + `FOREGROUND_SERVICE_SPECIAL_USE` | **DevConsole** (`devconsole`) | Default debug-only keep-alive for the dashboard server — [keep-alive](docs/BACKGROUND_KEEPALIVE.md). The service runs whenever the server is running. | **No** | +| `POST_NOTIFICATIONS` | **DevConsole** (`devconsole`) | Declared by the full runtime so the inspector can offer the Android 13+ runtime grant; it only controls notification visibility, not whether the service runs. | **No** | | `INTERNET` | **You**, in `src/main` | Binding the dashboard's TCP socket needs it. Not DevConsole-specific — most apps already declare it for their own networking, which is why DevConsole doesn't add it for you. | Yes — but it's yours, and almost certainly already there | Don't take the table's word for it. Check any build yourself: @@ -474,16 +498,18 @@ resolved runtime classpath, and the final APK/AAB bytes. See DevConsole deliberately exposes your app's internals to a browser, and two of its defaults trade safety for a working first run. Know where the edges are: -- **The dashboard speaks plaintext HTTP, and the default binding reaches your network.** There is no - TLS. `BindingMode.AUTO` binds your device's network address whenever it can, so anyone who can - watch your Wi-Fi packets can read everything the dashboard shows: headers, tokens, bodies, - exports. This is a debug-build-only surface behind a single-use expiring credential, which is why - the default favours reachability — but on an untrusted network (a conference, a café, a shared - office VLAN) pass `BindingMode.LOOPBACK`, or set - `BrowserConfig(binding = BrowserBinding.LOOPBACK)`, and use `adb forward`. -- **The connect URL is a credential.** Holding a live `#code=` fragment creates a session, with no - approval step on the device. Codes are single-use and expire in five minutes; sessions last 30. - Treat the URL like a password. You can revoke sessions from the More screen. +- **The dashboard speaks plaintext HTTP, and the default browser mode is open.** There is no TLS. + `BindingMode.AUTO` binds your device's network address whenever it can, and + `BrowserSecurity.NONE` means any client that can reach that address can read the dashboard and use + whatever editing capabilities the host enabled. Open mode still rejects browser mutations that + carry a foreign `Origin`; this protects against a cross-site browser request, not against another + client on the same reachable network. For a shared or untrusted network, pass + `BindingMode.LOOPBACK`, set `BrowserConfig(binding = BrowserBinding.LOOPBACK)`, or opt into + `BrowserSecurity.SESSION_CODE`. +- **The connect URL is a credential only in SESSION_CODE mode.** Holding a live `#code=` fragment + creates a session, with no approval step on the device. Codes are single-use and expire in five + minutes; sessions last 30. Treat that URL like a password. You can revoke sessions from the More + screen. - **Redaction is an allowlist.** About 25 well-known field names and `Bearer` tokens get masked. Custom header names, signed-URL query params, and PII inside bodies pass through verbatim. See [docs/SECURITY_AND_REDACTION.md](docs/SECURITY_AND_REDACTION.md). diff --git a/docs/BACKGROUND_KEEPALIVE.md b/docs/BACKGROUND_KEEPALIVE.md index d6af499..95b4be4 100644 --- a/docs/BACKGROUND_KEEPALIVE.md +++ b/docs/BACKGROUND_KEEPALIVE.md @@ -4,9 +4,9 @@ The Dev Console server runs inside the host app's own process. When the host app is backgrounded, the OS is free to kill that process at any time, which kills the server and drops -any connected dashboard session with it. The keep-alive feature is an opt-in foreground service -that pins the host process alive for as long as the server is running, so a backgrounded app keeps -serving the dashboard instead of silently dying. +any connected dashboard session with it. The keep-alive feature is enabled by default in the full +debug runtime: it pins the host process alive for as long as the server is running, so a +backgrounded app keeps serving the dashboard instead of silently dying. The service is a thin shell — it does not run the server itself (that already lives in the host process); it exists only so the OS treats the process as foreground-priority, and to own a status @@ -14,11 +14,10 @@ notification. While it's active you get an ongoing, low-priority notification ti server running" whose body is the current endpoint URL, with a "Stop server" action that tears both the server and the service down. -## Opt-in +## Default behavior -DevConsole declares **zero** `uses-permission` entries for this feature anywhere in its own -manifests — not even in `sdk:full`. The SDK's full manifest carries only the `` -component registration itself: +`sdk:full` declares the foreground-service and notification permissions in its own manifest. No +host-side permission block is required for the default debug setup: ```xml ``` -A component registration carries no permission footprint and no Play policy weight by itself, and -because `sdk:full` is consumed via `debugImplementation`, it never reaches a release build anyway. -The feature only turns on when the **host app** opts in, by declaring permissions in its own debug -manifest (`src/debug/AndroidManifest.xml`, the same file `ACCESS_LOCAL_NETWORK` already lives in -for LAN mode): +The full runtime also declares `ACCESS_LOCAL_NETWORK` and `NEARBY_WIFI_DEVICES` for the dashboard's +local-network binding. Because `sdk:full` is consumed via `debugImplementation`, these declarations +never reach a release build; `sdk:noop` has no server, service, or permissions. + +The equivalent declarations are: ```xml + + - ``` +A host may still remove these declarations with an explicit manifest-merger rule. `KeepAliveGate` +checks the merged manifest defensively and skips the service if its required foreground permission +is unavailable; the server itself is never blocked by a keep-alive failure. + What each permission is for: - **`FOREGROUND_SERVICE`** — a normal, auto-granted permission required on API 28+ to start any @@ -52,13 +58,17 @@ What each permission is for: declares `foregroundServiceType="specialUse"`. `specialUse` is the correct type for a developer-tool server: it has no runtime prerequisites and, unlike `dataSync` on Android 15, no six-hour cap. -- **`POST_NOTIFICATIONS`** — optional. It only controls whether the status notification is - *visible*; it has no bearing on whether the service, and therefore the server, keeps running. +- **`POST_NOTIFICATIONS`** — declared by the full runtime, but still a runtime grant on Android + 13+. It only controls whether the status notification is *visible*; it has no bearing on whether + the service, and therefore the server, keeps running. See the next section. +- **`ACCESS_LOCAL_NETWORK`** — a dangerous permission enforced for direct local-network traffic on + Android 17 (API 37+) and part of Android's Nearby devices group. +- **`NEARBY_WIFI_DEVICES`** — the Nearby devices permission used by Android 13–16's local-network + compatibility path. DevConsole does not use Wi-Fi information to derive physical location. -A host that adds none of this gets exactly the pre-feature behavior: no service starts, no -notification appears, nothing changes. There is no code-side toggle to flip — the manifest is the -only opt-in surface. +The foreground service is started whenever the full runtime successfully starts the dashboard +server, and it is stopped whenever the server stops. There is no separate keep-alive toggle. At runtime, `KeepAliveGate` (in `sdk:full`) reads the **merged** manifest — `PackageManager.getPackageInfo(packageName, GET_PERMISSIONS).requestedPermissions` — to decide @@ -67,11 +77,12 @@ whether it's safe to start the service, banded by API level: | API level | Requirement to start the foreground service | | --- | --- | | < 28 | None — no permission exists to check, the gate passes unconditionally. | -| 28–33 | Host manifest must declare `FOREGROUND_SERVICE`. | -| 34+ | Host manifest must declare both `FOREGROUND_SERVICE` and `FOREGROUND_SERVICE_SPECIAL_USE`. | +| 28–33 | The merged manifest must declare `FOREGROUND_SERVICE`; `sdk:full` supplies it by default. | +| 34+ | The merged manifest must declare both `FOREGROUND_SERVICE` and `FOREGROUND_SERVICE_SPECIAL_USE`; `sdk:full` supplies both by default. | -This check runs every time the server starts, using whatever the host's merged manifest actually -contains — there's nothing to configure beyond the manifest entries above. +This check runs every time the server starts, using whatever the app's merged manifest actually +contains. In the normal full-runtime setup, the default declarations above make the service start +automatically. ## Notification visibility vs. keep-alive @@ -82,16 +93,19 @@ These are two independent things, and it's easy to conflate them: - **Notification visibility** is controlled by `POST_NOTIFICATIONS`, a separate *runtime* permission on Android 13+ (API 33+). -On API 33+, if the host declared `POST_NOTIFICATIONS` but the user hasn't granted it (or has -denied it), the foreground service still starts and the process is still kept alive exactly as -before — the OS simply hides the notification. A denied notification permission never blocks or -stops the service; it only affects whether the user can see it's running. +On API 33+, if the full runtime declared `POST_NOTIFICATIONS` but the user hasn't granted it (or +has denied it), the foreground service still starts and the process is still kept alive exactly as +before for host/API starts — the OS simply hides the notification. A denied notification permission +never blocks or stops a host/API-started service; it only affects whether the user can see it's +running. Notification access is optional for the SDK-owned More-screen start too: the server starts +first, then the UI offers the grant so the notification and its Stop action become discoverable. -Because of that, DevConsole never asks for `POST_NOTIFICATIONS` on its own initiative. Instead: +The permission flows are: -- The Compose **Control and More** surfaces both show a dismissible snackbar offering the grant. - More matters as much as Control: it is where the server is started, so it is where someone who - just started one goes looking for the notification. +- The Compose **Control and More** surfaces show a dismissible snackbar offering the grant after a + start that began without it. Granting re-posts the notification; denial or dismissal leaves the + server running and does not immediately repeat the prompt in that process. More matters as much as + Control: it is where someone who just started one goes looking for the notification. - The views launcher (`DevConsolePanelView`) shows an equivalent notice row with "Allow" and "Dismiss" actions. @@ -103,12 +117,12 @@ again and the notification finally appears. (Granting from Settings instead, whi already running, does not go through that path: stop and start the server, or reopen the inspector and let it re-issue, to make the notification appear.) -Both are offered **only** when all of the following hold: the server is running, the host opted -into the foreground service at all, the host's manifest declares `POST_NOTIFICATIONS`, and the -permission isn't granted yet. If the host never declared `POST_NOTIFICATIONS`, neither surface -ever prompts for it — requesting a permission the manifest doesn't declare is a silent no-op on -Android, so offering it would just mislead the user. Dismissing the prompt silences it for the -rest of the process's lifetime; it reappears on the next app run. +The post-start snackbar is offered only when all of the following hold: the server is running, the +merged foreground-service permissions are present, `POST_NOTIFICATIONS` is declared, and the +runtime grant is missing. The full runtime supplies that declaration by default. If a host removes +it, no surface prompts for it — requesting a permission the manifest doesn't declare is a silent +no-op on Android, so offering it would just mislead the user. Dismissing the post-start prompt +silences it for the rest of the process's lifetime; it reappears on the next app run. ## Behavior matrix @@ -116,8 +130,8 @@ How the service behaves across every declaration and permission state: | Scenario | Outcome | | --- | --- | -| Host declared nothing | Gate fails, no FGS, no snackbar, behavior identical to today | -| FGS permissions declared, notifications denied (API 33+) | Service runs, process kept alive, notification hidden by OS; snackbar offers the grant if declared | +| Full runtime defaults (FGS permissions present), notifications denied (API 33+) | SDK-owned More Start waits for the grant; a host/API start runs with the notification hidden and the post-start snackbar offers the grant | +| Host removes the FGS permissions | Gate skips the service, while the server continues running; no keep-alive snackbar | | FGS start throws (background start, OEM quirk) | Caught, logged; server unaffected; retried naturally on next server start | | Server stops for any reason | Service stopped in `stopLocked` | | Task swipe (active keep-alive) | Process is **not** killed -- an active foreground service survives task removal (`stopWithTask` defaults `false`, `onTaskRemoved` isn't overridden); the notification's "Stop server" action (or the dashboard) is what stops it | diff --git a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md index 0d495a5..291a855 100644 --- a/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md +++ b/docs/BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md @@ -111,17 +111,15 @@ that doesn't exist in that build. ## Permissions never reach a release build Manifest entries merge from dependencies, so it is worth being explicit about which ones DevConsole -contributes and where they stop. `sdk:full` declares exactly two — `ACCESS_LOCAL_NETWORK` (Android -17+ gates local-network access; without it a LAN-bound dashboard binds and serves nobody) and -`ACCESS_NETWORK_STATE` (a normal permission, used only for connectivity-change timeline markers). -`sdk:noop` declares none. Since `sdk:full` is a `debugImplementation` and `sdk:noop` is what a -release variant compiles against, neither permission can appear in a released APK or AAB, and -there is nothing to declare to Google Play. - -The keep-alive permissions (`FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_SPECIAL_USE`, -`POST_NOTIFICATIONS`) are not DevConsole's at all — the SDK declares none of them, and a host opts -in by putting them in its **own `src/debug` manifest**, which is what keeps them out of release too. -See [BACKGROUND_KEEPALIVE.md](BACKGROUND_KEEPALIVE.md). +contributes and where they stop. `sdk:full` declares `ACCESS_LOCAL_NETWORK` (Android 17+ gates +local-network access; without it a LAN-bound dashboard binds and serves nobody), +`NEARBY_WIFI_DEVICES` (the Android 13–16 nearby-devices compatibility permission), +`ACCESS_NETWORK_STATE` (a normal permission used only for connectivity-change timeline markers), +and the default keep-alive permissions (`FOREGROUND_SERVICE`, +`FOREGROUND_SERVICE_SPECIAL_USE`, and `POST_NOTIFICATIONS`). `sdk:noop` declares none. Since +`sdk:full` is a `debugImplementation` and `sdk:noop` is what a release variant compiles against, +none of these DevConsole permissions can appear in a released APK or AAB, and there is nothing to +declare to Google Play. See [BACKGROUND_KEEPALIVE.md](BACKGROUND_KEEPALIVE.md). `INTERNET` is the one permission a DevConsole feature needs that the SDK does not declare: binding the dashboard's TCP socket requires it, but it is not DevConsole-specific and most apps already @@ -134,7 +132,7 @@ aapt2 dump permissions app/build/outputs/apk/release/app-release.apk ``` Run against `samples/compose-app` — the sample with every feature switched on — the debug APK lists -`ACCESS_LOCAL_NETWORK`, `ACCESS_NETWORK_STATE`, `FOREGROUND_SERVICE`, +`ACCESS_LOCAL_NETWORK`, `NEARBY_WIFI_DEVICES`, `ACCESS_NETWORK_STATE`, `FOREGROUND_SERVICE`, `FOREGROUND_SERVICE_SPECIAL_USE`, `POST_NOTIFICATIONS` and `INTERNET`, while its release APK lists only `INTERNET` (the sample's own) and the auto-generated dynamic-receiver permission. diff --git a/docs/COMPOSER_AND_MOCKS.md b/docs/COMPOSER_AND_MOCKS.md index 22cc9e9..d45384e 100644 --- a/docs/COMPOSER_AND_MOCKS.md +++ b/docs/COMPOSER_AND_MOCKS.md @@ -5,9 +5,10 @@ The request composer runs entirely inside the SDK's own isolated HTTP client (`UrlConnectionComposerTransport`) — it never reuses your application's authenticated OkHttp client, so composer traffic can't accidentally carry your app's auth tokens or interceptors. There -is nothing to wire from host code: connect with a session code (any authenticated session can open -the Composer page — see [PROTOCOL_REFERENCE.md](PROTOCOL_REFERENCE.md#2-auth-handshake-session_code)), -and either build a request by hand or use "Copy redacted cURL to composer" from a captured Network +is nothing to wire from host code: connect to the dashboard (open mode is the default; any +authenticated session can open the Composer page in `SESSION_CODE` mode — see +[PROTOCOL_REFERENCE.md](PROTOCOL_REFERENCE.md#2-auth-handshake-session_code)), and either build a +request by hand or use "Copy redacted cURL to composer" from a captured Network transaction (see [NETWORK_INSPECTOR.md](NETWORK_INSPECTOR.md)). The browser route (`POST /api/v1/composer/execute`) is off by default — the host must set `DevConsoleConfig.composerEnabled = true`, optionally with a `composerAllowedHosts` allowlist — diff --git a/docs/DATA_INSPECTORS_AND_EXPORTS.md b/docs/DATA_INSPECTORS_AND_EXPORTS.md index 24db89d..4cf59cc 100644 --- a/docs/DATA_INSPECTORS_AND_EXPORTS.md +++ b/docs/DATA_INSPECTORS_AND_EXPORTS.md @@ -84,10 +84,10 @@ The device-side "More" destination (`sdk:ui-compose`'s `InspectorMoreScreen`, re `DevConsoleConfig.openTriggers`) is the operator console for the running server, independent of any connected browser: -- **Session-code / connect** — shows the live `#code=` connect URL as text and as a **QR code** - (rendered on-device with an embedded QR encoder, no third-party dependency or network call), so a - second device can scan its way in without retyping an 8-character code. Regenerating shows the - new code/QR immediately; the previous code is invalidated the instant a new one is issued. +- **Browser access / connect** — shows the live dashboard URL as text and as a **QR code** (rendered + on-device with an embedded QR encoder, no third-party dependency or network call). The default open + mode needs no key; with `BrowserSecurity.SESSION_CODE`, the QR contains the live single-use code and + regenerating immediately invalidates the previous code. - **Browser sessions** — every connected browser (label, source IP, expiry) with a per-session **Revoke** action. Revocation is symmetric: any session, including one revoking itself, can end any other (`DELETE /api/v1/auth/principals/{id}`) — see diff --git a/docs/DESIGN_SPEC.md b/docs/DESIGN_SPEC.md index 2fcb189..9d00310 100644 --- a/docs/DESIGN_SPEC.md +++ b/docs/DESIGN_SPEC.md @@ -425,8 +425,8 @@ The final web visual contract relies on a rigid separation of concerns. `dashboa rather than pushing the page wide. - **Empty/first-run states were thin (E2)** — every list view's empty state now names the concrete next step: the device's More screen, the `adb forward tcp:8080 tcp:8080` command (with its caveat - that 8080 is only the first port tried), and that the `#code=` fragment is the credential without - which the page sits unauthenticated forever. + that 8080 is only the first port tried), and the two browser access modes: a bare URL by default or + the `#code=` credential when SESSION_CODE is selected. - **Cross-surface parity was undecided** — resolved and documented in §4c, with a full 16-row table of which web views the Android inspector mirrors, which it deliberately doesn't (Composer, capture rules, Overview), and one open naming mismatch (Timeline / Logs) left as a documented gap rather diff --git a/docs/FAQ_TROUBLESHOOTING.md b/docs/FAQ_TROUBLESHOOTING.md index bfb164c..b888dfe 100644 --- a/docs/FAQ_TROUBLESHOOTING.md +++ b/docs/FAQ_TROUBLESHOOTING.md @@ -1,5 +1,11 @@ # FAQ / troubleshooting +**Why does my team no longer need a new key after every build?** The public full SDK defaults to +`BrowserSecurity.NONE`, so the dashboard opens directly at the URL shown by `startBrowser` or the +More screen. This is intended for trusted local development. If the server is reachable by other +people or devices, opt into `BrowserSecurity.SESSION_CODE` with +`DevConsoleConfig.default().withBrowserSecurity(BrowserSecurity.SESSION_CODE)`. + **Can I connect from another machine on the same network?** Usually with no setup at all — the default `BindingMode.AUTO` binds your device's network address whenever there is one, so the connect URL and its QR code already work from another device. If you got a `127.0.0.1` URL, AUTO fell back @@ -49,9 +55,10 @@ It's still wired into your `OkHttpClient.Builder`, but every recorder and engine `enabled = false` in `devconsole-noop`. It becomes a fast no-op, so you never have to strip it out conditionally. -**My session code says expired or invalid, and a second browser can't join.** Codes are single-use, -only one is live at a time, and each lasts five minutes. There's no approval step on the device and -no automatic regeneration, so issue a fresh code from the More screen for each new browser. See +**I opted into SESSION_CODE and the code says expired or invalid, or a second browser can't join.** +Codes are single-use, only one is live at a time, and each lasts five minutes. There's no approval +step on the device and no automatic regeneration, so issue a fresh code from the More screen for each +new browser. See [LAN_PERMISSION_AND_TROUBLESHOOTING.md](LAN_PERMISSION_AND_TROUBLESHOOTING.md#session-codes-session_code_expired--session_code_invalid). **My debug build fails with a manifest merger conflict on `androidx.core.content.FileProvider`.** diff --git a/docs/GETTING_STARTED_COMPOSE.md b/docs/GETTING_STARTED_COMPOSE.md index 0f21cd7..4289e12 100644 --- a/docs/GETTING_STARTED_COMPOSE.md +++ b/docs/GETTING_STARTED_COMPOSE.md @@ -48,9 +48,10 @@ release no-op counterpart and merges `DevConsoleActivity` into your manifest, so into your release build with no build-time warning. The Gradle plugin's variant protection does not cover this module today; it is your responsibility to scope it to `debugImplementation` yourself. -3. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge - `ACCESS_LOCAL_NETWORK`/`ACCESS_NETWORK_STATE`, but not `INTERNET` — without it, the embedded - server fails with an opaque socket error instead of a clear permission message: +3. Add `INTERNET` to your own app's manifest. The full debug runtime auto-merges + `ACCESS_LOCAL_NETWORK`, `NEARBY_WIFI_DEVICES`, `ACCESS_NETWORK_STATE`, and the default + foreground-service permissions; it does not merge `INTERNET` — without it, the embedded server + fails with an opaque socket error instead of a clear permission message: ```xml @@ -58,10 +59,12 @@ cover this module today; it is your responsibility to scope it to `debugImplemen 4. On a debuggable build you can skip explicit `initialize` entirely — the SDK auto-initializes, so state/timeline/capture are ready without any `Application.onCreate` boilerplate. The browser - server itself is never auto-started; call `DevConsole.startBrowser()` yourself (step 5) and read - the connect URL from the returned `StartResult.Started.access` (or the device's More screen — the - logged URL deliberately omits the credential fragment). Initialize explicitly when you need to pass - configuration (state providers, flags, open triggers): + server itself is never auto-started; call `DevConsole.startBrowser()` yourself (step 5). Once it + starts, the full debug runtime automatically starts its foreground keep-alive service. Read + the connect URL from the returned `StartResult.Started.access` (or the device's More screen). The + default URL is open; initialize explicitly with `BrowserSecurity.SESSION_CODE` when a shared LAN + needs the single-use credential flow, or when you need other configuration (state providers, flags, + open triggers): ```kotlin DevConsole.initialize( @@ -104,9 +107,10 @@ setContent { ``` 6. Tap Start. The panel shows the bound address, something like `DevConsole server is running at - 192.168.0.15:8080`. Open that address in a browser, or use the connect URL from - `StartResult.Started.access.connectUrl`. If the device isn't local, run - `adb forward tcp:8080 tcp:8080` first. + 192.168.0.15:8080`. Open that address in the default open mode, or use the connect URL from + `StartResult.Started.access.connectUrl` when `SESSION_CODE` is enabled. If the device isn't local, run + `adb forward tcp:8080 tcp:8080` first — 8080 is only the first port tried, so use whatever port the + panel actually shows. For a full working example, [`samples/compose-app`](../samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt) has one button per capability: network and WebSocket capture, mocks, push simulation, a feature diff --git a/docs/GETTING_STARTED_XML_JAVA.md b/docs/GETTING_STARTED_XML_JAVA.md index a884021..96d310e 100644 --- a/docs/GETTING_STARTED_XML_JAVA.md +++ b/docs/GETTING_STARTED_XML_JAVA.md @@ -10,9 +10,10 @@ touch a coroutine: the `...Async` variants take a callback instead. The two coordinates are `com.github.devconsole-android.DevConsole:devconsole` for debug and `com.github.devconsole-android.DevConsole:devconsole-noop` for release; there is no BOM. -2. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge - `ACCESS_LOCAL_NETWORK`/`ACCESS_NETWORK_STATE`, but not `INTERNET` — without it, the embedded - server fails with an opaque socket error instead of a clear permission message: +2. Add `INTERNET` to your own app's manifest. The full debug runtime auto-merges + `ACCESS_LOCAL_NETWORK`, `NEARBY_WIFI_DEVICES`, `ACCESS_NETWORK_STATE`, and the default + foreground-service permissions; it does not merge `INTERNET` — without it, the embedded server + fails with an opaque socket error instead of a clear permission message: ```xml @@ -28,7 +29,8 @@ touch a coroutine: the `...Async` variants take a callback instead. ``` 4. Initialize, and use the `Async` counterparts of `startBrowser()`/`stop()` since Java has no - coroutines. Pass `startBrowserAsync(...)` a callback and call `panel.setEndpoint(...)` from it if + coroutines. The full debug runtime starts its foreground keep-alive service automatically when + `startBrowserAsync(...)` succeeds. Pass it a callback and call `panel.setEndpoint(...)` from it if you want the panel to show the bound address once it's known (`DevConsoleState.Running` itself carries no payload, so this is the only way to get it): diff --git a/docs/GETTING_STARTED_XML_KOTLIN.md b/docs/GETTING_STARTED_XML_KOTLIN.md index ebed87a..2c0f72f 100644 --- a/docs/GETTING_STARTED_XML_KOTLIN.md +++ b/docs/GETTING_STARTED_XML_KOTLIN.md @@ -47,9 +47,10 @@ release no-op counterpart, so a plain `implementation` dependency ships the laun release build with no build-time warning. The Gradle plugin's variant protection does not cover this module today; it is your responsibility to scope it to `debugImplementation` yourself. -3. Add `INTERNET` to your own app's manifest. The SDK's manifests auto-merge - `ACCESS_LOCAL_NETWORK`/`ACCESS_NETWORK_STATE`, but not `INTERNET` — without it, the embedded - server fails with an opaque socket error instead of a clear permission message: +3. Add `INTERNET` to your own app's manifest. The full debug runtime auto-merges + `ACCESS_LOCAL_NETWORK`, `NEARBY_WIFI_DEVICES`, `ACCESS_NETWORK_STATE`, and the default + foreground-service permissions; it does not merge `INTERNET` — without it, the embedded server + fails with an opaque socket error instead of a clear permission message: ```xml @@ -67,7 +68,8 @@ module today; it is your responsibility to scope it to `debugImplementation` you 5. Initialize and bind the panel. On a debuggable build the SDK has already auto-initialized by this point, so `initialize` is only needed when you have configuration to pass (state providers, flags, open triggers). The panel starts out showing "not running" either way -- the browser - server is never auto-started, so `onStart` below is what actually opens it. `DevConsoleState.Running` carries no + server is never auto-started, so `onStart` below is what actually opens it. Once opened, the full + debug runtime starts its foreground keep-alive service automatically. `DevConsoleState.Running` carries no payload, so call `panel.setEndpoint(...)` with the `StartResult.Started.endpoint` your own `onStart` receives if you want the running address shown — it's cleared automatically the next time the panel renders a non-running state: @@ -95,8 +97,9 @@ panel.bind( ) ``` -6. Tap Start — the panel now shows the bound address (e.g. `DevConsole server is running at 192.168.0.15:8080`) - — then open that address (or the connect URL with its `#code=` fragment) in a browser on the same machine (or - `adb forward tcp:8080 tcp:8080` first if the device isn't local). +6. Tap Start — the panel now shows the bound address (e.g. `DevConsole server is running at 192.168.0.15:8080`). + Open that address in the default open mode; if you configure `BrowserSecurity.SESSION_CODE`, use the + connect URL with its `#code=` fragment instead. Use `adb forward tcp:8080 tcp:8080` first if the device + isn't local — 8080 is only the first port tried, so use whatever port the panel actually shows. Every SDK entry point used above is also directly Java-callable — see [GETTING_STARTED_XML_JAVA.md](GETTING_STARTED_XML_JAVA.md) if your project is Java rather than Kotlin. [`samples/views-java-app`](../samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java) shows a complete working example with `DevConsolePanelView`, network capture, mocks, and the open triggers. See [NETWORK_INSPECTOR.md](NETWORK_INSPECTOR.md), [WEBSOCKET_INSPECTOR.md](WEBSOCKET_INSPECTOR.md), [PUSH.md](PUSH.md), [COMPOSER_AND_MOCKS.md](COMPOSER_AND_MOCKS.md), and [STATE_AND_FLAGS.md](STATE_AND_FLAGS.md) for wiring the actual inspectors once the panel is working. diff --git a/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md b/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md index 4a86394..bdb8d05 100644 --- a/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md +++ b/docs/LAN_PERMISSION_AND_TROUBLESHOOTING.md @@ -3,7 +3,7 @@ ## LAN binding ```kotlin -DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LAN, portRange = 8080..8099)) +DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LAN)) ``` > The default, `BindingMode.AUTO`, does the same thing when it can and binds loopback when it @@ -49,13 +49,16 @@ API 37, LAN mode works with no extra permission at all. > unreachable from a device that pings fine, this is why; upgrade, or grant the permission yourself > before starting. -**The permission is declared for you; requesting it is yours.** `sdk:full` declares -`ACCESS_LOCAL_NETWORK` in its own manifest, so it merges into your **debug** variant automatically -and you do not add a `` line. It never reaches release: `devconsole-noop` declares +**The permissions are declared for you.** `sdk:full` declares `NEARBY_WIFI_DEVICES` for the Android +13–16 compatibility path and `ACCESS_LOCAL_NETWORK` for Android 17+ in its own manifest, so they +merge into your **debug** variant automatically and you do not add `` lines. They +never reach release: `devconsole-noop` declares nothing, which is why a release APK carries no trace of it (and why Google Play never sees it). -Requesting it at runtime is still your app's job — use `ActivityResultContracts.RequestPermission` -with `StartResult.PermissionRequired.permission` when you get that result back, exactly as all three -samples do. +Host-issued `startBrowser(StartRequest(bindingMode = BindingMode.LAN))` calls still return the +version-appropriate `StartResult.PermissionRequired.permission` for the host to request with +`ActivityResultContracts.RequestPermission`, exactly as the samples do. The SDK-owned More-screen +Start button preflights the permission before launching the server, retries automatically after the +grant, and shows an App-settings snackbar when Android has blocked the request. ## AUTO binding @@ -94,11 +97,13 @@ preference only — it discovers nothing and starts nothing on its own. Still the safer default when you don't need cross-device access: ```kotlin -DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK, portRange = 8080..8099)) +DevConsole.startBrowser(StartRequest(bindingMode = BindingMode.LOOPBACK)) ``` -The server binds `127.0.0.1` on the first free port in `8080..8099`. On a physical device or an -emulator that isn't already loopback-reachable from your machine, run: +The server binds `127.0.0.1` on the first free port in `8080..8099` — 8080 is tried first, and the +rest of the range keeps a second app (or a restart before the old server released the port) from +failing outright. On a physical device or an emulator that isn't already loopback-reachable from +your machine, run: ```bash adb forward tcp:8080 tcp:8080 @@ -128,24 +133,24 @@ that start to `BindingMode.LAN`. subnet/network (a guest Wi-Fi network with client isolation enabled will block this even though both devices show "connected"). For loopback mode, confirm `adb forward` targets the same port the SDK actually bound (`StartResult.Started.endpoint.port`), not a hardcoded `8080` — the SDK picks -the first free port in the range, which may not be the first one. - -**Dashboard opens but every tab stays empty / status bar says "OFFLINE / PAUSED" forever** — -you opened the bare `http://:/` instead of the actual connect URL. The dashboard's -`Authorization` token only exists after the session-code exchange, and that exchange only runs if -the URL's fragment contains `#code=` — the plain host:port URL has no fragment, so -the page just sits there unauthenticated and every API call silently 401s. Always open (or scan -the QR code for) `StartResult.Started.access.connectUrl` specifically, not -`StartResult.Started.endpoint.host`/`.port` alone — the two are easy to conflate since the -endpoint is also directly answerable from the same `StartResult`, but only the full connect URL -actually authenticates the session. +the first free port in the range, which may not be the first one. A repeated start from the same +DevConsole runtime stops its own previous listener and retries `8080`; if an unrelated process owns +`8080`, DevConsole leaves it alone and falls forward through the configured range. + +**Dashboard opens but every tab stays empty / status bar says "OFFLINE / PAUSED" forever** — first +check which browser-security mode the server uses. The public full SDK defaults to open access, where +the bare `http://:/` URL is correct. If you opted into +`BrowserSecurity.SESSION_CODE`, use `StartResult.Started.access.connectUrl` or its QR so the +`#code=` fragment can create the browser session; a plain host:port URL has no +credential and will remain unauthenticated. The server's `/health` response says `open` or +`auth_required`. **`StartResult.DisabledForBuild`** — you're running against `devconsole-noop` (production/protected variant). See [BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md](BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md). -**Session expired / browser suddenly logged out** — sessions have an absolute 30-minute TTL (refreshable -via `/auth/refresh`); they are also revoked immediately on server stop. Issue a fresh session code -from the device and reconnect. +**Session expired / browser suddenly logged out** — this applies to `SESSION_CODE` mode: sessions have +an absolute 30-minute TTL (refreshable via `/auth/refresh`) and are revoked immediately on server stop. +Issue a fresh session code from the device and reconnect. Open mode has no browser session to expire. ## Session codes ("SESSION_CODE_EXPIRED" / "SESSION_CODE_INVALID") diff --git a/docs/PROTOCOL_REFERENCE.md b/docs/PROTOCOL_REFERENCE.md index 507cc07..c5471d9 100644 --- a/docs/PROTOCOL_REFERENCE.md +++ b/docs/PROTOCOL_REFERENCE.md @@ -13,18 +13,22 @@ protocol change. ## Conventions - **CSRF header:** `X-DevConsole-CSRF`. -- **CSRF/Origin check** (used by most mutating routes): +- **CSRF/Origin check** (used by most mutating routes in `SESSION_CODE` mode): ``` expectedOrigin = "http://" + Host header reject (403 CSRF_INVALID) unless Origin header == expectedOrigin AND X-DevConsole-CSRF == session.csrfToken ``` The expected origin is hardcoded to the `http://` scheme regardless of how the client actually connected. -- **Bearer auth:** `Authorization: Bearer `. Missing, invalid, or expired all collapse to the - same `{"code":"AUTH_REQUIRED"}` 401 — the server never distinguishes these cases at the HTTP layer. +- **Bearer auth:** In `SESSION_CODE` mode, requests use `Authorization: Bearer `. Missing, + invalid, or expired values all collapse to the same `{"code":"AUTH_REQUIRED"}` 401. In + `NONE` mode, bearer and CSRF headers are not required. Mutations in `NONE` mode still reject a + present `Origin` header unless it exactly matches `http://`; an absent `Origin` remains + valid for non-browser clients such as curl. - **Access levels:** none. Every authenticated session is equivalent (`auth` in the tables below - means "any live session"); mutating routes additionally gate on the host's `EditingCapabilities` - flags (`mocks`, `captureRules`, `preferences`, `database`, `files`), not on a session-level role. + means "any live session" in `SESSION_CODE` mode, or any request in `NONE` mode); mutating routes + additionally gate on the host's `EditingCapabilities` flags (`mocks`, `captureRules`, + `preferences`, `database`, `files`), not on a session-level role. - **Request-body content types.** Routes that read a form body (`POST /api/v1/push/simulate`, the `POST` halves of `/api/v1/network/har` and `/api/v1/network/postman`, `POST /api/v1/exports`, `POST /api/v1/preferences/{file}`, …) need @@ -65,10 +69,22 @@ One rate limiter is wired into the dispatcher's `when` for build. (`POST /api/v1/exports` and `GET /api/v1/report` do have routes — checked inline rather than through the table above — sharing one 5-per-10-minute export limiter; see §3.) +## Browser access modes + +The public full SDK defaults to `BrowserSecurity.NONE`, so the dashboard can be opened directly at +the server URL after each build. The server still applies its host allowlist and feature/capture +gates, but it does not mint or require a browser credential. `/health` reports +`{"status":"open",...}` in this mode. + +Set `DevConsoleConfig.default().withBrowserSecurity(BrowserSecurity.SESSION_CODE)` (or the Java +builder's `.browserSecurity(BrowserSecurity.SESSION_CODE)`) before starting the server to enable the +credentialed flow below. `/health` then reports `auth_required`, the dashboard uses the session-code +fragment, and bearer/CSRF checks apply as described here. + ## 2. Auth handshake (SESSION_CODE) -SESSION_CODE is the only browser-access flow. There is no approval step: possessing the code within -its TTL *is* the authorization decision. +This section applies only when `BrowserSecurity.SESSION_CODE` is selected. There is no approval step: +possessing the code within its TTL *is* the authorization decision. 1. **Issue.** `SessionCodeAuthority.issueCode()` generates an 8-character code from an unambiguous alphabet (`23456789ABCDEFGHJKMNPQRSTWXYZ` — excludes `0`/`O`, `1`/`I`/`L`, `U`/`V`), 5-minute TTL @@ -104,15 +120,16 @@ caller's own), `GET /api/v1/session` (auth — "who am I"). ## 3. REST routes -`auth` = any authenticated session, `none` = unauthenticated. +`auth` = any authenticated session in `SESSION_CODE` mode, or any request in `NONE` mode; +`none` = no browser credential is needed in either mode. ### Root, meta, overview | Route | Auth | Notes | |---|---|---| | `GET /` | none | Dashboard HTML, `Cache-Control: no-store` | -| `GET /health` | none | `{"status":"auth_required","protocolVersion":...,"appDisplayName":"..."}` (static status field) | -| `GET /api/v1/meta` | auth | App/build/capabilities/bound-endpoint/redaction policy | +| `GET /health` | none | `{"status":"auth_required"|"open","protocolVersion":...,"appDisplayName":"..."}` | +| `GET /api/v1/meta` | auth/open | App/build/capabilities/bound-endpoint/redaction policy | | `GET /api/v1/sdk-health` | auth | `SdkHealthSnapshot`, `activePrincipalCount` recomputed live | | `GET /api/v1/overview` | auth | App info + mock engine state + SDK health + network status histogram | diff --git a/docs/README.md b/docs/README.md index a3dc393..3a3e3ff 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,9 +13,9 @@ read one page here, make it the threat model, especially before you put the dash **Operating the SDK** - [Build variants and production safety](BUILD_VARIANTS_AND_PRODUCTION_SAFETY.md) -- [LAN permission and troubleshooting](LAN_PERMISSION_AND_TROUBLESHOOTING.md) — includes the - session-code connect flow -- [Background keep-alive](BACKGROUND_KEEPALIVE.md) — the opt-in foreground service that keeps the +- [LAN permission and troubleshooting](LAN_PERMISSION_AND_TROUBLESHOOTING.md) — includes open access + and the opt-in session-code connect flow +- [Background keep-alive](BACKGROUND_KEEPALIVE.md) — the default foreground service that keeps the server alive while the host app is backgrounded - [FAQ / troubleshooting](FAQ_TROUBLESHOOTING.md) - [Event storage and retention](STORAGE.md) diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 194fbd2..266f19b 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -7,10 +7,12 @@ is the honest version of that trade-off. Read it before turning on LAN mode. ## The one-paragraph summary The dashboard is served over **plaintext HTTP**. There is no TLS anywhere in this SDK. Whenever the -server is bound to a network address, the bearer token, every captured request and response header, -every WebSocket frame, every push payload, and every HAR export cross the network unencrypted. -Anyone in a position to observe that traffic — another device on the same Wi-Fi, a compromised -router, a guest network operator, someone running a packet capture in a café — reads all of it. +server is bound to a network address, every captured request and response header, every WebSocket +frame, every push payload, and every HAR export cross the network unencrypted. Anyone in a position +to observe that traffic — another device on the same Wi-Fi, a compromised router, a guest network +operator, someone running a packet capture in a café — reads all of it. The public full SDK defaults +to `BrowserSecurity.NONE` for local development: a reachable browser does not need a bearer token or +per-build session code. `BrowserSecurity.SESSION_CODE` restores the single-use credential flow. **The default binding reaches the network.** `BindingMode.AUTO` — what a bare `StartRequest()` and an unconfigured `BrowserConfig` both mean — binds a real interface whenever the @@ -116,14 +118,16 @@ the same recommendation this document makes for every other sensitive artifact t | Control | Stops | Does not stop | |---|---|---| +| `BrowserSecurity.SESSION_CODE` | Uncredentialed browsers reaching the dashboard | A code holder, traffic observation, or attacks after a session is created | +| `BrowserSecurity.NONE` | Nothing at the browser-authentication boundary | Any reachable client; use only on a trusted network or with loopback | | Bearer token + CSRF token | Cross-site requests from another origin | Reading the tokens off the wire | | Origin allowlist | Requests claiming a foreign `Host` | An attacker on the allowed network | | Redaction | Known-sensitive field *names* | Every field name not on the list | | 5-minute session-code TTL, 30-minute session TTL | Indefinite reuse of a stale credential | Use inside the window | -**There is no on-device approval gate.** SESSION_CODE (see +**There is no on-device approval gate.** When enabled, SESSION_CODE (see [PROTOCOL_REFERENCE.md](PROTOCOL_REFERENCE.md#2-auth-handshake-session_code)) is the only -browser-access flow: whoever presents the current, unexpired, not-yet-used 8-character code to +credentialed browser-access flow: whoever presents the current, unexpired, not-yet-used 8-character code to `POST /api/v1/auth/session-code/exchange` gets a session immediately -- no human decision in the loop, no notification to tap. The trust model collapses to a single fact -- **possession of the code within its 5-minute TTL is the entire authorization decision** -- which makes the fragment-URL @@ -140,6 +144,13 @@ trusted (typically loopback + `adb forward`, where the code never crosses a netw count the clipboard among the places the code lands: copying the connect URL to paste it somewhere hands a complete credential to every app with clipboard access. +In `BrowserSecurity.NONE`, there is no code or authenticated principal. The dashboard still honors +the host's `EditingCapabilities`, Composer allowlist, state-mutation flag, and capture-category +gates, but those are feature boundaries rather than browser identity. Mutation routes also reject a +foreign browser `Origin` (while allowing an absent `Origin` for command-line clients), which blocks +cross-site browser requests but does not authenticate a client. Anyone who can reach the server can +use the enabled surfaces, so do not use open mode on a shared or untrusted LAN. + **There is no read-only tier.** Every authenticated session is equivalent and has full control of everything the dashboard exposes; the only remaining gates are the host's per-feature `EditingCapabilities` flags (mocks, capture rules, preferences, database, files), which bound *what @@ -229,8 +240,9 @@ screen**, which issues no `StartRequest` and instead binds whatever The two settings are independent and neither overrides the other -- a host that wants to pin one surface to loopback has to say so on that surface. -**Stop the server when you are done.** `DevConsole.stop(...)` revokes browser sessions immediately -and unbinds the port. A dashboard left running on a desk overnight is an open dashboard. +**Stop the server when you are done.** `DevConsole.stop(...)` revokes any authenticated browser +sessions immediately and unbinds the port. A dashboard left running on a desk overnight is an open +dashboard, especially when `BrowserSecurity.NONE` is active. ## Things teams get surprised by diff --git a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/NoopRuntimeExcludesFullModulesTest.kt b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/NoopRuntimeExcludesFullModulesTest.kt index 6c968f2..5e1f31c 100644 --- a/gradle-plugin/src/test/kotlin/io/devconsole/gradle/NoopRuntimeExcludesFullModulesTest.kt +++ b/gradle-plugin/src/test/kotlin/io/devconsole/gradle/NoopRuntimeExcludesFullModulesTest.kt @@ -4,6 +4,7 @@ */ package io.devconsole.gradle +import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Test import java.io.File @@ -14,9 +15,9 @@ import java.io.File * no-op-shaped code is present, but that only exercises fixture projects built inside the test. * This is the complementary, much cheaper check on the real repository: the no-op modules a * release variant is meant to depend on (`sdk:noop` and the `-noop` capture adapters) must never - * themselves declare a dependency on a full/enabled-side module. If one did, R8/proguard - * shrinking would be the *only* thing keeping server/dashboard/capture code out of a protected - * build -- the two-coordinate story (`releaseImplementation(project(":sdk:noop"))` etc., see + * themselves declare a dependency on a full/enabled-side module or Android permission. If one did, + * R8/proguard shrinking would be the *only* thing keeping server/dashboard/capture code out of a + * protected build -- the two-coordinate story (`releaseImplementation(project(":sdk:noop"))` etc., see * `samples/foundation-app/build.gradle.kts`) would already have failed to keep it out at the * dependency-graph level. * @@ -84,6 +85,22 @@ class NoopRuntimeExcludesFullModulesTest { } } + @Test + fun `no-op modules do not declare Android permissions`() { + val repoRoot = repoRoot() + + noopModules.forEach { moduleRelativePath -> + val manifest = File(repoRoot, "$moduleRelativePath/src/main/AndroidManifest.xml") + if (!manifest.exists()) return@forEach + + assertFalse( + "$moduleRelativePath declares a permission in its no-op manifest; release variants " + + "must not inherit DevConsole permissions from the no-op side", + Regex(" - - - - - - - + diff --git a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt index 66156d0..e6bf7cb 100644 --- a/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt +++ b/samples/compose-app/src/main/kotlin/io/devconsole/sample/compose/MainActivity.kt @@ -401,9 +401,8 @@ class MainActivity : ComponentActivity() { // Re-seed on every Running transition (first start AND every restart) -- see the // comment in onCreate for why a one-shot install at init isn't enough. installMockRule() - // Poll while running: a browser exchange consumes the displayed code and the SDK - // immediately mints a fresh one -- a one-shot read here would keep advertising the - // dead URL. + // Poll while running so either access mode updates the displayed URL after a restart; + // SESSION_CODE also re-issues the code after a browser consumes it. while (true) { connectUrl = DevConsole.accessInfo()?.connectUrl kotlinx.coroutines.delay(CONNECT_URL_POLL_MS) @@ -931,6 +930,7 @@ private fun ConnectUrlPanel( ) { val clipboard = LocalClipboardManager.current val context = LocalContext.current + val usesSessionCode = "#code=" in connectUrl Surface( color = MaterialTheme.colorScheme.surfaceVariant, shape = MaterialTheme.shapes.medium, @@ -938,7 +938,7 @@ private fun ConnectUrlPanel( ) { Column(modifier = Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { Text( - "CONNECT URL -- FULL SESSION CREDENTIAL", + if (usesSessionCode) "CONNECT URL -- SESSION CODE" else "CONNECT URL -- OPEN ACCESS", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -950,19 +950,24 @@ private fun ConnectUrlPanel( ) Text( text = - "The #code= fragment is a live, single-use session code; the same code renders as a " + - "QR on the More screen inside the full inspector below. Treat both like a password.", + if (usesSessionCode) { + "The #code= fragment is a live, single-use session code; the same code renders as a " + + "QR on the More screen inside the full inspector below. Treat both like a password." + } else { + "No session code is required in the default open mode. Use SESSION_CODE before sharing " + + "a LAN-bound dashboard on an untrusted network." + }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) TextButton( onClick = { clipboard.setText(AnnotatedString(connectUrl)) - val message = "Session credential copied -- keep it private" + val message = if (usesSessionCode) "Session code copied -- keep it private" else "Dashboard URL copied" Toast.makeText(context, message, Toast.LENGTH_SHORT).show() }, modifier = Modifier.align(Alignment.End), - ) { Text("Copy session credential") } + ) { Text(if (usesSessionCode) "Copy session code URL" else "Copy dashboard URL") } if (showLanWarning) { Text( text = LOCAL_NETWORK_HTTP_WARNING, diff --git a/samples/foundation-app/src/debug/AndroidManifest.xml b/samples/foundation-app/src/debug/AndroidManifest.xml index e5f254f..5ba2c2d 100644 --- a/samples/foundation-app/src/debug/AndroidManifest.xml +++ b/samples/foundation-app/src/debug/AndroidManifest.xml @@ -1,18 +1,6 @@ - - - - - - - + diff --git a/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt b/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt index 86778a5..81eb5ec 100644 --- a/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt +++ b/samples/foundation-app/src/main/kotlin/io/devconsole/sample/MainActivity.kt @@ -161,8 +161,8 @@ class MainActivity : Activity() { DevConsole.state().collect { state -> if (state is DevConsoleState.Running) { installMockRule() - // Poll while running: an exchange consumes the shown code and the SDK - // mints a fresh one; a one-shot read would keep advertising the dead URL. + // Poll while running so either access mode updates the displayed URL after a + // restart; SESSION_CODE also re-issues the code after a browser consumes it. while (DevConsole.state().value is DevConsoleState.Running) { DevConsole.accessInfo()?.connectUrl?.let { url -> runOnUiThread { showConnectUrl(url) } } kotlinx.coroutines.delay(CONNECT_URL_POLL_MS) @@ -331,8 +331,8 @@ class MainActivity : Activity() { setOnClickListener { val url = connectUrl ?: return@setOnClickListener val clipboard = getSystemService(ClipboardManager::class.java) - clipboard.setPrimaryClip(ClipData.newPlainText("DevConsole session credential", url)) - val message = "Session credential copied -- keep it private" + clipboard.setPrimaryClip(ClipData.newPlainText("DevConsole dashboard URL", url)) + val message = if (url.contains("#code=")) "Session code copied -- keep it private" else "Dashboard URL copied" Toast.makeText(this@MainActivity, message, Toast.LENGTH_SHORT).show() } } @@ -490,16 +490,23 @@ class MainActivity : Activity() { private fun showConnectUrl(url: String) { connectUrl = url + val usesSessionCode = url.contains("#code=") val message = - "Tap to copy the session credential: $url\n\n" + - "This is a full, single-use session credential -- the same code also renders as a QR on " + - "the dashboard's More screen once you're connected. Treat it like a password.\n\n" + - "This debugging session uses local-network HTTP. Other participants on an untrusted network " + + if (usesSessionCode) { + "Tap to copy the session-code URL: $url\n\n" + + "This is a full, single-use session credential -- the same code also renders as a QR on " + + "the dashboard's More screen once you're connected. Treat it like a password.\n\n" + } else { + "Tap to copy the dashboard URL: $url\n\n" + + "No session code is required in the default open mode. Use SESSION_CODE before sharing " + + "a LAN-bound dashboard on an untrusted network.\n\n" + } + + "This debugging session uses local-network HTTP. Other participants on an untrusted network " + "may observe or modify traffic. Use ADB localhost mode or a trusted isolated network " + "for sensitive testing." statusView.text = message statusView.isClickable = true - statusView.contentDescription = "$message Double tap to copy the session credential." + statusView.contentDescription = "$message Double tap to copy the dashboard URL." } } diff --git a/samples/views-java-app/src/debug/AndroidManifest.xml b/samples/views-java-app/src/debug/AndroidManifest.xml index e5f254f..5ba2c2d 100644 --- a/samples/views-java-app/src/debug/AndroidManifest.xml +++ b/samples/views-java-app/src/debug/AndroidManifest.xml @@ -1,18 +1,6 @@ - - - - - - - + diff --git a/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java b/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java index 421bc7f..5ca6fa1 100644 --- a/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java +++ b/samples/views-java-app/src/main/java/io/devconsole/sample/viewsjava/MainActivity.java @@ -131,8 +131,8 @@ public final class MainActivity extends Activity { if (DevConsole.accessInfo() != null) { showConnectUrl(DevConsole.accessInfo().getConnectUrl()); } - // Poll while running: a browser exchange consumes the displayed code and - // the SDK mints a fresh one; a one-shot read would keep advertising the dead URL. + // Poll while running so either access mode updates the displayed URL after a + // restart; SESSION_CODE also re-issues the code after a browser consumes it. mainHandler.postDelayed(this, CONNECT_URL_POLL_MS); } else if (state == DevConsoleState.Starting.INSTANCE) { mainHandler.postDelayed(this, 50L); @@ -319,8 +319,8 @@ public void onRequestPermissionsResult(int requestCode, String[] permissions, in private void copyConnectUrlIfAvailable() { if (connectUrl == null) return; ClipboardManager clipboard = getSystemService(ClipboardManager.class); - clipboard.setPrimaryClip(ClipData.newPlainText("DevConsole session credential", connectUrl)); - Toast.makeText(this, "Session credential copied -- keep it private", Toast.LENGTH_SHORT).show(); + clipboard.setPrimaryClip(ClipData.newPlainText("DevConsole dashboard URL", connectUrl)); + Toast.makeText(this, connectUrl.contains("#code=") ? "Session code copied -- keep it private" : "Dashboard URL copied", Toast.LENGTH_SHORT).show(); } private void sendRequest(String url, String successLabel) { @@ -469,14 +469,19 @@ private void showResult(String text) { private void showConnectUrl(String url) { connectUrl = url; - String message = "Tap to copy the session credential: " + url + "\n\n" + boolean usesSessionCode = url.contains("#code="); + String message = (usesSessionCode + ? "Tap to copy the session-code URL: " + url + "\n\n" + "This is a full, single-use session credential -- the same code also renders as a QR on " + "the dashboard's More screen once you're connected. Treat it like a password.\n\n" + : "Tap to copy the dashboard URL: " + url + "\n\n" + + "No session code is required in the default open mode. Use SESSION_CODE before sharing " + + "a LAN-bound dashboard on an untrusted network.\n\n") + "This debugging session uses local-network HTTP. Other participants on an untrusted network " + "may observe or modify traffic. Use ADB localhost mode or a trusted isolated network for sensitive testing."; lastResponse.setText(message); lastResponse.setClickable(true); - lastResponse.setContentDescription(message + " Double tap to copy the session credential."); + lastResponse.setContentDescription(message + " Double tap to copy the dashboard URL."); } /** diff --git a/sdk/api/api/api.api b/sdk/api/api/api.api index 23936ec..792b4bc 100644 --- a/sdk/api/api/api.api +++ b/sdk/api/api/api.api @@ -62,6 +62,14 @@ public final class io/devconsole/api/BrowserEndpoint { public fun toString ()Ljava/lang/String; } +public final class io/devconsole/api/BrowserSecurity : java/lang/Enum { + public static final field NONE Lio/devconsole/api/BrowserSecurity; + public static final field SESSION_CODE Lio/devconsole/api/BrowserSecurity; + public static fun getEntries ()Lkotlin/enums/EnumEntries; + public static fun valueOf (Ljava/lang/String;)Lio/devconsole/api/BrowserSecurity; + public static fun values ()[Lio/devconsole/api/BrowserSecurity; +} + public final class io/devconsole/api/CaptureCategory : java/lang/Enum { public static final field CRASHES Lio/devconsole/api/CaptureCategory; public static final field Companion Lio/devconsole/api/CaptureCategory$Companion; @@ -249,6 +257,7 @@ public final class io/devconsole/api/DevConsoleConfig { public static final fun default ()Lio/devconsole/api/DevConsoleConfig; public fun equals (Ljava/lang/Object;)Z public final fun getBrowserConfig ()Lio/devconsole/api/BrowserConfig; + public final fun getBrowserSecurity ()Lio/devconsole/api/BrowserSecurity; public final fun getCaptureCategories ()Ljava/util/Set; public final fun getComposerAllowedHosts ()Ljava/util/Set; public final fun getComposerEnabled ()Z @@ -272,6 +281,7 @@ public final class io/devconsole/api/DevConsoleConfig { public final fun validationErrors (Z)Ljava/util/List; public static synthetic fun validationErrors$default (Lio/devconsole/api/DevConsoleConfig;ZILjava/lang/Object;)Ljava/util/List; public final fun withBrowserConfig (Lio/devconsole/api/BrowserConfig;)Lio/devconsole/api/DevConsoleConfig; + public final fun withBrowserSecurity (Lio/devconsole/api/BrowserSecurity;)Lio/devconsole/api/DevConsoleConfig; public final fun withCaptureCategories (Ljava/util/Set;)Lio/devconsole/api/DevConsoleConfig; public final fun withCaptureCategories ([Lio/devconsole/api/CaptureCategory;)Lio/devconsole/api/DevConsoleConfig; public final fun withCrashPolicy (Lio/devconsole/api/CrashPolicy;)Lio/devconsole/api/DevConsoleConfig; @@ -291,6 +301,7 @@ public final class io/devconsole/api/DevConsoleConfig$Builder { public final fun addRemoteConfigProvider (Lio/devconsole/remoteconfig/RemoteConfigProvider;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun addStateProvider (Lio/devconsole/state/StateProvider;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun browserConfig (Lio/devconsole/api/BrowserConfig;)Lio/devconsole/api/DevConsoleConfig$Builder; + public final fun browserSecurity (Lio/devconsole/api/BrowserSecurity;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun build ()Lio/devconsole/api/DevConsoleConfig; public final fun captureCategories (Ljava/util/Set;)Lio/devconsole/api/DevConsoleConfig$Builder; public final fun composerAllowedHosts (Ljava/util/Set;)Lio/devconsole/api/DevConsoleConfig$Builder; diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt index e9f55fd..eb841c1 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleConfig.kt @@ -52,6 +52,13 @@ data class DevConsoleConfig( var browserConfig: BrowserConfig = BrowserConfig() private set + /** + * Browser authentication is off by default for local developer convenience. Set + * [BrowserSecurity.SESSION_CODE] before exposing a LAN-bound server on a shared network. + */ + var browserSecurity: BrowserSecurity = BrowserSecurity.NONE + private set + /** Uncaught-exception / ANR capture depth. See [CrashPolicy] for the enable gates and caps. */ var crashPolicy: CrashPolicy = CrashPolicy() private set @@ -110,6 +117,8 @@ data class DevConsoleConfig( fun withBrowserConfig(value: BrowserConfig): DevConsoleConfig = duplicate().also { it.browserConfig = value } + fun withBrowserSecurity(value: BrowserSecurity): DevConsoleConfig = duplicate().also { it.browserSecurity = value } + fun withCrashPolicy(value: CrashPolicy): DevConsoleConfig = duplicate().also { it.crashPolicy = value } fun withScreenshotPolicy(value: ScreenshotPolicy): DevConsoleConfig = @@ -170,6 +179,7 @@ data class DevConsoleConfig( editingCapabilities == other.editingCapabilities && retentionPolicy == other.retentionPolicy && browserConfig == other.browserConfig && + browserSecurity == other.browserSecurity && crashPolicy == other.crashPolicy && screenshotPolicy == other.screenshotPolicy && captureCategories == other.captureCategories && @@ -183,6 +193,7 @@ data class DevConsoleConfig( it.editingCapabilities = editingCapabilities it.retentionPolicy = retentionPolicy it.browserConfig = browserConfig + it.browserSecurity = browserSecurity it.crashPolicy = crashPolicy it.screenshotPolicy = screenshotPolicy it.captureCategories = captureCategories @@ -205,6 +216,7 @@ data class DevConsoleConfig( private var editingCapabilities = EditingCapabilities() private var retentionPolicy: RetentionPolicy? = null private var browserConfig = BrowserConfig() + private var browserSecurity = BrowserSecurity.NONE private var crashPolicy = CrashPolicy() private var screenshotPolicy = ScreenshotPolicy() private var captureCategories: Set = CaptureCategory.all() @@ -235,6 +247,8 @@ data class DevConsoleConfig( fun browserConfig(value: BrowserConfig) = apply { browserConfig = value } + fun browserSecurity(value: BrowserSecurity) = apply { browserSecurity = value } + fun crashPolicy(value: CrashPolicy) = apply { crashPolicy = value } fun screenshotPolicy(value: ScreenshotPolicy) = apply { screenshotPolicy = value } @@ -261,6 +275,7 @@ data class DevConsoleConfig( .withSessionPolicy(sessionPolicy) .withEditingCapabilities(editingCapabilities) .withBrowserConfig(browserConfig) + .withBrowserSecurity(browserSecurity) .withCrashPolicy(crashPolicy) .withScreenshotPolicy(screenshotPolicy) .withCaptureCategories(captureCategories) diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt index 89426b1..1e9b1b4 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleFacadeProvider.kt @@ -64,7 +64,7 @@ interface DevConsoleFacadeProvider { */ fun endpoint(): BrowserEndpoint? - /** Session-code credentials for the running server, or null when it is not running. */ + /** Browser access information for the running server, or null when it is not running. */ fun accessInfo(): AccessInfo? /** Wrap in a `DevConsoleOkHttpInterceptor` and add it to the host's own `OkHttpClient`. */ diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleResult.kt b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleResult.kt index 567bc8e..63cff34 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleResult.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/DevConsoleResult.kt @@ -39,7 +39,7 @@ sealed interface InitResult { /** Outcome of [io.devconsole.DevConsole.startBrowser] / `startBrowserAsync`. */ sealed interface StartResult { - /** The server bound successfully. [endpoint] is where it's listening; [access] is the session credential. */ + /** The server bound successfully. [endpoint] is where it listens; [access] describes browser access. */ data class Started( val endpoint: BrowserEndpoint, val access: AccessInfo, @@ -63,7 +63,7 @@ sealed interface StartResult { val permission: String, ) : StartResult - /** Every port in [attempted] was already in use. Retry with a different [StartRequest.portRange]. */ + /** Every port in [attempted] was already in use. Free one or provide a wider port range. */ data class PortUnavailable( val attempted: IntRange, ) : StartResult diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt b/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt index 763a010..c19964f 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/FocusedPolicies.kt @@ -23,9 +23,10 @@ private const val DEFAULT_PORT_RANGE_END = 8099 * [LOOPBACK] to rule that out, or [LAN] to fail loudly instead of settling. See the KDoc on * [BindingMode] and `docs/THREAT_MODEL.md`. * - * Choosing [LAN] here has one practical edge over [AUTO] on this surface: an unpermitted LAN start - * surfaces [StartResult.PermissionRequired] through the More screen's own state polling, which is - * how the inspector prompts for `ACCESS_LOCAL_NETWORK`. [AUTO] binds loopback instead of prompting. + * The SDK-owned More screen preflights the platform's LAN permission for both [AUTO] and [LAN], so + * its preferred network URL is not silently replaced by loopback merely because the grant has not + * been requested yet. A host-issued [StartRequest] keeps its explicit API contract: [BindingMode.AUTO] + * may still fall back to loopback, while [BindingMode.LAN] returns [StartResult.PermissionRequired]. */ enum class BrowserBinding { LOOPBACK, LAN, AUTO } @@ -54,9 +55,24 @@ data class RetentionPolicy( } } -/** SESSION_CODE is the only browser-access flow; there is no longer an access-mode field to set. */ +/** + * Browser authentication policy. + * + * [NONE] is the developer-friendly default: the dashboard opens directly at the server URL and + * does not require a per-start credential. It is appropriate for a trusted local development + * workflow, especially with [BrowserBinding.LOOPBACK]. [SESSION_CODE] restores the single-use, + * expiring URL credential for hosts that expose the dashboard over a shared network. + */ +enum class BrowserSecurity { NONE, SESSION_CODE } + +/** Network binding and session-code timing for the browser server. */ data class BrowserConfig( val binding: BrowserBinding = BrowserBinding.AUTO, + /** + * Ports tried in order, so 8080 stays the preferred address while the range leaves room for a + * second app (or a second start before the first server stopped) to land on the next free port + * instead of failing with [StartResult.PortUnavailable]. + */ val portRange: IntRange = DEFAULT_PORT_RANGE_START..DEFAULT_PORT_RANGE_END, val sessionCodeTtlMs: Long = DEFAULT_SESSION_CODE_TTL_MS, ) { diff --git a/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt b/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt index 382a539..f320f5a 100644 --- a/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt +++ b/sdk/api/src/main/kotlin/io/devconsole/api/StartRequest.kt @@ -43,6 +43,11 @@ enum class BindingMode { LOOPBACK, LAN, AUTO } /** Stable host-facing server start options. */ data class StartRequest( val bindingMode: BindingMode = BindingMode.AUTO, + /** + * Ports tried in order, so 8080 stays the preferred address while the range leaves room for a + * second app (or a second start before the first server stopped) to land on the next free port + * instead of failing with [StartResult.PortUnavailable]. + */ val portRange: IntRange = DEFAULT_PORT_RANGE_START..DEFAULT_PORT_RANGE_END, ) { fun validationErrors(): List { @@ -69,10 +74,13 @@ data class BrowserEndpoint( ) /** - * Ephemeral connect information for the SESSION_CODE flow. [sessionCode] is a complete access - * credential -- the live 8-character code -- and [connectUrl] embeds it in the `#code=` fragment. - * There is no on-device approval step: whoever presents the code within its TTL gets a full - * session. Never log, display outside the trusted device screen, or persist either value. + * Connect information for the running browser server. + * + * In the default [BrowserSecurity.NONE] mode, [connectUrl] is a bare server URL, [sessionCode] is + * empty, and [expiresAtEpochMs] is [Long.MAX_VALUE]. In [BrowserSecurity.SESSION_CODE] mode, + * [sessionCode] is a complete ephemeral credential and [connectUrl] embeds it in the `#code=` + * fragment. There is no on-device approval step: whoever presents that code within its TTL gets a + * full session. Never log, display outside the trusted device screen, or persist a session code. */ class AccessInfo( val connectUrl: String, diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt index bcc6a04..ba43b1f 100644 --- a/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt +++ b/sdk/api/src/test/kotlin/io/devconsole/api/DevConsoleContractTest.kt @@ -61,6 +61,19 @@ class DevConsoleContractTest { assertEquals(BindingMode.LOOPBACK, StartRequest(bindingMode = BindingMode.LOOPBACK).bindingMode) } + /** + * 8080 stays the preferred port, but the default must stay a *range*: a single-port default + * makes a second app on the device -- or a restart before the previous server released the + * port -- fail with [StartResult.PortUnavailable] instead of taking the next free port. + */ + @Test + fun `StartRequest defaults to a port range headed by 8080`() { + val portRange = StartRequest().portRange + + assertEquals(8080, portRange.first) + assertTrue("default range must leave fallback ports", portRange.last > portRange.first) + } + @Test fun `default configuration is valid and uses documented session and storage limits`() { val config = DevConsoleConfig.default() diff --git a/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt b/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt index a1a33c4..f70ce37 100644 --- a/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt +++ b/sdk/api/src/test/kotlin/io/devconsole/api/FocusedConfigurationTest.kt @@ -112,6 +112,23 @@ class FocusedConfigurationTest { assertEquals(100L * 1024L * 1024L, retention.maxBytes) assertEquals(BrowserBinding.AUTO, browser.binding) assertEquals(8080..8099, browser.portRange) + assertEquals(BrowserSecurity.NONE, DevConsoleConfig.default().browserSecurity) + } + + @Test + fun `browser security is opt in and participates in config copies`() { + val secured = DevConsoleConfig.default().withBrowserSecurity(BrowserSecurity.SESSION_CODE) + + assertEquals(BrowserSecurity.SESSION_CODE, secured.browserSecurity) + assertFalse(secured.runtimeEquivalentTo(DevConsoleConfig.default())) + assertEquals( + BrowserSecurity.SESSION_CODE, + DevConsoleConfig + .builder() + .browserSecurity(BrowserSecurity.SESSION_CODE) + .build() + .browserSecurity, + ) } @Test diff --git a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt index 0fc5305..10aaeba 100644 --- a/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt +++ b/sdk/facade-shared/src/main/kotlin/io/devconsole/DevConsole.kt @@ -116,7 +116,8 @@ object DevConsole { * safer ADB-only choice on an untrusted network. See `docs/THREAT_MODEL.md` at the repository root. * * @param request binding mode and port range for this start attempt. Defaults to AUTO on - * `8080..8099`. + * `8080..8099` -- 8080 is preferred, and the rest of the range absorbs a second app on the + * device or a restart before the previous server released the port. * @return a [StartResult] -- [StartResult.Started] carries the bound [io.devconsole.api.BrowserEndpoint] * and the session [io.devconsole.api.AccessInfo] (the connect URL/code); every other variant is a * reason it didn't start (see [StartResult]'s KDoc for what each one means and whether it's diff --git a/sdk/full/src/main/AndroidManifest.xml b/sdk/full/src/main/AndroidManifest.xml index 19fdca1..89422bf 100644 --- a/sdk/full/src/main/AndroidManifest.xml +++ b/sdk/full/src/main/AndroidManifest.xml @@ -1,8 +1,21 @@ - + + + + + + + + sdk:full declares the required permissions above, so the service starts by default + whenever the server starts. sdk:full is a debugImplementation artifact; sdk:noop has + neither this service nor any of these permissions. KeepAliveGate still checks the + merged manifest defensively before starting the service. --> Boolean = { false }, + /** Permission preflight for the SDK-owned More-screen Start action; host starts bypass this. */ + private val serverStartPermissionSupplier: () -> String? = { null }, /** * More screen Start/Stop: suspend hooks into the facade's `startBrowser`/`stop`, launched on * [serverControlScope]. All three null on builds/tests that don't wire server control, which @@ -186,12 +189,15 @@ internal class FullInspectorDataSource( * [InspectorDataSource.onNotificationPermissionGranted] for why a grant alone shows nothing. */ private val republishKeepAliveNotification: () -> Unit = {}, -) : InspectorDataSource { +) : InspectorDataSource, + InspectorServerStartPermissionProvider { override fun onNotificationPermissionGranted() = republishKeepAliveNotification() override fun supportsServerControl(): Boolean = serverControlScope != null && startServer != null && stopServer != null + override fun serverStartPermission(): String? = serverStartPermissionSupplier() + @Suppress("ReturnCount") // Guard-clause early returns (no scope, no hook) are the clearest form here. override fun setServerRunning(running: Boolean): InspectorCommandResult { val scope = serverControlScope ?: return InspectorCommandResult.Unavailable diff --git a/sdk/full/src/main/kotlin/io/devconsole/KeepAliveGate.kt b/sdk/full/src/main/kotlin/io/devconsole/KeepAliveGate.kt index 7388ce4..005f450 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/KeepAliveGate.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/KeepAliveGate.kt @@ -10,12 +10,14 @@ import android.content.pm.PackageManager import android.os.Build /** - * Decides whether the keep-alive foreground service may run, from the host's merged manifest. + * Decides whether the keep-alive foreground service may run, from the app's merged manifest. * - * The SDK ships zero `uses-permission` entries for this feature: the host opts in by declaring - * `FOREGROUND_SERVICE` (plus `FOREGROUND_SERVICE_SPECIAL_USE` on API 34+) in its own debug - * manifest. A host that declares nothing gets exactly the pre-feature behavior -- these checks - * are what prevent `startForegroundService` from throwing `SecurityException` in that case. + * The `sdk:full` manifest declares `FOREGROUND_SERVICE` and + * `FOREGROUND_SERVICE_SPECIAL_USE`, so the service is enabled by default for the full debug + * runtime. The check remains defensive: a host can remove a merged permission, use an unusual + * manifest setup, or run an older platform where the type-specific permission is not needed. + * In those cases the server continues without keep-alive instead of receiving a permission + * exception from the service start. */ internal class KeepAliveGate( private val context: Context, @@ -45,14 +47,19 @@ internal class KeepAliveGate( Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || context.checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) == PackageManager.PERMISSION_GRANTED + /** Same manifest/foreground-service guard as the snackbar, evaluated before a new server start. */ + fun shouldRequestNotificationBeforeStart(): Boolean = + canRunForegroundService() && + hostDeclaresPostNotifications() && + !notificationsGranted() + /** * The inspector-UI snackbar predicate: offer the grant only when it would change something - * (server up, service opted in, permission declared by the host, not yet granted). Granting - * an undeclared permission is a silent no-op on Android, so offering it would mislead. + * (server up, the full runtime's service permissions are present, notification permission is + * declared, and the grant is missing). Granting an undeclared permission is a silent no-op on + * Android, so offering it would mislead when a host has removed the merged declaration. */ fun shouldOfferNotificationPrompt(serverRunning: Boolean): Boolean = serverRunning && - canRunForegroundService() && - hostDeclaresPostNotifications() && - !notificationsGranted() + shouldRequestNotificationBeforeStart() } diff --git a/sdk/full/src/main/kotlin/io/devconsole/KeepAliveServiceController.kt b/sdk/full/src/main/kotlin/io/devconsole/KeepAliveServiceController.kt index 584d83b..63013ca 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/KeepAliveServiceController.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/KeepAliveServiceController.kt @@ -8,9 +8,10 @@ import android.content.Context import androidx.core.content.ContextCompat /** - * Bridges server lifecycle to [DevConsoleForegroundService]. Kept out of PlatformFacadeProvider - * so the gate check, the start/stop intents, and the never-throw guarantee are testable without - * booting the whole facade. + * Bridges server lifecycle to [DevConsoleForegroundService]. The full runtime enables this by + * default through its manifest; the gate remains as a defensive boundary. Kept out of + * PlatformFacadeProvider so the gate check, the start/stop intents, and the never-throw guarantee + * are testable without booting the whole facade. */ internal class KeepAliveServiceController( private val gate: KeepAliveGate, diff --git a/sdk/full/src/main/kotlin/io/devconsole/LanPermissionPolicy.kt b/sdk/full/src/main/kotlin/io/devconsole/LanPermissionPolicy.kt new file mode 100644 index 0000000..da2f660 --- /dev/null +++ b/sdk/full/src/main/kotlin/io/devconsole/LanPermissionPolicy.kt @@ -0,0 +1,26 @@ +package io.devconsole + +import android.Manifest +import io.devconsole.server.api.LocalNetworkPermissionGate + +/** Android-version-specific runtime grants needed before the full SDK exposes a LAN URL. */ +internal object LanPermissionPolicy { + private const val NEARBY_WIFI_PERMISSION_API = 33 + private const val LOCAL_NETWORK_PERMISSION_API = 37 + + /** + * Android 13 through 16 use NEARBY_WIFI_DEVICES for the full runtime's local-network path; + * Android 17 and later use ACCESS_LOCAL_NETWORK. Loopback does not call this policy. + */ + fun missingPermission( + deviceApi: Int, + nearbyWifiGranted: Boolean, + localNetworkGranted: Boolean, + ): String? = + when { + deviceApi >= LOCAL_NETWORK_PERMISSION_API && !localNetworkGranted -> LocalNetworkPermissionGate.PERMISSION + deviceApi in NEARBY_WIFI_PERMISSION_API until LOCAL_NETWORK_PERMISSION_API && !nearbyWifiGranted -> + Manifest.permission.NEARBY_WIFI_DEVICES + else -> null + } +} diff --git a/sdk/full/src/main/kotlin/io/devconsole/PersistentTimeline.kt b/sdk/full/src/main/kotlin/io/devconsole/PersistentTimeline.kt index 51afa7e..ba5bc80 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PersistentTimeline.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PersistentTimeline.kt @@ -7,6 +7,7 @@ import io.devconsole.timeline.Timeline import io.devconsole.timeline.TimelineAppender import io.devconsole.timeline.TimelinePage import io.devconsole.timeline.TimelineQuery +import java.util.ArrayDeque /** * Serves reads from [delegate] while mirroring every appended event to durable storage through @@ -15,16 +16,30 @@ import io.devconsole.timeline.TimelineQuery * * Reads stay in memory deliberately: [Timeline.page] is synchronous and already implements cursors * and filtering, whereas [io.devconsole.storage.api.EventStore] is suspending and session-scoped. - * Persistence here is write-through, not read-through. + * Persistence is write-through once the active session row is durable; startup events are retained + * in a bounded handoff queue until that gate opens. */ internal class PersistentTimeline( private val delegate: Timeline, writer: EventBatchWriter, + persistenceReady: Boolean = true, + private val pendingCapacity: Int = EventBatchWriter.DEFAULT_CAPACITY, + private val onPendingDrop: (StoredEvent) -> Unit = {}, ) : Timeline, TimelineAppender { + private val persistenceLock = Any() + @Volatile private var writer = writer + private var persistenceReady = persistenceReady + private val pendingEvents = ArrayDeque() + + init { + require(pendingCapacity > 0) { "pendingCapacity must be positive" } + if (persistenceReady) writer.start() + } + override fun page(query: TimelineQuery): TimelinePage = delegate.page(query) override fun contains(eventId: String): Boolean = delegate.contains(eventId) @@ -48,14 +63,57 @@ internal class PersistentTimeline( /** Rebinds persistence after an auto-initialized config is replaced by the host config. */ fun replaceWriter(replacement: EventBatchWriter) { - writer = replacement + synchronized(persistenceLock) { writer = replacement } + } + + /** + * Enables Room writes after the current session row is durable. Starting the writer before + * flipping the gate closes the small race where a capture could otherwise submit to a stopped + * writer; queued startup events are drained only after the worker is live. + */ + fun setPersistenceReady(ready: Boolean) { + val handoff = + synchronized(persistenceLock) { + if (!ready) { + persistenceReady = false + null + } else { + val writerToUse = writer + writerToUse.start() + persistenceReady = true + val queued = + buildList { + while (pendingEvents.isNotEmpty()) add(pendingEvents.removeFirst()) + } + writerToUse to queued + } + } + handoff?.let { (writerToUse, queued) -> queued.forEach(writerToUse::submit) } + } + + /** Drops only events that were waiting for a session row that never became durable. */ + fun discardPendingPersistence() { + synchronized(persistenceLock) { + pendingEvents.clear() + } } override fun append(event: StoredEvent) { if (!delegate.contains(event.id)) { (delegate as? TimelineAppender)?.append(event) } - // Bounded channel with drop-oldest: a storage stall degrades history rather than the app. - writer.submit(event) + val writerToUse = + synchronized(persistenceLock) { + if (persistenceReady) { + writer + } else { + if (pendingEvents.size == pendingCapacity) { + onPendingDrop(pendingEvents.removeFirst()) + } + pendingEvents.addLast(event) + null + } + } + writerToUse?.submit(event) } } diff --git a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt index bb44020..5fbdd54 100644 --- a/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt +++ b/sdk/full/src/main/kotlin/io/devconsole/PlatformFacadeProvider.kt @@ -1,5 +1,6 @@ package io.devconsole +import android.Manifest import android.app.Activity import android.app.Application import android.content.Context @@ -10,6 +11,7 @@ import android.os.Build import io.devconsole.api.AccessInfo import io.devconsole.api.BrowserBinding import io.devconsole.api.BrowserEndpoint +import io.devconsole.api.BrowserSecurity import io.devconsole.api.CaptureCategory import io.devconsole.api.CaptureRuleEngine import io.devconsole.api.CaptureRuleStore @@ -51,7 +53,6 @@ import io.devconsole.remoteconfig.RemoteConfigSnapshot import io.devconsole.security.RedactionEngine import io.devconsole.security.RedactionPolicy import io.devconsole.server.api.BrowserPrincipal -import io.devconsole.server.api.LocalNetworkPermissionDecision import io.devconsole.server.api.LocalNetworkPermissionGate import io.devconsole.server.api.SdkHealthSnapshot import io.devconsole.server.api.ServerMetadata @@ -88,6 +89,7 @@ import io.devconsole.timeline.InMemoryTimelineAnnotations import io.devconsole.timeline.Timeline import io.devconsole.timeline.TimelineAnnotations import io.devconsole.timeline.TimelineAppender +import io.devconsole.ui.compose.DevConsoleInspectorBridge import io.devconsole.ui.compose.InspectorBrowserPrincipalUi import io.devconsole.ui.compose.InspectorBrowserUi import io.devconsole.ui.compose.InspectorHealthUi @@ -101,6 +103,7 @@ import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.sync.Mutex @@ -351,6 +354,10 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { @Volatile private var bootstrapJob: Job? = null + /** Room history is hydrated after the socket is live and cancelled before teardown completes. */ + @Volatile private var timelineHydrationJob: Job? = null + private val timelineHydrationGeneration = AtomicLong(0) + /** * Durable timeline storage. Room opens the database file lazily on first query, so building it * during [initialize] costs no disk I/O on the calling thread. Left null if construction fails — @@ -468,8 +475,13 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { val writer = createBatchWriter(store, eventBufferCapacity).also(EventBatchWriter::stop) batchWriter = writer batchWriterCapacity = eventBufferCapacity - PersistentTimeline(InMemoryTimeline(emptyList(), CursorCodec(randomCursorSecret())), writer) - .also { timelineAppender = it } + PersistentTimeline( + delegate = InMemoryTimeline(emptyList(), CursorCodec(randomCursorSecret())), + writer = writer, + persistenceReady = durableSessionReady.get(), + pendingCapacity = eventBufferCapacity, + onPendingDrop = { runtime.recordDroppedEvents(1) }, + ).also { timelineAppender = it } }.getOrElse { InMemoryTimeline(emptyList(), CursorCodec(randomCursorSecret())).also { timelineAppender = it } } private fun createBatchWriter( @@ -517,7 +529,16 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { /** Enables strict session writes only after the row is demonstrably durable. */ private fun scheduleSessionBootstrap(application: Application) { val expectedSessionId = activeSessionId() - bootstrapJob = lifecycleScope.launch(Dispatchers.IO) { bootstrapDurableSession(application, expectedSessionId) } + bootstrapJob = + lifecycleScope.launch(Dispatchers.IO) { + try { + bootstrapDurableSession(application, expectedSessionId) + } finally { + // The server may already be Running while Room catches up; refresh the SDK + // inspector so its active-session/uptime data appears without polling. + DevConsoleInspectorBridge.notifyServerStateChanged() + } + } } private fun disableSessionFirstRetention() { @@ -554,6 +575,9 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { roomEventStore?.withSessionFirstRetention() roomAttachmentStore?.withSessionFirstRetention() durableSessionReady.set(true) + if (runtime.state.value is DevConsoleState.Running) { + (cachedTimeline as? PersistentTimeline)?.setPersistenceReady(true) + } } active } catch (cancelled: CancellationException) { @@ -602,7 +626,11 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { val previous = batchWriter if (previous != null && batchWriterCapacity == capacity) return val replacement = createBatchWriter(store, capacity) - if (runtime.state.value is DevConsoleState.Running) replacement.start() else replacement.stop() + if (runtime.state.value is DevConsoleState.Running && durableSessionReady.get()) { + replacement.start() + } else { + replacement.stop() + } batchWriter = replacement batchWriterCapacity = capacity (cachedTimeline as? PersistentTimeline)?.replaceWriter(replacement) @@ -741,7 +769,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { * Split out of [initialize] purely to keep that function's cyclomatic complexity under the * project's detekt threshold -- every gated inspector below was already computed by the caller. */ - @Suppress("LongParameterList") + @Suppress("LongMethod", "LongParameterList") private fun installInspectorBridge( application: Application, gatedPreferencesInspector: AndroidPreferencesInspector?, @@ -802,10 +830,16 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { evidenceStore = roomEvidenceStore, evidenceSessionId = ::currentOrFallbackSessionId, serverControlScope = lifecycleScope, - startServer = { startBrowser(configuredStartRequest()) }, + startServer = { + val result = startBrowser(configuredStartRequest()) + if (result !is StartResult.Started) { + logcatInfo("DevConsole", "In-app server start did not start: $result") + } + }, stopServer = { stop(StopReason.UserRequested) }, republishKeepAliveNotification = ::republishKeepAliveNotification, keepAlivePromptSupplier = ::keepAlivePromptNeeded, + serverStartPermissionSupplier = ::serverStartPermissionNeeded, ), ) } @@ -900,6 +934,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { databaseEditable = config.editingCapabilities.database, filesEditable = config.editingCapabilities.files, ) + serverEngine.withBrowserSecurity(config.browserSecurity) } } @@ -973,6 +1008,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { sessionsProvider = { sessionStore?.sessions().orEmpty() }, screenshotCapture = ::captureScreenshot, ).withRetainedCaptures(RetainedCaptureQuery({ eventStore }, runtime::currentSessionId)) + .withBrowserSecurity(config.browserSecurity) .withAttachmentReader { attachmentId -> roomAttachmentStore?.read(attachmentId) } .withAttachmentMetadataReader { attachmentId -> roomAttachmentStore?.metadata(attachmentId) } @@ -984,8 +1020,14 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { private suspend fun startLocked(request: StartRequest): StartResult { val validationErrors = request.validationErrors() if (validationErrors.isNotEmpty()) return StartResult.InvalidConfiguration(validationErrors) - bootstrapJob?.cancelAndJoin() - bootstrapJob = null + // A repeated explicit start is a restart request for the DevConsole-owned server. Stop it + // through the normal lifecycle path while this mutex is held, so its engine and foreground + // service are torn down before the unchanged engine bind loop retries 8080 first. No process + // lookup or force-kill is attempted: a listener owned by another process remains for the + // engine's normal fallback handling. + if (runtime.state.value is DevConsoleState.Running) { + stopLocked(StopReason.UserRequested) + } val lifecycleRejection = synchronized(liveCaptureLock) { val sessionBeforeStart = runtime.currentSessionId() @@ -1005,28 +1047,33 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { // beginServerStart creates a new core-owned ID after an explicit stop. Make its // durable ACTIVE row visible before any restarted capture source can emit. disableSessionFirstRetention() - val sessionReady = withContext(Dispatchers.IO) { bootstrapDurableSession(application, activeSessionId()) } + val sessionReady = + if (sessionStore == null) { + // buildPersistentTimeline() deliberately falls back to an in-memory timeline + // when Room cannot be constructed. Keep that fallback usable: the browser + // server must not become unavailable just because durable history did. + logcatInfo("DevConsole", "Durable storage unavailable; starting with in-memory history") + true + } else { + // Initialization already starts this bootstrap in the background. Waiting for + // it here made the SDK-owned Start button pay the full five-second timeout + // when Room was still closing a stale session, even though the server itself + // was ready to bind. Keep the server start path latency-bound to the socket; + // the bootstrap enables durable writes when it completes. + if (!durableSessionReady.get() && bootstrapJob?.isActive != true) { + scheduleSessionBootstrap(application) + } + durableSessionReady.get() + } if (!sessionReady) { + // A Room/bootstrap failure must not take down the developer server. Captures stay + // in memory while durable writes remain gated by durableSessionReady=false. batchWriter?.stop() - runtime.serverFailed("Durable app-run session is unavailable") - return@withContext StartResult.Failed("Durable app-run session is unavailable") - } - val lanPermitted = localNetworkPermitted(application) - rejectUnpermittedLan(runtime, request, lanPermitted)?.let { return@withContext it } - withContext(Dispatchers.IO) { - runCatching { - val history = - roomEventStore - ?.recentEvents( - activeConfig?.storagePolicy?.maxTimelineEvents - ?: io.devconsole.api.StoragePolicy.DEFAULT_MAX_TIMELINE_EVENTS, - ).orEmpty() - .filter { it.sessionId == activeSessionId() } - (cachedTimeline as? PersistentTimeline)?.replaceHydratedForSession(activeSessionId(), history) - }.onFailure { - logcatInfo("DevConsole", "Timeline history is unavailable: ${it.javaClass.simpleName}") - } + logcatInfo("DevConsole", "Durable session unavailable; starting with in-memory history") } + val missingLanPermission = missingLanPermission(application) + rejectUnpermittedLan(runtime, request, missingLanPermission)?.let { return@withContext it } + val lanPermitted = missingLanPermission == null if (activeConfig?.crashPolicy?.anrWatchdogEnabled == true && categoryEnabled(CaptureCategory.CRASHES)) { anrWatchdog.start() } @@ -1042,8 +1089,6 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { portRange = request.portRange, sessionCodeTtlMs = sessionCodeTtlMs, ) - // The engine's bind loop does blocking socket probes (Thread.sleep per port); keep it off - // the caller's dispatcher so a host doing `lifecycleScope.launch { startBrowser() }` on Main never ANRs. val attempted = AutoBinding.initialMode(request.bindingMode, lanPermitted) val attempt = withContext(Dispatchers.IO) { activeEngine.start(serverRequest(attempted)) } // Only AUTO retries. The first attempt is left unmapped until the retry is settled so a @@ -1059,102 +1104,195 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { } else { attempt } - mapStartResult(result) + mapStartResult(result).also { + if (result is ServerStartResult.Started) scheduleTimelineHydration() + } } } - private fun mapStartResult(result: ServerStartResult): StartResult = - when (result) { - is ServerStartResult.Started -> { - val credential = - result.sessionCode.let { - AccessInfo( - connectUrl = it.browserUrl, - sessionCode = it.code, - expiresAtEpochMs = it.expiresAtEpochMs, + /** + * Reads only the active app-run history after the server is bound. The query can still be slow + * while Room recovers a stale database, but it no longer delays the SDK-owned Start action or + * the first browser connection. [PersistentTimeline] merges rows captured while this query is + * in flight, and the generation/session checks prevent a late result from crossing stop/start. + */ + @Suppress("ReturnCount") // Guard clauses prevent launching work without every required owner. + private fun scheduleTimelineHydration() { + val store = roomEventStore ?: return + val timeline = cachedTimeline as? PersistentTimeline ?: return + val expectedSessionId = runtime.currentSessionId() ?: return + val generation = timelineHydrationGeneration.incrementAndGet() + timelineHydrationJob?.cancel() + timelineHydrationJob = + lifecycleScope.launch(Dispatchers.IO) { + val history = + runCatching { + store.recentEventsForSession( + sessionId = expectedSessionId, + limit = + activeConfig?.storagePolicy?.maxTimelineEvents + ?: io.devconsole.api.StoragePolicy.DEFAULT_MAX_TIMELINE_EVENTS, ) - } - val started = - StartResult.Started( - endpoint = - BrowserEndpoint( - host = result.endpoint.host, - port = result.endpoint.port, - bindingMode = - when (result.endpoint.bindingMode) { - ServerBindingMode.LOOPBACK -> PublicBindingMode.LOOPBACK - ServerBindingMode.LAN -> PublicBindingMode.LAN - }, - ), - access = credential, - ) - batchWriter?.start() - lastStarted = started - runtime.serverStarted() - sessionMarkerMonitor?.start(result.endpoint.bindingMode.name) - keepAliveController?.onServerStarted( - application, - "http://${result.endpoint.host}:${result.endpoint.port}", - ) - logcatInfo( - "DevConsole", - "Dashboard available at: ${credential.connectUrl.withoutCredentials()} " + - "(access link available through the DevConsole API/launcher; " + - "binding: ${result.endpoint.bindingMode})", - ) - started + }.onFailure { + logcatInfo("DevConsole", "Timeline history is unavailable: ${it.javaClass.simpleName}") + }.getOrDefault(emptyList()) + + if (!isActive || generation != timelineHydrationGeneration.get()) return@launch + if (runtime.currentSessionId() != expectedSessionId || + runtime.state.value !is DevConsoleState.Running + ) { + return@launch + } + timeline.replaceHydratedForSession(expectedSessionId, history) + DevConsoleInspectorBridge.notifyServerStateChanged() } + } - ServerStartResult.DisabledForBuild -> { - runtime.serverFailed("Server is disabled for this build") - StartResult.DisabledForBuild - } + private fun mapStartResult(result: ServerStartResult): StartResult { + val mapped = + when (result) { + is ServerStartResult.Started -> { + val credential = + if (activeConfig?.browserSecurity == BrowserSecurity.NONE) { + AccessInfo( + connectUrl = "http://${result.endpoint.host}:${result.endpoint.port}", + sessionCode = "", + expiresAtEpochMs = Long.MAX_VALUE, + ) + } else { + result.sessionCode.let { + AccessInfo( + connectUrl = it.browserUrl, + sessionCode = it.code, + expiresAtEpochMs = it.expiresAtEpochMs, + ) + } + } + val started = + StartResult.Started( + endpoint = + BrowserEndpoint( + host = result.endpoint.host, + port = result.endpoint.port, + bindingMode = + when (result.endpoint.bindingMode) { + ServerBindingMode.LOOPBACK -> PublicBindingMode.LOOPBACK + ServerBindingMode.LAN -> PublicBindingMode.LAN + }, + ), + access = credential, + ) + (cachedTimeline as? PersistentTimeline)?.setPersistenceReady(durableSessionReady.get()) + lastStarted = started + runtime.serverStarted() + sessionMarkerMonitor?.start(result.endpoint.bindingMode.name) + keepAliveController?.onServerStarted( + application, + "http://${result.endpoint.host}:${result.endpoint.port}", + ) + logcatInfo( + "DevConsole", + "Dashboard available at: ${credential.connectUrl.withoutCredentials()} " + + "(access link available through the DevConsole API/launcher; " + + "binding: ${result.endpoint.bindingMode})", + ) + started + } - ServerStartResult.LocalNetworkPermissionRequired -> { - runtime.serverRequiresPermission() - StartResult.PermissionRequired("android.permission.ACCESS_LOCAL_NETWORK") - } + ServerStartResult.DisabledForBuild -> { + runtime.serverFailed("Server is disabled for this build") + StartResult.DisabledForBuild + } - is ServerStartResult.InvalidConfiguration -> { - runtime.serverFailed(result.detail) - StartResult.Failed(result.detail) - } + ServerStartResult.LocalNetworkPermissionRequired -> { + runtime.serverRequiresPermission() + StartResult.PermissionRequired("android.permission.ACCESS_LOCAL_NETWORK") + } - is ServerStartResult.PortUnavailable -> { - runtime.serverFailed("No loopback port available in ${result.attempted}") - StartResult.PortUnavailable(result.attempted) - } + is ServerStartResult.InvalidConfiguration -> { + runtime.serverFailed(result.detail) + StartResult.Failed(result.detail) + } - is ServerStartResult.NoEligibleNetwork -> { - runtime.serverFailed(result.detail) - StartResult.NoEligibleNetwork(result.detail) - } + is ServerStartResult.PortUnavailable -> { + runtime.serverFailed("No loopback port available in ${result.attempted}") + StartResult.PortUnavailable(result.attempted) + } - is ServerStartResult.Failed -> { - runtime.serverFailed(result.detail) - StartResult.Failed(result.detail) + is ServerStartResult.NoEligibleNetwork -> { + runtime.serverFailed(result.detail) + StartResult.NoEligibleNetwork(result.detail) + } + + is ServerStartResult.Failed -> { + runtime.serverFailed(result.detail) + StartResult.Failed(result.detail) + } } - } + // The SDK-owned More screen is snapshot-driven. Wake it as soon as the runtime has + // transitioned, instead of making a successful start wait for its five-second poll. + DevConsoleInspectorBridge.notifyServerStateChanged() + return mapped + } override suspend fun stop(reason: StopReason) = lifecycleMutex.withLock { stopLocked(reason) } private suspend fun stopLocked(reason: StopReason) { durableSessionReady.set(false) - bootstrapJob?.cancelAndJoin() - bootstrapJob = null + (cachedTimeline as? PersistentTimeline)?.setPersistenceReady(false) + (cachedTimeline as? PersistentTimeline)?.discardPendingPersistence() + timelineHydrationGeneration.incrementAndGet() lastStarted = null - sessionMarkerMonitor?.stop(reason.markerLabel()) - withContext(Dispatchers.IO) { batchWriter?.flushAndStop() } - if (::serverEngine.isInitialized) withContext(Dispatchers.IO) { serverEngine.stop() } - sessionAuthority.reset() - sessionCodeAuthority.reset() - if (::featureFlags.isInitialized) featureFlags.reset() - mockEngineInstance.clearSessionRules() - anrWatchdog.stop() - sessionStore?.end(activeSessionId(), System.currentTimeMillis()) - storedSessions = sessionStore?.sessions().orEmpty() - runtime.stop(reason) - if (::application.isInitialized) keepAliveController?.onServerStopped(application) + try { + stopStep("timeline hydration") { + timelineHydrationJob?.cancelAndJoin() + timelineHydrationJob = null + } + stopStep("bootstrap") { + bootstrapJob?.cancelAndJoin() + bootstrapJob = null + } + stopStep("session marker") { sessionMarkerMonitor?.stop(reason.markerLabel()) } + stopStep("event writer") { withContext(Dispatchers.IO) { batchWriter?.flushAndStop() } } + stopStep("server engine") { + if (::serverEngine.isInitialized) withContext(Dispatchers.IO) { serverEngine.stop() } + } + stopStep("browser sessions") { + sessionAuthority.reset() + sessionCodeAuthority.reset() + } + stopStep("feature flags") { if (::featureFlags.isInitialized) featureFlags.reset() } + stopStep("mock rules") { mockEngineInstance.clearSessionRules() } + stopStep("ANR watchdog") { anrWatchdog.stop() } + stopStep("durable session") { + runtime.currentSessionId()?.let { sessionId -> + sessionStore?.end(sessionId, System.currentTimeMillis()) + storedSessions = sessionStore?.sessions().orEmpty() + } + } + } finally { + // Notification Stop must never leave the SDK reporting Running just because a best- + // effort cleanup step failed. The service removes its notification after stopAsync's + // callback, so finalize the public runtime state and wake the SDK-owned inspector here. + runtime.stop(reason) + DevConsoleInspectorBridge.notifyServerStateChanged() + if (::application.isInitialized) keepAliveController?.onServerStopped(application) + } + } + + /** Cleanup is best-effort; cancellation still propagates so structured teardown can finish. */ + @Suppress("TooGenericExceptionCaught") // Every cleanup failure is isolated so later stop steps still run. + private suspend fun stopStep( + label: String, + action: suspend () -> Unit, + ) { + try { + action() + } catch (failure: CancellationException) { + throw failure + } catch (failure: Exception) { + logcatInfo("DevConsole", "Stop cleanup failed ($label): ${failure.javaClass.simpleName}") + } } @Synchronized @@ -1212,12 +1350,22 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { } override fun accessInfo(): AccessInfo? { - val info = liveSessionCodeInfo() ?: return null - return AccessInfo( - connectUrl = info.browserUrl, - sessionCode = info.code, - expiresAtEpochMs = info.expiresAtEpochMs, - ) + val started = lastStarted ?: return null + return if (activeConfig?.browserSecurity == BrowserSecurity.NONE) { + AccessInfo( + connectUrl = "http://${started.endpoint.host}:${started.endpoint.port}", + sessionCode = "", + expiresAtEpochMs = Long.MAX_VALUE, + ) + } else { + liveSessionCodeInfo()?.let { info -> + AccessInfo( + connectUrl = info.browserUrl, + sessionCode = info.code, + expiresAtEpochMs = info.expiresAtEpochMs, + ) + } + } } /** @@ -1228,7 +1376,7 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { * already-expired code. Null while the server isn't running. */ private fun liveSessionCodeInfo(): SessionCodeInfo? { - lastStarted ?: return null + if (lastStarted == null || activeConfig?.browserSecurity != BrowserSecurity.SESSION_CODE) return null return sessionCodeAuthority.currentInfo() ?: sessionCodeAuthority.issueCode() } @@ -1350,6 +1498,22 @@ internal class PlatformFacadeProvider : DevConsoleFacadeProvider { private fun keepAlivePromptNeeded(): Boolean = keepAliveGate?.shouldOfferNotificationPrompt(runtime.state.value is DevConsoleState.Running) ?: false + /** + * Permission preflight used only by the SDK-owned More-screen Start button. Explicit host/API + * starts retain their existing contract and still return [StartResult.PermissionRequired] when + * the caller requested a LAN bind without the local-network grant. + * + * AUTO and explicit LAN both surface the missing local-network grant here because this is the + * SDK-owned start path: the user can act on the permission before receiving a less useful + * loopback-only URL. Notification permission is deliberately not returned here. Android can + * run the foreground service while hiding its notification when POST_NOTIFICATIONS is denied, + * and the running-server snackbar remains available to request it later. + */ + private fun serverStartPermissionNeeded(): String? { + val binding = activeConfig?.browserConfig?.binding ?: return null + return if (binding == BrowserBinding.LOOPBACK) null else missingLanPermission(application) + } + /** Device/app metadata for the evidence bundle's session.json; honestly null before a durable session exists. */ private suspend fun currentSessionSnapshot(): StoredSession? = sessionStore?.session(activeSessionId()) @@ -1436,10 +1600,17 @@ private fun DevConsoleConfig.toInspectorBrowserUi( binding = endpoint?.bindingMode?.name ?: browserConfig.binding.name, endpoint = endpoint?.let { "${it.host}:${it.port}" }, principals = principals.map { it.toInspectorPrincipalUi() }, - sessionCodeUrl = sessionCode?.browserUrl, - sessionCode = sessionCode?.code, - sessionCodeExpiresAtEpochMs = sessionCode?.expiresAtEpochMs, - sessionCodeRemainingTtlMs = sessionCodeRemainingTtlMs, + sessionCodeUrl = + if (browserSecurity == BrowserSecurity.NONE) { + endpoint?.let { "http://${it.host}:${it.port}" } + } else { + sessionCode?.browserUrl + }, + sessionCode = if (browserSecurity == BrowserSecurity.NONE) "" else sessionCode?.code, + sessionCodeExpiresAtEpochMs = + if (browserSecurity == BrowserSecurity.NONE) null else sessionCode?.expiresAtEpochMs, + sessionCodeRemainingTtlMs = + if (browserSecurity == BrowserSecurity.NONE) null else sessionCodeRemainingTtlMs, bindAddressChanged = bindAddressChanged, ) @@ -1462,40 +1633,41 @@ private fun randomCursorSecret(): ByteArray = ByteArray(CURSOR_SECRET_BYTES).als /** * Whether a LAN bind would be allowed to reach the network right now. * - * Below API 37 this is always true. At or above it, an ungranted `ACCESS_LOCAL_NETWORK` means the - * platform silently drops LAN traffic even though the socket binds and completes handshakes -- see + * API 32 and below do not require a runtime LAN permission. API 33-36 require + * `NEARBY_WIFI_DEVICES`; API 37 and above require `ACCESS_LOCAL_NETWORK`. The latter can otherwise + * silently drop LAN traffic even though the socket binds and completes handshakes -- see * [LocalNetworkPermissionGate], which deliberately ignores `targetSdk` for that reason. */ -private fun localNetworkPermitted(application: Application): Boolean { - val isGranted = +private fun missingLanPermission(application: Application): String? { + val nearbyGranted = + Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU || + application.checkSelfPermission(Manifest.permission.NEARBY_WIFI_DEVICES) == + PackageManager.PERMISSION_GRANTED + val localNetworkGranted = application.checkSelfPermission(LocalNetworkPermissionGate.PERMISSION) == PackageManager.PERMISSION_GRANTED - val decision = - LocalNetworkPermissionGate.evaluate( - bindingMode = ServerBindingMode.LAN, - deviceApi = Build.VERSION.SDK_INT, - targetSdk = application.applicationInfo.targetSdkVersion, - isGranted = isGranted, - ) - return decision !is LocalNetworkPermissionDecision.PermissionRequired + return LanPermissionPolicy.missingPermission( + deviceApi = Build.VERSION.SDK_INT, + nearbyWifiGranted = nearbyGranted, + localNetworkGranted = localNetworkGranted, + ) } /** * Null means the start may proceed; a non-null result is the early-return for * [PlatformFacadeProvider.start]. * - * Only an explicit [PublicBindingMode.LAN] is rejected here. [PublicBindingMode.AUTO] treats a - * missing grant as a reason to bind loopback rather than a reason to fail, so it never reaches this - * function -- which also means AUTO never surfaces [StartResult.PermissionRequired] and never gives - * a host the cue to prompt for the permission. Hosts that want the prompt ask for LAN by name. + * Only an explicit [PublicBindingMode.LAN] is rejected here. [PublicBindingMode.AUTO] still keeps + * its host/API contract of falling back to loopback, while the SDK-owned More-screen preflight + * surfaces the same missing grant before it chooses a URL for the user. */ private fun rejectUnpermittedLan( runtime: DevConsoleRuntime, request: StartRequest, - lanPermitted: Boolean, + missingPermission: String?, ): StartResult? { - if (request.bindingMode != PublicBindingMode.LAN || lanPermitted) return null + if (request.bindingMode != PublicBindingMode.LAN || missingPermission == null) return null runtime.serverRequiresPermission() - return StartResult.PermissionRequired(LocalNetworkPermissionGate.PERMISSION) + return StartResult.PermissionRequired(missingPermission) } private fun Application.serverMetadata(): ServerMetadata { diff --git a/sdk/full/src/test/kotlin/io/devconsole/AutoBindingTest.kt b/sdk/full/src/test/kotlin/io/devconsole/AutoBindingTest.kt index 7067753..243377e 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/AutoBindingTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/AutoBindingTest.kt @@ -42,8 +42,10 @@ class AutoBindingTest { } /** - * Everything else is a genuine failure that loopback would hit too, so retrying would turn one - * honest error into two. A port clash is the sharp case: the range is the same either way. + * Everything else is a genuine failure that retrying would turn from one honest error into two. + * A port clash is the sharp case: loopback binds a different address, so it is not strictly + * doomed -- but exhausting all 20 ports is an environment problem, and quietly downgrading to a + * `127.0.0.1` URL the caller asked not to get is worse than saying so. */ @Test fun `failures loopback cannot rescue are left alone`() { diff --git a/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt b/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt index 7d59bfd..f0b48bd 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/FullFacadeTest.kt @@ -1,9 +1,11 @@ package io.devconsole +import android.Manifest import android.app.Application import androidx.test.core.app.ApplicationProvider import io.devconsole.api.BindingMode import io.devconsole.api.BrowserEndpoint +import io.devconsole.api.BrowserSecurity import io.devconsole.api.DevConsoleConfig import io.devconsole.api.DevConsoleState import io.devconsole.api.InitResult @@ -27,9 +29,11 @@ import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNull import org.junit.Assert.assertTrue +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config import java.net.HttpURLConnection import java.net.URL @@ -49,6 +53,12 @@ import java.net.URL @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) class FullFacadeTest { + @Before + fun grantNearbyWifiForLanAssertions() { + shadowOf(ApplicationProvider.getApplicationContext()) + .grantPermissions(Manifest.permission.NEARBY_WIFI_DEVICES) + } + @Test fun `invalid configuration returns structured errors before platform services are created`() { val provider = PlatformFacadeProvider() @@ -100,12 +110,29 @@ class FullFacadeTest { // interface, so the default start reaches the network. See PlatformFacadeProviderAutoBindingTest. assertEquals(BindingMode.LAN, started.endpoint.bindingMode) assertTrue(started.endpoint.port in 8080..8099) - assertTrue(started.access.connectUrl.contains("#code=")) + assertTrue(started.access.connectUrl.startsWith("http://")) + assertTrue(started.access.sessionCode.isEmpty()) assertEquals(DevConsoleState.Running, provider.state().value) provider.stop(StopReason.UserRequested) assertEquals(DevConsoleState.Stopped, provider.state().value) } + @Test + fun `repeated explicit start restarts the owned server and reclaims its requested port`() = + runTest { + val provider = PlatformFacadeProvider() + provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + val request = StartRequest(BindingMode.LOOPBACK, 8890..8893) + + val first = provider.startBrowser(request) as StartResult.Started + val second = provider.startBrowser(request) as StartResult.Started + + assertTrue(first.endpoint.port in request.portRange) + assertEquals(first.endpoint.port, second.endpoint.port) + assertEquals(DevConsoleState.Running, provider.state().value) + provider.stop(StopReason.UserRequested) + } + @Test fun `persistent mock rules survive full runtime recreation`() { val application: Application = ApplicationProvider.getApplicationContext() @@ -162,7 +189,10 @@ class FullFacadeTest { fun `explicit mock kill switch remains disabled across server restart`() = runTest { val provider = PlatformFacadeProvider() - provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + provider.initialize( + ApplicationProvider.getApplicationContext(), + DevConsoleConfig.default().withBrowserSecurity(BrowserSecurity.SESSION_CODE), + ) provider.startBrowser(StartRequest(BindingMode.LOOPBACK, 8160..8179)) provider.mockEngine().setEnabled(false) @@ -253,7 +283,10 @@ class FullFacadeTest { fun `a browser can exchange the session code over HTTP with no approval round trip`() = runTest { val provider = PlatformFacadeProvider() - provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + provider.initialize( + ApplicationProvider.getApplicationContext(), + DevConsoleConfig.default().withBrowserSecurity(BrowserSecurity.SESSION_CODE), + ) val started = provider.startBrowser(StartRequest(BindingMode.LOOPBACK, 8280..8299)) as StartResult.Started val accessToken = exchangeSessionCodeOverHttp(started, "Test Browser") @@ -268,7 +301,10 @@ class FullFacadeTest { fun `stopping the console revokes browser sessions`() = runTest { val provider = PlatformFacadeProvider() - provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + provider.initialize( + ApplicationProvider.getApplicationContext(), + DevConsoleConfig.default().withBrowserSecurity(BrowserSecurity.SESSION_CODE), + ) val started = provider.startBrowser(StartRequest(BindingMode.LOOPBACK, 8360..8379)) as StartResult.Started val accessToken = exchangeSessionCodeOverHttp(started, "Browser To Stop") @@ -277,7 +313,10 @@ class FullFacadeTest { provider.stop(StopReason.UserRequested) - provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + provider.initialize( + ApplicationProvider.getApplicationContext(), + DevConsoleConfig.default().withBrowserSecurity(BrowserSecurity.SESSION_CODE), + ) val restarted = provider.startBrowser(StartRequest(BindingMode.LOOPBACK, 8380..8399)) as StartResult.Started // The old session does not survive a stop/restart -- a fresh authority means a fresh store. assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, sessionStatusOverHttp(restarted, accessToken)) @@ -384,6 +423,7 @@ class FullFacadeTest { assertEquals(started.endpoint, provider.endpoint()) assertEquals(started.access.connectUrl, provider.accessInfo()?.connectUrl) + assertEquals("", started.access.sessionCode) provider.stop(StopReason.UserRequested) @@ -400,7 +440,10 @@ class FullFacadeTest { val provider = PlatformFacadeProvider() provider.initialize( ApplicationProvider.getApplicationContext(), - DevConsoleConfig.default().withBrowserConfig(io.devconsole.api.BrowserConfig(sessionCodeTtlMs = 20)), + DevConsoleConfig + .default() + .withBrowserSecurity(BrowserSecurity.SESSION_CODE) + .withBrowserConfig(io.devconsole.api.BrowserConfig(sessionCodeTtlMs = 20)), ) val started = provider.startBrowser(StartRequest(BindingMode.LOOPBACK, 8560..8579)) as StartResult.Started @@ -417,7 +460,10 @@ class FullFacadeTest { fun `More surface's session-code URL is readable while running and cleared on stop`() = runTest { val provider = PlatformFacadeProvider() - provider.initialize(ApplicationProvider.getApplicationContext(), DevConsoleConfig.default()) + provider.initialize( + ApplicationProvider.getApplicationContext(), + DevConsoleConfig.default().withBrowserSecurity(BrowserSecurity.SESSION_CODE), + ) provider.startBrowser(StartRequest(BindingMode.LOOPBACK, 8500..8519)) as StartResult.Started val browser = DevConsoleInspectorBridge.source().snapshot().browser diff --git a/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceServerControlTest.kt b/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceServerControlTest.kt index b347be2..087dc78 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceServerControlTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/FullInspectorDataSourceServerControlTest.kt @@ -49,4 +49,17 @@ class FullInspectorDataSourceServerControlTest { assertTrue(dataSource.setServerRunning(false) is InspectorCommandResult.Success) assertEquals(listOf("start", "stop"), calls) } + + @Test + fun `server start permission is exposed to the SDK-owned inspector`() { + val dataSource = + FullInspectorDataSource( + networkTransactionStore = InMemoryNetworkTransactionStore(NetworkCursorCodec(ByteArray(16))), + mockEngine = MockEngine(emptyList()), + configSupplier = { null }, + serverStartPermissionSupplier = { "android.permission.POST_NOTIFICATIONS" }, + ) + + assertEquals("android.permission.POST_NOTIFICATIONS", dataSource.serverStartPermission()) + } } diff --git a/sdk/full/src/test/kotlin/io/devconsole/KeepAliveGateTest.kt b/sdk/full/src/test/kotlin/io/devconsole/KeepAliveGateTest.kt index de31ad1..a2bd1e6 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/KeepAliveGateTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/KeepAliveGateTest.kt @@ -89,10 +89,12 @@ class KeepAliveGateTest { declarePermissions(Manifest.permission.FOREGROUND_SERVICE, Manifest.permission.POST_NOTIFICATIONS) val gate = KeepAliveGate(application) + assertTrue(gate.shouldRequestNotificationBeforeStart()) assertTrue(gate.shouldOfferNotificationPrompt(serverRunning = true)) assertFalse(gate.shouldOfferNotificationPrompt(serverRunning = false)) shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS) + assertFalse(gate.shouldRequestNotificationBeforeStart()) assertFalse(gate.shouldOfferNotificationPrompt(serverRunning = true)) } diff --git a/sdk/full/src/test/kotlin/io/devconsole/LanPermissionPolicyTest.kt b/sdk/full/src/test/kotlin/io/devconsole/LanPermissionPolicyTest.kt new file mode 100644 index 0000000..c2a3406 --- /dev/null +++ b/sdk/full/src/test/kotlin/io/devconsole/LanPermissionPolicyTest.kt @@ -0,0 +1,58 @@ +package io.devconsole + +import android.Manifest +import io.devconsole.server.api.LocalNetworkPermissionGate +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Test + +class LanPermissionPolicyTest { + @Test + fun `android 13 through 16 surface nearby wifi when LAN grant is missing`() { + assertEquals( + Manifest.permission.NEARBY_WIFI_DEVICES, + LanPermissionPolicy.missingPermission( + deviceApi = 33, + nearbyWifiGranted = false, + localNetworkGranted = false, + ), + ) + assertNull( + LanPermissionPolicy.missingPermission( + deviceApi = 36, + nearbyWifiGranted = true, + localNetworkGranted = false, + ), + ) + } + + @Test + fun `android 17 and later surface local network instead of nearby wifi`() { + assertEquals( + LocalNetworkPermissionGate.PERMISSION, + LanPermissionPolicy.missingPermission( + deviceApi = 37, + nearbyWifiGranted = false, + localNetworkGranted = false, + ), + ) + assertNull( + LanPermissionPolicy.missingPermission( + deviceApi = 37, + nearbyWifiGranted = true, + localNetworkGranted = true, + ), + ) + } + + @Test + fun `older Android does not require either runtime grant`() { + assertNull( + LanPermissionPolicy.missingPermission( + deviceApi = 32, + nearbyWifiGranted = false, + localNetworkGranted = false, + ), + ) + } +} diff --git a/sdk/full/src/test/kotlin/io/devconsole/PersistentTimelineTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PersistentTimelineTest.kt index 507381f..04ed565 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/PersistentTimelineTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/PersistentTimelineTest.kt @@ -33,6 +33,67 @@ class PersistentTimelineTest { assertEquals(0, store.inserted.size) } + @Test + fun `hydration keeps events captured while the Room query was in flight`() { + val store = RecordingStore() + val writer = EventBatchWriter(store, CoroutineScope(SupervisorJob())) + val timeline = + PersistentTimeline( + InMemoryTimeline(emptyList(), CursorCodec("merge-secret-1234".encodeToByteArray())), + writer, + ) + val persisted = storedEvent("persisted", sessionId = "session") + val live = storedEvent("live", sessionId = "session", sequence = 2) + + timeline.append(live) + timeline.replaceHydratedForSession("session", listOf(persisted)) + + val page = timeline.page(TimelineQuery()) as TimelinePage.Success + assertEquals(setOf("persisted", "live"), page.events.map(StoredEvent::id).toSet()) + assertEquals(0, store.inserted.size) + } + + @Test + fun `startup events wait for durable session before the writer starts`() = + runTest { + val store = RecordingStore() + val writer = EventBatchWriter(store, this) + val timeline = + PersistentTimeline( + delegate = InMemoryTimeline(emptyList(), CursorCodec("startup-secret-123".encodeToByteArray())), + writer = writer, + persistenceReady = false, + ) + val event = storedEvent("startup") + + timeline.append(event) + assertEquals(emptyList(), store.inserted) + + timeline.setPersistenceReady(true) + writer.flushAndStop() + + assertEquals(listOf("startup"), store.inserted.map(StoredEvent::id)) + } + + @Test + fun `a ready timeline starts a writer that was stopped before construction`() = + runTest { + val store = RecordingStore() + val writer = EventBatchWriter(store, this) + writer.stop() + val timeline = + PersistentTimeline( + delegate = InMemoryTimeline(emptyList(), CursorCodec("ready-secret-1234".encodeToByteArray())), + writer = writer, + persistenceReady = true, + ) + + timeline.append(storedEvent("ready")) + writer.flushAndStop() + + assertEquals(listOf("ready"), store.inserted.map(StoredEvent::id)) + } + @Test fun `replacing the persistence writer routes subsequent events to the configured queue`() = runTest { @@ -57,7 +118,11 @@ class PersistentTimelineTest { assertEquals(listOf("replacement"), replacementStore.inserted.map(StoredEvent::id)) } - private fun storedEvent(id: String) = StoredEvent(id, "session", 1, "system", "event", 1, 1, 1, "ready") + private fun storedEvent( + id: String, + sessionId: String = "session", + sequence: Long = 1, + ) = StoredEvent(id, sessionId, sequence, "system", "event", 1, sequence, 1, "ready") private class RecordingStore : EventStore { val inserted = mutableListOf() diff --git a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderAutoBindingTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderAutoBindingTest.kt index 0a70d2a..c10efd0 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderAutoBindingTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderAutoBindingTest.kt @@ -1,5 +1,6 @@ package io.devconsole +import android.Manifest import androidx.test.core.app.ApplicationProvider import io.devconsole.api.BindingMode import io.devconsole.api.DevConsoleConfig @@ -9,9 +10,11 @@ import io.devconsole.api.StopReason import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config /** @@ -26,6 +29,12 @@ import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) class PlatformFacadeProviderAutoBindingTest { + @Before + fun grantNearbyWifiForLanAssertions() { + shadowOf(ApplicationProvider.getApplicationContext()) + .grantPermissions(Manifest.permission.NEARBY_WIFI_DEVICES) + } + @Test fun `a default start request binds LAN when the device has a network`() = runTest { diff --git a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderBrowserBindingTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderBrowserBindingTest.kt index 6c04bb7..9a9e62e 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderBrowserBindingTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderBrowserBindingTest.kt @@ -4,6 +4,7 @@ */ package io.devconsole +import android.Manifest import androidx.test.core.app.ApplicationProvider import io.devconsole.api.BindingMode import io.devconsole.api.DevConsoleConfig @@ -13,9 +14,11 @@ import io.devconsole.api.StopReason import io.devconsole.ui.compose.DevConsoleInspectorBridge import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config /** @@ -29,6 +32,12 @@ import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) class PlatformFacadeProviderBrowserBindingTest { + @Before + fun grantNearbyWifiForLanAssertions() { + shadowOf(ApplicationProvider.getApplicationContext()) + .grantPermissions(Manifest.permission.NEARBY_WIFI_DEVICES) + } + @Test fun `More surface browser binding reflects the mode the server actually bound to`() = runTest { diff --git a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt index a5f3f28..773f9b6 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderMoreScreenBindingTest.kt @@ -4,6 +4,7 @@ */ package io.devconsole +import android.Manifest import androidx.test.core.app.ApplicationProvider import io.devconsole.api.BindingMode import io.devconsole.api.BrowserBinding @@ -18,9 +19,11 @@ import kotlinx.coroutines.test.runTest import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeout import org.junit.Assert.assertEquals +import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config /** @@ -37,6 +40,12 @@ import org.robolectric.annotation.Config @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) class PlatformFacadeProviderMoreScreenBindingTest { + @Before + fun grantNearbyWifiForLanAssertions() { + shadowOf(ApplicationProvider.getApplicationContext()) + .grantPermissions(Manifest.permission.NEARBY_WIFI_DEVICES) + } + @Test fun `More screen start binds LAN when the host configured LAN`() = runTest { diff --git a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderScreenshotTest.kt b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderScreenshotTest.kt index 7ca71e5..cca2f4a 100644 --- a/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderScreenshotTest.kt +++ b/sdk/full/src/test/kotlin/io/devconsole/PlatformFacadeProviderScreenshotTest.kt @@ -8,6 +8,7 @@ import android.app.Activity import android.view.View.MeasureSpec import androidx.test.core.app.ApplicationProvider import io.devconsole.api.BindingMode +import io.devconsole.api.BrowserSecurity import io.devconsole.api.DevConsoleConfig import io.devconsole.api.InitResult import io.devconsole.api.ScreenshotPolicy @@ -81,7 +82,11 @@ class PlatformFacadeProviderScreenshotTest { runTest { val provider = PlatformFacadeProvider() val application = ApplicationProvider.getApplicationContext() - val config = DevConsoleConfig.default().withScreenshotPolicy(ScreenshotPolicy(enabled = true)) + val config = + DevConsoleConfig + .default() + .withBrowserSecurity(BrowserSecurity.SESSION_CODE) + .withScreenshotPolicy(ScreenshotPolicy(enabled = true)) assertEquals(InitResult.Initialized, provider.initialize(application, config)) val started = provider.startBrowser(StartRequest(BindingMode.LOOPBACK, 8640..8659)) as StartResult.Started diff --git a/sdk/server-api/api/server-api.api b/sdk/server-api/api/server-api.api index ff206ec..eabe899 100644 --- a/sdk/server-api/api/server-api.api +++ b/sdk/server-api/api/server-api.api @@ -488,8 +488,11 @@ public final class io/devconsole/server/api/SessionAuthority { public fun ()V public fun (Lkotlin/jvm/functions/Function0;JILjava/security/SecureRandom;)V public synthetic fun (Lkotlin/jvm/functions/Function0;JILjava/security/SecureRandom;ILkotlin/jvm/internal/DefaultConstructorMarker;)V + public final fun configureBrowserAuthentication (Z)V public final fun configurePolicy (Lio/devconsole/server/api/SessionPolicy;)Z public final fun isAuthorized (Ljava/lang/String;)Z + public final fun isBrowserAuthenticationRequired ()Z + public final fun openAccessSession ()Lio/devconsole/server/api/BrowserSession; public final fun principals ()Ljava/util/List; public final fun purgeExpired ()V public final fun refresh (Ljava/lang/String;)Lio/devconsole/server/api/BrowserSession; diff --git a/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt b/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt index 5194df5..701eee3 100644 --- a/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt +++ b/sdk/server-api/src/main/kotlin/io/devconsole/server/api/LocalServerEngine.kt @@ -24,6 +24,10 @@ data class SessionPolicy( data class StartRequest( val bindingMode: BindingMode = BindingMode.LAN, + /** + * Ports tried in ascending order, so 8080 is preferred and the rest of the range absorbs a + * second app on the device (or a restart before the previous server released the port). + */ val portRange: IntRange = 8080..8099, val sessionCodeTtlMs: Long = SessionCodeAuthority.DEFAULT_SESSION_CODE_TTL_MS, ) @@ -208,6 +212,14 @@ class SessionAuthority( private val sessionMetadata = mutableMapOf() private var policy = SessionPolicy(maxAuthenticatedSessions = maxAuthenticatedSessions) + /** + * The low-level Ktor module historically defaulted to authenticated browser sessions. The + * full SDK can switch this off for its developer-friendly [openAccessSession] mode without + * changing the session store or the explicit SESSION_CODE flow. + */ + @Volatile + private var browserAuthenticationRequired = true + init { require(sessionTtlMs > 0) { "sessionTtlMs must be positive" } require(maxAuthenticatedSessions > 0) { "maxAuthenticatedSessions must be positive" } @@ -230,6 +242,26 @@ class SessionAuthority( sessionMetadata.clear() } + /** Configures whether browser requests must present a session credential. */ + fun configureBrowserAuthentication(required: Boolean) { + browserAuthenticationRequired = required + } + + /** True when the browser server must authenticate each request with a minted session. */ + fun isBrowserAuthenticationRequired(): Boolean = browserAuthenticationRequired + + /** + * Stable synthetic identity used only while browser authentication is disabled. It is never + * stored, never counted as an authenticated principal, and carries no usable credential. + */ + fun openAccessSession(): BrowserSession = + BrowserSession( + id = OPEN_ACCESS_SESSION_ID, + token = "", + csrfToken = "", + expiresAtEpochMs = Long.MAX_VALUE, + ) + @Synchronized fun purgeExpired() { val now = nowEpochMs() @@ -307,14 +339,22 @@ class SessionAuthority( @Synchronized fun isAuthorized(token: String): Boolean = - sessions.values.any { session -> - constantTimeEquals(token, session.token) && session.expiresAtEpochMs > nowEpochMs() + if (!browserAuthenticationRequired) { + true + } else { + sessions.values.any { session -> + constantTimeEquals(token, session.token) && session.expiresAtEpochMs > nowEpochMs() + } } @Synchronized fun sessionForToken(token: String): BrowserSession? = - sessions.values.firstOrNull { session -> - constantTimeEquals(token, session.token) && session.expiresAtEpochMs > nowEpochMs() + if (!browserAuthenticationRequired) { + openAccessSession() + } else { + sessions.values.firstOrNull { session -> + constantTimeEquals(token, session.token) && session.expiresAtEpochMs > nowEpochMs() + } } @OptIn(ExperimentalEncodingApi::class) @@ -331,6 +371,7 @@ class SessionAuthority( companion object { const val DEFAULT_SESSION_TTL_MS: Long = 30 * 60 * 1000L const val DEFAULT_MAX_AUTHENTICATED_SESSIONS: Int = 10 + private const val OPEN_ACCESS_SESSION_ID = "open-browser" private const val TOKEN_BYTE_LENGTH = 32 private const val MAX_BROWSER_LABEL_LENGTH = 128 } diff --git a/sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt b/sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt index 92a6740..8896482 100644 --- a/sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt +++ b/sdk/server-api/src/test/kotlin/io/devconsole/server/api/StartRequestDefaultsTest.kt @@ -1,6 +1,7 @@ package io.devconsole.server.api import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue import org.junit.Test class StartRequestDefaultsTest { @@ -8,4 +9,14 @@ class StartRequestDefaultsTest { fun `default server start request uses LAN binding`() { assertEquals(BindingMode.LAN, StartRequest().bindingMode) } + + @Test + fun `default port range prefers 8080 but leaves room to fall forward`() { + // A single-port default makes the second app on a device -- or a restart before the old + // server released the port -- fail with PortUnavailable instead of taking the next port. + val portRange = StartRequest().portRange + + assertEquals(8080, portRange.first) + assertTrue("default range must leave fallback ports", portRange.last > portRange.first) + } } diff --git a/sdk/server-ktor/api/server-ktor.api b/sdk/server-ktor/api/server-ktor.api index 6b53a6e..59355fa 100644 --- a/sdk/server-ktor/api/server-ktor.api +++ b/sdk/server-ktor/api/server-ktor.api @@ -10,6 +10,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun getAttachmentMetadataReader ()Lkotlin/jvm/functions/Function2; public final fun getAttachmentReader ()Lkotlin/jvm/functions/Function2; public final fun getBoundEndpoint ()Lkotlin/jvm/functions/Function0; + public final fun getBrowserSecurity ()Lio/devconsole/api/BrowserSecurity; public final fun getCaptureRules ()Lio/devconsole/api/CaptureRuleEngine; public final fun getCaptureRulesEditable ()Z public final fun getCommandAuditLog ()Lio/devconsole/server/api/CommandAuditLog; @@ -51,6 +52,7 @@ public final class io/devconsole/server/ktor/DevConsoleModuleConfig { public final fun setAttachmentMetadataReader (Lkotlin/jvm/functions/Function2;)V public final fun setAttachmentReader (Lkotlin/jvm/functions/Function2;)V public final fun setBoundEndpoint (Lkotlin/jvm/functions/Function0;)V + public final fun setBrowserSecurity (Lio/devconsole/api/BrowserSecurity;)V public final fun setCaptureRules (Lio/devconsole/api/CaptureRuleEngine;)V public final fun setCaptureRulesEditable (Z)V public final fun setCommandAuditLog (Lio/devconsole/server/api/CommandAuditLog;)V @@ -115,6 +117,7 @@ public final class io/devconsole/server/ktor/KtorLocalServerEngine : io/devconso public fun stop (Lkotlin/coroutines/Continuation;)Ljava/lang/Object; public final fun withAttachmentMetadataReader (Lkotlin/jvm/functions/Function2;)Lio/devconsole/server/ktor/KtorLocalServerEngine; public final fun withAttachmentReader (Lkotlin/jvm/functions/Function2;)Lio/devconsole/server/ktor/KtorLocalServerEngine; + public final fun withBrowserSecurity (Lio/devconsole/api/BrowserSecurity;)Lio/devconsole/server/ktor/KtorLocalServerEngine; public final fun withRetainedCaptures (Lio/devconsole/storage/api/RetainedCaptureQuery;)Lio/devconsole/server/ktor/KtorLocalServerEngine; } diff --git a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt index 0bd529f..b28983d 100644 --- a/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt +++ b/sdk/server-ktor/src/main/kotlin/io/devconsole/server/ktor/DevConsoleKtorModule.kt @@ -1,5 +1,6 @@ package io.devconsole.server.ktor +import io.devconsole.api.BrowserSecurity import io.devconsole.api.CaptureRule import io.devconsole.api.CaptureRuleEngine import io.devconsole.api.ScreenshotResult @@ -184,6 +185,13 @@ import kotlin.time.Duration.Companion.seconds */ class DevConsoleModuleConfig { var allowedHosts: Set = setOf("localhost", "127.0.0.1") + + /** + * Browser authentication policy. The standalone Ktor module keeps its historical secure + * default; the public full SDK explicitly supplies [BrowserSecurity.NONE] by default. + */ + var browserSecurity: BrowserSecurity = BrowserSecurity.SESSION_CODE + var streamHub: EventStreamHub = EventStreamHub() var timeline: Timeline = InMemoryTimeline(emptyList(), CursorCodec(ByteArray(16).also(SecureRandom()::nextBytes))) var annotations: TimelineAnnotations = InMemoryTimelineAnnotations() @@ -312,6 +320,7 @@ fun Application.devConsoleModule( configure: DevConsoleModuleConfig.() -> Unit = {}, ) { val config = DevConsoleModuleConfig().apply(configure) + sessionAuthority.configureBrowserAuthentication(config.browserSecurity == BrowserSecurity.SESSION_CODE) val allowedHosts = config.allowedHosts val streamHub = config.streamHub val timeline = config.timeline @@ -463,11 +472,7 @@ fun Application.devConsoleModule( val path = call.request.uri.substringBefore('?') val method = call.request.httpMethod.value val browserSession = - call.request.headers[HttpHeaders.Authorization] - .orEmpty() - .removePrefix("Bearer ") - .takeIf { it.isNotBlank() } - ?.let { token -> sessionAuthority.sessionForToken(token) } + sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) if (!composerEnabled && path.startsWith("/api/v1/composer")) { browserSession ?.let { session -> @@ -608,8 +613,10 @@ fun Application.devConsoleModule( call.respondBytes(DashboardAssets.favicon(), contentType = io.ktor.http.ContentType("image", "webp")) } get("/health") { + val status = if (sessionAuthority.isBrowserAuthenticationRequired()) "auth_required" else "open" call.respondText( - "{\"status\":\"auth_required\",\"protocolVersion\":${metadata.protocolVersion}," + + "{\"status\":\"$status\"," + + "\"protocolVersion\":${metadata.protocolVersion}," + "\"appDisplayName\":\"${metadata.appDisplayName.escapeJson()}\"}", contentType = io.ktor.http.ContentType.Application.Json, ) @@ -710,9 +717,7 @@ fun Application.devConsoleModule( return@post } val expectedOrigin = "http://${call.request.headers[HttpHeaders.Host].orEmpty()}" - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, "session.code.rotate", "session-code") call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post @@ -730,9 +735,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@post } - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post } @@ -759,9 +762,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@post } - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post } @@ -790,9 +791,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@delete } - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, "session.revoke", principalId.ifBlank { "principal" }) call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@delete @@ -885,9 +884,7 @@ fun Application.devConsoleModule( return@post } val expectedOrigin = "http://${call.request.headers[HttpHeaders.Host].orEmpty()}" - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordExport(session.id, CommandAuditResult.REJECTED, "csrf") call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post @@ -1291,9 +1288,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@post } - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, "mock.disable_all", "mocks") call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post @@ -1560,9 +1555,7 @@ fun Application.devConsoleModule( return@post } val key = call.parameters["key"].orEmpty() - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, "flag.override", key.ifBlank { "flag" }) call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post @@ -2158,9 +2151,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@post } - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, "database.sql.execute", database) call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post @@ -2643,9 +2634,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@post } - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, "composer.import", "curl") call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post @@ -2677,9 +2666,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@post } - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, "composer.collection.save", "collection") call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post @@ -2720,9 +2707,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@delete } - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure( session.id, "composer.collection.delete", @@ -2778,9 +2763,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@post } - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, "push.simulate", "push") call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post @@ -2883,9 +2866,7 @@ fun Application.devConsoleModule( call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@post } - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin || - call.request.headers[CSRF_HEADER] != session.csrfToken - ) { + if (!call.isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure( session.id, "state.mutation", @@ -3350,17 +3331,24 @@ fun Application.devConsoleModule( post("/api/v1/session/stop") { val session = sessionAuthority.bearerSession(call.request.headers[HttpHeaders.Authorization]) val expectedOrigin = "http://${call.request.headers[HttpHeaders.Host].orEmpty()}" + val origin = call.request.headers[HttpHeaders.Origin] val csrf = call.request.headers[CSRF_HEADER] if (session == null) { call.respondText("{\"code\":\"AUTH_REQUIRED\"}", status = HttpStatusCode.Unauthorized) return@post } - if (call.request.headers[HttpHeaders.Origin] != expectedOrigin) { + val originRejected = + if (sessionAuthority.isBrowserAuthenticationRequired()) { + origin != expectedOrigin + } else { + origin != null && origin != expectedOrigin + } + if (originRejected) { commandAuditLog.recordControlFailure(session.id, "session.stop", "server") call.respondText("{\"code\":\"ORIGIN_REJECTED\"}", status = HttpStatusCode.Forbidden) return@post } - if (csrf != session.csrfToken) { + if (sessionAuthority.isBrowserAuthenticationRequired() && csrf != session.csrfToken) { commandAuditLog.recordControlFailure(session.id, "session.stop", "server") call.respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return@post @@ -3388,7 +3376,9 @@ fun Application.devConsoleModule( .removePrefix("Bearer ") .takeIf(String::isNotBlank) ?: call.streamSessionCookie() - if (authorization.isBlank() || !sessionAuthority.isAuthorized(authorization)) { + if (sessionAuthority.isBrowserAuthenticationRequired() && + (authorization.isBlank() || !sessionAuthority.isAuthorized(authorization)) + ) { close(CloseReason(CloseReason.Codes.VIOLATED_POLICY.code, "AUTH_REQUIRED")) return@webSocket } @@ -3409,7 +3399,9 @@ fun Application.devConsoleModule( try { while (isActive) { delay(STREAM_AUTH_RECHECK_MS) - if (!sessionAuthority.isAuthorized(authorization)) { + if (sessionAuthority.isBrowserAuthenticationRequired() && + !sessionAuthority.isAuthorized(authorization) + ) { close(CloseReason(CloseReason.Codes.VIOLATED_POLICY.code, "AUTH_REVOKED")) break } @@ -3499,6 +3491,10 @@ class KtorLocalServerEngine( @Volatile private var currentEndpoint: Endpoint? = null + /** Applied before the next server start; a running Ktor application captures its mode. */ + @Volatile + private var browserSecurity: BrowserSecurity = BrowserSecurity.SESSION_CODE + @Volatile private var attachmentReader: suspend (String) -> ByteArray? = { null } @@ -3513,6 +3509,12 @@ class KtorLocalServerEngine( retainedCaptures = query } + /** Sets the browser authentication policy used by the next server start. */ + fun withBrowserSecurity(value: BrowserSecurity): KtorLocalServerEngine = + apply { + browserSecurity = value + } + @Volatile private var runtimeConfiguration = RuntimeConfiguration( @@ -3573,7 +3575,11 @@ class KtorLocalServerEngine( override suspend fun start(request: StartRequest): ServerStartResult = synchronized(this) { - if (engine != null) return@synchronized ServerStartResult.Failed("Server already running") + // A repeated start from this SDK instance is a restart request. Tear down our own + // listener before probing the preferred port so a stale/running DevConsole server does + // not force its replacement onto a fallback port. An unrelated process that owns 8080 + // is left alone and the normal range scan falls forward to the next available port. + if (engine != null) runCatching { stopLocked() } if ( request.portRange.isEmpty() || request.portRange.first !in 1..65_535 || @@ -3608,6 +3614,7 @@ class KtorLocalServerEngine( if (!isPortAvailable(bindHost, port)) return@forEach val endpoint = Endpoint(bindHost, port, effectiveBinding) val configuration = runtimeConfiguration + val security = browserSecurity val candidate = runCatching { serverScope @@ -3619,6 +3626,7 @@ class KtorLocalServerEngine( ) { devConsoleModule(sessionAuthority, sessionCodeAuthority) { allowedHosts = setOf("localhost", endpoint.host) + browserSecurity = security this.networkTransactions = this@KtorLocalServerEngine.networkTransactions this.socketStore = this@KtorLocalServerEngine.socketStore this.pushStore = this@KtorLocalServerEngine.pushStore @@ -3677,22 +3685,23 @@ class KtorLocalServerEngine( return@synchronized ServerStartResult.PortUnavailable(request.portRange) } - override suspend fun stop() = - synchronized(this) { - // A throwing engine.stop() (e.g. the CIO engine's own shutdown machinery blowing up) - // must not skip the state reset below -- otherwise `engine` is left non-null forever, - // and every subsequent start() permanently answers "Server already running" until the - // process dies. The finally block guarantees the reset runs whether or not stop() threw. - try { - engine?.stop(gracePeriodMillis = 500, timeoutMillis = 1_000) - Unit - } finally { - engine = null - currentEndpoint = null - sessionAuthority.reset() - sessionCodeAuthority.reset() - } + override suspend fun stop() = synchronized(this) { stopLocked() } + + /** Caller must hold this engine's monitor. */ + private fun stopLocked() { + // A throwing engine.stop() (e.g. the CIO engine's own shutdown machinery blowing up) + // must not skip the state reset below -- otherwise `engine` is left non-null forever, + // and every subsequent start() permanently answers "Server already running" until the + // process dies. The finally block guarantees the reset runs whether or not stop() threw. + try { + engine?.stop(gracePeriodMillis = 0, timeoutMillis = 1_000) + } finally { + engine = null + currentEndpoint = null + sessionAuthority.reset() + sessionCodeAuthority.reset() } + } override fun bindAddressChanged(): Boolean = bindAddressChanged(currentEndpoint, selectLanAddress(lanInterfaces())) @@ -4163,11 +4172,32 @@ private const val MAX_TIMELINE_SCAN_PAGES = 200 private val MAX_EVIDENCE_ITEMS_PER_RESPONSE = EvidenceStore.MAX_ITEMS_PER_SESSION private fun SessionAuthority.bearerSession(authorization: String?) = - authorization - .orEmpty() - .removePrefix("Bearer ") - .takeIf { it.isNotBlank() } - ?.let { sessionForToken(it) } + if (!isBrowserAuthenticationRequired()) { + openAccessSession() + } else { + authorization + .orEmpty() + .removePrefix("Bearer ") + .takeIf { it.isNotBlank() } + ?.let { token -> sessionForToken(token) } + } + +private fun io.ktor.server.application.ApplicationCall.isOriginAndCsrfAuthorized( + authority: SessionAuthority, +): Boolean { + val expectedOrigin = "http://${request.headers[HttpHeaders.Host].orEmpty()}" + val origin = request.headers[HttpHeaders.Origin] + return if (!authority.isBrowserAuthenticationRequired()) { + // Open mode removes credentials, not the browser's same-origin boundary. Browsers send an + // Origin on cross-site mutations, so reject a foreign value while keeping curl/CLI clients + // (which normally omit Origin) usable without inventing a replacement secret. + origin == null || origin == expectedOrigin + } else { + authority.bearerSession(request.headers[HttpHeaders.Authorization])?.let { session -> + origin == expectedOrigin && request.headers[CSRF_HEADER] == session.csrfToken + } ?: false + } +} /** * Shared entry gate for every capture-rule mutation route: authenticated bearer session, then origin @@ -4189,7 +4219,7 @@ private suspend fun io.ktor.server.application.ApplicationCall.captureRuleContro return null } val expectedOrigin = "http://${request.headers[HttpHeaders.Host].orEmpty()}" - if (request.headers[HttpHeaders.Origin] != expectedOrigin || request.headers[CSRF_HEADER] != session.csrfToken) { + if (!isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, commandType, target) respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return null @@ -4221,7 +4251,7 @@ private suspend fun io.ktor.server.application.ApplicationCall.mockRuleControlSe return null } val expectedOrigin = "http://${request.headers[HttpHeaders.Host].orEmpty()}" - if (request.headers[HttpHeaders.Origin] != expectedOrigin || request.headers[CSRF_HEADER] != session.csrfToken) { + if (!isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, commandType, target) respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return null @@ -4253,7 +4283,7 @@ private suspend fun io.ktor.server.application.ApplicationCall.preferencesContro return null } val expectedOrigin = "http://${request.headers[HttpHeaders.Host].orEmpty()}" - if (request.headers[HttpHeaders.Origin] != expectedOrigin || request.headers[CSRF_HEADER] != session.csrfToken) { + if (!isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, commandType, target) respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return null @@ -4286,7 +4316,7 @@ private suspend fun io.ktor.server.application.ApplicationCall.filesControlSessi return null } val expectedOrigin = "http://${request.headers[HttpHeaders.Host].orEmpty()}" - if (request.headers[HttpHeaders.Origin] != expectedOrigin || request.headers[CSRF_HEADER] != session.csrfToken) { + if (!isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, commandType, target) respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return null @@ -4320,7 +4350,7 @@ private suspend fun io.ktor.server.application.ApplicationCall.composerExecution return null } val expectedOrigin = "http://${request.headers[HttpHeaders.Host].orEmpty()}" - if (request.headers[HttpHeaders.Origin] != expectedOrigin || request.headers[CSRF_HEADER] != session.csrfToken) { + if (!isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, commandType, target) respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return null @@ -4354,7 +4384,7 @@ private suspend fun io.ktor.server.application.ApplicationCall.evidenceControlSe return null } val expectedOrigin = "http://${request.headers[HttpHeaders.Host].orEmpty()}" - if (request.headers[HttpHeaders.Origin] != expectedOrigin || request.headers[CSRF_HEADER] != session.csrfToken) { + if (!isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordControlFailure(session.id, commandType, target) respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return null @@ -5095,7 +5125,7 @@ private suspend fun io.ktor.server.application.ApplicationCall.authorizeNetworkE return null } val expectedOrigin = "http://${request.headers[HttpHeaders.Host].orEmpty()}" - if (request.headers[HttpHeaders.Origin] != expectedOrigin || request.headers[CSRF_HEADER] != session.csrfToken) { + if (!isOriginAndCsrfAuthorized(sessionAuthority)) { commandAuditLog.recordExport(session.id, CommandAuditResult.REJECTED, "csrf") respondText("{\"code\":\"CSRF_INVALID\"}", status = HttpStatusCode.Forbidden) return null @@ -5484,9 +5514,15 @@ private fun StateValue.json(): String = } private fun io.ktor.server.application.ApplicationCall.isReadMutationAuthorized(authority: SessionAuthority): Boolean { - val session = authority.bearerSession(request.headers[HttpHeaders.Authorization]) ?: return false val expectedOrigin = "http://${request.headers[HttpHeaders.Host].orEmpty()}" - return request.headers[HttpHeaders.Origin] == expectedOrigin && request.headers[CSRF_HEADER] == session.csrfToken + val origin = request.headers[HttpHeaders.Origin] + return if (!authority.isBrowserAuthenticationRequired()) { + origin == null || origin == expectedOrigin + } else { + authority.bearerSession(request.headers[HttpHeaders.Authorization])?.let { session -> + origin == expectedOrigin && request.headers[CSRF_HEADER] == session.csrfToken + } ?: false + } } // ============================================================================================ diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js index 183ead0..114caf5 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js +++ b/sdk/server-ktor/src/main/resources/devconsole-web/dashboard.js @@ -2,8 +2,8 @@ * DevConsole browser dashboard. * * Single external script (CSP: script-src 'self', no 'unsafe-inline') that drives every - * view. All fetch routes, param names, and the session-code exchange flow are the - * functional contract shared with the SDK server — see server-ktor's DevConsoleKtorModule. + * view. All fetch routes, param names, and the open/session-code access flows are the functional + * contract shared with the SDK server — see server-ktor's DevConsoleKtorModule. */ (() => { 'use strict'; @@ -12,6 +12,7 @@ // State // ================================================================ let token = ''; + let openAccess = false; let currentView = 'overview'; let csrf = ''; let paused = true; @@ -225,7 +226,7 @@ // DOM / formatting helpers // ================================================================ const $ = (id) => document.getElementById(id); - const auth = () => ({ Authorization: 'Bearer ' + token }); + const auth = () => (openAccess ? {} : { Authorization: 'Bearer ' + token }); const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const icon = (name, cls) => ``; @@ -2785,6 +2786,7 @@ sessionExpired = true; consecutiveAuthFailures = 0; clearTimeout(streamRetry); + openAccess = false; token = ''; csrf = ''; stream?.close(); @@ -2904,6 +2906,33 @@ el.textContent = text; el.title = title || text; } + function activateBrowserAccess(accessToken, csrfToken, source, isOpen = false) { + openAccess = isOpen; + token = isOpen ? 'open' : accessToken; + csrf = isOpen ? '' : csrfToken; + sessionExpired = false; + consecutiveAuthFailures = 0; + if (source !== 'manual') history.replaceState(null, '', location.pathname); + setStatus(isOpen ? 'Connected (open)' : 'Connected'); + toast(isOpen ? 'Connected to DevConsole.' : 'Connected to DevConsole session.'); + updateControlUi(); + connectStream(); + // `paused` starts true because there is nothing to tail before a session exists. Connecting is + // the moment that stops being true, and a console labelled LIVE / TAILING that quietly tails + // nothing until you notice the toggle is worse than one that never offered to. Paging into + // history still re-pauses (see the cursor check in the timeline load). + setPaused(false); + loadOverview(); + // Prime the mocks/composer capability flags so "Mock this response"/"Resend" aren't dead + // until Mocks/Composer are visited. + loadMockRules(); + loadComposerHostAllowlist(); + refreshHostLine(); + // Prime the evidence cache immediately on connect (not lazily on first Evidence-tray visit) + // so every row's flag button and the rail count are already correct across every view. + loadEvidenceFlags(); + } + async function exchangeSessionCode(code, source) { if (!code) return; setStatus('Connecting…'); @@ -2925,29 +2954,7 @@ return; } const b = await r.json(); - token = b.accessToken; - csrf = b.csrfToken; - sessionExpired = false; - consecutiveAuthFailures = 0; - if (source !== 'manual') history.replaceState(null, '', location.pathname); - setStatus('Connected'); - toast('Connected to DevConsole session.'); - updateControlUi(); - connectStream(); - // `paused` starts true because there is nothing to tail before a session exists. Connecting is - // the moment that stops being true, and a console labelled LIVE / TAILING that quietly tails - // nothing until you notice the toggle is worse than one that never offered to. Paging into - // history still re-pauses (see the cursor check in the timeline load). - setPaused(false); - loadOverview(); - // Prime the mocks/composer capability flags so "Mock this response"/"Resend" aren't dead - // until Mocks/Composer are visited. - loadMockRules(); - loadComposerHostAllowlist(); - refreshHostLine(); - // Prime the evidence cache immediately on connect (not lazily on first Evidence-tray visit) - // so every row's flag button and the rail count are already correct across every view. - loadEvidenceFlags(); + activateBrowserAccess(b.accessToken, b.csrfToken, source); } /** The previous-run-crashed banner, driven by GET /api/v1/runs — `previousRun` is * already "the most recent non-active run" by the time it gets here (see loadOverview). Shown @@ -2980,9 +2987,9 @@ // input, since cardHtml() always renders fieldsHtml before its own buttons/lede order // isn't ours to change (it's shared by every card-grid view, not scoped to Overview). fieldsHtml: ` -

This session is unauthenticated. On the device, open DevConsole → More — it shows the connect QR and an 8-character, single-use code that expires after five minutes. Scan the QR, or paste the code below.

+

This server requires a browser session. On the device, open DevConsole → More — it shows the connect QR and an 8-character, single-use code that expires after five minutes. Scan the QR, or paste the code below.

    -
  • The #code= fragment in that link is the credential — a bare http://host:port/ address alone stays unauthenticated forever.
  • +
  • The #code= fragment in that link is the credential because this server is using SESSION_CODE; a bare http://host:port/ address is not enough.
  • Emulator or firewalled device? Forward the port first: adb forward tcp:8080 tcp:8080 — 8080 is only the first port tried; the server takes the next free one up to 8099, so confirm the exact address on the device's More screen.
  • Logcat deliberately never prints the code — read it from the device screen, not the log.
@@ -5154,14 +5161,13 @@ // probes instead (each endpoint's own `editable` bit, or a reactive 404 for composer). // ================================================================ let sessionPrincipals = []; - // Populated only after an explicit "Rotate code now" — the server never surfaces the live - // session code to an already-authenticated browser any other way, so there is nothing to show - // until the user asks for a fresh one. + // Populated only after an explicit "Rotate code now" in SESSION_CODE mode — the server never + // surfaces the live session code to an already-authenticated browser any other way. let rotatedSessionCode = null; let lastSessionMeta = {}; let lastSessionCapabilities = {}; async function rotateSessionCode() { - if (!hasSession()) return; + if (!hasSession() || openAccess) return; if (!(await openConfirm('Rotate session code?', 'This immediately invalidates the current session code. Any device that has not yet connected with it will need the new one.', 'Rotate code'))) return; const r = await fetch('/api/v1/auth/session-code/rotate', { method: 'POST', headers: controlHeaders() }); @@ -5255,7 +5261,7 @@ ]; const capOnCount = capRows.filter(([, on]) => on).length; $('sessionMetrics').innerHTML = metricsStripHtml([ - { label: 'Browsers', val: String(sessionPrincipals.length + 1), sub: 'incl. this one', tone: 'ink' }, + { label: openAccess ? 'Auth' : 'Browsers', val: openAccess ? 'open' : String(sessionPrincipals.length + 1), sub: openAccess ? 'no session' : 'incl. this one', tone: 'ink' }, { label: 'Capabilities', val: String(capOnCount), sub: 'of ' + capRows.length + ' on', tone: capOnCount ? 'signal' : 'warn' }, { label: 'Build', val: meta.build?.variant || '—', tone: 'ink' }, { label: 'Protocol', val: meta.protocolVersion ? 'v' + meta.protocolVersion : '—', tone: 'muted' }, @@ -5264,12 +5270,14 @@ { icon: 'alert', iconTone: lan ? 'warn' : 'signal', title: lan ? 'This console is reachable on your LAN' : 'This console is bound to the loopback interface', span: 2, lede: lan - ? 'Anyone on this network who has the session code can read every capture in this session, including redacted-but-present metadata. Debug builds only — the SDK refuses to start in release.' + ? (openAccess + ? 'Anyone on this network can read every capture and use the enabled dashboard capabilities. Use LOOPBACK or SESSION_CODE on shared networks. Debug builds only — the SDK refuses to start in release.' + : 'Anyone on this network who has the session code can read every capture in this session, including redacted-but-present metadata. Debug builds only — the SDK refuses to start in release.') : 'Only this device can reach the console — the SDK bound to loopback rather than a LAN-visible address.', rows: [ { k: 'Bound address', v: endpoint ? endpoint.host + ':' + endpoint.port : '—', tone: 'ink', tag: endpoint?.bindingMode || false, tagTone: lan ? 'warn' : 'signal' }, { k: 'Transport', v: 'http + ws, no TLS', tone: 'warn', tag: 'PLAINTEXT', tagTone: 'warn' }, - { k: 'Auth', v: 'rotating session code', tone: 'signal' }, + { k: 'Auth', v: openAccess ? 'open browser access' : 'rotating session code', tone: openAccess ? 'warn' : 'signal', tag: openAccess ? 'OPEN' : false, tagTone: 'warn' }, { k: 'Build type', v: meta.build?.variant || 'unknown', tone: meta.build?.variant === 'debug' ? 'signal' : 'muted', tag: meta.build?.variant === 'debug' ? 'GUARDED' : false, tagTone: 'signal' }, ].concat( rotatedSessionCode @@ -5281,8 +5289,8 @@ : [], ), buttons: [ - { id: 'end-session', label: 'End session', icon: 'trash', kind: 'danger', disabled: !hasSession(), title: hasSession() ? 'End session' : 'Connect this browser first' }, - { id: 'rotate-code', label: 'Rotate code now', icon: 'refresh', disabled: !hasSession(), title: hasSession() ? 'Invalidate the current session code and mint a new one' : 'Connect this browser first' }, + { id: 'end-session', label: openAccess ? 'Stop server' : 'End session', icon: 'trash', kind: 'danger', disabled: !hasSession(), title: hasSession() ? (openAccess ? 'Stop the DevConsole server' : 'End this browser session') : 'Connect this browser first' }, + { id: 'rotate-code', label: 'Rotate code now', icon: 'refresh', disabled: !hasSession() || openAccess, title: openAccess ? 'Session codes are disabled in open mode' : hasSession() ? 'Invalidate the current session code and mint a new one' : 'Connect this browser first' }, ], }, { @@ -5956,7 +5964,7 @@ // Shared control helpers // ================================================================ - const controlHeaders = () => ({ ...auth(), 'X-DevConsole-CSRF': csrf }); + const controlHeaders = () => (openAccess ? {} : { ...auth(), 'X-DevConsole-CSRF': csrf }); const updateControlUi = () => { const enabled = hasSession(); $('composerRun').disabled = !enabled; @@ -7236,6 +7244,22 @@ await exchangeSessionCode(code, 'hash'); } + async function beginBrowserAccess() { + let health = null; + try { + const response = await fetch('/health'); + if (response.ok) health = await response.json(); + } catch (_) { + // Fall through to the legacy code/hash state if the health probe is unavailable. + } + if (health?.status === 'open') { + activateBrowserAccess('', '', 'open', true); + return; + } + if (location.hash.includes('code=')) beginSessionCode(); + else loadOverview(); + } + /** * Populates the topbar host line from real server info — app id/version (overview) and the * bound LAN address (meta) — instead of a hard-coded example string. @@ -7583,16 +7607,10 @@ } }); - // Without a valid `code=` hash there's no token to exchange — on a first-ever load that's - // just the static empty state, but after a successful connect the hash is stripped - // (exchangeSessionCode, source !== 'manual') and the token lives only in the `token` - // variable above, so a plain browser refresh would otherwise land here with no session and - // no way to get one back. Render the "Connect this browser" card (session-code input + - // Connect button, built by renderOverview/loadOverview when hasSession() is false) so the - // user can always paste a fresh code, instead of leaving the static placeholder text in - // index.html as a dead end. - if (location.hash.includes('code=')) beginSessionCode(); - else loadOverview(); + // The health response selects the connection flow. Open mode activates immediately; secure + // mode still accepts the single-use code in the URL fragment, while a plain secure URL keeps + // the existing manual-code empty state. + beginBrowserAccess(); } if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', wireEvents); diff --git a/sdk/server-ktor/src/main/resources/devconsole-web/index.html b/sdk/server-ktor/src/main/resources/devconsole-web/index.html index 94ef5ab..8b203f4 100644 --- a/sdk/server-ktor/src/main/resources/devconsole-web/index.html +++ b/sdk/server-ktor/src/main/resources/devconsole-web/index.html @@ -70,7 +70,7 @@ DevConsole - Not connected — see the device's More screen for the connect QR + Not connected — see the device's More screen for the dashboard URL
Open DevConsole on device → More → scan the QR @@ -151,7 +151,7 @@
-
Not connected yet
Open DevConsole on the device → More → scan the QR, or paste the session code below to inspect this session.
+
Not connected yet
Open the dashboard URL from DevConsole → More. Open mode loads directly; SESSION_CODE mode uses the QR or code shown there.
@@ -189,11 +189,11 @@
Not connected yet
-
The unified event tail appears here once this browser is connected. On the device, open DevConsole → More — it shows the connect QR and an 8-character, single-use code.
+
The unified event tail appears here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.
    -
  • The #code= fragment in that link is the credential — a bare http://host:port/ address alone stays unauthenticated forever.
  • +
  • Open mode accepts the bare http://host:port/ address. In SESSION_CODE mode, the #code= fragment is the credential.
  • Emulator or firewalled device? Forward the port first: adb forward tcp:8080 tcp:8080 — 8080 is only the first port tried; the server takes the next free one up to 8099, so confirm the exact address on the device's More screen.
  • -
  • Scan the QR, or paste the code into Overview — either connects this browser.
  • +
  • Open the URL directly, or scan the QR/paste the code when SESSION_CODE is enabled.
@@ -272,11 +272,11 @@
Not connected yet
-
Captured HTTP transactions appear here once this browser is connected. On the device, open DevConsole → More — it shows the connect QR and an 8-character, single-use code.
+
Captured HTTP transactions appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.
    -
  • The #code= fragment in that link is the credential — a bare http://host:port/ address alone stays unauthenticated forever.
  • +
  • Open mode accepts the bare http://host:port/ address. In SESSION_CODE mode, the #code= fragment is the credential.
  • Emulator or firewalled device? Forward the port first: adb forward tcp:8080 tcp:8080 — 8080 is only the first port tried; the server takes the next free one up to 8099, so confirm the exact address on the device's More screen.
  • -
  • Scan the QR, or paste the code into Overview — either connects this browser.
  • +
  • Open the URL directly, or scan the QR/paste the code when SESSION_CODE is enabled.
@@ -351,11 +351,11 @@
Not connected yet
-
WebSocket connections and frames appear here once this browser is connected. On the device, open DevConsole → More — it shows the connect QR and an 8-character, single-use code.
+
WebSocket connections and frames appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.
    -
  • The #code= fragment in that link is the credential — a bare http://host:port/ address alone stays unauthenticated forever.
  • +
  • Open mode accepts the bare http://host:port/ address. In SESSION_CODE mode, the #code= fragment is the credential.
  • Emulator or firewalled device? Forward the port first: adb forward tcp:8080 tcp:8080 — 8080 is only the first port tried; the server takes the next free one up to 8099, so confirm the exact address on the device's More screen.
  • -
  • Scan the QR, or paste the code into Overview — either connects this browser.
  • +
  • Open the URL directly, or scan the QR/paste the code when SESSION_CODE is enabled.
@@ -398,11 +398,11 @@
Not connected yet
-
Captured push lifecycle events appear here once this browser is connected. On the device, open DevConsole → More — it shows the connect QR and an 8-character, single-use code.
+
Captured push lifecycle events appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.
    -
  • The #code= fragment in that link is the credential — a bare http://host:port/ address alone stays unauthenticated forever.
  • +
  • Open mode accepts the bare http://host:port/ address. In SESSION_CODE mode, the #code= fragment is the credential.
  • Emulator or firewalled device? Forward the port first: adb forward tcp:8080 tcp:8080 — 8080 is only the first port tried; the server takes the next free one up to 8099, so confirm the exact address on the device's More screen.
  • -
  • Scan the QR, or paste the code into Overview — either connects this browser.
  • +
  • Open the URL directly, or scan the QR/paste the code when SESSION_CODE is enabled.
@@ -442,11 +442,11 @@
Not connected yet
-
Crashes and ANRs appear here once this browser is connected. On the device, open DevConsole → More — it shows the connect QR and an 8-character, single-use code.
+
Crashes and ANRs appear here once this browser is connected. On the device, open DevConsole → More — it shows the dashboard URL, and a code only when SESSION_CODE is enabled.
    -
  • The #code= fragment in that link is the credential — a bare http://host:port/ address alone stays unauthenticated forever.
  • +
  • Open mode accepts the bare http://host:port/ address. In SESSION_CODE mode, the #code= fragment is the credential.
  • Emulator or firewalled device? Forward the port first: adb forward tcp:8080 tcp:8080 — 8080 is only the first port tried; the server takes the next free one up to 8099, so confirm the exact address on the device's More screen.
  • -
  • Scan the QR, or paste the code into Overview — either connects this browser.
  • +
  • Open the URL directly, or scan the QR/paste the code when SESSION_CODE is enabled.
diff --git a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt index 0713b60..8ac21b9 100644 --- a/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt +++ b/sdk/server-ktor/src/test/kotlin/io/devconsole/server/ktor/DevConsoleKtorModuleTest.kt @@ -1,5 +1,6 @@ package io.devconsole.server.ktor +import io.devconsole.api.BrowserSecurity import io.devconsole.api.EventEnvelope import io.devconsole.api.EventSeverity import io.devconsole.composer.ComposerExecutor @@ -105,6 +106,53 @@ import kotlin.time.Duration.Companion.seconds import io.ktor.server.websocket.WebSockets as ServerWebSockets class DevConsoleKtorModuleTest { + @Test + fun `open browser mode exposes data and mutations without credentials`() = + testApplication { + application { + devConsoleModule(SessionAuthority()) { + browserSecurity = BrowserSecurity.NONE + } + } + + val health = client.get("/health") { header(HttpHeaders.Host, "localhost") } + val meta = client.get("/api/v1/meta") { header(HttpHeaders.Host, "localhost") } + val mutation = + client.post("/api/v1/mocks/disable-all") { + header(HttpHeaders.Host, "localhost") + } + + assertEquals(HttpStatusCode.OK, health.status) + assertTrue(health.bodyAsText().contains("\"status\":\"open\"")) + assertEquals(HttpStatusCode.OK, meta.status) + assertEquals(HttpStatusCode.OK, mutation.status) + } + + @Test + fun `open browser mode rejects cross-site mutations without requiring credentials`() = + testApplication { + application { + devConsoleModule(SessionAuthority()) { + browserSecurity = BrowserSecurity.NONE + } + } + + val mutation = + client.post("/api/v1/mocks/disable-all") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Origin, "https://attacker.example") + } + val stop = + client.post("/api/v1/session/stop") { + header(HttpHeaders.Host, "localhost") + header(HttpHeaders.Origin, "https://attacker.example") + } + + assertEquals(HttpStatusCode.Forbidden, mutation.status) + assertEquals(HttpStatusCode.Forbidden, stop.status) + assertTrue(stop.bodyAsText().contains("ORIGIN_REJECTED")) + } + @Test fun `unauthenticated health exposes only auth status protocol and display name`() = testApplication { @@ -2519,7 +2567,7 @@ class DevConsoleKtorModuleTest { } @Test - fun `KtorLocalServerEngine prevents double start and handles lifecycle safely`() { + fun `KtorLocalServerEngine replaces its own listener and reclaims the preferred port`() { val authority = SessionAuthority() val engine = KtorLocalServerEngine( @@ -2531,9 +2579,12 @@ class DevConsoleKtorModuleTest { kotlinx.coroutines.runBlocking { val startResult = engine.start(StartRequest(BindingMode.LOOPBACK, 8400..8419)) assertTrue(startResult is ServerStartResult.Started) + startResult as ServerStartResult.Started - val doubleStartResult = engine.start(StartRequest(BindingMode.LOOPBACK, 8400..8419)) - assertTrue(doubleStartResult is ServerStartResult.Failed) + val replacement = engine.start(StartRequest(BindingMode.LOOPBACK, 8400..8419)) + assertTrue(replacement is ServerStartResult.Started) + replacement as ServerStartResult.Started + assertEquals(startResult.endpoint.port, replacement.endpoint.port) engine.stop() diff --git a/sdk/ui-compose/api/ui-compose.api b/sdk/ui-compose/api/ui-compose.api index 8cd66f7..f969d06 100644 --- a/sdk/ui-compose/api/ui-compose.api +++ b/sdk/ui-compose/api/ui-compose.api @@ -210,7 +210,9 @@ public final class io/devconsole/ui/compose/DevConsoleInspectorBridge { public static final field $stable I public static final field INSTANCE Lio/devconsole/ui/compose/DevConsoleInspectorBridge; public final fun install (Lio/devconsole/ui/compose/InspectorDataSource;)V + public final fun notifyServerStateChanged ()V public final fun reset ()V + public final fun serverStateChanges ()Lkotlinx/coroutines/flow/Flow; public final fun source ()Lio/devconsole/ui/compose/InspectorDataSource; } @@ -515,6 +517,18 @@ public final class io/devconsole/ui/compose/InspectorAction$SelectTransactions : public fun toString ()Ljava/lang/String; } +public final class io/devconsole/ui/compose/InspectorAction$ServerStartPermissionResult : io/devconsole/ui/compose/InspectorAction { + public static final field $stable I + public fun (Z)V + public final fun component1 ()Z + public final fun copy (Z)Lio/devconsole/ui/compose/InspectorAction$ServerStartPermissionResult; + public static synthetic fun copy$default (Lio/devconsole/ui/compose/InspectorAction$ServerStartPermissionResult;ZILjava/lang/Object;)Lio/devconsole/ui/compose/InspectorAction$ServerStartPermissionResult; + public fun equals (Ljava/lang/Object;)Z + public final fun getGranted ()Z + public fun hashCode ()I + public fun toString ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorAction$SetCaptureRuleEnabled : io/devconsole/ui/compose/InspectorAction { public static final field $stable I public fun (Ljava/lang/String;Z)V @@ -1326,6 +1340,10 @@ public final class io/devconsole/ui/compose/InspectorRetentionUi { public fun toString ()Ljava/lang/String; } +public abstract interface class io/devconsole/ui/compose/InspectorServerStartPermissionProvider { + public abstract fun serverStartPermission ()Ljava/lang/String; +} + public final class io/devconsole/ui/compose/InspectorSessionUi { public static final field $stable I public fun (Ljava/lang/String;JLjava/lang/String;Ljava/lang/String;JJ)V diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt index 0d56502..d62b7cc 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorAction.kt @@ -15,6 +15,11 @@ sealed interface InspectorAction { */ data object NotificationPermissionGranted : InspectorAction + /** Result of the permission request made before the SDK-owned More-screen Start action. */ + data class ServerStartPermissionResult( + val granted: Boolean, + ) : InspectorAction + data class SelectObserveTab( val tab: ObserveTab, ) : InspectorAction diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt index 6808816..699078c 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorDataSource.kt @@ -2,6 +2,9 @@ package io.devconsole.ui.compose import io.devconsole.api.CaptureCategory import io.devconsole.api.ScreenshotResult +import kotlinx.coroutines.flow.Flow +import kotlinx.coroutines.flow.MutableSharedFlow +import kotlinx.coroutines.flow.asSharedFlow data class InspectorEditingUi( val requestExecution: Boolean = false, @@ -344,12 +347,13 @@ data class InspectorHealthUi( data class InspectorBrowserUi( val binding: String, val endpoint: String?, - /** Authenticated browsers, mirroring the dashboard's Session view; see [InspectorAction.RevokePrincipal]. */ + /** Authenticated browsers, mirroring the dashboard's Session view; open mode has none. */ val principals: List = emptyList(), /** - * Populated while a session code is live (unexpired). [sessionCodeUrl] is the fragment URL a - * browser would open; [sessionCode] is the same 8-character code shown standalone for manual - * entry. Null once the server stops or the code expires with no fallback. + * In open mode, [sessionCodeUrl] is the bare URL and [sessionCode] is empty. In SESSION_CODE + * mode, these are populated while a code is live (unexpired): [sessionCodeUrl] is the fragment + * URL a browser would open and [sessionCode] is the same 8-character code shown standalone for + * manual entry. Null once the server stops or the code expires with no fallback. */ val sessionCodeUrl: String? = null, val sessionCode: String? = null, @@ -691,12 +695,22 @@ object DevConsoleInspectorBridge { @Volatile private var installedSource: InspectorDataSource = UnavailableInspectorDataSource + private val serverStateChanges = MutableSharedFlow(extraBufferCapacity = 1) + fun install(source: InspectorDataSource) { installedSource = source } fun source(): InspectorDataSource = installedSource + /** Emits an immediate refresh signal when the full runtime changes server lifecycle state. */ + fun notifyServerStateChanged() { + serverStateChanges.tryEmit(Unit) + } + + /** Process-local lifecycle signals consumed by SDK-owned inspector ViewModels. */ + fun serverStateChanges(): Flow = serverStateChanges.asSharedFlow() + fun reset() { installedSource = UnavailableInspectorDataSource } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt index 8a4eeaf..0056638 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorMoreScreen.kt @@ -71,7 +71,9 @@ import java.util.Locale private const val EXPORT_ALL_SUBTITLE = "Redacted · all captured traffic (capped at the 500 most recent)" private const val LAN_BINDING = "LAN" +private const val LOCAL_NETWORK_PERMISSION = "android.permission.ACCESS_LOCAL_NETWORK" private const val SERVER_STATE_RUNNING = "Running" +private const val SERVER_STATE_PERMISSION_REQUIRED = "PermissionRequired" private const val ACTIVE_SESSION_STATUS = "ACTIVE" // Byte-size and MS_PER_* constants live in InspectorObserveFormat.kt (formatByteSize/MS_PER_SECOND // etc.) -- this file used to duplicate both; see that file's own doc. @@ -87,6 +89,7 @@ internal fun MoreRoute( viewModel: InspectorViewModel = viewModel(), ) { val state by viewModel.state.collectAsStateWithLifecycle() + val pendingServerStartPermission by viewModel.serverStartPermission.collectAsStateWithLifecycle() val clipboard = LocalClipboardManager.current val snackbarHostState = remember { SnackbarHostState() } val scope = rememberCoroutineScope() @@ -126,6 +129,24 @@ internal fun MoreRoute( snackbarHostState = snackbarHostState, onPermissionResult = { viewModel.dispatch(InspectorAction.NotificationPermissionGranted) }, ) + val legacyPermissionRequired = state.health?.state == SERVER_STATE_PERMISSION_REQUIRED + val serverStartPermission = + pendingServerStartPermission ?: LOCAL_NETWORK_PERMISSION.takeIf { legacyPermissionRequired } + ServerPermissionPromptEffect( + permission = serverStartPermission, + snackbarHostState = snackbarHostState, + onPermissionResult = { granted -> + if (pendingServerStartPermission != null) { + viewModel.dispatch(InspectorAction.ServerStartPermissionResult(granted)) + } else if (granted) { + // Compatibility path for a host/API start that reached PermissionRequired before + // this SDK-owned preflight was installed. + viewModel.dispatch(InspectorAction.SetServerRunning(true)) + } else { + viewModel.dispatch(InspectorAction.Refresh) + } + }, + ) Box(modifier = modifier.fillMaxSize()) { MoreScreen( @@ -434,13 +455,17 @@ private fun MoreUrlCard( running && browser?.bindAddressChanged == true -> StaleAddressUrlCard(state.serverControlSupported, actions, colors) running && browser?.sessionCodeUrl != null && browser.sessionCode != null -> - RunningUrlCard( - browser.sessionCodeUrl, - browser.sessionCode, - browser.sessionCodeRemainingTtlMs, - actions, - colors, - ) + if (browser.sessionCode.isBlank()) { + RunningOpenUrlCard(browser.sessionCodeUrl, actions, colors) + } else { + RunningUrlCard( + browser.sessionCodeUrl, + browser.sessionCode, + browser.sessionCodeRemainingTtlMs, + actions, + colors, + ) + } else -> StoppedUrlCard(state.serverControlSupported, actions, colors) } } @@ -494,6 +519,39 @@ private fun RunningUrlCard( ) } +@Composable +private fun RunningOpenUrlCard( + url: String, + actions: MoreActions, + colors: DevConsoleColors, +) { + InspectorUrlCard( + dotColor = colors.signal, + dotPulsing = true, + label = "Open in a browser", + url = url, + subtitle = "No session code required. Plaintext on your LAN — use SESSION_CODE on shared networks.", + actions = + listOf( + InspectorUrlAction( + "Copy URL", + { actions.onCopyUrl(url) }, + colors.signal, + colors.signalInk, + flex = 1.5f, + icon = { UrlActionCopyIcon(colors.signalInk) }, + ), + InspectorUrlAction( + "QR", + { actions.onShowQr(url) }, + colors.surface3, + colors.ink, + icon = { UrlActionEyeIcon(colors.ink) }, + ), + ), + ) +} + private fun runningUrlCardActions( url: String, code: String, diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorServerStartPermissionProvider.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorServerStartPermissionProvider.kt new file mode 100644 index 0000000..7e74da4 --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorServerStartPermissionProvider.kt @@ -0,0 +1,17 @@ +/** + * Optional server-start permission preflight for the SDK-owned inspector UI. + * + * This stays separate from [InspectorDataSource] so adding the feature does not add a method to a + * long-lived public interface that existing Java or Kotlin host adapters already implement. A + * runtime that needs a permission prompt implements this capability; all other adapters continue + * to start through [InspectorDataSource.setServerRunning] unchanged. + */ +package io.devconsole.ui.compose + +interface InspectorServerStartPermissionProvider { + /** + * Returns the Android runtime permission required before the SDK UI may start the server, or + * `null` when the requested start can proceed immediately. Host/API starts are unaffected. + */ + fun serverStartPermission(): String? +} diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt index bfc28cc..f8c79ab 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/InspectorViewModel.kt @@ -16,6 +16,7 @@ import kotlinx.coroutines.ensureActive import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch @@ -27,6 +28,7 @@ private const val CAPABILITY_FEATURE_FLAGS = "featureFlags" private const val CAPABILITY_PREFERENCES = "preferences" private const val CAPABILITY_FILES = "files" private const val CAPABILITY_CAPTURE_RULES = "captureRules" +private const val NOTIFICATION_PERMISSION = "android.permission.POST_NOTIFICATIONS" /** * Presentation-layer MVI store for the Observe and Control surfaces. Reads go through @@ -48,6 +50,14 @@ class InspectorViewModel private val mutableState = MutableStateFlow(InspectorState()) val state: StateFlow = mutableState.asStateFlow() + /** + * A transient, route-only permission preflight. This intentionally lives outside + * [InspectorState]: it is not persisted snapshot data and adding it to that public data + * class changes its constructor and `copy` JVM ABI for every SDK consumer. + */ + private val mutableServerStartPermission = MutableStateFlow(null) + internal val serverStartPermission: StateFlow = mutableServerStartPermission.asStateFlow() + /** * Tracks the in-flight snapshot fetch so a newer refresh (filter change, mutation, * explicit [InspectorAction.Refresh]) always requests cancellation of an older one still @@ -61,6 +71,9 @@ class InspectorViewModel private var snapshotJob: Job? = null init { + viewModelScope.launch(dispatcher) { + DevConsoleInspectorBridge.serverStateChanges().collect { refreshSnapshot() } + } refreshSnapshot() } @@ -74,6 +87,8 @@ class InspectorViewModel dataSource.onNotificationPermissionGranted() refreshSnapshot() } + is InspectorAction.ServerStartPermissionResult -> + serverStartPermissionResult(action.granted) is InspectorAction.SelectObserveTab -> selectObserveTab(action.tab) is InspectorAction.ToggleTransactionSelection -> toggleTransactionSelection(action.id) is InspectorAction.SelectTransactions -> selectTransactions(action.ids) @@ -580,11 +595,48 @@ class InspectorViewModel /** Ungated, like the exports above: starting/stopping is a device-owner action, not a data capability. */ private fun setServerRunning(running: Boolean) { viewModelScope.launch(dispatcher) { - showComposerResult(dataSource.setServerRunning(running)) - loadSnapshot() + if (running) { + // A fast double-tap while the snackbar/dialog is visible must leave one + // preflight in flight rather than queue duplicate permission requests. + if (mutableServerStartPermission.value != null) return@launch + val permission = + (dataSource as? InspectorServerStartPermissionProvider)?.serverStartPermission() + if (permission != null) { + mutableServerStartPermission.value = permission + return@launch + } + } else { + mutableServerStartPermission.value = null + } + runServerCommand(running) } } + /** + * Continues a preflighted start. Local-network access is required for the requested LAN + * bind, whereas notification permission only affects foreground-notification visibility; + * declining the latter must not make the Start button a dead end. + */ + private fun serverStartPermissionResult(granted: Boolean) { + val permission = mutableServerStartPermission.value ?: return + mutableServerStartPermission.value = null + if (!granted && permission != NOTIFICATION_PERMISSION) { + // Keep the runtime stopped and refresh the explanatory health/browser state. The + // permission prompt owns the separate Settings snackbar for a blocked denial. + refreshSnapshot() + return + } + // Do not ask the adapter to preflight again: the permission result is authoritative + // for this Start attempt, and a notification denial is explicitly allowed through. + viewModelScope.launch(dispatcher) { runServerCommand(running = true) } + } + + /** Performs the adapter call after any required permission preflight has completed. */ + private suspend fun runServerCommand(running: Boolean) { + showComposerResult(dataSource.setServerRunning(running)) + loadSnapshot() + } + /** * The More screen's screenshot capture button. Ungated here, like the exports above: every * [ScreenshotResult] variant (including [ScreenshotResult.Disabled]) is a legitimate, always- diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/KeepAliveNotificationPrompt.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/KeepAliveNotificationPrompt.kt index 2df0d45..8bcf0bf 100644 --- a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/KeepAliveNotificationPrompt.kt +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/KeepAliveNotificationPrompt.kt @@ -24,6 +24,14 @@ import androidx.compose.runtime.LaunchedEffect */ private var keepAlivePromptDismissedThisProcess: Boolean = false +/** + * The SDK-owned server-start flow already offered a notification decision. Do not immediately + * repeat the generic keep-alive prompt once that same Start succeeds without the permission. + */ +internal fun suppressKeepAliveNotificationPromptForThisProcess() { + keepAlivePromptDismissedThisProcess = true +} + /** * Offers the POST_NOTIFICATIONS grant that makes the keep-alive foreground service's notification * visible. Only ever shown when the full adapter's KeepAliveGate said so ([promptNeeded]) -- which @@ -57,7 +65,7 @@ internal fun KeepAliveNotificationPromptEffect( ) when (result) { SnackbarResult.ActionPerformed -> permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS) - SnackbarResult.Dismissed -> keepAlivePromptDismissedThisProcess = true + SnackbarResult.Dismissed -> suppressKeepAliveNotificationPromptForThisProcess() } } } diff --git a/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/LocalNetworkPermissionPrompt.kt b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/LocalNetworkPermissionPrompt.kt new file mode 100644 index 0000000..410d4fc --- /dev/null +++ b/sdk/ui-compose/src/main/kotlin/io/devconsole/ui/compose/LocalNetworkPermissionPrompt.kt @@ -0,0 +1,149 @@ +/** + * @author Shakib + * @since 24/08/26 + */ +package io.devconsole.ui.compose + +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.os.Build +import android.provider.Settings +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.material3.SnackbarDuration +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.SnackbarResult +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.platform.LocalContext +import kotlinx.coroutines.launch + +private const val LOCAL_NETWORK_PERMISSION = "android.permission.ACCESS_LOCAL_NETWORK" +private const val NOTIFICATION_PERMISSION = "android.permission.POST_NOTIFICATIONS" +private const val LOCAL_NETWORK_PERMISSION_API = 37 + +private const val SETTINGS_ACTION_LABEL = "Settings" +private const val NOTIFICATION_VISIBILITY_MESSAGE = + "Server will start, but Android will hide its notification until notifications are allowed." + +/** + * Handles the permission preflight produced by an in-app More-screen server start. The sample apps + * own their start buttons and can request permissions directly; the SDK-owned inspector has to + * provide the same bridge or a start would otherwise race a platform permission prompt. + * + * A denial gets a second snackbar with a Settings action. Android can stop showing the runtime + * dialog after the user blocks a permission, and a plain retry would then look like a broken Start + * button. Opening the app's settings is the only reliable recovery path in that state. + */ +@Composable +@Suppress("FunctionNaming") // Compose entry points are conventionally PascalCase. +internal fun ServerPermissionPromptEffect( + permission: String?, + snackbarHostState: SnackbarHostState, + onPermissionResult: (Boolean) -> Unit, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + var blockedPermission by remember { mutableStateOf(null) } + var activeRequestPermission by remember { mutableStateOf(null) } + val permissionLauncher = + rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + val requestedPermission = activeRequestPermission + activeRequestPermission = null + if (!granted && requestedPermission != null) { + if (requestedPermission == NOTIFICATION_PERMISSION) { + suppressKeepAliveNotificationPromptForThisProcess() + // Notification access affects discoverability of the running foreground + // service, not whether Android may start it. Keep this informational snackbar + // separate from the required-permission Settings recovery below. + scope.launch { + snackbarHostState.showSnackbar(NOTIFICATION_VISIBILITY_MESSAGE) + } + } else { + blockedPermission = requestedPermission + } + } + onPermissionResult(granted) + } + + LaunchedEffect(permission) { + val requestedPermission = permission ?: return@LaunchedEffect + if (requestedPermission == LOCAL_NETWORK_PERMISSION && Build.VERSION.SDK_INT < LOCAL_NETWORK_PERMISSION_API) { + // ACCESS_LOCAL_NETWORK does not exist on earlier Android versions, so a compatibility + // PermissionRequired state must not strand this Start attempt behind a no-op prompt. + onPermissionResult(true) + return@LaunchedEffect + } + blockedPermission = null + activeRequestPermission = requestedPermission + val result = + snackbarHostState.showSnackbar( + message = permissionPromptMessage(requestedPermission), + actionLabel = "Allow", + withDismissAction = true, + duration = SnackbarDuration.Long, + ) + when (result) { + SnackbarResult.ActionPerformed -> permissionLauncher.launch(requestedPermission) + SnackbarResult.Dismissed -> { + activeRequestPermission = null + if (requestedPermission == NOTIFICATION_PERMISSION) { + suppressKeepAliveNotificationPromptForThisProcess() + scope.launch { + snackbarHostState.showSnackbar(NOTIFICATION_VISIBILITY_MESSAGE) + } + } + onPermissionResult(false) + } + } + } + + LaunchedEffect(blockedPermission) { + val blocked = blockedPermission ?: return@LaunchedEffect + val result = + snackbarHostState.showSnackbar( + message = "${permissionLabel(blocked)} is blocked. Enable it in App settings to start the server.", + actionLabel = SETTINGS_ACTION_LABEL, + withDismissAction = true, + duration = SnackbarDuration.Long, + ) + if (result == SnackbarResult.ActionPerformed) openAppSettings(context) + blockedPermission = null + } +} + +private fun permissionPromptMessage(permission: String): String = + when (permission) { + LOCAL_NETWORK_PERMISSION -> "Allow local network access before starting the Dev Console server" + NOTIFICATION_PERMISSION -> "Allow notifications so the server stays visible in the notification shade" + else -> "Allow ${permissionLabel(permission)} before starting the Dev Console server" + } + +private fun permissionLabel(permission: String): String = + when (permission) { + LOCAL_NETWORK_PERMISSION -> "Local network access" + NOTIFICATION_PERMISSION -> "Notifications" + else -> + permission + .substringAfterLast('.') + .replace('_', ' ') + .lowercase() + .replaceFirstChar { it.uppercase() } + } + +private fun openAppSettings(context: Context) { + runCatching { + context.startActivity( + Intent( + Settings.ACTION_APPLICATION_DETAILS_SETTINGS, + Uri.parse("package:${context.packageName}"), + ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), + ) + } +} diff --git a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt index 1db030e..724e291 100644 --- a/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt +++ b/sdk/ui-compose/src/test/kotlin/io/devconsole/ui/compose/InspectorViewModelTest.kt @@ -62,6 +62,128 @@ class InspectorViewModelTest { assertEquals(listOf(newTransaction), viewModel.state.value.transactions) } + @Test + fun `server lifecycle signal refreshes the snapshot without waiting for polling`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = RecordingInspectorDataSource(InspectorSnapshot(available = true)) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + val stoppedSnapshot = + InspectorSnapshot( + available = true, + health = InspectorHealthUi("Stopped", 1, 0, 0), + ) + source.snapshotToReturn = stoppedSnapshot + DevConsoleInspectorBridge.notifyServerStateChanged() + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(stoppedSnapshot.health, viewModel.state.value.health) + } + + @Test + fun `server start waits for the SDK permission preflight`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = PermissionRecordingInspectorDataSource(InspectorSnapshot(available = true)) + source.serverStartPermissionToReturn = "android.permission.ACCESS_LOCAL_NETWORK" + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SetServerRunning(true)) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals("android.permission.ACCESS_LOCAL_NETWORK", viewModel.serverStartPermission.value) + assertEquals(0, source.setServerRunningCallCount) + } + + @Test + fun `granted required server start permission starts without a second preflight`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = PermissionRecordingInspectorDataSource(InspectorSnapshot(available = true)) + source.serverStartPermissionToReturn = "android.permission.ACCESS_LOCAL_NETWORK" + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SetServerRunning(true)) + dispatcher.scheduler.advanceUntilIdle() + viewModel.dispatch(InspectorAction.ServerStartPermissionResult(granted = true)) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, source.setServerRunningCallCount) + assertNull(viewModel.serverStartPermission.value) + } + + @Test + fun `source without a permission capability starts directly`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = RecordingInspectorDataSource(InspectorSnapshot(available = true)) + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SetServerRunning(true)) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, source.setServerRunningCallCount) + assertNull(viewModel.serverStartPermission.value) + } + + @Test + fun `denied required server start permission leaves the server stopped`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = PermissionRecordingInspectorDataSource(InspectorSnapshot(available = true)) + source.serverStartPermissionToReturn = "android.permission.ACCESS_LOCAL_NETWORK" + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SetServerRunning(true)) + dispatcher.scheduler.advanceUntilIdle() + viewModel.dispatch(InspectorAction.ServerStartPermissionResult(granted = false)) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(0, source.setServerRunningCallCount) + assertNull(viewModel.serverStartPermission.value) + } + + @Test + fun `denied notification permission still starts the server`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = PermissionRecordingInspectorDataSource(InspectorSnapshot(available = true)) + source.serverStartPermissionToReturn = "android.permission.POST_NOTIFICATIONS" + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SetServerRunning(true)) + dispatcher.scheduler.advanceUntilIdle() + viewModel.dispatch(InspectorAction.ServerStartPermissionResult(granted = false)) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals(1, source.setServerRunningCallCount) + assertNull(viewModel.serverStartPermission.value) + } + + @Test + fun `repeated start taps keep one permission preflight in flight`() = + runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + val source = PermissionRecordingInspectorDataSource(InspectorSnapshot(available = true)) + source.serverStartPermissionToReturn = "android.permission.ACCESS_LOCAL_NETWORK" + val viewModel = InspectorViewModel(dataSource = source, dispatcher = dispatcher) + dispatcher.scheduler.advanceUntilIdle() + + viewModel.dispatch(InspectorAction.SetServerRunning(true)) + viewModel.dispatch(InspectorAction.SetServerRunning(true)) + dispatcher.scheduler.advanceUntilIdle() + + assertEquals("android.permission.ACCESS_LOCAL_NETWORK", viewModel.serverStartPermission.value) + assertEquals(0, source.setServerRunningCallCount) + } + @Test fun `empty transactions produce an empty state`() = runTest { @@ -1545,7 +1667,7 @@ private fun sampleMockRule() = private fun sampleCaptureRule() = InspectorCaptureRuleUi(id = "capture-rule-1", host = "api.example.test") -private class RecordingInspectorDataSource( +private open class RecordingInspectorDataSource( initialSnapshot: InspectorSnapshot = InspectorSnapshot(), ) : InspectorDataSource { var snapshotToReturn: InspectorSnapshot = initialSnapshot @@ -1628,6 +1750,8 @@ private class RecordingInspectorDataSource( private set var captureScreenshotCallCount = 0 private set + var setServerRunningCallCount = 0 + private set var lastRevokedPrincipalId: String? = null private set var lastExportHarSelection: Set? = null @@ -1665,6 +1789,11 @@ private class RecordingInspectorDataSource( override fun snapshot(): InspectorSnapshot = snapshotToReturn + override fun setServerRunning(running: Boolean): InspectorCommandResult { + setServerRunningCallCount++ + return InspectorCommandResult.Success(summary = if (running) "Starting server" else "Stopping server") + } + override suspend fun flaggedTransactionIds(): Set = flaggedTransactionIdsToReturn override suspend fun flagTransaction(id: String): InspectorCommandResult { @@ -1857,3 +1986,12 @@ private class RecordingInspectorDataSource( return captureScreenshotResult } } + +private class PermissionRecordingInspectorDataSource( + snapshot: InspectorSnapshot, +) : RecordingInspectorDataSource(snapshot), + InspectorServerStartPermissionProvider { + var serverStartPermissionToReturn: String? = null + + override fun serverStartPermission(): String? = serverStartPermissionToReturn +}