diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md index 8b1016fb..ac647775 100644 --- a/.claude/CLAUDE.md +++ b/.claude/CLAUDE.md @@ -45,7 +45,10 @@ the upstream did not design for: bridge output coalescing, GSD. OpenCode is the default agent. - **Every phone event is signed by the identity key** (commands, grants, NIP-42 AUTH, Blossom auth). Session keys only key NIP-44 payloads; they - never sign. + never sign. The one other signer is a browser on the web page: its + commands are signed by a key of its own, which an identity-signed + `web-sign-in` let in, and it may send only what + `bridge_core::browser_may_send` names (`docs/WEB-CLIENT.md`). - **No migrations.** A breaking change to persisted or wire data is reshaped directly, old data skipped tolerantly on load, and the PR says so. @@ -111,7 +114,8 @@ crates kept apart). ./codedeck typecheck # typecheck / clippy only ./codedeck test # tests only ./codedeck e2e # the ignored tests that drive a built agent host - # from Rust: driver protocol, bridge end to end + # from Rust: driver protocol, bridge end to end, + # a browser on the web page ./codedeck ci [PR] # the pull request's checks, and the end of the log # of each failed one (--watch waits for them) @@ -150,8 +154,8 @@ Narrower loops run in the dev container, which keeps its node_modules and the caches between commands: `./codedeck dev cargo test -p `, `./codedeck dev vitest run ` (the agent host's own tests). Tests marked `#[ignore]` need Node and a built agent host; `./codedeck e2e` builds the -bundle and runs the two CI runs (the driver-protocol spawn test and the -bridge end-to-end test). Before a release, the acceptance test runs the real +bundle and runs the two CI runs (the driver-protocol spawn test, and the +bridge end-to-end tests: a phone, and a browser on the web page). Before a release, the acceptance test runs the real phone core against a throwaway bridge with the real OpenCode (MCP changes across restarts, a free model's session resumed across a restart): `./codedeck dev sh -c 'CODEDECK_AGENT_CACHE=/agents cargo test -p bridge-runtime --test acceptance -- --ignored --test-threads 1'`. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 008b25f6..26d4e795 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -207,7 +207,7 @@ jobs: pnpm install --frozen-lockfile pnpm --filter @codedeck/agent-host run build cargo test --locked -p agent-protocol --test agent_host -- --ignored - cargo test --locked -p bridge-runtime --test e2e -- --ignored + cargo test --locked -p bridge-runtime --test e2e --test web_page -- --ignored # The bridge on Windows — what the Windows release archive ships: the crates # the binary is built from, the agent host's tests and bundle, and the same @@ -257,7 +257,7 @@ jobs: run: | cargo test --locked -p protocol -p agent-protocol -p nostr-transport -p bridge-core -p bridge-runtime cargo test --locked -p agent-protocol --test agent_host -- --ignored - cargo test --locked -p bridge-runtime --test e2e -- --ignored + cargo test --locked -p bridge-runtime --test e2e --test web_page -- --ignored # apps/android: Gradle unit tests + Paparazzi screenshot verification # + the UniFFI Kotlin bindings drift check. The crates it watches are diff --git a/Cargo.lock b/Cargo.lock index f029a0eb..dd889409 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -252,6 +252,12 @@ dependencies = [ "windows-link", ] +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64" version = "0.22.1" @@ -437,6 +443,7 @@ dependencies = [ "nix", "nostr", "nostr-transport", + "p256", "portable-pty", "protocol", "qrcode", @@ -692,6 +699,12 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + [[package]] name = "core_detect" version = "1.0.0" @@ -716,6 +729,18 @@ dependencies = [ "libc", ] +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core 0.6.4", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -773,6 +798,16 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "zeroize", +] + [[package]] name = "deranged" version = "0.5.8" @@ -786,6 +821,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ "block-buffer", + "const-oid", "crypto-common", "subtle", ] @@ -807,12 +843,45 @@ version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + [[package]] name = "either" version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "pkcs8", + "rand_core 0.6.4", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "env_filter" version = "0.1.4" @@ -880,6 +949,16 @@ version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "filedescriptor" version = "0.8.3" @@ -981,6 +1060,7 @@ checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" dependencies = [ "typenum", "version_check", + "zeroize", ] [[package]] @@ -1043,6 +1123,17 @@ dependencies = [ "scroll", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core 0.6.4", + "subtle", +] + [[package]] name = "hashbrown" version = "0.15.5" @@ -1607,6 +1698,18 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + [[package]] name = "password-hash" version = "0.5.0" @@ -1640,6 +1743,16 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -1735,6 +1848,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro-crate" version = "3.5.0" @@ -1781,9 +1903,11 @@ dependencies = [ "hex", "miniz_oxide", "nostr", + "p256", "proptest", "serde", "serde_json", + "sha2", "specta", "specta-typescript", "thiserror 1.0.69", @@ -2016,6 +2140,16 @@ dependencies = [ "webpki-roots 1.0.9", ] +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + [[package]] name = "ring" version = "0.17.14" @@ -2178,6 +2312,20 @@ dependencies = [ "sha2", ] +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + [[package]] name = "secp256k1" version = "0.29.1" @@ -2337,6 +2485,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core 0.6.4", +] + [[package]] name = "siphasher" version = "1.0.4" @@ -2413,6 +2571,16 @@ dependencies = [ "specta", ] +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" diff --git a/README.md b/README.md index 5590468a..174ef492 100644 --- a/README.md +++ b/README.md @@ -54,8 +54,9 @@ Pairing is a one-time QR scan; it survives restarts on both ends. - NIP-42 `AUTH` relays, and Tor on both ends (see below) - A direct link on your LAN or VPN: the phone talks to the bridge over its own WebSocket, with the relays as the fallback -- A web page on the same port: the bridge's dashboard in a browser, signed in - from a paired phone instead of a password +- A web page on the same port: drive the sessions from a browser, signed in + from a paired phone instead of a password, every command signed by a key + the browser cannot hand out ([`docs/BRIDGE.md`](docs/BRIDGE.md#web-page)) ## About this fork @@ -249,6 +250,7 @@ the full runbook. - [`docs/DEEPSEEK.md`](docs/DEEPSEEK.md) — the DeepSeek Harness: API key, models and reasoning, gateways, MCP servers and plugins - [`docs/QWEN.md`](docs/QWEN.md) — Qwen Code: install, OpenAI-compatible providers, its home, modes, MCP servers and extensions - [`docs/PI.md`](docs/PI.md) — Pi: install, accounts and providers, its home, the permission gate and its tiers, MCP servers and packages +- [`docs/WEB-CLIENT.md`](docs/WEB-CLIENT.md) — the bridge's web page as a client: the browser's signing key, its stream, what it may send, the threat model - [`docs/AGENT-CANDIDATES.md`](docs/AGENT-CANDIDATES.md) — which agents to add next and how - [`.claude/skills/cut-release/SKILL.md`](.claude/skills/cut-release/SKILL.md) — the release runbook diff --git a/apps/android/app/src/main/java/com/codedeck/plus/ui/screens/MachineWebPage.kt b/apps/android/app/src/main/java/com/codedeck/plus/ui/screens/MachineWebPage.kt index 29fc51d8..e8de181b 100644 --- a/apps/android/app/src/main/java/com/codedeck/plus/ui/screens/MachineWebPage.kt +++ b/apps/android/app/src/main/java/com/codedeck/plus/ui/screens/MachineWebPage.kt @@ -5,8 +5,10 @@ import android.content.ClipData import android.content.pm.PackageManager import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts +import androidx.activity.compose.BackHandler import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -158,6 +160,12 @@ internal fun MachineWebPageGroup(machine: UniffiMachineSummary, onOpenWebSignIn: * Under that, the browsers signed in now ([browsers], null until the bridge * answers), each signed out with [onSignOut] after a confirmation; * [ownNpub] is this phone's identity, which a row does not repeat. + * + * [checking] is a code scanned or typed but not sent yet: the page asks the + * user to compare the certificate fingerprint the bridge pins + * ([fingerprint], lowercase hex) with the one the browser shows, since the + * browser's own warning is the only place a man in the middle shows up. + * [onConfirm] sends it, [onCancel] drops it. */ @Composable fun WebSignInContent( @@ -173,14 +181,22 @@ fun WebSignInContent( now: Long, onSignOut: (UniffiWebBrowser) -> Unit, onBack: () -> Unit, + checking: String?, + fingerprint: String?, + onConfirm: () -> Unit, + onCancel: () -> Unit, ) { var confirming by remember { mutableStateOf(null) } + if (checking != null) { + CertificateCheck(checking, fingerprint, onConfirm, onCancel) + return + } Page(title = "Browsers", onBack = onBack) { if (signIn?.state == UniffiWebSignInState.SIGNED_IN) { EmptyState( icon = Icons.Outlined.Check, title = "Browser signed in", - body = "It opens the dashboard now, and stays signed in for 30 days or until it is signed out.", + body = "It opens the dashboard now. It stays signed in while it is used — 7 days without it, or 30 days in all, end it — or until it is signed out.", action = "Done", onAction = onBack, modifier = Modifier.fillMaxWidth().padding(top = Tokens.Space7), @@ -236,6 +252,48 @@ fun WebSignInContent( } } +/** + * A certificate fingerprint as browsers' certificate viewers write it: + * uppercase hex pairs joined by colons, eight pairs to a line. + */ +internal fun fingerprintLines(hex: String): String = + hex.uppercase().chunked(2).chunked(8).joinToString("\n") { it.joinToString(":") } + +/** + * The step before a code is sent: the certificate the bridge pins, to compare + * with what the browser accepted for the page. A page whose certificate + * differs is served by something else, and signing it in would hand it this + * machine. + */ +@Composable +private fun CertificateCheck(code: String, fingerprint: String?, onConfirm: () -> Unit, onCancel: () -> Unit) { + BackHandler(onBack = onCancel) + Page(title = "Check the page", onBack = onCancel) { + Group( + title = "Certificate SHA-256", + footer = "Your browser warned about this page because the bridge's certificate is its own. " + + "Open the warning's details, or the site information beside the address, and compare its SHA-256 " + + "fingerprint with this one. If they differ, something between you and the bridge serves the page: do not sign it in.", + ) { + GroupBody { + Text( + fingerprint?.let(::fingerprintLines) ?: "The bridge advertised no certificate.", + color = Tokens.Text, + fontFamily = Tokens.FontMono, + fontSize = Tokens.TextMd, + ) + } + } + Group(title = "Code") { + ValueRow(code, mono = true) {} + } + Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(Tokens.Space1)) { + PrimaryButton("They match: sign in", onClick = onConfirm, modifier = Modifier.fillMaxWidth()) + SecondaryButton("Cancel", onClick = onCancel, modifier = Modifier.fillMaxWidth()) + } + } +} + /** "Firefox on Windows" from a User-Agent, as the web page names it, or the string itself. */ internal fun browserName(agent: String): String { if (agent.isBlank()) return "A browser" @@ -271,7 +329,7 @@ private fun ago(ms: Long, now: Long): String { /** The browsers signed in to the page now, each with where it is, when it was last seen, and Sign out. */ @Composable private fun SignedInBrowsers(browsers: List?, ownNpub: String, now: Long, onSignOut: (UniffiWebBrowser) -> Unit) { - Group(title = "Signed in", footer = "A browser stays signed in for 30 days after its sign-in.") { + Group(title = "Signed in", footer = "A browser stays signed in while it is used: 7 days without it, or 30 days after its sign-in, end it.") { when { browsers == null -> ValueRow("Asking the bridge") { RowSpinner() } browsers.isEmpty() -> ValueRow("No browser is signed in") {} @@ -311,6 +369,9 @@ fun WebSignInScreen(core: CoreHost, pubkey: String, onBack: () -> Unit) { var scanOpen by remember { mutableStateOf(false) } // Each send waits for its own answer, a resend of the same code too. var attempt by remember { mutableIntStateOf(0) } + // A code scanned or typed waits here until the user has compared the + // certificate the browser accepted with the one this machine pins. + var checking by rememberSaveable { mutableStateOf(null) } fun send(sent: String) { notice = null @@ -344,7 +405,7 @@ fun WebSignInScreen(core: CoreHost, pubkey: String, onBack: () -> Unit) { notice = notice, code = code, onCodeChange = { code = it }, - onSend = ::send, + onSend = { checking = it }, onScan = { if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) { scanOpen = true @@ -357,6 +418,13 @@ fun WebSignInScreen(core: CoreHost, pubkey: String, onBack: () -> Unit) { now = System.currentTimeMillis(), onSignOut = { b -> scope.launch { core.dispatch(UniffiIntent.SignOutWebBrowser(pubkey, b.id)) } }, onBack = onBack, + checking = checking, + fingerprint = machine.directCertSha256, + onConfirm = { + checking?.let(::send) + checking = null + }, + onCancel = { checking = null }, ) if (scanOpen) { PairingScanView( @@ -366,7 +434,7 @@ fun WebSignInScreen(core: CoreHost, pubkey: String, onBack: () -> Unit) { when (val scanned = readSignInQr(text, machine.npub)) { is ScannedSignIn.Code -> { code = scanned.code - send(scanned.code) + checking = scanned.code } ScannedSignIn.OtherMachine -> notice = "That QR is another machine's web page, not this one's." ScannedSignIn.NotSignIn -> notice = "That is not a web page's sign-in QR." diff --git a/apps/android/app/src/main/java/uniffi/client_ffi/client_ffi.kt b/apps/android/app/src/main/java/uniffi/client_ffi/client_ffi.kt index 7b5b982b..8658f662 100644 --- a/apps/android/app/src/main/java/uniffi/client_ffi/client_ffi.kt +++ b/apps/android/app/src/main/java/uniffi/client_ffi/client_ffi.kt @@ -6333,6 +6333,13 @@ data class UniffiMachineSummary ( */ var `directPinned`: kotlin.Boolean , + /** + * The SHA-256 of the certificate the bridge's `wss://` listener serves + * (lowercase hex), as its signed heartbeat pins it: what a browser + * opening the web page must be shown, checked before a sign-in. + */ + var `directCertSha256`: kotlin.String? + , /** * The direct endpoints the user added, tried after the advertised ones. */ @@ -6414,6 +6421,7 @@ public object FfiConverterTypeUniffiMachineSummary: FfiConverterRustBuffer Unit> = linkedMapOf( "web_sign_in_sending" to { WebSignIn(UniffiWebSignIn("K7QM-4XTR", UniffiWebSignInState.SENDING), code = "K7QM-4XTR") }, "web_sign_in_not_matched" to { WebSignIn(UniffiWebSignIn("K7QM-4XTR", UniffiWebSignInState.NOT_MATCHED), code = "K7QM-4XTR") }, "web_sign_in_signed_in" to { WebSignIn(UniffiWebSignIn("K7QM-4XTR", UniffiWebSignInState.SIGNED_IN), code = "K7QM-4XTR") }, + "web_sign_in_check_certificate" to { WebSignIn(signIn = null, code = "K7QM-4XTR", checking = "K7QM-4XTR") }, "settings_agent_opencode" to { AgentPage("opencode") }, "settings_agent_claude" to { AgentPage("claude-code") }, "settings_agent_not_installed" to { AgentPage("deepseek-harness") }, @@ -482,9 +483,10 @@ private fun AgentPage(agent: String) = AgentSettingsContent( /** Signing a browser in to the workstation's web page. */ @Composable -private fun WebSignIn(signIn: UniffiWebSignIn?, code: String, browsers: List? = signedInBrowsers) = WebSignInContent( +private fun WebSignIn(signIn: UniffiWebSignIn?, code: String, browsers: List? = signedInBrowsers, checking: String? = null) = WebSignInContent( signIn = signIn, noAnswer = false, notice = null, code = code, onCodeChange = {}, onSend = {}, onScan = {}, browsers = browsers, ownNpub = workstation.npub, now = NOW, onSignOut = {}, onBack = {}, + checking = checking, fingerprint = workstation.directCertSha256, onConfirm = {}, onCancel = {}, ) /** Two browsers on the workstation's page: one this identity signed in, one another identity did. */ @@ -575,6 +577,7 @@ class DesignSnapshotTest { @Test fun web_sign_in_sending() = paparazzi.page("web_sign_in_sending") @Test fun web_sign_in_not_matched() = paparazzi.page("web_sign_in_not_matched") @Test fun web_sign_in_signed_in() = paparazzi.page("web_sign_in_signed_in") + @Test fun web_sign_in_check_certificate() = paparazzi.page("web_sign_in_check_certificate") @Test fun settings_agent_opencode() = paparazzi.page("settings_agent_opencode") @Test fun settings_agent_claude() = paparazzi.page("settings_agent_claude") @Test fun settings_agent_not_installed() = paparazzi.page("settings_agent_not_installed") diff --git a/apps/android/app/src/test/java/com/codedeck/plus/ui/screens/WebSignInTest.kt b/apps/android/app/src/test/java/com/codedeck/plus/ui/screens/WebSignInTest.kt index 5a37ace7..fa3e597a 100644 --- a/apps/android/app/src/test/java/com/codedeck/plus/ui/screens/WebSignInTest.kt +++ b/apps/android/app/src/test/java/com/codedeck/plus/ui/screens/WebSignInTest.kt @@ -26,4 +26,13 @@ class WebSignInTest { assertEquals(ScannedSignIn.NotSignIn, readSignInQr("codedeck://pair?npub=$npub&token=x", npub)) assertEquals(ScannedSignIn.NotSignIn, readSignInQr("codedeck://web-sign-in?machine=$npub&code=", npub)) } + + @Test + fun the_fingerprint_reads_as_a_browsers_certificate_viewer_writes_it() { + val pin = "3f9a1c0e7b2d4a58c6e1f0b9d8a7c6e5f4d3c2b1a09f8e7d6c5b4a3928170615" + assertEquals( + "3F:9A:1C:0E:7B:2D:4A:58\nC6:E1:F0:B9:D8:A7:C6:E5\nF4:D3:C2:B1:A0:9F:8E:7D\n6C:5B:4A:39:28:17:06:15", + fingerprintLines(pin), + ) + } } diff --git a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignFullPageSnapshotTest_web_sign_in.png b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignFullPageSnapshotTest_web_sign_in.png index 68978664..2e9d1ae5 100644 Binary files a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignFullPageSnapshotTest_web_sign_in.png and b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignFullPageSnapshotTest_web_sign_in.png differ diff --git a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in.png b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in.png index 30b4fc82..45ffcad7 100644 Binary files a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in.png and b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in.png differ diff --git a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_asking.png b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_asking.png index f1122d3f..d09bb401 100644 Binary files a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_asking.png and b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_asking.png differ diff --git a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_check_certificate.png b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_check_certificate.png new file mode 100644 index 00000000..468a2545 Binary files /dev/null and b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_check_certificate.png differ diff --git a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_none.png b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_none.png index 9f5501b3..9c1245a5 100644 Binary files a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_none.png and b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_none.png differ diff --git a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_sending.png b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_sending.png index a44778be..20a43f7d 100644 Binary files a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_sending.png and b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_sending.png differ diff --git a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_signed_in.png b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_signed_in.png index 0316fa81..ad6eab90 100644 Binary files a/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_signed_in.png and b/apps/android/app/src/test/snapshots/images/com.codedeck.plus.ui_DesignSnapshotTest_web_sign_in_signed_in.png differ diff --git a/codedeck b/codedeck index bfcfb1a2..9652a0b4 100755 --- a/codedeck +++ b/codedeck @@ -913,7 +913,7 @@ cmd_e2e() { step "driver protocol" ${run[@]+"${run[@]}"} \ cargo test --locked -p agent-protocol --test agent_host -- --ignored || true step "bridge end to end" ${run[@]+"${run[@]}"} \ - cargo test --locked -p bridge-runtime --test e2e -- --ignored || true + cargo test --locked -p bridge-runtime --test e2e --test web_page -- --ignored || true fi check_summary } diff --git a/crates/bridge-core/src/engine/mod.rs b/crates/bridge-core/src/engine/mod.rs index 919120ff..5b95fa67 100644 --- a/crates/bridge-core/src/engine/mod.rs +++ b/crates/bridge-core/src/engine/mod.rs @@ -27,7 +27,7 @@ mod permission_rules; mod phone; mod session_keys; pub use session_keys::MAX_CLIENTS; -pub use web::MAX_WEB_SIGN_IN_CODES; +pub use web::{browser_may_send, MAX_WEB_SIGN_IN_CODES}; mod settings; mod terminal; pub use terminal::{TerminalAllowlist, TerminalAuditRecord, TerminalAuditWhat, TerminalConfig, PendingDevice}; @@ -177,6 +177,9 @@ pub struct Engine { pairing_epoch: u64, /// The sign-in codes the web page is showing. web_sign_ins: web::WebSignIns, + /// The web page's browsers with a stream open: clients of the + /// identities that let them in. + browsers: web::Browsers, nacks: NackBudget, started: bool, stopped: bool, @@ -239,6 +242,7 @@ impl Engine { terminals, pairing: None, web_sign_ins: web::WebSignIns::default(), + browsers: web::Browsers::new(), pairing_epoch: 0, nacks: NackBudget::default(), started: false, @@ -288,6 +292,9 @@ impl Engine { Input::Shutdown => self.shutdown(), Input::WebSignInPending { code, expires_ms } => self.on_web_sign_in_pending(code, expires_ms), Input::WebSignInWithdrawn { code } => self.on_web_sign_in_withdrawn(&code), + Input::WebBrowserOnline { id, by } => self.on_web_browser_online(id, &by), + Input::WebBrowserOffline { id } => self.on_web_browser_offline(&id), + Input::WebCommand { id, by, msg } => self.on_web_command(id, &by, *msg), } self.requester = None; self.flush(); diff --git a/crates/bridge-core/src/engine/pairing.rs b/crates/bridge-core/src/engine/pairing.rs index 05e7be66..93ef1584 100644 --- a/crates/bridge-core/src/engine/pairing.rs +++ b/crates/bridge-core/src/engine/pairing.rs @@ -129,13 +129,12 @@ impl Engine { /// machine's terminals are not left running for a phone that is no longer /// paired. pub(super) fn unpair(&mut self, identity: &str) { - let before = self.paired.len(); + let Some(npub) = self.paired.iter().find(|p| p.pubkey_hex == identity).map(|p| p.npub.clone()) else { return }; self.paired.retain(|p| p.pubkey_hex != identity); - if self.paired.len() == before { - return; - } log::info!("[Engine] Unpaired {}...", identity.get(..8).unwrap_or(identity)); self.close_identity_terminals(identity, TerminalEndReason::Killed); + // The browsers it let in on the web page were its; they end too. + self.end_identity_browsers(identity, &npub); self.store_paired(); // Nothing from that author is heard any more, and every other phone's // list changed. diff --git a/crates/bridge-core/src/engine/phone.rs b/crates/bridge-core/src/engine/phone.rs index c5f09cbf..98f59437 100644 --- a/crates/bridge-core/src/engine/phone.rs +++ b/crates/bridge-core/src/engine/phone.rs @@ -6,7 +6,7 @@ use protocol::commands::{ PluginActionMsg, QuestionAnswer, QuestionResponseMsg, SetOptionMsg, UploadFileMsg, }; use protocol::common::{ - is_valid_provider_base_url, AgentAction, AgentStyle, EntryBody, Role, SessionOption, PROVIDER_BASE_URL_ERROR, + TerminalVia, is_valid_provider_base_url, AgentAction, AgentStyle, EntryBody, Role, SessionOption, PROVIDER_BASE_URL_ERROR, }; use protocol::events::{ AgentAckMsg, BridgeToPhone, CloseSessionAckMsg, FolderAckMsg, InputAckMsg, InputFailedMsg, @@ -131,14 +131,16 @@ impl Engine { self.grant_session_key(&event.pubkey, m.session_key, &key); } PhoneToBridge::Presence(_) => {} - msg => self.dispatch(msg, &event.pubkey, via), + msg => self.dispatch(msg, &event.pubkey, super::terminal::via_of(via)), } self.requester = None; } } } - fn dispatch(&mut self, msg: PhoneToBridge, phone: &str, via: Via) { + /// Run one command of `phone` (an identity, hex). `via` is the way it + /// came, which only the terminal keeps, for its audit. + pub(super) fn dispatch(&mut self, msg: PhoneToBridge, phone: &str, via: TerminalVia) { match msg { PhoneToBridge::Input(m) => self.on_input(m), PhoneToBridge::PermissionResponse(m) => self.on_permission_response(m), @@ -200,12 +202,12 @@ impl Engine { } // Terminals: the engine decides, the runtime runs their shells // (see the `terminal` module). - PhoneToBridge::TerminalOpen(m) => self.on_terminal_open(m, super::terminal::via_of(via)), - PhoneToBridge::TerminalInput(m) => self.on_terminal_input(m, super::terminal::via_of(via)), - PhoneToBridge::TerminalResize(m) => self.on_terminal_resize(m, super::terminal::via_of(via)), - PhoneToBridge::TerminalReplay(m) => self.on_terminal_replay(m, super::terminal::via_of(via)), - PhoneToBridge::TerminalTakeover(m) => self.on_terminal_takeover(m, super::terminal::via_of(via)), - PhoneToBridge::TerminalClose(m) => self.on_terminal_close(m, super::terminal::via_of(via)), + PhoneToBridge::TerminalOpen(m) => self.on_terminal_open(m, via), + PhoneToBridge::TerminalInput(m) => self.on_terminal_input(m, via), + PhoneToBridge::TerminalResize(m) => self.on_terminal_resize(m, via), + PhoneToBridge::TerminalReplay(m) => self.on_terminal_replay(m, via), + PhoneToBridge::TerminalTakeover(m) => self.on_terminal_takeover(m, via), + PhoneToBridge::TerminalClose(m) => self.on_terminal_close(m, via), PhoneToBridge::WebSignIn(m) => self.on_web_sign_in(&m.code, phone), PhoneToBridge::WebBrowsersRequest(_) => self.on_web_browsers_request(), PhoneToBridge::WebBrowserSignOut(m) => self.on_web_browser_sign_out(m.id), diff --git a/crates/bridge-core/src/engine/session_keys.rs b/crates/bridge-core/src/engine/session_keys.rs index 1dc063c5..b3a96013 100644 --- a/crates/bridge-core/src/engine/session_keys.rs +++ b/crates/bridge-core/src/engine/session_keys.rs @@ -300,7 +300,7 @@ impl Engine { /// shows are complete instead of waiting for the entry that completes /// each part. A part that outgrew the cap has nothing to send, and a /// session with no live parts nothing either. - fn catch_up_live_text(&mut self, identity: &str, client_key: &str, session_id: &str) { + pub(super) fn catch_up_live_text(&mut self, identity: &str, client_key: &str, session_id: &str) { let Some(run) = self.sessions.get(session_id).and_then(|s| s.run.as_ref()) else { return }; let messages: Vec = run .parts @@ -406,7 +406,12 @@ impl Engine { Stream::Terminal(term) => self.copy_keys_watching_terminal(&a.phone, now, term), Stream::Everyone => self.copy_keys(&a.phone, now), }; - keys.into_iter().map(|key| Addressee { phone: a.phone.clone(), key }).collect() + let mut copies: Vec = + keys.into_iter().map(|key| Addressee { phone: a.phone.clone(), key }).collect(); + // The identity's browsers on the web page are its + // clients too. + copies.extend(self.browser_copies(&a.phone, message)); + copies } else { vec![a.clone()] } diff --git a/crates/bridge-core/src/engine/web.rs b/crates/bridge-core/src/engine/web.rs index 684b3e3f..0f3742f8 100644 --- a/crates/bridge-core/src/engine/web.rs +++ b/crates/bridge-core/src/engine/web.rs @@ -7,12 +7,84 @@ //! ([`Effect::WebSignedIn`]). A code works once, and only until it lapses: //! anyone who reads it off the screen still needs a paired phone to use it. -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; +use protocol::commands::PhoneToBridge; +use protocol::common::TerminalVia; use protocol::events::{BridgeToPhone, WebSignInResultMsg}; use super::Engine; -use crate::io::Effect; +use crate::io::{Addressee, Effect, WatchState}; + +/// Whether a browser may send `msg`. A browser drives sessions and reads; +/// what belongs to an identity (its keys, letting in another browser, +/// pairing), what moves a secret or a sign-in, the terminal (whose allowlist +/// names devices, and a browser is none), uploads and the agents' +/// configuration stay with the phone. Every command is named, so a new one +/// is decided here rather than let through by default. +pub fn browser_may_send(msg: &PhoneToBridge) -> bool { + match msg { + PhoneToBridge::Input(_) + | PhoneToBridge::PermissionResponse(_) + | PhoneToBridge::QuestionResponse(_) + | PhoneToBridge::PlanResponse(_) + | PhoneToBridge::SetOption(_) + | PhoneToBridge::SyncRequest(_) + | PhoneToBridge::SyncAck(_) + | PhoneToBridge::CreateSession(_) + | PhoneToBridge::RefreshSessions(_) + | PhoneToBridge::CloseSession(_) + | PhoneToBridge::Interrupt(_) + | PhoneToBridge::StopTask(_) + | PhoneToBridge::CreateFolder(_) + | PhoneToBridge::Presence(_) + | PhoneToBridge::UsageRequest(_) + | PhoneToBridge::ModelsRequest(_) + | PhoneToBridge::AgentStyleRequest(_) + | PhoneToBridge::CommandsRequest(_) + | PhoneToBridge::PersonasRequest(_) + | PhoneToBridge::PluginsRequest(_) + | PhoneToBridge::McpRequest(_) + | PhoneToBridge::SessionMcpRequest(_) + | PhoneToBridge::PermissionRulesRequest(_) + | PhoneToBridge::AccountsRequest(_) + | PhoneToBridge::ProviderProfilesRequest(_) + | PhoneToBridge::WebBrowsersRequest(_) + | PhoneToBridge::WebBrowserSignOut(_) => true, + PhoneToBridge::SessionKey(_) + | PhoneToBridge::PairRequest(_) + | PhoneToBridge::WebSignIn(_) + | PhoneToBridge::SetCredentials(_) + | PhoneToBridge::SetProviderProfile(_) + | PhoneToBridge::AccountAction(_) + | PhoneToBridge::TerminalOpen(_) + | PhoneToBridge::TerminalInput(_) + | PhoneToBridge::TerminalResize(_) + | PhoneToBridge::TerminalReplay(_) + | PhoneToBridge::TerminalTakeover(_) + | PhoneToBridge::TerminalClose(_) + | PhoneToBridge::UploadFile(_) + | PhoneToBridge::PluginAction(_) + | PhoneToBridge::McpAction(_) + | PhoneToBridge::AgentAction(_) + | PhoneToBridge::SessionMcpToggle(_) + | PhoneToBridge::PermissionRulesRemove(_) => false, + } +} + +/// A browser with a stream open: a present client of the identity that let +/// it in. One whose streams all closed is not kept — it gets nothing until it +/// opens one, and says again what it watches. +#[derive(Debug)] +pub(super) struct BrowserClient { + /// The identity that let it in (hex). + identity: String, + /// Which session's live text it wants. + watch: WatchState, +} + +/// The browsers with a stream open, by their public id. +pub(super) type Browsers = BTreeMap; /// Codes the page is showing at once; the soonest to lapse goes first past /// it. The page caps its own pending sign-ins at this too, and withdraws a @@ -89,6 +161,91 @@ impl Engine { self.out.push(Effect::WebBrowserSignOut { id, client }); } } + + /// The paired identity whose npub is `by`, as hex. + fn identity_of_npub(&self, by: &str) -> Option { + self.paired.iter().find(|p| p.npub == by).map(|p| p.pubkey_hex.clone()) + } + + /// A browser that `by` let in opened its first stream. An identity that + /// is no longer paired lets nothing in: its browsers are ended. + pub(super) fn on_web_browser_online(&mut self, id: String, by: &str) { + let Some(identity) = self.identity_of_npub(by) else { + self.out.push(Effect::WebEndBrowsers { by: by.to_string() }); + return; + }; + self.browser_present(&id, &identity); + } + + /// `id` is a present client of `identity`; one that was not gets a + /// heartbeat of its own, as a phone's client back from away does. + fn browser_present(&mut self, id: &str, identity: &str) { + if self.browsers.contains_key(id) { + return; + } + log::info!("[Engine] A browser of {}... is online", identity.get(..8).unwrap_or(identity)); + self.want_list(Addressee::browser(identity, id)); + self.browsers.insert(id.to_string(), BrowserClient { identity: identity.to_string(), watch: WatchState::Unknown }); + } + + pub(super) fn on_web_browser_offline(&mut self, id: &str) { + self.browsers.remove(id); + } + + /// A command from browser `id`, whose signature the runtime checked. + /// It runs as its identity's — the reply goes to the browser alone — + /// unless the identity is no longer paired or the command is one a + /// browser may not send ([`browser_may_send`]). + pub(super) fn on_web_command(&mut self, id: String, by: &str, msg: PhoneToBridge) { + let Some(identity) = self.identity_of_npub(by) else { + log::info!("[Engine] Ignoring a browser command: the identity that let it in is not paired"); + self.out.push(Effect::WebEndBrowsers { by: by.to_string() }); + return; + }; + if !browser_may_send(&msg) { + log::info!("[Engine] Ignoring a command a browser may not send"); + return; + } + self.browser_present(&id, &identity); + let client = Addressee::browser(&identity, &id); + if let PhoneToBridge::Presence(m) = &msg { + let next = WatchState::Watching(if m.away { None } else { m.watching.clone() }); + let Some(browser) = self.browsers.get_mut(&id) else { return }; + if browser.watch != next { + browser.watch = next.clone(); + // A browser that starts watching a session is caught up on + // its live parts at once, as a phone's client is. + if let WatchState::Watching(Some(session)) = next { + self.catch_up_live_text(&identity, &client.key, &session); + } + } + return; + } + self.requester = Some(client); + self.dispatch(msg, &identity, TerminalVia::Unknown); + } + + /// The browsers of `identity` a copy of `message` goes to: every one + /// with a stream open, narrowed to those watching the session for live + /// text. Never a terminal's output — a browser opens no terminal. + pub(super) fn browser_copies(&self, identity: &str, message: &BridgeToPhone) -> Vec { + self.browsers + .iter() + .filter(|(_, b)| b.identity == identity) + .filter(|(_, b)| match message { + BridgeToPhone::Partial(m) => b.watch.wants(&m.session_id), + BridgeToPhone::TerminalOutput(_) => false, + _ => true, + }) + .map(|(id, _)| Addressee::browser(identity, id)) + .collect() + } + + /// `identity` was unpaired: the browsers it let in go with it. + pub(super) fn end_identity_browsers(&mut self, identity: &str, npub: &str) { + self.browsers.retain(|_, b| b.identity != identity); + self.out.push(Effect::WebEndBrowsers { by: npub.to_string() }); + } } #[cfg(test)] diff --git a/crates/bridge-core/src/io.rs b/crates/bridge-core/src/io.rs index 1787ec1e..beb613dd 100644 --- a/crates/bridge-core/src/io.rs +++ b/crates/bridge-core/src/io.rs @@ -7,7 +7,7 @@ //! runtime did not provide — the same inputs always give the same effects. use agent_protocol::{BridgeFrame, HostFrame}; -use protocol::commands::UploadFileMsg; +use protocol::commands::{PhoneToBridge, UploadFileMsg}; use protocol::common::TerminalEndReason; use protocol::events::BridgeToPhone; use serde::{Deserialize, Serialize}; @@ -171,15 +171,32 @@ pub struct Addressee { /// session key, or the identity when it has granted none. The copy's /// recipient tag is derived from it (`protocol::recipients`). Inside the /// engine only, an empty key stands for every present client of the - /// identity, until it is addressed. + /// identity, until it is addressed. For a browser on the web page, see + /// [`Addressee::browser`]. pub key: String, } +/// What a browser's [`Addressee::key`] starts with. A Nostr key is 64 hex +/// characters, so no client key can be mistaken for one. +const BROWSER_KEY_PREFIX: &str = "web:"; + impl Addressee { /// Every present client of `phone`. pub(crate) fn identity(phone: &str) -> Self { Self { phone: phone.to_string(), key: String::new() } } + + /// The web page's browser `id`, signed in by `identity`: a client of + /// that identity whose copies are neither encrypted nor signed — the + /// runtime writes them to the browser's stream, over TLS. + pub fn browser(identity: &str, id: &str) -> Self { + Self { phone: identity.to_string(), key: format!("{BROWSER_KEY_PREFIX}{id}") } + } + + /// The browser this copy is for, if it is for one. + pub fn browser_id(&self) -> Option<&str> { + self.key.strip_prefix(BROWSER_KEY_PREFIX) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -259,6 +276,15 @@ pub enum Input { /// dropped to make room, before a phone sent it. A phone sending it now /// would be told a browser was let in that is no longer there. WebSignInWithdrawn { code: String }, + /// A signed-in browser opened its first stream: it is a present client + /// of the identity `by` (an npub) that let it in, and gets a heartbeat. + WebBrowserOnline { id: String, by: String }, + /// A browser's last stream closed: it gets nothing until it opens one. + WebBrowserOffline { id: String }, + /// A command from a browser, its signature already checked by the + /// runtime against the key the browser signed in with. `by` is the npub + /// of the identity that let it in. + WebCommand { id: String, by: String, msg: Box }, } #[derive(Debug)] @@ -336,6 +362,9 @@ pub enum Effect { /// with the fresh list, so an id that matches nothing is still answered /// with the truth rather than silence. WebBrowserSignOut { id: String, client: Addressee }, + /// The identity `by` (an npub) is no longer paired: every browser it let + /// in is signed out, and its streams closed. + WebEndBrowsers { by: String }, } /// Well-known [`Store`](crate::ports::Store) keys. diff --git a/crates/bridge-core/src/lib.rs b/crates/bridge-core/src/lib.rs index 8a777df0..2f13449c 100644 --- a/crates/bridge-core/src/lib.rs +++ b/crates/bridge-core/src/lib.rs @@ -34,7 +34,7 @@ pub mod time; pub use engine::{ Config, Engine, PendingDevice, TerminalAllowlist, TerminalAuditRecord, TerminalAuditWhat, TerminalConfig, - DEFAULT_HEARTBEAT_INTERVAL_MS, MAX_CLIENTS, MAX_WEB_SIGN_IN_CODES, + browser_may_send, DEFAULT_HEARTBEAT_INTERVAL_MS, MAX_CLIENTS, MAX_WEB_SIGN_IN_CODES, }; pub use sync::SyncConfig; pub use io::*; diff --git a/crates/bridge-core/tests/web_client.rs b/crates/bridge-core/tests/web_client.rs new file mode 100644 index 00000000..cf6f40a1 --- /dev/null +++ b/crates/bridge-core/tests/web_client.rs @@ -0,0 +1,172 @@ +//! A browser on the bridge's web page as a client of the identity that let it +//! in: what it may send, what it gets, and what ends it. The runtime has +//! already checked each command's signature; the engine decides what a +//! browser's command may do. + +mod support; + +use agent_protocol::{BridgeMessage, SessionEvent}; +use bridge_core::{Addressee, Effect, Input}; +use protocol::commands::PhoneToBridge; +use protocol::common::PartialKind; +use protocol::events::BridgeToPhone; +use serde_json::{json, Value}; +use support::*; + +const BROWSER: &str = "0123456789abcdef"; +const OTHER_BROWSER: &str = "fedcba9876543210"; + +fn command(msg: Value) -> Box { + let mut msg = msg; + msg["v"] = json!(protocol::capabilities::PROTOCOL_VERSION); + Box::new(serde_json::from_value(msg).expect("a command")) +} + +/// A browser `id` of the rig's phone, with its stream open. +fn online(rig: &mut Rig, id: &str) { + let by = rig.phone.npub.clone(); + rig.input(Input::WebBrowserOnline { id: id.into(), by }); +} + +/// A command from browser `id`, let in by the rig's phone; its effects. +fn from_browser(rig: &mut Rig, id: &str, msg: Value) -> Vec { + rig.take(); + let by = rig.phone.npub.clone(); + rig.input(Input::WebCommand { id: id.into(), by, msg: command(msg) }); + rig.take() +} + +/// Every publish's addressees, with the message. +fn publishes(effects: &[Effect]) -> Vec<(Vec, BridgeToPhone)> { + effects + .iter() + .filter_map(|e| match e { + Effect::Publish { to, message } => Some((to.clone(), message.clone())), + _ => None, + }) + .collect() +} + +fn to_browser(rig: &Rig, id: &str) -> Addressee { + Addressee::browser(&rig.phone.pubkey_hex, id) +} + +#[test] +fn a_browser_online_gets_a_heartbeat_of_its_own() { + let mut rig = Rig::new(); + rig.take(); + online(&mut rig, BROWSER); + let sent = publishes(&rig.take()); + assert!( + sent.iter().any(|(to, m)| matches!(m, BridgeToPhone::Sessions(_)) && to.contains(&to_browser(&rig, BROWSER))), + "{sent:#?}" + ); +} + +#[test] +fn a_browser_drives_a_session_as_its_identity() { + let mut rig = Rig::new(); + rig.host_up(); + online(&mut rig, BROWSER); + rig.take(); + let by = rig.phone.npub.clone(); + rig.input(Input::WebCommand { id: BROWSER.into(), by, msg: command(json!({"type":"create-session","agent":"alpha"})) }); + let (id, params) = rig.start_request(); + rig.host_reply(&id, agent_protocol::HostMessage::Ack); + rig.host_event(¶ms.session_id, SessionEvent::Ready {}); + rig.take(); + + let effects = from_browser(&mut rig, BROWSER, json!({"type":"input","sessionId":params.session_id,"text":"hi","inputId":"i1"})); + assert!( + effects.iter().any(|e| matches!(e, Effect::Host(f) if matches!(&f.message, BridgeMessage::Prompt { .. }))), + "the input reached the agent: {effects:#?}" + ); + let acks: Vec<_> = publishes(&effects).into_iter().filter(|(_, m)| matches!(m, BridgeToPhone::InputAck(_))).collect(); + assert!(acks.iter().any(|(to, _)| to.contains(&to_browser(&rig, BROWSER))), "the browser hears its ack: {acks:#?}"); +} + +#[test] +fn a_reply_goes_to_the_asking_browser_alone() { + let mut rig = Rig::new(); + online(&mut rig, BROWSER); + online(&mut rig, OTHER_BROWSER); + let sent = publishes(&from_browser(&mut rig, BROWSER, json!({"type":"refresh-sessions"}))); + let lists: Vec<_> = sent.into_iter().filter(|(_, m)| matches!(m, BridgeToPhone::Sessions(_))).collect(); + assert_eq!(lists.len(), 1, "{lists:#?}"); + assert_eq!(lists[0].0, vec![to_browser(&rig, BROWSER)]); +} + +#[test] +fn a_command_a_browser_may_not_send_does_nothing() { + let mut rig = Rig::new(); + rig.input(Input::WebSignInPending { code: "K7QM-4XPA".into(), expires_ms: T0 + 60_000 }); + online(&mut rig, BROWSER); + for msg in [ + json!({"type":"web-sign-in","code":"K7QM-4XPA"}), + json!({"type":"set-credentials","agent":"alpha","values":{"anthropic_api_key":"sk-ant-x"}}), + json!({"type":"mcp-action","agent":"alpha","action":"remove","names":["github"]}), + json!({"type":"terminal-open","openId":"o1","cols":80,"rows":24}), + ] { + let Ok(parsed) = serde_json::from_value::({ + let mut m = msg.clone(); + m["v"] = json!(protocol::capabilities::PROTOCOL_VERSION); + m + }) else { + panic!("not a command: {msg}") + }; + assert!(!bridge_core::browser_may_send(&parsed), "{msg}"); + let effects = from_browser(&mut rig, BROWSER, msg.clone()); + assert!(effects.is_empty(), "{msg} did something: {effects:#?}"); + } +} + +#[test] +fn live_text_reaches_only_a_browser_watching_that_session() { + let mut rig = Rig::new(); + rig.host_up(); + let s1 = rig.ready_session("alpha"); + let s2 = rig.ready_session("alpha"); + online(&mut rig, BROWSER); + online(&mut rig, OTHER_BROWSER); + from_browser(&mut rig, BROWSER, json!({"type":"presence","watching":s1})); + from_browser(&mut rig, OTHER_BROWSER, json!({"type":"presence","watching":s2})); + rig.take(); + + let partial = SessionEvent::Partial { key: "p1".into(), entry_type: PartialKind::Text, subagent: None, offset: 0, text: "x".into() }; + rig.host_event(&s1, partial); + let to: Vec = publishes(&rig.take()) + .into_iter() + .filter(|(_, m)| matches!(m, BridgeToPhone::Partial(_))) + .flat_map(|(to, _)| to) + .filter(|a| a.browser_id().is_some()) + .collect(); + assert_eq!(to, vec![to_browser(&rig, BROWSER)]); +} + +#[test] +fn a_browser_offline_gets_nothing() { + let mut rig = Rig::new(); + online(&mut rig, BROWSER); + rig.input(Input::WebBrowserOffline { id: BROWSER.into() }); + rig.take(); + rig.input(Input::WorkspaceChanged); + let sent = publishes(&rig.take()); + assert!(!sent.is_empty(), "a heartbeat went out"); + assert!(sent.iter().all(|(to, _)| to.iter().all(|a| a.browser_id().is_none())), "{sent:#?}"); +} + +#[test] +fn unpairing_ends_the_browsers_it_let_in() { + let mut rig = Rig::new(); + online(&mut rig, BROWSER); + rig.take(); + let identity = rig.phone.pubkey_hex.clone(); + rig.input(Input::Unpaired { identity }); + let npub = rig.phone.npub.clone(); + assert!(rig.take().iter().any(|e| matches!(e, Effect::WebEndBrowsers { by } if *by == npub))); + + // A command still in flight from one of them does nothing but end them. + let effects = from_browser(&mut rig, BROWSER, json!({"type":"refresh-sessions"})); + assert!(effects.iter().all(|e| matches!(e, Effect::WebEndBrowsers { .. })), "{effects:#?}"); + assert!(!effects.is_empty()); +} diff --git a/crates/bridge-runtime/Cargo.toml b/crates/bridge-runtime/Cargo.toml index 8ea40e03..3d24f352 100644 --- a/crates/bridge-runtime/Cargo.toml +++ b/crates/bridge-runtime/Cargo.toml @@ -66,6 +66,8 @@ portable-pty = "0.9" nix = { version = "0.28", features = ["hostname", "term", "user"] } [dev-dependencies] +# Signs as a browser's WebCrypto key does, for the web stream's tests. +p256 = { version = "0.13", default-features = false, features = ["ecdsa", "std"] } tempfile = "3" # Paused time for the tests that wait on timers (`start_paused`). tokio = { version = "1", features = ["test-util"] } diff --git a/crates/bridge-runtime/src/direct.rs b/crates/bridge-runtime/src/direct.rs index 2a9f8c44..cc3d9c9c 100644 --- a/crates/bridge-runtime/src/direct.rs +++ b/crates/bridge-runtime/src/direct.rs @@ -171,7 +171,7 @@ struct Conn { /// larger than the bounds can still be delivered to a phone that is reading: /// the bounds decide whether the phone has *stopped* reading, not how big one /// publish pass may be. -struct FrameLane { +pub(crate) struct FrameLane { queue: RefCell>, bytes: Cell, /// When the serve loop last took a frame out. @@ -182,7 +182,7 @@ struct FrameLane { } impl FrameLane { - fn new() -> Self { + pub(crate) fn new() -> Self { Self { queue: RefCell::new(VecDeque::new()), bytes: Cell::new(0), @@ -195,7 +195,7 @@ impl FrameLane { /// Queue a frame; false once the connection has been closed as stalled. /// An over-cap queue while frames are still being taken is accepted: it /// is a big burst, and the phone will drain it. - fn push(&self, frame: String) -> bool { + pub(crate) fn push(&self, frame: String) -> bool { if self.closed.get() { return false; } @@ -219,21 +219,21 @@ impl FrameLane { true } - fn pop(&self) -> Option { + pub(crate) fn pop(&self) -> Option { let frame = self.queue.borrow_mut().pop_front()?; self.bytes.set(self.bytes.get().saturating_sub(frame.len())); self.last_taken.set(std::time::Instant::now()); Some(frame) } - fn is_closed(&self) -> bool { + pub(crate) fn is_closed(&self) -> bool { self.closed.get() } /// Stop accepting frames and wake the serve loop, which sends its /// `closed` frame and ends. The lane is shared with that loop, so /// dropping the connection is not enough to end it. - fn close(&self) { + pub(crate) fn close(&self) { self.closed.set(true); self.wake.notify_one(); } @@ -241,7 +241,7 @@ impl FrameLane { /// Ready once a frame is waiting or the lane is closed. A `push` while /// nobody waits leaves `Notify`'s permit behind, so no wake-up is lost /// between the check and the wait. - async fn ready(&self) { + pub(crate) async fn ready(&self) { while self.queue.borrow().is_empty() && !self.closed.get() { self.wake.notified().await; } @@ -316,6 +316,22 @@ fn recipient_of(event: &SignedEvent) -> Option<&str> { } impl Hub { + /// A browser's stream from `peer` stops counting against its host's + /// connections ([`MAX_CONNECTIONS_PER_HOST`]): the page caps streams + /// itself, and on an IPv6 LAN — one /64 for every device — a few tabs + /// would otherwise lock the phones on it out of their direct link. + /// [`Hub::retake_host_slot`] gives the slot back when the stream ends, + /// so the accept loop's own release still balances. + pub(crate) fn release_host_slot(&self, peer: IpAddr) { + if let Some(held) = self.open_by_host.borrow_mut().get_mut(&crate::web::rate_key(peer)) { + *held = held.saturating_sub(1); + } + } + + pub(crate) fn retake_host_slot(&self, peer: IpAddr) { + *self.open_by_host.borrow_mut().entry(crate::web::rate_key(peer)).or_insert(0) += 1; + } + pub fn new(bridge_pubkey: String, inputs: mpsc::UnboundedSender) -> Rc { Rc::new(Self { bridge_pubkey, @@ -637,7 +653,13 @@ where async fn route(mut stream: S, peer: IpAddr, hub: &Hub, web: &crate::web::Web, limits: Limits) { let Ok(Some(head)) = tokio::time::timeout(limits.handshake, crate::web::read_head(&mut stream)).await else { return }; if crate::web::is_websocket(&head) { - serve(Replay { prefix: head, at: 0, inner: stream }, hub, limits).await; + // A browser's stream is the page's, on its own path; every other + // upgrade is a phone's direct link. + if crate::web::is_stream_request(&head) { + crate::web_stream::serve(head, stream, web, Some((hub, peer))).await; + } else { + serve(Replay::new(head, stream), hub, limits).await; + } } else { crate::web::serve(&head, stream, peer, web).await; } @@ -646,12 +668,18 @@ async fn route(mut stream: S, peer: IpAddr, h /// A stream that yields `prefix` before reading on from `inner`: the request /// head [`route`] read to tell a WebSocket from a page, given back to the /// WebSocket handshake that needs it. -struct Replay { +pub(crate) struct Replay { prefix: Vec, at: usize, inner: S, } +impl Replay { + pub(crate) fn new(prefix: Vec, inner: S) -> Self { + Self { prefix, at: 0, inner } + } +} + impl AsyncRead for Replay { fn poll_read(mut self: std::pin::Pin<&mut Self>, cx: &mut std::task::Context<'_>, buf: &mut ReadBuf<'_>) -> std::task::Poll> { if self.at < self.prefix.len() { diff --git a/crates/bridge-runtime/src/lib.rs b/crates/bridge-runtime/src/lib.rs index 9781b322..cffae0dd 100644 --- a/crates/bridge-runtime/src/lib.rs +++ b/crates/bridge-runtime/src/lib.rs @@ -12,6 +12,7 @@ pub mod direct; pub mod host; pub mod uploads; pub mod web; +pub mod web_stream; pub mod pairing; pub mod qr; pub mod relay; diff --git a/crates/bridge-runtime/src/runtime.rs b/crates/bridge-runtime/src/runtime.rs index d2f14597..0fce5294 100644 --- a/crates/bridge-runtime/src/runtime.rs +++ b/crates/bridge-runtime/src/runtime.rs @@ -17,7 +17,7 @@ use base64::engine::general_purpose::STANDARD; use base64::Engine as _; use bridge_core::ports::{Ports, System}; use bridge_core::{ - Config as EngineConfig, Effect, Engine, Input, NotifyLevel, PairingCloseReason, PairingWindowInfo, TerminalConfig, + Addressee, Config as EngineConfig, Effect, Engine, Input, NotifyLevel, PairingCloseReason, PairingWindowInfo, TerminalConfig, TimerId, }; use protocol::commands::UploadFileMsg; @@ -373,6 +373,22 @@ impl Runtime { self.direct.as_ref().map(|direct| direct.web.browsers()).unwrap_or_default() } + /// Send `message` to `to`: a browser's copy goes down its stream on the + /// web page as it is (TLS carries it; no message holds a secret), every + /// other copy to the relays and the direct link, encrypted and signed. + fn publish(&self, to: Vec, message: BridgeToPhone) { + let (browsers, phones): (Vec, Vec) = to.into_iter().partition(|a| a.browser_id().is_some()); + if let (false, Some(direct)) = (browsers.is_empty(), &self.direct) { + let text = protocol::encode_bridge_to_phone(&message); + for browser in browsers.iter().filter_map(Addressee::browser_id) { + direct.web.deliver(browser, &text); + } + } + if !phones.is_empty() { + self.relays.publish(phones, message); + } + } + /// Carry out one effect; true for [`Effect::Stopped`]. Async because one /// effect does blocking file work that must not run here: opening a /// terminal's recording, which is handed to a blocking task before its @@ -380,14 +396,13 @@ impl Runtime { async fn execute(&mut self, effect: Effect) -> bool { match effect { Effect::Publish { to, message } => { - if let (protocol::events::BridgeToPhone::Sessions(list), Some(direct)) = (&message, &self.direct) { - direct.web.set_heartbeat(list); - // The devices API follows the heartbeat: the paired - // phones are cheap to hand over, and this is where they - // change. + if let (protocol::events::BridgeToPhone::Sessions(_), Some(direct)) = (&message, &self.direct) { + // The page's devices view follows the heartbeat: the + // paired phones are cheap to hand over, and this is where + // they change. direct.web.set_devices(self.engine.paired_phones()); } - self.relays.publish(to, message) + self.publish(to, message); } Effect::WebSignedIn { code, by } => { if let Some(direct) = &self.direct { @@ -400,7 +415,7 @@ impl Runtime { // fresh list. Both go to the asking client alone. Effect::WebBrowsers { client } => { let message = BridgeToPhone::WebBrowsers(WebBrowsersMsg { browsers: self.web_browsers() }); - self.relays.publish(vec![client], message); + self.publish(vec![client], message); } Effect::WebBrowserSignOut { id, client } => { // `revoke` persists through the web page's own writer thread, @@ -409,7 +424,12 @@ impl Runtime { direct.web.revoke(&id); } let message = BridgeToPhone::WebBrowsers(WebBrowsersMsg { browsers: self.web_browsers() }); - self.relays.publish(vec![client], message); + self.publish(vec![client], message); + } + Effect::WebEndBrowsers { by } => { + if let Some(direct) = &self.direct { + direct.web.end_by(&by); + } } Effect::Host(frame) => self.host.send(&frame), Effect::SetTimer { id, after_ms } => { @@ -551,7 +571,7 @@ impl Runtime { data: STANDARD.encode(data), replay: Some(true), }); - self.relays.publish(vec![client], message); + self.publish(vec![client], message); } } Effect::TerminalClose { term } => self.terminals.close(&term), diff --git a/crates/bridge-runtime/src/web.rs b/crates/bridge-runtime/src/web.rs index e8a93942..483da172 100644 --- a/crates/bridge-runtime/src/web.rs +++ b/crates/bridge-runtime/src/web.rs @@ -48,7 +48,8 @@ use std::time::Duration; use base64::Engine as _; use bridge_core::{Input, PairedPhone}; -use protocol::events::{SessionListMsg, WebBrowserInfo}; +use protocol::events::WebBrowserInfo; +use protocol::web::BrowserKey; use serde_json::Value; use sha2::{Digest, Sha256}; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; @@ -62,8 +63,15 @@ const MAX_BODY_BYTES: usize = 16 * 1024; const BODY_TIMEOUT: Duration = Duration::from_secs(10); /// How long a sign-in code shown on the page can be approved. pub const PENDING_TTL_MS: u64 = 5 * 60 * 1000; -/// How long a signed-in browser stays signed in. +/// How long a signed-in browser stays signed in, at most. const SESSION_TTL_MS: u64 = 30 * 24 * 3600 * 1000; +/// How long a signed-in browser stays signed in without signing anything: a +/// browser left behind lapses well before its 30 days. +pub(crate) const IDLE_TTL_MS: u64 = 7 * 24 * 3600 * 1000; +/// Streams one browser may hold open (its tabs). +const MAX_STREAMS_PER_BROWSER: usize = 4; +/// Streams open at once, every browser together. +const MAX_STREAMS: usize = 16; /// How often a signed-in browser's `lastSeenMs` is written to disk at most; /// a request touches it in memory every time, but the file no more often. const LAST_SEEN_WRITE_MS: u64 = 60 * 1000; @@ -84,8 +92,8 @@ const COOKIE: &str = "__Host-codedeck"; /// The characters a sign-in code is drawn from: no 0/O, 1/I/L, so it can be /// read off a screen and typed on a phone without doubt. const CODE_ALPHABET: &[u8] = b"23456789ABCDEFGHJKMNPQRSTUVWXYZ"; -/// How many hex characters of a browser's key are its public id. -const ID_LEN: usize = 16; +/// How many hex characters of a browser's public id there are. +const ID_LEN: usize = protocol::web::BROWSER_ID_LEN; /// Longest `User-Agent` kept for a browser; the header is the client's, so it /// is bounded before it is stored or shown. const AGENT_MAX_CHARS: usize = 120; @@ -110,6 +118,9 @@ enum Access { #[derive(Debug, Clone)] struct Browser { access: Access, + /// The key the browser made for this sign-in, sent with its start: every + /// frame on its stream must be signed by it. Its id is the browser's. + key: BrowserKey, peer: IpAddr, /// When it got where it stands, as a count: what the caps drop the /// lowest of (a clock can give two browsers the same millisecond). @@ -118,11 +129,50 @@ struct Browser { /// (control characters stripped, at most [`AGENT_MAX_CHARS`]). Shown on /// the page so the owner can tell one browser from another. agent: String, - /// When it last made an authenticated request. Kept in memory on every - /// one, written at most every [`LAST_SEEN_WRITE_MS`]. + /// When it last signed something on its stream: only a signature moves + /// it, so a copied cookie cannot keep a sign-in alive. Kept in memory on + /// every one, written at most every [`LAST_SEEN_WRITE_MS`]. last_seen_ms: u64, } +impl Browser { + /// When it stops being let in: a pending code's lapse, or for a signed-in + /// browser the sooner of its 30 days and [`IDLE_TTL_MS`] since it last + /// signed anything. + fn lapses_ms(&self) -> u64 { + match self.access { + Access::Pending { expires_ms, .. } => expires_ms, + Access::SignedIn { expires_ms, .. } => expires_ms.min(self.last_seen_ms.saturating_add(IDLE_TTL_MS)), + } + } +} + +/// A browser allowed to open a stream: its cookie names a signed-in one. +#[derive(Debug)] +pub(crate) struct StreamGrant { + /// The SHA-256 of its cookie: how the page finds it again. + pub key: String, + /// Its public id. + pub id: String, + /// The npub of the identity that let it in. + pub by: String, + pub browser_key: BrowserKey, +} + +/// An open stream as its server holds it: its number, its lane, and the cell +/// the page leaves its closing reason in. +pub(crate) type OpenStream = (u64, Rc, Rc>); + +/// One open stream of a browser. +struct WebStream { + /// The browser's cookie hash. + key: String, + id: String, + lane: Rc, + /// Why the page closed it, for its `CLOSED` frame. + reason: Rc>, +} + /// What the page's config API needs: where `config.json` lives, and the view /// of the config as it is in effect (flags and environment already applied). #[derive(Clone, Default)] @@ -138,6 +188,11 @@ pub struct ConfigView { #[serde(rename_all = "camelCase")] struct StoredSession { key: String, + /// The browser's public key (base64url of the raw point). A record + /// without one predates browser keys and is skipped: that browser signs + /// in again. + #[serde(default)] + public_key: String, by: String, since_ms: u64, expires_ms: u64, @@ -174,7 +229,6 @@ pub struct Web { /// Host names (lowercase, no port) a request may name besides an IP /// address and `localhost`. hosts: Vec, - heartbeat: RefCell>, /// By the SHA-256 of the cookie's value, so the table holds no token a /// memory dump could replay. browsers: RefCell>, @@ -197,6 +251,11 @@ pub struct Web { writer: Writer, /// Page requests being served now ([`MAX_PAGE_REQUESTS`]). serving: Cell, + /// The browsers' open streams, by a number of their own. + streams: RefCell>, + next_stream: Cell, + /// The clock (ms since the Unix epoch); a test moves it. + clock: Box u64>, } impl Web { @@ -206,10 +265,21 @@ impl Web { inputs: mpsc::UnboundedSender, home: &Path, config: ConfigView, + ) -> Rc { + Self::with_clock(machine_npub, endpoints, inputs, home, config, Box::new(now_ms)) + } + + pub(crate) fn with_clock( + machine_npub: String, + endpoints: &[String], + inputs: mpsc::UnboundedSender, + home: &Path, + config: ConfigView, + clock: Box u64>, ) -> Rc { let hosts = endpoints.iter().filter_map(|url| endpoint_host(url)).collect(); let sessions_path = home.join("web-sessions.json"); - let browsers = load_sessions(&sessions_path); + let browsers = load_sessions(&sessions_path, clock()); let order = browsers.values().map(|b| b.order).max().unwrap_or(0) + 1; if !browsers.is_empty() { log::info!("[Web] {} signed-in browser(s) restored from {}", browsers.len(), sessions_path.display()); @@ -217,7 +287,6 @@ impl Web { Rc::new(Self { machine_npub, hosts, - heartbeat: RefCell::default(), browsers: RefCell::new(browsers), starts: RefCell::default(), order: Cell::new(order), @@ -229,12 +298,25 @@ impl Web { last_persist_ms: Cell::new(0), writer: Writer::spawn(), serving: Cell::new(0), + streams: RefCell::default(), + next_stream: Cell::new(1), + clock, }) } - /// The heartbeat the bridge just published, which the status page shows. - pub fn set_heartbeat(&self, list: &SessionListMsg) { - *self.heartbeat.borrow_mut() = Some(list.clone()); + fn now(&self) -> u64 { + (self.clock)() + } + + /// The machine this page belongs to (its npub): part of every signed + /// input, so a signature for another bridge is good for nothing here. + pub(crate) fn machine(&self) -> &str { + &self.machine_npub + } + + /// Where a browser's verified commands go: the engine's inputs. + pub(crate) fn inputs(&self) -> &mpsc::UnboundedSender { + &self.inputs } /// The paired identities, refreshed alongside the heartbeat: what the @@ -259,7 +341,7 @@ impl Web { /// A phone of `by` sent `code`, and the engine matched it to a code this /// page showed: that browser is signed in. pub fn signed_in(&self, code: &str, by: &str) { - let now = now_ms(); + let now = self.now(); { let mut browsers = self.browsers.borrow_mut(); for browser in browsers.values_mut() { @@ -274,46 +356,47 @@ impl Web { } evict_oldest(&mut browsers, MAX_SESSIONS, |b| matches!(b.access, Access::SignedIn { .. })); } + self.close_orphan_streams(); self.persist(); } + /// The browser a cookie names, by its key, unless it has lapsed — a + /// lapsed one is ended here. A cookie alone never moves `lastSeenMs`: + /// only a signature does ([`Self::seen`]). fn browser(&self, token: Option<&str>) -> Option<(String, Browser)> { - let key = token_key(token?); - let now = now_ms(); - let mut expired = false; - let mut touched = false; - { - let mut browsers = self.browsers.borrow_mut(); - let browser = browsers.get_mut(&key)?; - let expires_ms = match browser.access { - Access::Pending { expires_ms, .. } | Access::SignedIn { expires_ms, .. } => expires_ms, - }; - if expires_ms <= now { - expired = true; - } else if matches!(browser.access, Access::SignedIn { .. }) { - // An authenticated request: its `lastSeenMs` moves, and the - // file follows at most once a minute. - browser.last_seen_ms = now; - touched = true; - } - } - if expired { - self.browsers.borrow_mut().remove(&key); - self.persist(); + self.by_key(&token_key(token?)) + } + + /// [`Self::browser`], by the cookie's hash. + fn by_key(&self, key: &str) -> Option<(String, Browser)> { + let lapsed = self.browsers.borrow().get(key)?.lapses_ms() <= self.now(); + if lapsed { + self.sign_out_for(key, protocol::web::closed::EXPIRED); return None; } - if touched && now.saturating_sub(self.last_persist_ms.get()) >= LAST_SEEN_WRITE_MS { + self.browsers.borrow().get(key).map(|b| (key.to_string(), b.clone())) + } + + /// The browser `key` signed a frame: it is in use, so its idle limit + /// starts again. The file follows at most once a minute. + pub(crate) fn seen(&self, key: &str) { + let now = self.now(); + if let Some(browser) = self.browsers.borrow_mut().get_mut(key) { + browser.last_seen_ms = now; + } + if now.saturating_sub(self.last_persist_ms.get()) >= LAST_SEEN_WRITE_MS { self.last_persist_ms.set(now); self.persist(); } - self.browsers.borrow().get(&key).map(|b| (key.clone(), b.clone())) } - /// Start a sign-in for a browser at `peer` (its `User-Agent` is `agent`): - /// a new code, and the cookie that names it. `None` when the address - /// started too many lately. - fn start_sign_in(&self, peer: IpAddr, agent: &str) -> Option<(String, String)> { - let now = now_ms(); + /// Start a sign-in for a browser at `peer` (its `User-Agent` is `agent`) + /// holding `key`: a new code, and the cookie that names it. The key is + /// bound here, before any phone sees the code, so the code an identity + /// approves names exactly one key. `None` when the address started too + /// many lately. + fn start_sign_in(&self, peer: IpAddr, agent: &str, key: BrowserKey) -> Option<(String, String)> { + let now = self.now(); { let mut starts = self.starts.borrow_mut(); starts.retain(|_, (window, _)| now - *window < 60_000); @@ -332,11 +415,10 @@ impl Web { let code = new_code(); let expires_ms = now + PENDING_TTL_MS; let mut browsers = self.browsers.borrow_mut(); - browsers.retain(|_, b| match b.access { - Access::Pending { expires_ms, .. } | Access::SignedIn { expires_ms, .. } => expires_ms > now, - }); + browsers.retain(|_, b| b.lapses_ms() > now); let browser = Browser { access: Access::Pending { code: code.clone(), expires_ms }, + key, peer, order: self.next_order(), agent: agent.to_string(), @@ -349,15 +431,28 @@ impl Web { for dropped in evict_oldest(&mut browsers, MAX_PENDING, |b| matches!(b.access, Access::Pending { .. })) { self.withdraw(&dropped); } + drop(browsers); + // A lapsed signed-in browser reaped above may still hold a stream. + self.close_orphan_streams(); Some((token, code)) } fn sign_out(&self, key: &str) { + self.sign_out_for(key, protocol::web::closed::SIGNED_OUT); + } + + /// End the browser `key`: its record, its code if it was showing one, + /// and its streams, each closed with `reason`. + fn sign_out_for(&self, key: &str, reason: &'static str) { let removed = self.browsers.borrow_mut().remove(key); if let Some(browser) = removed { self.withdraw(&browser); self.persist(); } + let ended: Vec = self.streams.borrow().iter().filter(|(_, s)| s.key == key).map(|(n, _)| *n).collect(); + for n in ended { + self.end_stream(n, reason); + } } /// Sign out the browser whose id (the first `ID_LEN` hex characters of @@ -374,7 +469,7 @@ impl Web { .browsers .borrow() .iter() - .find(|(key, browser)| key.starts_with(id) && matches!(browser.access, Access::SignedIn { .. })) + .find(|(_, browser)| browser.key.id() == id && matches!(browser.access, Access::SignedIn { .. })) .map(|(key, _)| key.clone()); match key { Some(key) => { @@ -385,6 +480,24 @@ impl Web { } } + /// Sign out every browser the identity `by` (an npub) let in: it is no + /// longer paired, and what it let in goes with it. + pub fn end_by(&self, by: &str) { + let keys: Vec = self + .browsers + .borrow() + .iter() + .filter(|(_, b)| matches!(&b.access, Access::SignedIn { by: approver, .. } if approver == by)) + .map(|(key, _)| key.clone()) + .collect(); + if !keys.is_empty() { + log::info!("[Web] {} browser(s) signed out: the identity that let them in was unpaired", keys.len()); + } + for key in keys { + self.sign_out(&key); + } + } + fn next_order(&self) -> u64 { let order = self.order.get(); self.order.set(order + 1); @@ -402,6 +515,7 @@ impl Web { .filter_map(|(key, browser)| match &browser.access { Access::SignedIn { by, since_ms, expires_ms } => Some(StoredSession { key: key.clone(), + public_key: browser.key.to_base64url(), by: by.clone(), since_ms: *since_ms, expires_ms: *expires_ms, @@ -432,86 +546,50 @@ impl Web { } } - fn status_json(&self, by: &str, since_ms: u64) -> String { - let heartbeat = self.heartbeat.borrow(); - serde_json::json!({ - "machine": self.machine_npub, - "signedInBy": by, - "signedInSince": since_ms, - "heartbeat": heartbeat.as_ref().map(|h| serde_json::to_value(h).unwrap_or(serde_json::Value::Null)), - }) - .to_string() - } - - /// The signed-in browsers, oldest signed in first, as `(key, info)`. The - /// page's own list: both `browsers_json` and `browsers` read it, so what - /// `GET /api/browsers` serves and what a phone's `web-browsers-request` - /// is answered with can never disagree. - /// A browser whose sign-in has lapsed is left out: it is only reaped when - /// it next asks for something, and until then it is not signed in. - fn browser_rows(&self) -> Vec<(String, WebBrowserInfo)> { - let now = now_ms(); - let mut rows: Vec<(u64, String, WebBrowserInfo)> = self + /// The signed-in browsers, oldest signed in first: what a + /// `web-browsers-request` is answered with, from a phone or a browser. + /// `expiresMs` is when each actually lapses — the sooner of its 30 days + /// and its idle limit. A browser whose sign-in has lapsed is left out: it + /// is only reaped when it next asks for something, and until then it is + /// not signed in. + pub fn browsers(&self) -> Vec { + let now = self.now(); + let mut rows: Vec<(u64, WebBrowserInfo)> = self .browsers .borrow() - .iter() - .filter_map(|(key, browser)| match &browser.access { - Access::SignedIn { by, since_ms, expires_ms } if *expires_ms > now => Some(( + .values() + .filter(|browser| browser.lapses_ms() > now) + .filter_map(|browser| match &browser.access { + Access::SignedIn { by, since_ms, .. } => Some(( browser.order, - key.clone(), WebBrowserInfo { - id: key[..ID_LEN].to_string(), + id: browser.key.id(), by: by.clone(), since_ms: *since_ms, last_seen_ms: browser.last_seen_ms, - expires_ms: *expires_ms, + expires_ms: browser.lapses_ms(), peer: browser.peer.to_string(), agent: browser.agent.clone(), }, )), - _ => None, - }) - .collect(); - rows.sort_by_key(|(order, _, _)| *order); - rows.into_iter().map(|(_, key, info)| (key, info)).collect() - } - - /// The signed-in browsers, oldest signed in first: what a paired phone's - /// `web-browsers-request` is answered with, from the same rows - /// `GET /api/browsers` serves. - pub fn browsers(&self) -> Vec { - self.browser_rows().into_iter().map(|(_, info)| info).collect() - } - - /// The signed-in browsers, oldest first, for `GET /api/browsers`. Each - /// row carries `current` — whether it is the browser asking — which only - /// the page's own request can know. - fn browsers_json(&self, current: Option<&str>) -> String { - let rows: Vec = self - .browser_rows() - .into_iter() - .map(|(key, info)| { - let mut row = serde_json::to_value(&info).unwrap_or(Value::Null); - if let Value::Object(map) = &mut row { - map.insert("current".to_string(), Value::Bool(current == Some(key.as_str()))); - } - row + Access::Pending { .. } => None, }) .collect(); - serde_json::json!({ "browsers": rows }).to_string() + rows.sort_by_key(|(order, _)| *order); + rows.into_iter().map(|(_, info)| info).collect() } - /// The paired identities, for `GET /api/devices`. + /// The paired identities, for the `devices` page request. fn devices_json(&self) -> String { serde_json::json!({ "devices": self.devices.borrow().clone() }).to_string() } - /// The config as it is in effect, for `GET /api/config`. + /// The config as it is in effect, for the `config` page request. fn config_json(&self) -> String { serde_json::json!({ "fields": self.config_fields.borrow().clone() }).to_string() } - /// Apply a `POST /api/config` body: only safe-set keys, each validated, + /// Apply a `config-set` page request's body: only safe-set keys, each validated, /// then written to the config file keeping every other key. `by` is the /// approver's npub, for the log line (key names only, never a value). fn apply_config(&self, body: &[u8], by: &str) -> Response { @@ -545,11 +623,195 @@ impl Web { } } +impl Web { + /// Whether a stream request may be upgraded: an allowed `Host`, an + /// `Origin` that is the page's own (a browser sends cookies on a + /// cross-site WebSocket handshake too), and a cookie naming a signed-in + /// browser. Checked before any signature work, so a stranger costs one + /// hash. The error is the HTTP status to refuse with. + pub(crate) fn stream_grant(&self, head: &[u8]) -> Result { + let request = parse_head(head).ok_or(400u16)?; + let host = request.host.as_deref().filter(|h| host_allowed(h, &self.hosts)).ok_or(403u16)?; + if request.origin.as_deref() != Some(&format!("https://{host}")) { + return Err(403); + } + match self.browser(request.cookie.as_deref()) { + Some((key, Browser { access: Access::SignedIn { by, .. }, key: browser_key, .. })) if self.is_paired(&by) => { + Ok(StreamGrant { id: browser_key.id(), key, by, browser_key }) + } + _ => Err(401), + } + } + + /// Whether the identity `by` (an npub) is paired now, as the heartbeat + /// last told the page. + fn is_paired(&self, by: &str) -> bool { + self.devices.borrow().iter().any(|d| d.npub == by) + } + + /// Close every stream whose browser is no longer signed in: one dropped + /// to make room, or lapsed and reaped, would otherwise stay open. + fn close_orphan_streams(&self) { + let orphans: Vec = { + let browsers = self.browsers.borrow(); + self.streams + .borrow() + .iter() + .filter(|(_, s)| !matches!(browsers.get(&s.key), Some(Browser { access: Access::SignedIn { .. }, .. }))) + .map(|(n, _)| *n) + .collect() + }; + for n in orphans { + self.end_stream(n, protocol::web::closed::SIGNED_OUT); + } + } + + /// Open a stream for `grant`: its lane, and the cell its closing reason + /// is left in. `None` past the caps (per browser, and in all). The first + /// stream of a browser makes it a present client of its identity. + pub(crate) fn open_stream(&self, grant: &StreamGrant) -> Option { + let mut streams = self.streams.borrow_mut(); + let of_browser = streams.values().filter(|s| s.key == grant.key).count(); + if streams.len() >= MAX_STREAMS || of_browser >= MAX_STREAMS_PER_BROWSER { + return None; + } + let n = self.next_stream.get(); + self.next_stream.set(n + 1); + let lane = Rc::new(crate::direct::FrameLane::new()); + let reason = Rc::new(Cell::new(protocol::web::closed::SIGNED_OUT)); + streams.insert(n, WebStream { key: grant.key.clone(), id: grant.id.clone(), lane: Rc::clone(&lane), reason: Rc::clone(&reason) }); + if of_browser == 0 { + let _ = self.inputs.send(Input::WebBrowserOnline { id: grant.id.clone(), by: grant.by.clone() }); + } + Some((n, lane, reason)) + } + + /// The stream `n` ended (either side). A browser whose last stream it + /// was gets nothing more until it opens one. + pub(crate) fn close_stream(&self, n: u64) { + let Some(stream) = self.streams.borrow_mut().remove(&n) else { return }; + let others = self.streams.borrow().values().any(|s| s.key == stream.key); + if !others { + let _ = self.inputs.send(Input::WebBrowserOffline { id: stream.id }); + } + } + + /// Close stream `n` from the page's side, with `reason`. + fn end_stream(&self, n: u64, reason: &'static str) { + if let Some(stream) = self.streams.borrow().get(&n) { + stream.reason.set(reason); + stream.lane.close(); + } + self.close_stream(n); + } + + /// Queue `message` (a `BridgeToPhone`, encoded) on each stream of the + /// browser `id`. A browser whose sign-in lapsed is ended instead; one + /// that stopped reading is closed as busy, never waited on — the phones' + /// links share this thread. + pub fn deliver(&self, id: &str, message: &str) { + let targets: Vec<(u64, String, Rc)> = + self.streams.borrow().iter().filter(|(_, s)| s.id == id).map(|(n, s)| (*n, s.key.clone(), Rc::clone(&s.lane))).collect(); + let Some((_, key, _)) = targets.first() else { return }; + if self.by_key(key).is_none() { + self.close_orphan_streams(); + return; + } + let frame = protocol::web::encode_web_frame(&protocol::web::WebFrame::Msg(message.to_string())); + for (n, _, lane) in targets { + if !lane.push(frame.clone()) { + log::info!("[Web] A browser stopped reading its stream; closing it"); + self.end_stream(n, protocol::web::closed::BUSY); + } + } + } + + /// Whether the browser `key` is still signed in: what each frame on its + /// stream is checked against, so a lapse or a sign-out ends the stream + /// at its next frame even when nothing was sent to it. + pub(crate) fn still_signed_in(&self, key: &str) -> bool { + matches!(self.by_key(key), Some((_, Browser { access: Access::SignedIn { .. }, .. }))) + } + + /// Answer a page request (its `body`, already verified) from browser + /// `by`'s stream: `{status, body}`, and a config write to make first + /// when it changes the config. + pub(crate) fn page_request(&self, body: &str, by: &str) -> (u16, String, Option) { + // Only for a browser whose identity is still paired: one restored + // from disk after its phone was unpaired must not reach the config + // before the engine has ended it. + if !self.is_paired(by) { + return (403, error_body(403), None); + } + let Ok(doc) = serde_json::from_str::(body) else { return (400, error_body(400), None) }; + match doc.get("type").and_then(Value::as_str) { + Some("devices") => (200, self.devices_json(), None), + Some("config") => (200, self.config_json(), None), + Some("config-set") => { + let set = serde_json::json!({ "set": doc.get("set").cloned().unwrap_or(Value::Null) }); + let mut response = self.apply_config(set.to_string().as_bytes(), by); + let write = response.config_write.take(); + (response.status, String::from_utf8(response.body).unwrap_or_default(), write) + } + _ => (400, error_body(400), None), + } + } +} + +fn error_body(status: u16) -> String { + serde_json::json!({ "error": reason(status) }).to_string() +} + +/// The fields of a request head the stream's gate reads. +fn parse_head(buf: &[u8]) -> Option { + let mut headers = [httparse::EMPTY_HEADER; 64]; + let mut parsed = httparse::Request::new(&mut headers); + if !matches!(parsed.parse(buf), Ok(httparse::Status::Complete(_))) { + return None; + } + let header = |name: &str| { + parsed.headers.iter().find(|h| h.name.eq_ignore_ascii_case(name)).and_then(|h| std::str::from_utf8(h.value).ok()).map(str::to_string) + }; + Some(Request { + method: parsed.method.unwrap_or("").to_string(), + path: parsed.path.unwrap_or("").split('?').next().unwrap_or("").to_string(), + host: header("host"), + origin: header("origin"), + cookie: header("cookie").and_then(|all| cookie_value(&all)), + user_agent: header("user-agent"), + body: Vec::new(), + }) +} + +/// The session cookie's value in a `Cookie` header. +fn cookie_value(all: &str) -> Option { + all.split(';').find_map(|pair| pair.trim().strip_prefix(&format!("{COOKIE}=")).map(str::to_string)) +} + +/// Whether the request head in `buf` asks for the browser's stream rather +/// than the direct link: a WebSocket upgrade of [`STREAM_PATH`]. +pub fn is_stream_request(buf: &[u8]) -> bool { + parse_head(buf).is_some_and(|r| r.path == STREAM_PATH) +} + +/// Where a browser opens its stream. +pub const STREAM_PATH: &str = "/api/stream"; + +/// Refuse a request with `status` and close the connection. +pub(crate) async fn refuse(stream: &mut S, status: u16) { + write_response(stream, Response::error(status)).await; +} + +/// Make a validated config write, off the bridge's thread: `{status, body}`. +pub(crate) async fn write_config_now(write: ConfigWrite) -> (u16, String) { + let response = write_config(write).await; + (response.status, String::from_utf8(response.body).unwrap_or_default()) +} + /// The signed-in browsers a previous run left in `path`, expired ones /// dropped. A missing or unreadable file is an empty set, with a warning: a /// page that will not start is worse than one whose browsers sign in again. -fn load_sessions(path: &Path) -> HashMap { - let now = now_ms(); +fn load_sessions(path: &Path, now: u64) -> HashMap { let raw = match std::fs::read_to_string(path) { Ok(raw) => raw, Err(e) if e.kind() == std::io::ErrorKind::NotFound => return HashMap::new(), @@ -571,14 +833,13 @@ fn load_sessions(path: &Path) -> HashMap { // A key is always 64 hex characters; anything else is not one this // page wrote, so it is dropped rather than trusted. let Ok(peer) = session.peer.parse::() else { continue }; - if session.expires_ms <= now || session.key.len() != 64 { + let Some(key) = BrowserKey::parse(&session.public_key) else { continue }; + let access = Access::SignedIn { by: session.by, since_ms: session.since_ms, expires_ms: session.expires_ms }; + let browser = Browser { access, key, peer, order, agent: session.agent, last_seen_ms: session.last_seen_ms }; + if browser.lapses_ms() <= now || session.key.len() != 64 { continue; } - let access = Access::SignedIn { by: session.by, since_ms: session.since_ms, expires_ms: session.expires_ms }; - browsers.insert( - session.key, - Browser { access, peer, order, agent: session.agent, last_seen_ms: session.last_seen_ms }, - ); + browsers.insert(session.key, browser); order += 1; } browsers @@ -790,7 +1051,7 @@ struct Response { } /// Config-file changes the page validated, still to be written. -struct ConfigWrite { +pub(crate) struct ConfigWrite { path: PathBuf, changes: Vec<(String, Option)>, /// Who asked, for the log line (an npub prefix). @@ -953,19 +1214,23 @@ fn route(request: &Request, peer: IpAddr, web: &Web) -> Response { return Response::error(403); } let browser = web.browser(request.cookie.as_deref()); + let now = web.now(); match (request.method.as_str(), request.path.as_str()) { ("GET", "/") => Response::new(200, "text/html; charset=utf-8", INDEX_HTML), ("GET", "/app.js") => Response::new(200, "text/javascript; charset=utf-8", APP_JS), ("GET", "/app.css") => Response::new(200, "text/css; charset=utf-8", APP_CSS), - ("GET", "/api/me") => Response::json(200, me_json(browser.as_ref().map(|(_, b)| b))), - ("POST", "/api/sign-in") => match web.start_sign_in(peer, &clean_agent(request.user_agent.as_deref())) { - Some((token, code)) => { - let mut response = Response::json(200, serde_json::json!({ "state": "pending", "code": code, "expiresInMs": PENDING_TTL_MS }).to_string()); - response.set_cookie = Some(session_cookie(&token, SESSION_TTL_MS / 1000)); - response + ("GET", "/api/me") => Response::json(200, me_json(browser.as_ref().map(|(_, b)| b), &web.machine_npub, now)), + ("POST", "/api/sign-in") => { + let Some(key) = sign_in_key(&request.body) else { return Response::error(400) }; + match web.start_sign_in(peer, &clean_agent(request.user_agent.as_deref()), key) { + Some((token, code)) => { + let mut response = Response::json(200, serde_json::json!({ "state": "pending", "code": code, "expiresInMs": PENDING_TTL_MS }).to_string()); + response.set_cookie = Some(session_cookie(&token, SESSION_TTL_MS / 1000)); + response + } + None => Response::error(429), } - None => Response::error(429), - }, + } ("GET", "/api/sign-in/qr.svg") => match browser { Some((_, Browser { access: Access::Pending { code, .. }, .. })) => { let url = format!("codedeck://web-sign-in?machine={}&code={code}", web.machine_npub); @@ -976,64 +1241,25 @@ fn route(request: &Request, peer: IpAddr, web: &Web) -> Response { } _ => Response::error(404), }, + // Ending its own sign-in is the one thing a cookie alone may do. ("POST", "/api/sign-out") => { if let Some((key, _)) = browser { web.sign_out(&key); } - let mut response = Response::json(200, me_json(None)); + let mut response = Response::json(200, me_json(None, &web.machine_npub, now)); response.set_cookie = Some(session_cookie("", 0)); response } - ("GET", "/api/status") => match &browser { - Some((_, Browser { access: Access::SignedIn { by, since_ms, .. }, .. })) => Response::json(200, web.status_json(by, *since_ms)), - _ => Response::error(401), - }, - ("GET", "/api/browsers") => match signed_in(&browser) { - Some((key, _)) => Response::json(200, web.browsers_json(Some(key))), - None => Response::error(401), - }, - ("POST", "/api/browsers/sign-out") => match signed_in(&browser) { - Some(_) => match sign_out_id(&request.body) { - Some(id) if web.revoke(&id) => Response::json(200, serde_json::json!({ "ok": true }).to_string()), - Some(_) => Response::error(404), - None => Response::error(400), - }, - None => Response::error(401), - }, - ("GET", "/api/devices") => match signed_in(&browser) { - Some(_) => Response::json(200, web.devices_json()), - None => Response::error(401), - }, - ("GET", "/api/config") => match signed_in(&browser) { - Some(_) => Response::json(200, web.config_json()), - None => Response::error(401), - }, - ("POST", "/api/config") => match signed_in(&browser) { - Some((_, by)) => web.apply_config(&request.body, by), - None => Response::error(401), - }, - ( - _, - "/" | "/app.js" | "/app.css" | "/api/me" | "/api/sign-in" | "/api/sign-in/qr.svg" | "/api/sign-out" | "/api/status" - | "/api/browsers" | "/api/browsers/sign-out" | "/api/devices" | "/api/config", - ) => Response::error(405), + (_, "/" | "/app.js" | "/app.css" | "/api/me" | "/api/sign-in" | "/api/sign-in/qr.svg" | "/api/sign-out") => Response::error(405), _ => Response::error(404), } } -/// The signed-in browser's key and approver, if it is signed in. -fn signed_in(browser: &Option<(String, Browser)>) -> Option<(&str, &str)> { - match browser { - Some((key, Browser { access: Access::SignedIn { by, .. }, .. })) => Some((key.as_str(), by.as_str())), - _ => None, - } -} - -/// The browser id a sign-out POST names, or `None` when the body is not a -/// JSON object with a string `id`. -fn sign_out_id(body: &[u8]) -> Option { +/// The browser's public key a sign-in start carries (`{"key": …}`), or +/// `None` when it carries none a browser could sign with. +fn sign_in_key(body: &[u8]) -> Option { let doc: Value = serde_json::from_slice(body).ok()?; - doc.get("id")?.as_str().map(str::to_string) + BrowserKey::parse(doc.get("key")?.as_str()?) } /// A 400 naming the setting at fault, so the page can point at it. @@ -1041,52 +1267,108 @@ fn bad_request(key: &str, message: &str) -> Response { Response::json(400, serde_json::json!({ "error": message, "key": key }).to_string()) } -fn me_json(browser: Option<&Browser>) -> String { - let now = now_ms(); - match browser.map(|b| &b.access) { - Some(Access::Pending { code, expires_ms }) => { - serde_json::json!({ "state": "pending", "code": code, "expiresInMs": expires_ms.saturating_sub(now) }) - } - Some(Access::SignedIn { by, since_ms, .. }) => { - serde_json::json!({ "state": "signed-in", "by": by, "since": since_ms }) - } - None => serde_json::json!({ "state": "signed-out" }), +/// What `GET /api/me` answers: where the browser stands, and what it needs +/// to sign on its stream — the machine and its own id. +fn me_json(browser: Option<&Browser>, machine: &str, now: u64) -> String { + match browser { + Some(Browser { access: Access::Pending { code, expires_ms }, key, .. }) => serde_json::json!({ + "state": "pending", "code": code, "expiresInMs": expires_ms.saturating_sub(now), "machine": machine, "id": key.id(), + }), + Some(browser @ Browser { access: Access::SignedIn { by, since_ms, .. }, key, .. }) => serde_json::json!({ + "state": "signed-in", "by": by, "since": since_ms, "lapses": browser.lapses_ms(), "machine": machine, "id": key.id(), + }), + None => serde_json::json!({ "state": "signed-out", "machine": machine }), } .to_string() } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; + use p256::ecdsa::signature::Signer as _; + use p256::ecdsa::{Signature, SigningKey}; + + /// A browser's key pair, as WebCrypto makes one: the signing half stays + /// with the test (the browser), the public half is what the page sends. + pub(crate) struct TestKey { + signing: SigningKey, + pub public: BrowserKey, + } + + impl TestKey { + pub(crate) fn new(seed: u8) -> Self { + let signing = SigningKey::from_bytes(&[seed.max(1); 32].into()).expect("a scalar"); + let raw = signing.verifying_key().to_encoded_point(false); + let public = BrowserKey::parse(&base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(raw.as_bytes())).unwrap(); + Self { signing, public } + } + + pub(crate) fn base64url(&self) -> String { + self.public.to_base64url() + } - /// A page over `home`, with no config view. - fn web_in(home: &Path) -> (Rc, mpsc::UnboundedReceiver) { - web_with_config(home, Vec::new()) + /// Sign `input` as WebCrypto does: `r‖s`, base64url. + pub(crate) fn sign(&self, input: &[u8]) -> String { + let sig: Signature = self.signing.sign(input); + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sig.to_bytes()) + } + } + + /// A clock the test moves. + pub(crate) fn clock() -> (Rc>, Box u64>) { + let now = Rc::new(Cell::new(1_800_000_000_000u64)); + let read = Rc::clone(&now); + (now, Box::new(move || read.get())) } - /// A page over `home`, its config API showing `fields`. - fn web_with_config(home: &Path, fields: Vec) -> (Rc, mpsc::UnboundedReceiver) { + /// A page over `home` on the clock `now`, its config view showing `fields`. + pub(crate) fn page(home: &Path, fields: Vec, now: Box u64>) -> (Rc, mpsc::UnboundedReceiver) { let (tx, rx) = mpsc::unbounded_channel(); let config = ConfigView { path: home.join("config.json"), fields }; - (Web::new("npub1machine".into(), &["wss://box.tail1234.ts.net:7447".into()], tx, home, config), rx) + let web = Web::with_clock("npub1machine".into(), &["wss://box.tail1234.ts.net:7447".into()], tx, home, config, now); + // The identity the tests sign browsers in with is paired, as the + // heartbeat tells the page. + web.set_devices(&[phone("npub1owner")]); + (web, rx) + } + + /// A paired identity, as the heartbeat hands it to the page. + fn phone(npub: &str) -> bridge_core::PairedPhone { + bridge_core::PairedPhone { + npub: npub.into(), + pubkey_hex: "ab".repeat(32), + label: "Pixel".into(), + paired_at: "2026-01-02T03:04:05Z".into(), + clients: Vec::new(), + } } /// A page over a fresh temp dir, which the caller must keep alive. fn web() -> (Rc, mpsc::UnboundedReceiver, tempfile::TempDir) { let dir = tempfile::tempdir().unwrap(); - let (web, rx) = web_in(dir.path()); + let (web, rx) = page(dir.path(), Vec::new(), Box::new(now_ms)); (web, rx, dir) } - /// Start a sign-in at [`PEER`] and have the owner approve it, returning - /// the browser's cookie token. - fn sign_in(web: &Web, inputs: &mut mpsc::UnboundedReceiver) -> String { - let (token, _) = web.start_sign_in(PEER, "Mozilla/5.0").expect("a start"); - let Some(Input::WebSignInPending { code, .. }) = inputs.try_recv().ok() else { panic!("the engine is told the code") }; + /// Start a sign-in at [`PEER`] with `key` and have the owner approve it, + /// returning the browser's cookie token. + pub(crate) fn sign_in_with(web: &Web, inputs: &mut mpsc::UnboundedReceiver, key: &TestKey) -> String { + let (token, _) = web.start_sign_in(PEER, "Mozilla/5.0", key.public.clone()).expect("a start"); + let code = loop { + match inputs.try_recv() { + Ok(Input::WebSignInPending { code, .. }) => break code, + Ok(_) => continue, + Err(_) => panic!("the engine is told the code"), + } + }; web.signed_in(&code, "npub1owner"); token } + fn sign_in(web: &Web, inputs: &mut mpsc::UnboundedReceiver) -> String { + sign_in_with(web, inputs, &TestKey::new(7)) + } + fn request(method: &str, path: &str, host: &str) -> Request { Request { method: method.into(), @@ -1099,8 +1381,19 @@ mod tests { } } - const PEER: IpAddr = IpAddr::V4(std::net::Ipv4Addr::new(192, 168, 1, 20)); - const HOST: &str = "192.168.1.5:7447"; + /// The head of a stream request, as a browser on the page sends it. + pub(crate) fn stream_head(origin: &str, cookie: Option<&str>) -> Vec { + let cookie = cookie.map(|c| format!("Cookie: {COOKIE}={c}\r\n")).unwrap_or_default(); + format!( + "GET {STREAM_PATH} HTTP/1.1\r\nHost: {HOST}\r\nOrigin: {origin}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\ + Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n{cookie}\r\n" + ) + .into_bytes() + } + + pub(crate) const PEER: IpAddr = IpAddr::V4(std::net::Ipv4Addr::new(192, 168, 1, 20)); + pub(crate) const HOST: &str = "192.168.1.5:7447"; + const DAY: u64 = 24 * 3600 * 1000; #[test] fn only_addresses_localhost_and_the_endpoints_hosts_are_served() { @@ -1116,7 +1409,8 @@ mod tests { #[test] fn a_post_from_another_origin_is_refused() { let (web, _, _dir) = web(); - let mut post = request("POST", "/api/sign-in", "192.168.1.5:7447"); + let mut post = request("POST", "/api/sign-in", HOST); + post.body = serde_json::json!({ "key": TestKey::new(1).base64url() }).to_string().into_bytes(); post.origin = Some("https://evil.example".into()); assert_eq!(route(&post, PEER, &web).status, 403); post.origin = None; @@ -1124,41 +1418,147 @@ mod tests { } #[test] - fn the_status_needs_a_signed_in_browser() { + fn a_sign_in_start_needs_a_key_a_browser_can_sign_with() { + let (web, _, _dir) = web(); + let mut post = request("POST", "/api/sign-in", HOST); + assert_eq!(route(&post, PEER, &web).status, 400, "no key"); + post.body = br#"{"key":"AAAA"}"#.to_vec(); + assert_eq!(route(&post, PEER, &web).status, 400, "not a point"); + post.body = serde_json::json!({ "key": TestKey::new(1).base64url() }).to_string().into_bytes(); + let started = route(&post, PEER, &web); + assert_eq!(started.status, 200); + let cookie = started.set_cookie.unwrap(); + assert!(cookie.contains("Secure") && cookie.contains("HttpOnly") && cookie.contains("SameSite=Strict")); + } + + #[test] + fn a_cookie_alone_reaches_nothing_but_its_own_sign_in() { + let (web, mut inputs, _dir) = web(); + let token = sign_in(&web, &mut inputs); + let mut me = request("GET", "/api/me", HOST); + me.cookie = Some(token.clone()); + let body: Value = serde_json::from_slice(&route(&me, PEER, &web).body).unwrap(); + assert_eq!(body["state"], "signed-in"); + assert_eq!(body["machine"], "npub1machine"); + assert_eq!(body["id"], TestKey::new(7).public.id()); + for (method, path) in [ + ("GET", "/api/status"), + ("GET", "/api/browsers"), + ("POST", "/api/browsers/sign-out"), + ("GET", "/api/devices"), + ("GET", "/api/config"), + ("POST", "/api/config"), + ] { + let mut req = request(method, path, HOST); + req.cookie = Some(token.clone()); + assert_eq!(route(&req, PEER, &web).status, 404, "{method} {path} answers only on the signed stream"); + } + } + + #[test] + fn only_a_signature_keeps_a_browser_signed_in_for_seven_idle_days() { + let dir = tempfile::tempdir().unwrap(); + let (now, clock) = clock(); + let (web, mut inputs) = page(dir.path(), Vec::new(), clock); + let token = sign_in(&web, &mut inputs); + let key = token_key(&token); + let mut me = request("GET", "/api/me", HOST); + me.cookie = Some(token); + + // Six days of a cookie being shown, and nothing signed. + for _ in 0..6 { + now.set(now.get() + DAY); + route(&me, PEER, &web); + } + now.set(now.get() + DAY - 1); + assert!(web.still_signed_in(&key), "one ms short of seven days"); + now.set(now.get() + 1); + assert!(!web.still_signed_in(&key), "the cookie did not keep it alive"); + } + + #[test] + fn a_browser_in_use_still_lapses_after_thirty_days() { + let dir = tempfile::tempdir().unwrap(); + let (now, clock) = clock(); + let (web, mut inputs) = page(dir.path(), Vec::new(), clock); + let key = token_key(&sign_in(&web, &mut inputs)); + for _ in 0..29 { + now.set(now.get() + DAY); + assert!(web.still_signed_in(&key)); + web.seen(&key); + } + let row = &web.browsers()[0]; + assert_eq!(row.expires_ms, row.since_ms + SESSION_TTL_MS, "the list shows when it actually lapses"); + now.set(now.get() + DAY); + assert!(!web.still_signed_in(&key)); + assert!(web.browsers().is_empty()); + } + + #[test] + fn the_list_shows_the_idle_lapse_when_it_comes_first() { let (web, mut inputs, _dir) = web(); - let host = "192.168.1.5:7447"; - assert_eq!(route(&request("GET", "/api/status", host), PEER, &web).status, 401); + sign_in(&web, &mut inputs); + let row = &web.browsers()[0]; + assert_eq!(row.expires_ms, row.last_seen_ms + IDLE_TTL_MS); + } - let started = route(&request("POST", "/api/sign-in", host), PEER, &web); - let cookie = started.set_cookie.clone().unwrap(); - assert!(cookie.contains("Secure") && cookie.contains("HttpOnly") && cookie.contains("SameSite=Strict")); - let token = cookie.split(';').next().unwrap().strip_prefix(&format!("{COOKIE}=")).unwrap().to_string(); - let Some(Input::WebSignInPending { code, .. }) = inputs.try_recv().ok() else { panic!("the engine is told the code") }; + #[test] + fn the_stream_is_let_through_only_from_the_page_with_a_signed_in_cookie() { + let (web, mut inputs, _dir) = web(); + let key = TestKey::new(7); + let token = sign_in_with(&web, &mut inputs, &key); + let origin = format!("https://{HOST}"); + let grant = web.stream_grant(&stream_head(&origin, Some(&token))).expect("let through"); + assert_eq!(grant.id, key.public.id()); + assert_eq!(grant.by, "npub1owner"); + assert_eq!(web.stream_grant(&stream_head("https://evil.example", Some(&token))).err(), Some(403), "another origin"); + assert_eq!(web.stream_grant(&stream_head(&origin, None)).err(), Some(401), "no cookie"); + assert_eq!(web.stream_grant(&stream_head(&origin, Some("forged"))).err(), Some(401), "a cookie the page never set"); - let mut status = request("GET", "/api/status", host); - status.cookie = Some(token.clone()); - assert_eq!(route(&status, PEER, &web).status, 401, "a pending browser sees no status"); + let (pending, _) = web.start_sign_in(PEER, "", TestKey::new(9).public).unwrap(); + assert_eq!(web.stream_grant(&stream_head(&origin, Some(&pending))).err(), Some(401), "a browser still waiting for its phone"); + } - web.signed_in(&code, "npub1owner"); - assert_eq!(route(&status, PEER, &web).status, 200); + #[test] + fn streams_are_capped_per_browser_and_the_first_and_last_say_so() { + let (web, mut inputs, _dir) = web(); + let token = sign_in(&web, &mut inputs); + while inputs.try_recv().is_ok() {} + let grant = web.stream_grant(&stream_head(&format!("https://{HOST}"), Some(&token))).expect("let through"); + let opened: Vec = (0..MAX_STREAMS_PER_BROWSER).map(|_| web.open_stream(&grant).expect("room").0).collect(); + assert!(web.open_stream(&grant).is_none(), "one tab too many"); + let online: Vec = std::iter::from_fn(|| inputs.try_recv().ok()).collect(); + assert!(matches!(online.as_slice(), [Input::WebBrowserOnline { .. }]), "online once: {online:?}"); + for n in &opened { + web.close_stream(*n); + } + let offline: Vec = std::iter::from_fn(|| inputs.try_recv().ok()).collect(); + assert!(matches!(offline.as_slice(), [Input::WebBrowserOffline { .. }]), "offline once: {offline:?}"); + } - let mut out = request("POST", "/api/sign-out", host); - out.cookie = Some(token); - route(&out, PEER, &web); - assert_eq!(route(&status, PEER, &web).status, 401, "signed out"); + #[test] + fn signing_out_closes_the_browsers_streams() { + let (web, mut inputs, _dir) = web(); + let token = sign_in(&web, &mut inputs); + let grant = web.stream_grant(&stream_head(&format!("https://{HOST}"), Some(&token))).expect("let through"); + let (_, lane, reason) = web.open_stream(&grant).unwrap(); + assert!(web.revoke(&grant.id)); + assert!(lane.is_closed()); + assert_eq!(reason.get(), protocol::web::closed::SIGNED_OUT); } #[test] fn an_ipv6_host_is_rate_limited_by_its_slash_64() { let (web, _, _dir) = web(); + let key = || TestKey::new(3).public; for i in 0..STARTS_PER_MINUTE { let peer = IpAddr::V6(std::net::Ipv6Addr::new(0x2001, 0xdb8, 1, 2, 0, 0, 0, i as u16 + 1)); - assert!(web.start_sign_in(peer, "").is_some()); + assert!(web.start_sign_in(peer, "", key()).is_some()); } let same_64 = IpAddr::V6(std::net::Ipv6Addr::new(0x2001, 0xdb8, 1, 2, 9, 9, 9, 9)); - assert!(web.start_sign_in(same_64, "").is_none(), "another address in the same /64 counts as the same host"); + assert!(web.start_sign_in(same_64, "", key()).is_none(), "another address in the same /64 counts as the same host"); let other_64 = IpAddr::V6(std::net::Ipv6Addr::new(0x2001, 0xdb8, 1, 3, 0, 0, 0, 1)); - assert!(web.start_sign_in(other_64, "").is_some()); + assert!(web.start_sign_in(other_64, "", key()).is_some()); } #[test] @@ -1168,7 +1568,7 @@ mod tests { for i in 0..=MAX_PENDING { // A peer of its own each, so the rate limit does not interfere. let peer = IpAddr::V4(std::net::Ipv4Addr::new(10, 0, (i / 250) as u8, (i % 250) as u8 + 1)); - let (token, code) = web.start_sign_in(peer, "").expect("a start"); + let (token, code) = web.start_sign_in(peer, "", TestKey::new(3).public).expect("a start"); first.get_or_insert((token, code)); } let (first_token, first_code) = first.unwrap(); @@ -1181,7 +1581,7 @@ mod tests { assert_eq!(withdrawn, vec![first_code], "the oldest pending browser made room, and its code went with it"); assert!(web.browser(Some(&first_token)).is_none()); - let (token, code) = web.start_sign_in(IpAddr::V4(std::net::Ipv4Addr::new(10, 9, 9, 9)), "").unwrap(); + let (token, code) = web.start_sign_in(IpAddr::V4(std::net::Ipv4Addr::new(10, 9, 9, 9)), "", TestKey::new(3).public).unwrap(); while inputs.try_recv().is_ok() {} web.sign_out(&token_key(&token)); assert!(matches!(inputs.try_recv(), Ok(Input::WebSignInWithdrawn { code: c }) if c == code)); @@ -1193,7 +1593,7 @@ mod tests { let mut tokens = Vec::new(); for i in 0..=MAX_SESSIONS { let peer = IpAddr::V4(std::net::Ipv4Addr::new(10, 1, (i / 250) as u8, (i % 250) as u8 + 1)); - let (token, code) = web.start_sign_in(peer, "").unwrap(); + let (token, code) = web.start_sign_in(peer, "", TestKey::new(3).public).unwrap(); web.signed_in(&code, "npub1owner"); tokens.push(token); } @@ -1207,17 +1607,17 @@ mod tests { fn sign_in_starts_are_rate_limited_per_address() { let (web, _, _dir) = web(); for _ in 0..STARTS_PER_MINUTE { - assert!(web.start_sign_in(PEER, "").is_some()); + assert!(web.start_sign_in(PEER, "", TestKey::new(3).public).is_some()); } - assert!(web.start_sign_in(PEER, "").is_none()); - assert!(web.start_sign_in(IpAddr::V4(std::net::Ipv4Addr::new(192, 168, 1, 21)), "").is_some()); + assert!(web.start_sign_in(PEER, "", TestKey::new(3).public).is_none()); + assert!(web.start_sign_in(IpAddr::V4(std::net::Ipv4Addr::new(192, 168, 1, 21)), "", TestKey::new(3).public).is_some()); } #[test] fn pending_sign_ins_are_capped() { let (web, _, _dir) = web(); for i in 0..(MAX_PENDING as u8 + 10) { - web.start_sign_in(IpAddr::V4(std::net::Ipv4Addr::new(10, 0, 0, i)), "").unwrap(); + web.start_sign_in(IpAddr::V4(std::net::Ipv4Addr::new(10, 0, 0, i)), "", TestKey::new(3).public).unwrap(); } assert!(web.browsers.borrow().len() <= MAX_PENDING); } @@ -1234,22 +1634,24 @@ mod tests { assert!(is_websocket(b"GET / HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n")); assert!(!is_websocket(b"GET / HTTP/1.1\r\nHost: x\r\n\r\n")); assert_eq!(head_len(b"GET / HTTP/1.1\r\n\r\nbody"), Some(18)); + assert!(is_stream_request(&stream_head("https://x", None)), "the browser's stream"); + assert!(!is_stream_request(b"GET / HTTP/1.1\r\nHost: x\r\nUpgrade: websocket\r\n\r\n"), "a phone's direct link"); } #[test] fn signed_in_browsers_survive_a_restart() { let dir = tempfile::tempdir().unwrap(); - let (web, mut inputs) = web_in(dir.path()); - let token = sign_in(&web, &mut inputs); + let (web, mut inputs) = page(dir.path(), Vec::new(), Box::new(now_ms)); + let key = TestKey::new(7); + let token = sign_in_with(&web, &mut inputs, &key); web.writer.flush(); // A new page over the same home, as after a restart. - let (again, _rx) = web_in(dir.path()); - let mut status = request("GET", "/api/status", HOST); - status.cookie = Some(token.clone()); - assert_eq!(route(&status, PEER, &again).status, 200, "the cookie still works"); + let (again, _rx) = page(dir.path(), Vec::new(), Box::new(now_ms)); + let grant = again.stream_grant(&stream_head(&format!("https://{HOST}"), Some(&token))).expect("the cookie still works"); + assert_eq!(grant.browser_key, key.public, "and so does the key it signed in with"); - // The file holds the key's SHA-256, never the token itself. + // The file holds the cookie's SHA-256, never the token itself. let raw = std::fs::read_to_string(dir.path().join("web-sessions.json")).unwrap(); assert!(!raw.contains(&token), "no token is written"); assert!(raw.contains(&token_key(&token)), "the key's hash is"); @@ -1257,70 +1659,45 @@ mod tests { } #[test] - fn an_expired_or_corrupt_sessions_file_starts_empty() { + fn an_expired_keyless_or_corrupt_sessions_file_starts_empty() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("web-sessions.json"); - let expired = serde_json::json!([{ - "key": "a".repeat(64), "by": "npub1x", "sinceMs": 1, "expiresMs": 2, "lastSeenMs": 1, - "peer": "192.168.1.5", "agent": "x", - }]); - std::fs::write(&path, expired.to_string()).unwrap(); - assert!(web_in(dir.path()).0.browsers.borrow().is_empty(), "an expired one is dropped"); - - std::fs::write(&path, "{not json").unwrap(); - assert!(web_in(dir.path()).0.browsers.borrow().is_empty(), "a corrupt file is empty, not fatal"); - } - - #[test] - fn the_browsers_api_lists_browsers_and_marks_the_current_one() { - let (web, mut inputs, _dir) = web(); - let first = sign_in(&web, &mut inputs); - let (second, _) = web.start_sign_in(PEER, "curl/8").unwrap(); - let Some(Input::WebSignInPending { code, .. }) = inputs.try_recv().ok() else { panic!("the engine is told the code") }; - web.signed_in(&code, "npub1owner"); - - let mut get = request("GET", "/api/browsers", HOST); - get.cookie = Some(first.clone()); - let response = route(&get, PEER, &web); - assert_eq!(response.status, 200); - let body: Value = serde_json::from_slice(&response.body).unwrap(); - let rows = body["browsers"].as_array().unwrap(); - assert_eq!(rows.len(), 2); - assert_eq!(rows[0]["id"], &token_key(&first)[..ID_LEN]); - assert_eq!(rows[0]["current"], true); - assert_eq!(rows[1]["current"], false); - assert_eq!(rows[1]["agent"], "curl/8"); - assert_eq!(rows[0]["peer"], "192.168.1.20"); - for field in ["sinceMs", "lastSeenMs", "expiresMs"] { - assert!(rows[0][field].is_number(), "{field}"); - } - assert_eq!(rows[0]["by"], "npub1owner"); - assert!(serde_json::from_slice::(&response.body).unwrap().get("token").is_none()); - assert!(second.len() > ID_LEN, "the full token is not what the page sees"); + let record = |public_key: Option, expires: u64| { + let mut r = serde_json::json!({ + "key": "a".repeat(64), "by": "npub1x", "sinceMs": 1, "expiresMs": expires, "lastSeenMs": now_ms(), + "peer": "192.168.1.5", "agent": "x", + }); + if let Some(k) = public_key { + r["publicKey"] = Value::String(k); + } + serde_json::json!([r]) + }; + let empty = |raw: String| { + std::fs::write(&path, raw).unwrap(); + page(dir.path(), Vec::new(), Box::new(now_ms)).0.browsers.borrow().is_empty() + }; + assert!(empty(record(Some(TestKey::new(1).base64url()), 2).to_string()), "an expired one is dropped"); + assert!(empty(record(None, u64::MAX).to_string()), "one from before browser keys signs in again"); + assert!(!empty(record(Some(TestKey::new(1).base64url()), u64::MAX).to_string()), "a good one is kept"); + assert!(empty("{not json".into()), "a corrupt file is empty, not fatal"); } #[test] - fn the_phone_list_is_the_page_list_without_the_current_mark() { + fn the_phone_list_names_each_browser_by_its_keys_id() { let (web, mut inputs, _dir) = web(); - let first = sign_in(&web, &mut inputs); - let (_second, _) = web.start_sign_in(PEER, "curl/8").unwrap(); - let Some(Input::WebSignInPending { code, .. }) = inputs.try_recv().ok() else { panic!("the engine is told the code") }; + let first = TestKey::new(7); + sign_in_with(&web, &mut inputs, &first); + let (_second, _) = web.start_sign_in(PEER, "curl/8", TestKey::new(8).public).unwrap(); + let code = loop { + if let Ok(Input::WebSignInPending { code, .. }) = inputs.try_recv() { + break code; + } + }; web.signed_in(&code, "npub1owner"); - let mut get = request("GET", "/api/browsers", HOST); - get.cookie = Some(first.clone()); - let body: Value = serde_json::from_slice(&route(&get, PEER, &web).body).unwrap(); - let json_ids: Vec = body["browsers"] - .as_array() - .unwrap() - .iter() - .map(|row| row["id"].as_str().unwrap().to_string()) - .collect(); - - // The phone's list and the page's are one list: same rows, same order. let phone = web.browsers(); - assert_eq!(phone.iter().map(|b| b.id.clone()).collect::>(), json_ids); - assert_eq!(phone[0].id, &token_key(&first)[..ID_LEN], "the id is the key's short public form, never the token"); + assert_eq!(phone.len(), 2); + assert_eq!(phone[0].id, first.public.id(), "the id is the key's, never the token's"); assert_eq!(phone[0].by, "npub1owner"); assert_eq!(phone[0].peer, "192.168.1.20"); assert_eq!(phone[1].agent, "curl/8"); @@ -1330,29 +1707,54 @@ mod tests { } #[test] - fn revoking_another_browser_ends_its_cookie() { + fn revoking_a_browser_ends_its_cookie() { let (web, mut inputs, _dir) = web(); - let victim = sign_in(&web, &mut inputs); - let owner = sign_in(&web, &mut inputs); - - let mut status = request("GET", "/api/status", HOST); - status.cookie = Some(victim.clone()); - assert_eq!(route(&status, PEER, &web).status, 200); + let victim = TestKey::new(7); + let token = sign_in_with(&web, &mut inputs, &victim); + assert!(web.still_signed_in(&token_key(&token))); + assert!(web.revoke(&victim.public.id())); + assert!(!web.still_signed_in(&token_key(&token)), "the revoked browser's cookie no longer works"); + assert!(!web.revoke("0123456789abcdef"), "an unknown id"); + } - let mut post = request("POST", "/api/browsers/sign-out", HOST); - post.cookie = Some(owner); - post.body = serde_json::json!({ "id": &token_key(&victim)[..ID_LEN] }).to_string().into_bytes(); - assert_eq!(route(&post, PEER, &web).status, 200); - assert_eq!(route(&status, PEER, &web).status, 401, "the revoked browser's cookie no longer works"); + #[test] + fn a_browser_whose_identity_is_no_longer_paired_reaches_nothing() { + let (web, mut inputs, _dir) = web(); + let token = sign_in(&web, &mut inputs); + // Unpaired while the bridge was down: the record survived on disk, + // the heartbeat no longer lists its identity. + web.set_devices(&[phone("npub1someoneelse")]); + assert_eq!(web.page_request(r#"{"type":"config"}"#, "npub1owner").0, 403); + assert_eq!(web.stream_grant(&stream_head(&format!("https://{HOST}"), Some(&token))).err(), Some(401)); + } - post.body = serde_json::json!({ "id": "0123456789abcdef" }).to_string().into_bytes(); - assert_eq!(route(&post, PEER, &web).status, 404, "an unknown id"); + #[test] + fn a_browser_dropped_to_make_room_loses_its_streams() { + let (web, mut inputs, _dir) = web(); + let token = sign_in(&web, &mut inputs); + let grant = web.stream_grant(&stream_head(&format!("https://{HOST}"), Some(&token))).expect("let through"); + let (_, lane, _) = web.open_stream(&grant).unwrap(); + for i in 0..MAX_SESSIONS { + let peer = IpAddr::V4(std::net::Ipv4Addr::new(10, 2, (i / 250) as u8, (i % 250) as u8 + 1)); + let (_, code) = web.start_sign_in(peer, "", TestKey::new(3).public).unwrap(); + web.signed_in(&code, "npub1owner"); + } + assert!(lane.is_closed(), "the oldest browser went, and its stream with it"); } #[test] - fn the_devices_api_shows_paired_phones_without_any_secret() { + fn unpairing_its_identity_ends_a_browser() { let (web, mut inputs, _dir) = web(); let token = sign_in(&web, &mut inputs); + web.end_by("npub1someoneelse"); + assert!(web.still_signed_in(&token_key(&token))); + web.end_by("npub1owner"); + assert!(!web.still_signed_in(&token_key(&token))); + } + + #[test] + fn the_devices_request_shows_paired_phones_without_any_secret() { + let (web, _, _dir) = web(); let phone = bridge_core::PairedPhone { npub: "npub1phone".into(), pubkey_hex: "ab".repeat(32), @@ -1377,11 +1779,9 @@ mod tests { }; web.set_devices(&[phone]); - let mut get = request("GET", "/api/devices", HOST); - get.cookie = Some(token); - let response = route(&get, PEER, &web); - assert_eq!(response.status, 200); - let body = String::from_utf8(response.body).unwrap(); + let (status, body, write) = web.page_request(r#"{"type":"devices"}"#, "npub1phone"); + assert_eq!(status, 200); + assert!(write.is_none()); let json: Value = serde_json::from_str(&body).unwrap(); assert_eq!(json["devices"][0]["npub"], "npub1phone"); assert_eq!(json["devices"][0]["label"], "Pixel"); @@ -1393,80 +1793,59 @@ mod tests { } #[test] - fn the_config_api_serves_every_field_with_its_value() { + fn the_config_request_serves_every_field_with_its_value() { let dir = tempfile::tempdir().unwrap(); - let fields = vec![ - serde_json::json!({ "key": "machineName", "value": "desktop", "editable": true, "overridden": false }), - ]; - let (web, mut inputs) = web_with_config(dir.path(), fields); - let token = sign_in(&web, &mut inputs); - - let mut get = request("GET", "/api/config", HOST); - get.cookie = Some(token); - let response = route(&get, PEER, &web); - assert_eq!(response.status, 200); - let json: Value = serde_json::from_slice(&response.body).unwrap(); - let fields = json["fields"].as_array().unwrap(); - assert!(fields.iter().any(|f| f["key"] == "machineName" && f["value"] == "desktop")); + let fields = vec![serde_json::json!({ "key": "machineName", "value": "desktop", "editable": true, "overridden": false })]; + let (web, _) = page(dir.path(), fields, Box::new(now_ms)); + let (status, body, _) = web.page_request(r#"{"type":"config"}"#, "npub1owner"); + assert_eq!(status, 200); + let json: Value = serde_json::from_str(&body).unwrap(); + assert!(json["fields"].as_array().unwrap().iter().any(|f| f["key"] == "machineName" && f["value"] == "desktop")); } #[test] - fn a_config_post_outside_the_safe_set_is_refused_and_leaves_the_file() { + fn a_config_set_outside_the_safe_set_is_refused_and_leaves_the_file() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("config.json"); let before = r#"{"machineName":"desktop","workspaceRoots":["/srv/w"],"keepMe":42}"#; std::fs::write(&path, before).unwrap(); - let (web, mut inputs) = web_with_config(dir.path(), Vec::new()); - let token = sign_in(&web, &mut inputs); - - let mut post = request("POST", "/api/config", HOST); - post.cookie = Some(token); - post.body = serde_json::json!({ "set": { "nodePath": "/evil" } }).to_string().into_bytes(); - let response = route(&post, PEER, &web); - assert_eq!(response.status, 400); - assert_eq!(serde_json::from_slice::(&response.body).unwrap()["key"], "nodePath"); + let (web, _) = page(dir.path(), Vec::new(), Box::new(now_ms)); + let (status, body, write) = web.page_request(r#"{"type":"config-set","set":{"nodePath":"/evil"}}"#, "npub1owner"); + assert_eq!(status, 400); + assert!(write.is_none()); + assert_eq!(serde_json::from_str::(&body).unwrap()["key"], "nodePath"); assert_eq!(std::fs::read_to_string(&path).unwrap(), before, "the file is untouched"); } #[test] fn an_endpoint_the_bridge_has_no_listener_for_is_refused() { let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("config.json"); - std::fs::write(&path, "{}").unwrap(); - let (web, mut inputs) = web_with_config(dir.path(), Vec::new()); - let mut post = request("POST", "/api/config", HOST); - post.cookie = Some(sign_in(&web, &mut inputs)); - post.body = serde_json::json!({ "set": { "direct.endpoints": ["ws://abc.onion:7448"] } }).to_string().into_bytes(); - let response = route(&post, PEER, &web); - assert_eq!(response.status, 400, "the bridge would refuse to start from it"); - assert_eq!(std::fs::read_to_string(&path).unwrap(), "{}"); + std::fs::write(dir.path().join("config.json"), "{}").unwrap(); + let (web, _) = page(dir.path(), Vec::new(), Box::new(now_ms)); + let (status, _, write) = web.page_request(r#"{"type":"config-set","set":{"direct.endpoints":["ws://abc.onion:7448"]}}"#, "npub1owner"); + assert_eq!(status, 400, "the bridge would refuse to start from it"); + assert!(write.is_none()); } #[test] - fn a_config_post_writes_the_file_keeping_every_other_key() { + fn a_config_set_writes_the_file_keeping_every_other_key() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("config.json"); std::fs::write(&path, r#"{"machineName":"desktop","direct":{"listen":"0.0.0.0:7447"},"keepMe":{"x":1}}"#).unwrap(); // The bridge runs the direct listener, so a wss:// endpoint is one it can serve. let listening = serde_json::json!({ "key": "direct.listen", "value": "0.0.0.0:7447", "editable": false, "overridden": false }); - let (web, mut inputs) = web_with_config(dir.path(), vec![listening]); - let token = sign_in(&web, &mut inputs); - - let mut post = request("POST", "/api/config", HOST); - post.cookie = Some(token); - post.body = serde_json::json!({ + let (web, _) = page(dir.path(), vec![listening], Box::new(now_ms)); + let request = serde_json::json!({ + "type": "config-set", "set": { "machineName": "laptop", "relays": ["wss://relay.example"], "direct.endpoints": ["wss://192.168.1.9:7447"] }, - }) - .to_string() - .into_bytes(); - let mut response = route(&post, PEER, &web); - assert_eq!(response.status, 200); - // The write runs on the blocking pool in `serve`; here, in place. - let write = response.config_write.take().expect("a write to do"); - crate::config::write_web_settings(&write.path, &write.changes).unwrap(); - let json: Value = serde_json::from_slice(&response.body).unwrap(); - assert_eq!(json["ok"], true); + }); + let (status, body, write) = web.page_request(&request.to_string(), "npub1owner"); + assert_eq!(status, 200); + let json: Value = serde_json::from_str(&body).unwrap(); assert_eq!(json["restartNeeded"], true); + // The stream makes the write on the blocking pool; here, in place. + let write = write.expect("a write to do"); + crate::config::write_web_settings(&write.path, &write.changes).unwrap(); let written: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap(); assert_eq!(written["machineName"], "laptop"); @@ -1477,36 +1856,18 @@ mod tests { } #[test] - fn a_config_post_with_a_bad_value_is_refused() { + fn a_config_set_with_a_bad_value_is_refused() { let dir = tempfile::tempdir().unwrap(); std::fs::write(dir.path().join("config.json"), "{}").unwrap(); - let (web, mut inputs) = web_with_config(dir.path(), Vec::new()); - let token = sign_in(&web, &mut inputs); - + let (web, _) = page(dir.path(), Vec::new(), Box::new(now_ms)); for (key, value) in [ ("machineName", serde_json::json!("")), ("relays", serde_json::json!(["ws://192.168.1.9:7447"])), ("direct.endpoints", serde_json::json!(["https://x"])), ("transcriptKeepLast", serde_json::json!(-1)), ] { - let mut post = request("POST", "/api/config", HOST); - post.cookie = Some(token.clone()); - post.body = serde_json::json!({ "set": { key: value } }).to_string().into_bytes(); - assert_eq!(route(&post, PEER, &web).status, 400, "{key}"); - } - } - - #[test] - fn every_new_api_needs_a_signed_in_browser() { - let (web, _rx, _dir) = web(); - for (method, path) in [ - ("GET", "/api/browsers"), - ("POST", "/api/browsers/sign-out"), - ("GET", "/api/devices"), - ("GET", "/api/config"), - ("POST", "/api/config"), - ] { - assert_eq!(route(&request(method, path, HOST), PEER, &web).status, 401, "{method} {path}"); + let request = serde_json::json!({ "type": "config-set", "set": { key: value } }); + assert_eq!(web.page_request(&request.to_string(), "npub1owner").0, 400, "{key}"); } } } diff --git a/crates/bridge-runtime/src/web_stream.rs b/crates/bridge-runtime/src/web_stream.rs new file mode 100644 index 00000000..f9f28c22 --- /dev/null +++ b/crates/bridge-runtime/src/web_stream.rs @@ -0,0 +1,387 @@ +//! A browser's stream on the web page: the one WebSocket a signed-in browser +//! drives sessions over (`protocol::web` is the spec). +//! +//! The upgrade is let through only for an allowed `Host`, the page's own +//! `Origin` and a cookie naming a signed-in browser (`Web::stream_grant`). +//! Then the browser must prove it holds the key it signed in with: it signs +//! the connection's challenge (`HELLO`), and every frame after that, each +//! with a `seq` above the last. A frame that does not verify closes the +//! stream. A verified command is checked against what a browser may send +//! (`bridge_core::browser_may_send`) and handed to the engine as the +//! identity's that let the browser in; a page request is answered here. +//! +//! What the bridge sends a browser goes through the same lane as a phone's +//! direct link: queued, never waited on, and a browser that stops reading is +//! closed rather than allowed to hold the bridge's one thread. + +use std::time::Duration; + +use bridge_core::Input; +use futures_util::{SinkExt, StreamExt}; +use protocol::web::{closed, decode_web_frame, encode_web_frame, signed_input, WebFrame}; +use tokio::io::{AsyncRead, AsyncWrite}; +use tokio_tungstenite::tungstenite::protocol::WebSocketConfig; +use tokio_tungstenite::tungstenite::Message; + +use crate::web::{StreamGrant, Web}; + +/// How long a browser has to say `HELLO` once it has its challenge: it +/// signs with a key it already holds, so no prompt stands in the way. +const HELLO_TIMEOUT: Duration = Duration::from_secs(10); +/// A stream silent this long is dropped; the page renews its presence well +/// within it. +const IDLE_TIMEOUT: Duration = Duration::from_secs(400); +/// How long the WebSocket handshake may take. +const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(10); +/// Largest frame accepted from a browser: a command and its signature. +const MAX_FRAME_BYTES: usize = 256 * 1024; + +/// Serve a request for the stream whose head is `head` (still unread from +/// `stream`'s point of view: it is replayed to the WebSocket handshake). +/// `slot`: the direct link's hub and the peer, whose per-host connection +/// slot an open stream gives back (see `Hub::release_host_slot`). +pub async fn serve(head: Vec, mut stream: S, web: &Web, slot: Option<(&crate::direct::Hub, std::net::IpAddr)>) { + let grant = match web.stream_grant(&head) { + Ok(grant) => grant, + Err(status) => { + crate::web::refuse(&mut stream, status).await; + return; + } + }; + let config = WebSocketConfig { max_message_size: Some(MAX_FRAME_BYTES), max_frame_size: Some(MAX_FRAME_BYTES), ..Default::default() }; + let replay = crate::direct::Replay::new(head, stream); + let Ok(Ok(ws)) = tokio::time::timeout(HANDSHAKE_TIMEOUT, tokio_tungstenite::accept_async_with_config(replay, Some(config))).await + else { + return; + }; + run(ws, grant, web, slot).await; +} + +/// The stream once upgraded: the handshake, then frames both ways. +async fn run(ws: W, grant: StreamGrant, web: &Web, slot: Option<(&crate::direct::Hub, std::net::IpAddr)>) +where + W: futures_util::Stream> + + futures_util::Sink + + Unpin, +{ + let (mut sink, mut source) = ws.split(); + let send = |frame: &WebFrame| Message::Text(encode_web_frame(frame)); + let challenge = base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE_NO_PAD, rand::random::<[u8; 32]>()); + if sink.send(send(&WebFrame::Challenge(challenge.clone()))).await.is_err() { + return; + } + let verifies = |seq: u64, body: &str, sig: &str| { + grant.browser_key.verifies(&signed_input(web.machine(), &grant.id, &challenge, seq, body), sig) + }; + let hello = tokio::time::timeout(HELLO_TIMEOUT, next_text(&mut source)).await.ok().flatten(); + match hello.as_deref().map(decode_web_frame) { + Some(Ok(WebFrame::Hello { sig })) if verifies(0, "", &sig) => {} + _ => { + let _ = sink.send(send(&WebFrame::Closed(closed::BAD_SIGNATURE.into()))).await; + return; + } + } + if !web.still_signed_in(&grant.key) { + let _ = sink.send(send(&WebFrame::Closed(closed::EXPIRED.into()))).await; + return; + } + web.seen(&grant.key); + let Some((n, lane, reason)) = web.open_stream(&grant) else { + let _ = sink.send(send(&WebFrame::Closed(closed::BUSY.into()))).await; + return; + }; + log::info!("[Web] A browser opened its stream"); + // Open and signed: from here the page's own caps bound it. + if let Some((hub, peer)) = slot { + hub.release_host_slot(peer); + } + let mut last_seq = 0u64; + let mut ok = sink.send(send(&WebFrame::Ready)).await.is_ok(); + while ok { + if let Some(text) = lane.pop() { + ok = sink.send(Message::Text(text)).await.is_ok(); + continue; + } + if lane.is_closed() { + let _ = sink.send(send(&WebFrame::Closed(reason.get().into()))).await; + break; + } + tokio::select! { + biased; + () = lane.ready() => { + if let Some(text) = lane.pop() { + ok = sink.send(Message::Text(text)).await.is_ok(); + } + }, + incoming = tokio::time::timeout(IDLE_TIMEOUT, source.next()) => match incoming { + Ok(Some(Ok(Message::Text(text)))) => { + match handle(&text, &grant, web, &mut last_seq, &verifies).await { + Ok(Some(answer)) => ok = sink.send(send(&answer)).await.is_ok(), + Ok(None) => {} + Err(why) => { + let _ = sink.send(send(&WebFrame::Closed(why.into()))).await; + ok = false; + } + } + } + Ok(Some(Ok(Message::Ping(_) | Message::Pong(_)))) => ok = sink.flush().await.is_ok(), + Ok(Some(Ok(Message::Binary(_) | Message::Frame(_)))) => {} + _ => ok = false, + }, + } + } + web.close_stream(n); + if let Some((hub, peer)) = slot { + hub.retake_host_slot(peer); + } + log::info!("[Web] A browser closed its stream"); +} + +/// One frame from the browser: its answer, nothing, or why the stream ends. +async fn handle( + text: &str, + grant: &StreamGrant, + web: &Web, + last_seq: &mut u64, + verifies: &impl Fn(u64, &str, &str) -> bool, +) -> Result, &'static str> { + let (seq, body, sig, page) = match decode_web_frame(text) { + Ok(WebFrame::Cmd { seq, body, sig }) => (seq, body, sig, false), + Ok(WebFrame::Page { seq, body, sig }) => (seq, body, sig, true), + _ => return Err(closed::BAD_FRAME), + }; + // A `seq` that does not grow is a replay, however good its signature. + if seq <= *last_seq || !verifies(seq, &body, &sig) { + return Err(closed::BAD_SIGNATURE); + } + *last_seq = seq; + if !web.still_signed_in(&grant.key) { + return Err(closed::EXPIRED); + } + web.seen(&grant.key); + if page { + let (status, reply, write) = web.page_request(&body, &grant.by); + let (status, reply) = match write { + Some(write) => crate::web::write_config_now(write).await, + None => (status, reply), + }; + let reply = serde_json::json!({ "status": status, "body": serde_json::from_str::(&reply).unwrap_or_default() }); + return Ok(Some(WebFrame::Reply { seq, reply: reply.to_string() })); + } + let msg = match protocol::decode_phone_to_bridge(&body) { + Ok(msg) => msg, + Err(err) => return Ok(Some(WebFrame::Ok { seq, accepted: false, message: format!("invalid: {err}") })), + }; + if !bridge_core::browser_may_send(&msg) { + return Ok(Some(WebFrame::Ok { seq, accepted: false, message: "not from a browser".into() })); + } + let _ = web.inputs().send(Input::WebCommand { id: grant.id.clone(), by: grant.by.clone(), msg: Box::new(msg) }); + Ok(Some(WebFrame::Ok { seq, accepted: true, message: String::new() })) +} + +async fn next_text(source: &mut S) -> Option +where + S: futures_util::Stream> + Unpin, +{ + loop { + match source.next().await? { + Ok(Message::Text(text)) => return Some(text), + Ok(Message::Ping(_) | Message::Pong(_)) => continue, + _ => return None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::web::tests::{clock, page, sign_in_with, TestKey, HOST}; + use crate::web::STREAM_PATH; + use tokio::io::DuplexStream; + use tokio_tungstenite::tungstenite::client::IntoClientRequest; + use tokio_tungstenite::WebSocketStream; + + type Ws = WebSocketStream; + + /// Serve one stream request from a browser holding `cookie` at `origin`, + /// while `client` plays the browser's side; both run to their end. + async fn with_stream(web: &Web, cookie: &str, origin: &str, client: F) + where + F: FnOnce(Ws) -> Fut, + Fut: std::future::Future, + { + let (client_io, mut server_io) = tokio::io::duplex(1 << 20); + let server = async { + if let Some(head) = crate::web::read_head(&mut server_io).await { + serve(head, server_io, web, None).await; + } + }; + let browser = async { + let mut request = format!("ws://{HOST}{STREAM_PATH}").into_client_request().unwrap(); + request.headers_mut().insert("Origin", origin.parse().unwrap()); + request.headers_mut().insert("Cookie", format!("__Host-codedeck={cookie}").parse().unwrap()); + if let Ok((ws, _)) = tokio_tungstenite::client_async(request, client_io).await { + client(ws).await; + } + }; + tokio::join!(server, browser); + } + + async fn recv(ws: &mut Ws) -> WebFrame { + let text = next_text(ws).await.expect("a frame"); + decode_web_frame(&text).expect("a web frame") + } + + async fn send(ws: &mut Ws, frame: WebFrame) { + ws.send(Message::Text(encode_web_frame(&frame))).await.unwrap(); + } + + /// What `key` signs for frame `seq` with `body`, on a connection whose + /// challenge is `challenge`. + fn sign(key: &TestKey, challenge: &str, seq: u64, body: &str) -> String { + key.sign(&signed_input("npub1machine", &key.public.id(), challenge, seq, body)) + } + + /// Read the challenge and say a good `HELLO`; returns the challenge once + /// the bridge said `READY`. + async fn hello(ws: &mut Ws, key: &TestKey) -> String { + let WebFrame::Challenge(challenge) = recv(ws).await else { panic!("a challenge first") }; + send(ws, WebFrame::Hello { sig: sign(key, &challenge, 0, "") }).await; + assert_eq!(recv(ws).await, WebFrame::Ready); + challenge + } + + fn commands(inputs: &mut tokio::sync::mpsc::UnboundedReceiver) -> Vec { + std::iter::from_fn(|| inputs.try_recv().ok()) + .filter_map(|input| match input { + Input::WebCommand { msg, .. } => Some(protocol::encode_phone_to_bridge(&msg).unwrap()), + _ => None, + }) + .collect() + } + + const REFRESH: &str = r#"{"v":12,"type":"refresh-sessions"}"#; + + #[tokio::test(flavor = "current_thread")] + async fn a_signed_command_reaches_the_engine_and_the_bridge_answers_down_the_stream() { + let dir = tempfile::tempdir().unwrap(); + let (_, now) = clock(); + let (web, mut inputs) = page(dir.path(), Vec::new(), now); + let key = TestKey::new(7); + let cookie = sign_in_with(&web, &mut inputs, &key); + while inputs.try_recv().is_ok() {} + let (page_ref, key_ref) = (&web, &key); + with_stream(&web, &cookie, &format!("https://{HOST}"), |mut ws| async move { + let (web, key) = (page_ref, key_ref); + let challenge = hello(&mut ws, key).await; + send(&mut ws, WebFrame::Cmd { seq: 1, body: REFRESH.into(), sig: sign(key, &challenge, 1, REFRESH) }).await; + assert_eq!(recv(&mut ws).await, WebFrame::Ok { seq: 1, accepted: true, message: String::new() }); + web.deliver(&key.public.id(), r#"{"v":12,"type":"input-ack","sessionId":"s","inputId":"i"}"#); + let WebFrame::Msg(message) = recv(&mut ws).await else { panic!("the bridge's message") }; + assert!(message.contains("input-ack")); + }) + .await; + let got: Vec = std::iter::from_fn(|| inputs.try_recv().ok()).collect(); + assert!(matches!(&got[0], Input::WebBrowserOnline { id, by } if *id == key.public.id() && by == "npub1owner"), "{got:?}"); + assert!(matches!(&got[1], Input::WebCommand { id, .. } if *id == key.public.id()), "{got:?}"); + assert!(matches!(&got[2], Input::WebBrowserOffline { .. }), "{got:?}"); + } + + #[tokio::test(flavor = "current_thread")] + async fn a_hello_by_another_key_is_closed() { + let dir = tempfile::tempdir().unwrap(); + let (web, mut inputs) = page(dir.path(), Vec::new(), clock().1); + let cookie = sign_in_with(&web, &mut inputs, &TestKey::new(7)); + while inputs.try_recv().is_ok() {} + let thief = TestKey::new(8); + with_stream(&web, &cookie, &format!("https://{HOST}"), |mut ws| async move { + let WebFrame::Challenge(challenge) = recv(&mut ws).await else { panic!() }; + // The cookie alone, with a key of the thief's own. + let sig = thief.sign(&signed_input("npub1machine", &TestKey::new(7).public.id(), &challenge, 0, "")); + send(&mut ws, WebFrame::Hello { sig }).await; + assert_eq!(recv(&mut ws).await, WebFrame::Closed(closed::BAD_SIGNATURE.into())); + }) + .await; + assert!(commands(&mut inputs).is_empty()); + } + + #[tokio::test(flavor = "current_thread")] + async fn a_replayed_frame_closes_the_stream() { + let dir = tempfile::tempdir().unwrap(); + let (web, mut inputs) = page(dir.path(), Vec::new(), clock().1); + let key = TestKey::new(7); + let cookie = sign_in_with(&web, &mut inputs, &key); + let origin = format!("https://{HOST}"); + + // The same seq twice on one connection. + let replay_key = TestKey::new(7); + with_stream(&web, &cookie, &origin, |mut ws| async move { + let challenge = hello(&mut ws, &replay_key).await; + let frame = WebFrame::Cmd { seq: 1, body: REFRESH.into(), sig: sign(&replay_key, &challenge, 1, REFRESH) }; + send(&mut ws, frame.clone()).await; + assert!(matches!(recv(&mut ws).await, WebFrame::Ok { accepted: true, .. })); + send(&mut ws, frame).await; + assert_eq!(recv(&mut ws).await, WebFrame::Closed(closed::BAD_SIGNATURE.into())); + }) + .await; + assert_eq!(commands(&mut inputs).len(), 1, "the replay ran nothing"); + + // A frame signed for an earlier connection's challenge. + let first = TestKey::new(7); + let old_challenge = std::cell::RefCell::new(String::new()); + let (slot, first) = (&old_challenge, &first); + with_stream(&web, &cookie, &origin, |mut ws| async move { + *slot.borrow_mut() = hello(&mut ws, first).await; + }) + .await; + let second = TestKey::new(7); + let old = old_challenge.borrow().clone(); + with_stream(&web, &cookie, &origin, |mut ws| async move { + hello(&mut ws, &second).await; + send(&mut ws, WebFrame::Cmd { seq: 1, body: REFRESH.into(), sig: sign(&second, &old, 1, REFRESH) }).await; + assert_eq!(recv(&mut ws).await, WebFrame::Closed(closed::BAD_SIGNATURE.into())); + }) + .await; + assert!(commands(&mut inputs).is_empty(), "nothing from another connection runs"); + } + + #[tokio::test(flavor = "current_thread")] + async fn a_command_a_browser_may_not_send_is_refused_and_a_page_request_answered() { + let dir = tempfile::tempdir().unwrap(); + let (web, mut inputs) = page(dir.path(), Vec::new(), clock().1); + let key = TestKey::new(7); + let cookie = sign_in_with(&web, &mut inputs, &key); + with_stream(&web, &cookie, &format!("https://{HOST}"), |mut ws| async move { + let challenge = hello(&mut ws, &key).await; + let sign_in = r#"{"v":12,"type":"web-sign-in","code":"K7QM-4XPA"}"#; + send(&mut ws, WebFrame::Cmd { seq: 1, body: sign_in.into(), sig: sign(&key, &challenge, 1, sign_in) }).await; + assert_eq!(recv(&mut ws).await, WebFrame::Ok { seq: 1, accepted: false, message: "not from a browser".into() }); + let devices = r#"{"type":"devices"}"#; + send(&mut ws, WebFrame::Page { seq: 2, body: devices.into(), sig: sign(&key, &challenge, 2, devices) }).await; + let WebFrame::Reply { seq: 2, reply } = recv(&mut ws).await else { panic!("a reply") }; + let reply: serde_json::Value = serde_json::from_str(&reply).unwrap(); + assert_eq!(reply["status"], 200); + assert!(reply["body"]["devices"].is_array()); + }) + .await; + assert!(commands(&mut inputs).is_empty(), "the engine never saw the sign-in"); + } + + #[tokio::test(flavor = "current_thread")] + async fn a_lapsed_browser_is_closed_at_its_next_frame() { + let dir = tempfile::tempdir().unwrap(); + let (now, clock) = clock(); + let (web, mut inputs) = page(dir.path(), Vec::new(), clock); + let key = TestKey::new(7); + let cookie = sign_in_with(&web, &mut inputs, &key); + while inputs.try_recv().is_ok() {} + with_stream(&web, &cookie, &format!("https://{HOST}"), |mut ws| async move { + let challenge = hello(&mut ws, &key).await; + now.set(now.get() + crate::web::IDLE_TTL_MS + 1); + send(&mut ws, WebFrame::Cmd { seq: 1, body: REFRESH.into(), sig: sign(&key, &challenge, 1, REFRESH) }).await; + assert_eq!(recv(&mut ws).await, WebFrame::Closed(closed::EXPIRED.into())); + }) + .await; + assert!(commands(&mut inputs).is_empty()); + } +} diff --git a/crates/bridge-runtime/tests/web_page.rs b/crates/bridge-runtime/tests/web_page.rs new file mode 100644 index 00000000..95d56851 --- /dev/null +++ b/crates/bridge-runtime/tests/web_page.rs @@ -0,0 +1,332 @@ +//! The bridge's web page as a client, end to end: the real runtime and agent +//! host (its scripted `fake` agent), a real phone core paired through a relay +//! on loopback, and a browser played by this test over real TLS — its own +//! P-256 key, the sign-in the phone approves, then a session driven over the +//! signed stream. +//! +//! Needs `node` and a built agent host, like `e2e.rs`: +//! `cargo test -p bridge-runtime --test web_page -- --ignored`. +//! +//! `hold_a_bridge_for_a_real_browser` is a tool rather than a test: with +//! `CODEDECK_WEB_HOLD=` it runs the same bridge and phone, prints the +//! page's address, and has the phone approve every code written to `` +//! for `CODEDECK_WEB_HOLD_SECS` (default 300), so a real browser can be +//! pointed at the page. + +mod support; + +use std::path::{Path, PathBuf}; +use std::rc::Rc; +use std::sync::Arc; +use std::time::Duration; + +use base64::Engine as _; +use bridge_runtime::config::{self, Flags}; +use bridge_runtime::runtime::{self, Mode, Options}; +use bridge_runtime::state::StateFile; +use client_runtime::client_core::connection::ConnectionStatus; +use client_runtime::protocol::crypto::generate_keypair; +use client_runtime::protocol::events::BridgeToPhone; +use client_runtime::{Core, CoreConfig, CoreObserver, CorePorts, Intent, LocalSigner, MemoryTranscriptStore, SystemClock, TimeEntropy}; +use futures_util::{SinkExt, StreamExt}; +use p256::ecdsa::signature::Signer as _; +use p256::ecdsa::{Signature, SigningKey}; +use protocol::web::{decode_web_frame, encode_web_frame, signed_input, WebFrame}; +use rustls::pki_types::ServerName; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::sync::oneshot; +use tokio::task::LocalSet; +use tokio_tungstenite::tungstenite::client::IntoClientRequest; +use tokio_tungstenite::tungstenite::Message; + +const TIMEOUT: Duration = Duration::from_secs(20); + +fn bundle() -> PathBuf { + std::env::var("AGENT_HOST_BUNDLE") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../packages/agent-host/dist/main.js")) +} + +struct Observer; +impl CoreObserver for Observer { + fn connection_changed(&self, _: ConnectionStatus, _: bool, _: &[String]) {} + fn bridge_message(&self, _: String, _: BridgeToPhone) {} +} + +/// Poll `check` until it gives a value (or fail after [`TIMEOUT`]). +async fn until(what: &str, mut check: F) -> T +where + F: FnMut() -> Fut, + Fut: std::future::Future>, +{ + let deadline = tokio::time::Instant::now() + TIMEOUT; + loop { + if let Some(v) = check().await { + return v; + } + assert!(tokio::time::Instant::now() < deadline, "timed out waiting for {what}"); + tokio::time::sleep(Duration::from_millis(50)).await; + } +} + +/// A free loopback port for the page's listener. +fn free_port() -> u16 { + std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() +} + +/// The bridge with its direct link (and so its page) on `port`, and a phone +/// paired with it. Returns the phone and the machine it knows. +async fn bridge_and_phone(home: &Path, workspace: &Path, port: u16) -> (Core, String, oneshot::Sender<()>) { + let relay = support::relay::start().await; + let flags = Flags { + home: Some(home.into()), + machine_name: Some("web".into()), + relays: vec![relay], + workspaces: vec![workspace.into()], + agent_host: Some(bundle()), + ..Default::default() + }; + let mut config = config::load(&flags).expect("config"); + config.host_env.insert("CODEDECK_AGENT_HOST_DRIVERS".into(), "fake".into()); + config.direct.listen = Some(format!("127.0.0.1:{port}").parse().unwrap()); + config.direct.endpoints = vec![format!("wss://127.0.0.1:{port}")]; + let state = StateFile::open(home).unwrap(); + let keys = state.identity().unwrap(); + let (stop, stop_rx) = oneshot::channel(); + let (urls_tx, mut urls) = tokio::sync::mpsc::unbounded_channel(); + let mut options = Options::new(Mode::Run); + options.signals = false; + options.stop = Some(stop_rx); + options.pairing_urls = Some(urls_tx); + tokio::task::spawn_local(runtime::run(config, state, keys, options)); + let pairing_url = tokio::time::timeout(TIMEOUT, urls.recv()).await.expect("a pairing window opens").unwrap(); + + let core = Core::spawn( + CoreConfig::new(Rc::new(LocalSigner(generate_keypair())), None, false, None), + CorePorts { transcript_store: Rc::new(MemoryTranscriptStore::new()), ..CorePorts::default() }, + Rc::new(Observer), + Rc::new(SystemClock), + Rc::new(TimeEntropy), + ) + .await; + core.start(); + core.dispatch(Intent::BeginPairing { url: pairing_url, label: "web-phone".into() }).await; + until("pairing", || async { + let view = core.pairing_view().await?; + assert_ne!(view.phase, "failed", "pairing failed: {:?}", view.error); + (view.phase == "paired").then_some(()) + }) + .await; + let machine = until("the machine", || async { core.machines_view().await.machines.keys().next().cloned() }).await; + // A session can start only once the agent host has reported its + // catalog; before that a create-session is refused. + until("the agent catalog", || async { + core.machines_view().await.machines.get(&machine)?.agents.iter().any(|a| a.id == "fake").then_some(()) + }) + .await; + (core, machine, stop) +} + +/// The browser: a key, a cookie, and TLS pinned to the certificate the +/// bridge made in `home` — what a user checks against the phone's pin. +struct Browser { + port: u16, + tls: tokio_rustls::TlsConnector, + key: SigningKey, + cookie: Option, +} + +impl Browser { + fn new(home: &Path, port: u16) -> Self { + let cert = std::fs::read(home.join("direct/cert.der")).expect("the page's certificate"); + let pin = hex::encode(Sha256::digest(&cert)); + let tls = tokio_rustls::TlsConnector::from(Arc::new(nostr_transport::direct::pinned_client_config(&pin))); + Self { port, tls, key: SigningKey::from_bytes(&[42u8; 32].into()).unwrap(), cookie: None } + } + + fn public_key(&self) -> String { + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(self.key.verifying_key().to_encoded_point(false).as_bytes()) + } + + fn id(&self) -> String { + hex::encode(Sha256::digest(self.key.verifying_key().to_encoded_point(false).as_bytes()))[..16].to_string() + } + + async fn tls(&self) -> tokio_rustls::client::TlsStream { + let tcp = tokio::net::TcpStream::connect(("127.0.0.1", self.port)).await.unwrap(); + self.tls.connect(ServerName::try_from("codedeck-bridge").unwrap(), tcp).await.unwrap() + } + + /// One HTTPS request as a browser on the page makes it: (status, JSON). + async fn request(&mut self, method: &str, path: &str, body: Option) -> (u16, Value) { + let mut stream = self.tls().await; + let body = body.map(|b| b.to_string()).unwrap_or_default(); + let cookie = self.cookie.as_ref().map(|c| format!("Cookie: __Host-codedeck={c}\r\n")).unwrap_or_default(); + let head = format!( + "{method} {path} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nOrigin: https://127.0.0.1:{port}\r\n{cookie}\ + Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len(), + port = self.port, + ); + stream.write_all(head.as_bytes()).await.unwrap(); + let mut raw = Vec::new(); + let _ = stream.read_to_end(&mut raw).await; + let text = String::from_utf8_lossy(&raw).to_string(); + let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, "")); + let status = head.split(' ').nth(1).and_then(|s| s.parse().ok()).unwrap_or(0); + if let Some(value) = head.lines().find_map(|l| l.strip_prefix("Set-Cookie: __Host-codedeck=")) { + self.cookie = Some(value.split(';').next().unwrap().to_string()); + } + (status, serde_json::from_str(body).unwrap_or(Value::Null)) + } + + fn sign(&self, challenge: &str, seq: u64, body: &str) -> String { + let sig: Signature = self.key.sign(&signed_input(&machine_npub(), &self.id(), challenge, seq, body)); + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sig.to_bytes()) + } +} + +/// The page's machine, as `/api/me` names it (set once the browser asked). +static MACHINE: std::sync::OnceLock = std::sync::OnceLock::new(); +fn machine_npub() -> String { + MACHINE.get().cloned().unwrap_or_default() +} + +type Stream = tokio_tungstenite::WebSocketStream>; + +async fn next(ws: &mut Stream) -> WebFrame { + loop { + let msg = tokio::time::timeout(TIMEOUT, ws.next()).await.expect("a frame in time").expect("open").unwrap(); + if let Message::Text(text) = msg { + return decode_web_frame(&text).unwrap(); + } + } +} + +#[tokio::test(flavor = "current_thread")] +#[ignore = "needs node and a built packages/agent-host bundle"] +async fn a_browser_signed_in_by_the_phone_drives_a_session_over_its_signed_stream() { + assert!(bundle().exists(), "agent host bundle missing at {} — build packages/agent-host first", bundle().display()); + LocalSet::new() + .run_until(async { + let home = tempfile::tempdir().unwrap(); + let workspace = tempfile::tempdir().unwrap(); + let port = free_port(); + let (core, machine, stop) = bridge_and_phone(home.path(), workspace.path(), port).await; + let mut browser = Browser::new(home.path(), port); + + // --- sign-in: the key goes with the start, the phone approves --- + let (status, started) = browser.request("POST", "/api/sign-in", Some(json!({ "key": browser.public_key() }))).await; + assert_eq!(status, 200, "{started}"); + let code = started["code"].as_str().unwrap().to_string(); + core.dispatch(Intent::WebSignIn { machine: machine.clone(), code }).await; + let me = until("the phone to let the browser in", || { + let mut b = Browser { cookie: browser.cookie.clone(), ..Browser::new(home.path(), port) }; + async move { + let (_, me) = b.request("GET", "/api/me", None).await; + (me["state"] == "signed-in").then_some(me) + } + }) + .await; + assert_eq!(me["id"], browser.id(), "the browser let in is the key's"); + MACHINE.set(me["machine"].as_str().unwrap().to_string()).unwrap(); + + // --- the cookie alone gets nothing beyond its own state --- + let (status, _) = browser.request("GET", "/api/config", None).await; + assert_eq!(status, 404); + + // --- the stream --- + let tls = browser.tls().await; + let mut request = format!("wss://127.0.0.1:{port}/api/stream").into_client_request().unwrap(); + request.headers_mut().insert("Origin", format!("https://127.0.0.1:{port}").parse().unwrap()); + request.headers_mut().insert("Cookie", format!("__Host-codedeck={}", browser.cookie.clone().unwrap()).parse().unwrap()); + let (mut ws, _) = tokio_tungstenite::client_async(request, tls).await.expect("the stream opens"); + let WebFrame::Challenge(challenge) = next(&mut ws).await else { panic!("a challenge") }; + ws.send(Message::Text(encode_web_frame(&WebFrame::Hello { sig: browser.sign(&challenge, 0, "") }))).await.unwrap(); + assert_eq!(next(&mut ws).await, WebFrame::Ready); + + let mut seq = 0; + let mut command = async |ws: &mut Stream, msg: Value| { + seq += 1; + let body = msg.to_string(); + let frame = WebFrame::Cmd { seq, body: body.clone(), sig: browser.sign(&challenge, seq, &body) }; + ws.send(Message::Text(encode_web_frame(&frame))).await.unwrap(); + }; + command(&mut ws, json!({"v":12,"type":"create-session","agent":"fake"})).await; + + // The browser hears the session become ready, then drives it. + let mut session = None; + let mut echoed = false; + let deadline = tokio::time::Instant::now() + TIMEOUT; + while !echoed { + assert!(tokio::time::Instant::now() < deadline, "the session and its echo, in time"); + match next(&mut ws).await { + WebFrame::Ok { accepted, message, .. } => assert!(accepted, "{message}"), + WebFrame::Msg(text) => { + let msg: Value = serde_json::from_str(&text).unwrap(); + assert_ne!(msg["type"], "session-failed", "the session did not start: {msg}"); + if msg["type"] == "session-ready" && session.is_none() { + let id = msg["session"]["id"].as_str().unwrap().to_string(); + command(&mut ws, json!({"v":12,"type":"presence","watching":id})).await; + command(&mut ws, json!({"v":12,"type":"input","sessionId":id,"text":"hello","inputId":"w1"})).await; + session = Some(id); + } + let text = msg["entries"].as_array().into_iter().flatten().filter_map(|e| e["text"].as_str()).collect::(); + echoed |= msg["type"] == "output" && text.contains("echo: hello"); + } + other => panic!("unexpected {other:?}"), + } + } + + // The phone sees the session the browser made: one engine, two clients. + let session = session.unwrap(); + until("the phone to list the browser's session", || async { + core.machines_view().await.machines.get(&machine)?.sessions.contains_key(&session).then_some(()) + }) + .await; + + // Signing out from the phone closes the stream at once. + core.dispatch(Intent::SignOutWebBrowser { machine: machine.clone(), id: browser.id() }).await; + loop { + match next(&mut ws).await { + WebFrame::Closed(reason) => { + assert_eq!(reason, "signed-out"); + break; + } + _ => continue, + } + } + let _ = stop.send(()); + }) + .await; +} + +#[tokio::test(flavor = "current_thread")] +#[ignore = "a tool: holds a bridge for a real browser when CODEDECK_WEB_HOLD names a code file"] +async fn hold_a_bridge_for_a_real_browser() { + let Ok(code_file) = std::env::var("CODEDECK_WEB_HOLD") else { return }; + let secs: u64 = std::env::var("CODEDECK_WEB_HOLD_SECS").ok().and_then(|s| s.parse().ok()).unwrap_or(300); + LocalSet::new() + .run_until(async { + let home = tempfile::tempdir().unwrap(); + let workspace = tempfile::tempdir().unwrap(); + let port: u16 = std::env::var("CODEDECK_WEB_HOLD_PORT").ok().and_then(|p| p.parse().ok()).unwrap_or_else(free_port); + let (core, machine, stop) = bridge_and_phone(home.path(), workspace.path(), port).await; + println!("PAGE https://127.0.0.1:{port}/"); + let deadline = tokio::time::Instant::now() + Duration::from_secs(secs); + let mut approved = String::new(); + while tokio::time::Instant::now() < deadline { + let code = std::fs::read_to_string(&code_file).unwrap_or_default().trim().to_string(); + if !code.is_empty() && code != approved { + println!("APPROVING {code}"); + core.dispatch(Intent::WebSignIn { machine: machine.clone(), code: code.clone() }).await; + approved = code; + } + tokio::time::sleep(Duration::from_millis(200)).await; + } + let _ = stop.send(()); + }) + .await; +} diff --git a/crates/bridge-runtime/web/app.css b/crates/bridge-runtime/web/app.css index 2ff4ed5d..92fa8f2f 100644 --- a/crates/bridge-runtime/web/app.css +++ b/crates/bridge-runtime/web/app.css @@ -78,16 +78,8 @@ button.quiet:hover { color: var(--text); border-color: var(--muted); } .state.busy::before { background: var(--busy); } .state.bad::before { background: var(--bad); } -.table-wrap { overflow-x: auto; } -table.sessions { width: 100%; border-collapse: collapse; } -.sessions th { text-align: left; font-weight: 500; color: var(--muted); font-size: 13px; padding: 0 12px 10px 0; border-bottom: 1px solid var(--line); } -.sessions td { padding: 11px 12px 11px 0; border-bottom: 1px solid var(--line); vertical-align: top; } -.sessions tr:last-child td { border-bottom: none; } -.sessions .title { max-width: 360px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.sessions .folder { color: var(--dim); max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } -.sessions .when { color: var(--dim); white-space: nowrap; } - -.tabs { display: flex; gap: 4px; margin: -4px 0 20px; border-bottom: 1px solid var(--line); overflow-x: auto; } + +.tabs { display: flex; gap: 4px; margin: -4px 0 20px; border-bottom: 1px solid var(--line); overflow-x: auto; overflow-y: hidden; } .tabs a { color: var(--dim); text-decoration: none; padding: 10px 14px; border-bottom: 2px solid transparent; margin-bottom: -1px; white-space: nowrap; } .tabs a:hover { color: var(--text); } .tabs a.on { color: var(--text); border-bottom-color: var(--text); } @@ -121,9 +113,84 @@ button.danger:hover { color: var(--bad); border-color: var(--bad); } .actions .primary { margin-top: 0; } .ok { color: var(--ok); } +.bar-end { display: flex; align-items: center; gap: 14px; } +.field select, .session-tools select { font: inherit; color: var(--text); background: var(--raised); border: 1px solid var(--line); border-radius: 10px; padding: 9px 12px; } + +/* Sessions: the list beside the open one, which fills the window. */ +main.wide { max-width: 1400px; } +.split { display: grid; grid-template-columns: 280px 1fr; gap: 18px; align-items: start; } +.session-list { display: flex; flex-direction: column; gap: 4px; position: sticky; top: 80px; max-height: calc(100vh - 170px); overflow-y: auto; } +.new-link { color: var(--text); text-decoration: none; border: 1px dashed var(--line); border-radius: 12px; padding: 10px 14px; margin-bottom: 6px; } +.new-link:hover { border-color: var(--muted); } +.session-item { display: flex; flex-direction: column; gap: 4px; padding: 10px 14px; border-radius: 12px; color: var(--text); text-decoration: none; border: 1px solid transparent; } +.session-item:hover { background: var(--surface); } +.session-item.on { background: var(--surface); border-color: var(--line); } +.session-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.session-meta { display: flex; gap: 10px; align-items: center; min-width: 0; flex-wrap: wrap; } +.session-main { min-width: 0; } +.session-view { display: flex; flex-direction: column; height: calc(100vh - 150px); background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; } +.session-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 14px 18px; border-bottom: 1px solid var(--line); } +.session-head-main { min-width: 0; display: flex; flex-direction: column; gap: 4px; } +.session-name { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.session-tools { display: flex; gap: 8px; align-items: center; flex-shrink: 0; } +.session-tools button { padding: 7px 14px; } +.transcript { flex: 1; overflow-y: auto; padding: 18px; display: flex; flex-direction: column; } +#entries, #live { display: flex; flex-direction: column; gap: 10px; } +#live { margin-top: 10px; } +#live:empty { display: none; } + +.msg { line-height: 1.55; overflow-wrap: anywhere; } +.msg p { margin: 0 0 8px; white-space: pre-wrap; } +.msg p:last-child { margin-bottom: 0; } +.msg.from-user { align-self: flex-end; max-width: 80%; background: var(--raised); border: 1px solid var(--line); border-radius: 14px 14px 4px 14px; padding: 9px 14px; white-space: pre-wrap; } +.msg.live { opacity: 0.85; } +.msg code, .block code { font-family: ui-monospace, "JetBrains Mono", Menlo, Consolas, monospace; font-size: 13px; background: var(--raised); border-radius: 5px; padding: 1px 5px; } +.code-block { background: var(--bg); border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; overflow-x: auto; margin: 0 0 8px; } +.code-block code { background: none; padding: 0; } +.thinking { color: var(--muted); font-size: 14px; white-space: pre-wrap; } +.thinking summary { cursor: pointer; color: var(--dim); } +.tool { border: 1px solid var(--line); border-radius: 10px; padding: 7px 12px; } +.tool summary { cursor: pointer; display: flex; gap: 8px; align-items: center; min-width: 0; } +.tool-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--dim); } +.tool-io, .diff { font-family: ui-monospace, "JetBrains Mono", Menlo, Consolas, monospace; font-size: 12.5px; background: var(--bg); border-radius: 8px; padding: 8px 10px; margin: 8px 0 2px; max-height: 320px; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; } +.tool-io.error { color: var(--bad); } +.diff-path { color: var(--dim); margin-bottom: 4px; } +.diff-add { color: var(--ok); } +.diff-del { color: var(--bad); } +.diff-context { color: var(--dim); } +.block { border-left: 2px solid var(--line); padding: 2px 0 2px 12px; } +.block-head { font-size: 12px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--dim); margin-bottom: 6px; } +.block p { margin: 0 0 6px; white-space: pre-wrap; } +.todos { margin: 0; padding-left: 18px; line-height: 1.6; } +.todo.completed, .todo.cancelled { color: var(--muted); text-decoration: line-through; } +.todo.in_progress { color: var(--busy); } +.line { font-size: 14px; } +.sub { border-left: 2px solid var(--raised); padding-left: 10px; display: flex; flex-direction: column; gap: 4px; } +.sub-label { font-size: 12px; color: var(--muted); } + +.card-entry { border: 1px solid var(--dim); border-radius: 12px; padding: 12px 14px; display: flex; flex-direction: column; gap: 8px; } +.card-entry.done { border-color: var(--line); } +.card-entry textarea, .card-entry .other, .composer textarea { font: inherit; color: var(--text); background: var(--raised); border: 1px solid var(--line); border-radius: 10px; padding: 8px 12px; width: 100%; resize: vertical; } +.card-actions { display: flex; flex-wrap: wrap; gap: 8px; } +button.small-btn { padding: 6px 14px; margin-top: 0; font-size: 14px; } +.choices { display: flex; flex-direction: column; gap: 6px; } +.choice { display: flex; gap: 8px; align-items: baseline; } + +.composer { display: flex; gap: 10px; align-items: flex-end; padding: 12px 14px; border-top: 1px solid var(--line); } +.composer textarea { min-height: 44px; max-height: 40vh; } +.composer .primary { margin-top: 0; } + +.toast { position: fixed; bottom: 22px; left: 50%; transform: translateX(-50%); background: var(--raised); border: 1px solid var(--line); border-radius: 12px; padding: 10px 16px; max-width: min(560px, calc(100vw - 32px)); } + +@media (max-width: 800px) { + .split { grid-template-columns: 1fr; } + .session-list { position: static; max-height: 220px; } +} + @media (max-width: 600px) { main { padding: 16px; } .bar { padding: 12px 16px; } - .sessions .folder, .sessions th:nth-child(4) { display: none; } + .session-view { height: calc(100vh - 120px); } + .msg.from-user { max-width: 92%; } } diff --git a/crates/bridge-runtime/web/app.js b/crates/bridge-runtime/web/app.js index 158604b6..0de84f32 100644 --- a/crates/bridge-runtime/web/app.js +++ b/crates/bridge-runtime/web/app.js @@ -1,21 +1,33 @@ -// The bridge's web page. Plain DOM, no dependencies: everything it loads is +// The bridge's web page: a client that drives the bridge's sessions, signed +// in by a paired phone. Plain DOM, no dependencies: everything it loads is // served by the bridge itself (its CSP allows nothing else). Text from the -// bridge is always set as text, never as HTML. +// bridge — transcripts above all, which hold whatever a tool read — is always +// set as text, never as HTML. +// +// The browser holds a key of its own: a WebCrypto ECDSA P-256 key made at +// sign-in, whose private half cannot be exported. Every frame it sends on +// its stream is signed with it (protocol::web is the spec), so the cookie +// alone is worth nothing to whoever copies it. "use strict"; +const PROTOCOL_VERSION = 12; +const SIGNING_CONTEXT = "codedeck-web-v1"; +// The page renews its presence (a signed frame) this often: it keeps the +// stream from going idle and the browser's sign-in from lapsing while open. +const PRESENCE_MS = 5 * 60 * 1000; + const views = ["loading", "signed-out", "pending", "dashboard"]; -const tabs = ["overview", "usage", "browsers", "devices", "settings"]; +const tabs = ["sessions", "overview", "usage", "browsers", "devices", "settings"]; let pollTimer = null; let expiresAt = 0; -// The latest status, so switching tabs renders at once instead of waiting -// for the next poll. -let lastStatus = null; +let me = null; const $ = (id) => document.getElementById(id); function show(view) { for (const v of views) $(v).hidden = v !== view; $("sign-out").hidden = view !== "dashboard"; + $("link").hidden = view !== "dashboard"; } async function api(path, method = "GET", payload = {}) { @@ -32,37 +44,90 @@ async function api(path, method = "GET", payload = {}) { function el(tag, attrs = {}, ...children) { const node = document.createElement(tag); for (const [k, v] of Object.entries(attrs)) { + if (v == null || v === false) continue; if (k === "class") node.className = v; - else node.setAttribute(k, v); + else node.setAttribute(k, v === true ? "" : v); } - for (const child of children) { - if (child == null) continue; + for (const child of children.flat()) { + if (child == null || child === false) continue; node.append(child instanceof Node ? child : document.createTextNode(String(child))); } return node; } +function button(label, onClick, cls = "quiet") { + const b = el("button", { class: cls, type: "button" }, label); + b.addEventListener("click", onClick); + return b; +} + function schedule(fn, ms) { clearTimeout(pollTimer); pollTimer = setTimeout(fn, ms); } +// --- the browser's key --------------------------------------------------- + +const b64url = (bytes) => btoa(String.fromCharCode(...new Uint8Array(bytes))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +const hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join(""); + +function keyStore(mode, fn) { + return new Promise((resolve, reject) => { + const open = indexedDB.open("codedeck", 1); + open.onupgradeneeded = () => open.result.createObjectStore("keys"); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const tx = open.result.transaction("keys", mode); + const request = fn(tx.objectStore("keys")); + tx.oncomplete = () => resolve(request && request.result); + tx.onerror = () => reject(tx.error); + }; + }); +} + +/** The key pair this browser signed in with, or null. */ +const loadKey = () => keyStore("readonly", (s) => s.get("pair")).catch(() => null); +const dropKey = () => keyStore("readwrite", (s) => s.delete("pair")).catch(() => {}); + +/** A fresh key for a new sign-in: its private half can sign, never leave. */ +async function newKey() { + const pair = await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, false, ["sign", "verify"]); + await keyStore("readwrite", (s) => s.put(pair, "pair")); + return pair; +} + +async function keyId(pair) { + const raw = await crypto.subtle.exportKey("raw", pair.publicKey); + return hex(await crypto.subtle.digest("SHA-256", raw)).slice(0, 16); +} + +// --- sign-in ------------------------------------------------------------- + async function refresh() { - let me; try { me = (await api("/api/me")).body; } catch { schedule(refresh, 3000); return; } - if (me.state === "signed-in") return dashboard(); + if (me.state === "signed-in") return signedIn(); if (me.state === "pending") return pending(me); + link.stop(); show("signed-out"); } async function start() { $("start-error").hidden = true; - const { status, body } = await api("/api/sign-in", "POST"); + let raw; + try { + const pair = await newKey(); + raw = b64url(await crypto.subtle.exportKey("raw", pair.publicKey)); + } catch { + $("start-error").textContent = "This browser cannot make a signing key here (it needs WebCrypto and IndexedDB on this page)."; + $("start-error").hidden = false; + return; + } + const { status, body } = await api("/api/sign-in", "POST", { key: raw }); if (status === 429) { $("start-error").textContent = "Too many sign-in attempts from here. Wait a minute and try again."; $("start-error").hidden = false; @@ -76,13 +141,13 @@ async function start() { pending(body); } -function pending(me) { +function pending(state) { show("pending"); - if ($("code").textContent !== me.code) { - $("code").textContent = me.code; - $("qr").src = "/api/sign-in/qr.svg?code=" + encodeURIComponent(me.code); + if ($("code").textContent !== state.code) { + $("code").textContent = state.code; + $("qr").src = "/api/sign-in/qr.svg?code=" + encodeURIComponent(state.code); } - expiresAt = Date.now() + me.expiresInMs; + expiresAt = Date.now() + state.expiresInMs; tickExpiry(); // Waiting for the phone: ask again until the browser is in or the code lapses. schedule(refresh, 2000); @@ -95,6 +160,303 @@ function tickExpiry() { } setInterval(() => { if (!$("pending").hidden) tickExpiry(); }, 1000); +/** Signed in: the key this browser holds must be the one the bridge let in. */ +async function signedIn() { + const pair = await loadKey(); + if (!pair || (await keyId(pair)) !== me.id) { + // The key is gone (site data cleared) or another: this sign-in can sign + // nothing, so it ends here and a new one starts. + await signOut(); + return; + } + show("dashboard"); + render(); + link.start(pair); +} + +async function signOut() { + link.stop(); + await api("/api/sign-out", "POST").catch(() => {}); + await dropKey(); + me = null; + show("signed-out"); +} + +// --- the stream ---------------------------------------------------------- + +/** The signed stream: one WebSocket, every frame signed by the browser's key. */ +const link = { + ws: null, + pair: null, + id: null, + challenge: null, + seq: 0, + ready: false, + stopped: true, + retry: 1000, + waiting: new Map(), + presenceTimer: null, + // The frames being signed and sent, one after another. + queue: Promise.resolve(), + + async start(pair) { + this.pair = pair; + this.id = await keyId(pair); + this.stopped = false; + if (!this.ws) this.connect(); + }, + + stop() { + this.stopped = true; + clearInterval(this.presenceTimer); + if (this.ws) this.ws.close(); + this.ws = null; + this.ready = false; + status(); + }, + + connect() { + const ws = new WebSocket(`wss://${location.host}/api/stream`); + this.ws = ws; + this.ready = false; + this.seq = 0; + status(); + ws.onmessage = (event) => this.receive(event.data); + ws.onclose = () => { + if (this.ws !== ws) return; + this.ws = null; + this.ready = false; + clearInterval(this.presenceTimer); + for (const [, w] of this.waiting) w.resolve({ accepted: false, message: "The connection dropped: it may not have arrived." }); + this.waiting.clear(); + status(); + if (this.stopped) return; + // A closed stream may be a lapsed sign-in: ask before dialling again. + setTimeout(() => refresh(), this.retry); + this.retry = Math.min(this.retry * 2, 30000); + }; + }, + + async sign(seq, body) { + const input = `${SIGNING_CONTEXT}\n${me.machine}\n${this.id}\n${this.challenge}\n${seq}\n${body}`; + const sig = await crypto.subtle.sign({ name: "ECDSA", hash: "SHA-256" }, this.pair.privateKey, new TextEncoder().encode(input)); + return b64url(sig); + }, + + async receive(text) { + let frame; + try { frame = JSON.parse(text); } catch { return; } + const [label, ...rest] = frame; + if (label === "CHALLENGE") { + this.challenge = rest[0]; + this.ws.send(JSON.stringify(["HELLO", await this.sign(0, "")])); + } else if (label === "READY") { + this.ready = true; + this.retry = 1000; + status(); + onConnected(); + clearInterval(this.presenceTimer); + this.presenceTimer = setInterval(() => sendPresence(), PRESENCE_MS); + } else if (label === "CLOSED") { + const reason = rest[0]; + if (reason === "expired" || reason === "signed-out" || reason === "bad-signature") { + this.stop(); + await dropKey(); + refresh(); + } + } else if (label === "OK" || label === "REPLY") { + const w = this.waiting.get(rest[0]); + if (!w) return; + this.waiting.delete(rest[0]); + w.resolve(label === "OK" ? { accepted: rest[1], message: rest[2] } : rest[1]); + } else if (label === "MSG") { + onMessage(rest[0]); + } + }, + + /** + * Send a signed frame; resolves with its answer (`OK` or `REPLY`). Frames + * are signed and sent one at a time, in `seq` order: signing is async, and + * a frame whose `seq` does not grow closes the stream. + */ + send(label, body) { + const ws = this.ws; + const turn = this.queue.then(async () => { + if (!this.ready || this.ws !== ws) return label === "CMD" ? { accepted: false, message: "Not connected." } : { status: 0, body: {} }; + const seq = ++this.seq; + const sig = await this.sign(seq, body); + if (this.ws !== ws) return label === "CMD" ? { accepted: false, message: "Not connected." } : { status: 0, body: {} }; + const answer = new Promise((resolve) => this.waiting.set(seq, { resolve })); + ws.send(JSON.stringify([label, seq, body, sig])); + return { answer }; + }); + this.queue = turn.catch(() => {}); + return turn.then((r) => (r && r.answer ? r.answer : r)); + }, + + /** A command, as the phone would send it. */ + command(msg) { + return this.send("CMD", JSON.stringify({ v: PROTOCOL_VERSION, ...msg })); + }, + + /** A page request: `{status, body}`. */ + page(request) { + return this.send("PAGE", JSON.stringify(request)); + }, +}; + +function status() { + const live = link.ready; + $("link").className = `state ${live ? "ok" : "busy"}`; + $("link").textContent = live ? "live" : "connecting"; +} + +// --- what the bridge sends ---------------------------------------------- + +let heartbeat = null; +let heartbeatRev = 0; +const transcripts = new Map(); +let selected = null; +let browserList = null; + +function transcript(sessionId) { + let t = transcripts.get(sessionId); + if (!t) { + t = { entries: new Map(), live: new Map(), syncId: null, acks: [], ackTimer: null, sent: [] }; + transcripts.set(sessionId, t); + } + return t; +} + +function onConnected() { + // A creation whose answer the dropped connection lost is not waited for. + if (pendingCreate) { + pendingCreate = null; + renderNewSession(); + } + sendPresence(); + if (selected) syncSession(selected); + if (currentTab() === "browsers") link.command({ type: "web-browsers-request" }); +} + +function onMessage(msg) { + switch (msg.type) { + case "sessions": + if (msg.rev != null && msg.rev <= heartbeatRev) return; + if (msg.rev != null) heartbeatRev = msg.rev; + heartbeat = msg; + for (const id of msg.removedSessions || []) transcripts.delete(id); + render(); + return; + case "output": { + if (!transcripts.has(msg.sessionId)) return; + const t = transcript(msg.sessionId); + msg.entries.forEach((entry, i) => t.entries.set(msg.seq + i, entry)); + for (const entry of msg.entries) { + if (entry.part) t.live.delete(entry.part); + if (entry.entryType === "turn_complete") t.live.clear(); + } + if (msg.sessionId === selected) redrawTranscript(); + return; + } + case "partial": { + if (msg.sessionId !== selected) return; + const t = transcript(msg.sessionId); + const row = t.live.get(msg.key); + if (msg.offset === 0) t.live.set(msg.key, { entryType: msg.entryType, text: msg.text, subagent: msg.subagent }); + else if (row && !row.broken && row.text.length === msg.offset) row.text += msg.text; + else if (row) row.broken = true; + drawLive(); + return; + } + case "sync-begin": + transcript(msg.sessionId).syncId = msg.syncId; + return; + case "sync-chunk": { + const t = transcript(msg.sessionId); + for (const { seq, entry } of msg.entries) t.entries.set(seq, entry); + // Acks for chunks that arrive together go out as one command — each + // under the sync its chunks came in. + if (t.ackSync !== msg.syncId) flushAcks(t); + t.ackSync = msg.syncId; + t.acks.push(msg.range); + clearTimeout(t.ackTimer); + t.ackTimer = setTimeout(() => flushAcks(t), 50); + if (msg.sessionId === selected) redrawTranscript(); + return; + } + case "session-pending": + // The answer to this page's own create-session (replies go to the + // asking browser alone): the id the session will have. + if (pendingCreate === "?") pendingCreate = msg.pendingId; + return; + case "session-ready": + if (pendingCreate === msg.pendingId) { + pendingCreate = null; + location.hash = `#sessions/${msg.session.id}`; + } + return; + case "session-failed": + if (pendingCreate === msg.pendingId) { + pendingCreate = null; + notify(`The session did not start: ${msg.reason || "the agent failed"}.`); + renderNewSession(); + } + return; + case "input-failed": + notify(msg.reason === "no-session" ? "The bridge knows no such session." : "The session is not running."); + return; + case "option-confirmed": { + const s = (heartbeat?.sessions || []).find((x) => x.id === msg.sessionId); + if (s) s[msg.option] = msg.value; + if (msg.sessionId === selected) renderSessionHead(); + return; + } + case "web-browsers": + browserList = msg.browsers; + if (currentTab() === "browsers") renderBrowsers(); + return; + default: + } +} + +function flushAcks(t) { + clearTimeout(t.ackTimer); + const ranges = t.acks.splice(0); + if (ranges.length) link.command({ type: "sync-ack", syncId: t.ackSync, ranges }); +} + +let toastTimer = null; +function notify(text) { + $("toast").textContent = text; + $("toast").hidden = false; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { $("toast").hidden = true; }, 6000); +} + +function sendPresence() { + link.command({ type: "presence", away: document.hidden, watching: document.hidden ? null : selected }); +} +document.addEventListener("visibilitychange", () => { if (link.ready) sendPresence(); }); + +/** The seqs a transcript holds, as `[first, last]` runs. */ +function haveRanges(t) { + const seqs = [...t.entries.keys()].sort((a, b) => a - b); + const ranges = []; + for (const s of seqs) { + const last = ranges[ranges.length - 1]; + if (last && s === last[1] + 1) last[1] = s; + else ranges.push([s, s]); + } + return ranges; +} + +function syncSession(sessionId) { + link.command({ type: "sync-request", sessionId, haveRanges: haveRanges(transcript(sessionId)) }); +} + +// --- the frame ----------------------------------------------------------- + function relative(iso) { const at = typeof iso === "number" ? iso : Date.parse(iso); if (!Number.isFinite(at)) return ""; @@ -140,45 +502,371 @@ function facts(target, rows) { target.replaceChildren(...rows.flatMap(([k, v]) => [el("dt", {}, k), el("dd", {}, v)])); } -function currentTab() { - const tab = location.hash.slice(1); - return tabs.includes(tab) ? tab : "overview"; -} - -async function dashboard() { - const { status, body } = await api("/api/status"); - if (status === 401) return refresh(); - if (status !== 200) return schedule(dashboard, 5000); - lastStatus = body; - show("dashboard"); - render(); - schedule(dashboard, 5000); +/** The open tab, and for `sessions` the session in it. */ +function route() { + const [tab, id] = location.hash.slice(1).split("/"); + let session = null; + try { session = id ? decodeURIComponent(id) : null; } catch { session = null; } + return { tab: tabs.includes(tab) ? tab : "sessions", id: session }; } +const currentTab = () => route().tab; +const agentName = (id) => (heartbeat?.agents || []).find((a) => a.id === id)?.displayName || id; -/** The dashboard's frame and the open tab, from the latest status. */ +/** The frame and the open tab, from the latest heartbeat. */ function render() { - const body = lastStatus; - if (!body) return; - const hb = body.heartbeat || {}; + if ($("dashboard").hidden) return; + const hb = heartbeat || {}; $("machine").textContent = hb.machine || ""; document.title = `${hb.machine || "Bridge"} · CodeDeck+`; - const tab = currentTab(); - for (const link of document.querySelectorAll("[data-tab]")) link.classList.toggle("on", link.dataset.tab === tab); + const { tab, id } = route(); + for (const tabLink of document.querySelectorAll("[data-tab]")) tabLink.classList.toggle("on", tabLink.dataset.tab === tab); for (const pane of document.querySelectorAll("[data-pane]")) pane.hidden = pane.dataset.pane !== tab; - $("signed-in-as").textContent = `Signed in by ${body.signedInBy.slice(0, 16)}… ${relative(body.signedInSince)}.`; - if (tab === "usage") usage(hb); - else if (tab === "browsers") browsers(); + $("dashboard").classList.toggle("wide", tab === "sessions"); + if (me?.by) { + const lapse = me.lapses ? ` Stays signed in until ${new Date(me.lapses).toLocaleDateString()} while used.` : ""; + $("signed-in-as").textContent = `Signed in by ${me.by.slice(0, 16)}… ${relative(me.since)}.${lapse}`; + } + const watching = tab === "sessions" ? id : null; + if (watching !== selected) { + selected = watching; + if (link.ready) sendPresence(); + if (selected) { + transcript(selected); + if (link.ready) syncSession(selected); + } + transcriptKey = null; + } + if (!heartbeat) return; + if (tab === "sessions") sessionsPane(); + else if (tab === "usage") usage(hb); + else if (tab === "browsers") renderBrowsers(); else if (tab === "devices") devices(); else if (tab === "settings") settings(); - else overview(body, hb); + else overview(hb); +} + +// --- sessions ------------------------------------------------------------ + +let pendingCreate = null; + +function sortedSessions() { + return [...(heartbeat?.sessions || [])].sort((a, b) => Date.parse(b.lastActivity) - Date.parse(a.lastActivity)); } -function overview(body, hb) { +function sessionsPane() { + const sessions = sortedSessions(); + $("session-list").replaceChildren(...sessions.map((s) => el("a", { class: `session-item${s.id === selected ? " on" : ""}`, href: `#sessions/${encodeURIComponent(s.id)}` }, + el("span", { class: "session-title" }, s.title || s.slug), + el("span", { class: "session-meta" }, stateOf(s), el("span", { class: "dim small" }, `${agentName(s.agent)} · ${s.project || s.cwd}`)), + ))); + $("no-sessions").hidden = sessions.length > 0; + const session = sessions.find((s) => s.id === selected); + $("session-view").hidden = !session; + $("new-session").hidden = !!session; + if (session) { + renderSessionHead(); + redrawTranscript(); + } else { + renderNewSession(); + } +} + +function renderNewSession() { + const agents = (heartbeat?.agents || []).filter((a) => (a.install?.state || "ready") !== "failed"); + const agentSelect = $("new-agent"); + if (agentSelect.options.length !== agents.length) { + agentSelect.replaceChildren(...agents.map((a) => el("option", { value: a.id }, a.displayName))); + } + const folders = heartbeat?.folders || []; + const folderSelect = $("new-folder"); + const wanted = ["", ...folders]; + if (JSON.stringify([...folderSelect.options].map((o) => o.value)) !== JSON.stringify(wanted)) { + folderSelect.replaceChildren(el("option", { value: "" }, "The workspace itself"), ...folders.map((f) => el("option", { value: f }, f))); + } + $("new-start").disabled = !!pendingCreate || !agents.length; + $("new-start").textContent = pendingCreate ? "Starting…" : "Start"; +} + +$("new-session").addEventListener("submit", async (event) => { + event.preventDefault(); + const msg = { type: "create-session", agent: $("new-agent").value }; + if ($("new-folder").value) msg.cwd = $("new-folder").value; + const answer = await link.command(msg); + if (!answer.accepted) return notify(answer.message || "The bridge did not take it."); + // The bridge names the session after the pending id it answers with. + pendingCreate = "?"; + renderNewSession(); +}); + +/** The session's header: its name, state and options. */ +function renderSessionHead() { + const session = (heartbeat?.sessions || []).find((s) => s.id === selected); + if (!session) return; + const agent = (heartbeat.agents || []).find((a) => a.id === session.agent); + $("session-name").textContent = session.title || session.slug; + const meta = [agentName(session.agent), session.model, session.project || session.cwd].filter(Boolean).join(" · "); + $("session-meta").replaceChildren(stateOf(session), el("span", { class: "dim small" }, meta)); + const modes = agent?.modes || []; + const mode = $("session-mode"); + mode.hidden = modes.length === 0; + mode.replaceChildren(...modes.map((m) => el("option", { value: m.id, selected: m.id === (session.mode || agent.defaultMode) }, m.label))); + const busy = session.state && session.state !== "idle" && session.state !== "offline"; + $("interrupt").hidden = !busy || agent?.supports?.interrupt === false; +} + +$("session-mode").addEventListener("change", async () => { + const answer = await link.command({ type: "set-option", sessionId: selected, option: "mode", value: $("session-mode").value }); + if (!answer.accepted) notify(answer.message || "The bridge did not take it."); +}); +$("interrupt").addEventListener("click", () => link.command({ type: "interrupt", sessionId: selected })); +$("close-session").addEventListener("click", async () => { + if (!confirm("End this session? Its agent stops; the transcript stays on the bridge until it is pruned.")) return; + await link.command({ type: "close-session", sessionId: selected }); + location.hash = "#sessions"; +}); + +$("composer").addEventListener("submit", async (event) => { + event.preventDefault(); + const text = $("input").value; + if (!text.trim() || !selected) return; + const inputId = crypto.randomUUID(); + $("input").value = ""; + const answer = await link.command({ type: "input", sessionId: selected, text, inputId }); + if (!answer.accepted) { + $("input").value = text; + notify(answer.message || "It did not reach the bridge."); + } +}); +$("input").addEventListener("keydown", (event) => { + if (event.key === "Enter" && !event.shiftKey && !event.isComposing) { + event.preventDefault(); + $("composer").requestSubmit(); + } +}); + +// --- the transcript ------------------------------------------------------ + +let transcriptKey = null; +let redrawQueued = false; + +function redrawTranscript() { + if (redrawQueued) return; + redrawQueued = true; + requestAnimationFrame(() => { + redrawQueued = false; + drawTranscript(); + }); +} + +function atBottom(node) { + return node.scrollHeight - node.scrollTop - node.clientHeight < 80; +} + +function drawTranscript() { + if (!selected) return; + const t = transcript(selected); + const scroller = $("transcript"); + const stick = transcriptKey !== selected || atBottom(scroller); + const seqs = [...t.entries.keys()].sort((a, b) => a - b); + const entries = seqs.map((s) => t.entries.get(s)); + // What a card became, and each call's result and diff, by id. + const resolved = new Map(); + const results = new Map(); + const diffs = new Map(); + for (const e of entries) { + if (e.entryType === "resolved") resolved.set(e.requestId, e.summary); + if (e.entryType === "tool_result") results.set(e.callId, e); + if (e.entryType === "diff" && e.callId) diffs.set(e.callId, e); + } + const rows = []; + for (const e of entries) { + const row = entryRow(e, { resolved, results, diffs, session: selected }); + if (row) rows.push(e.subagent ? el("div", { class: "sub" }, el("span", { class: "sub-label" }, e.subagent.label || "sub-agent"), row) : row); + } + $("entries").replaceChildren(...rows); + $("transcript-empty").hidden = rows.length > 0; + drawLive(); + if (stick) scroller.scrollTop = scroller.scrollHeight; + transcriptKey = selected; +} + +function drawLive() { + const t = selected && transcripts.get(selected); + const scroller = $("transcript"); + const stick = atBottom(scroller); + $("live").replaceChildren(...(t ? [...t.live.values()] : []).map((row) => + row.entryType === "thinking" + ? el("div", { class: "thinking live" }, row.text) + : el("div", { class: "msg from-agent live" }, markdown(row.text)))); + if (stick) scroller.scrollTop = scroller.scrollHeight; +} + +/** Light markdown, built as elements: fences, paragraphs, `code`, **bold**. */ +function markdown(text) { + const out = document.createDocumentFragment(); + const parts = String(text).split(/^```[^\n]*\n?/m); + parts.forEach((part, i) => { + if (i % 2 === 1) { + out.append(el("pre", { class: "code-block" }, el("code", {}, part.replace(/\n$/, "")))); + return; + } + for (const para of part.split(/\n{2,}/)) { + if (!para.trim()) continue; + const p = el("p", {}); + for (const piece of para.split(/(`[^`\n]+`|\*\*[^*\n]+\*\*)/)) { + if (/^`[^`]+`$/.test(piece)) p.append(el("code", {}, piece.slice(1, -1))); + else if (/^\*\*[^*]+\*\*$/.test(piece)) p.append(el("strong", {}, piece.slice(2, -2))); + else if (piece) p.append(piece); + } + out.append(p); + } + }); + return out; +} +const KIND_WORDS = { + read: "Read", edit: "Edit", delete: "Delete", move: "Move", search: "Search", execute: "Run", + think: "Think", fetch: "Fetch", switch_mode: "Mode", agent: "Agent", other: "Tool", +}; + +function diffView(d) { + return el("pre", { class: "diff" }, + el("div", { class: "diff-path" }, d.path), + ...(d.lines || []).map((l) => el("div", { class: `diff-${l.type}` }, (l.type === "add" ? "+" : l.type === "del" ? "-" : " ") + l.text)), + d.truncated ? el("div", { class: "dim" }, "…") : null); +} + +function entryRow(e, ctx) { + switch (e.entryType) { + case "text": + return el("div", { class: `msg from-${e.role}` }, e.role === "user" ? e.text : markdown(e.text)); + case "thinking": + return e.redacted ? el("div", { class: "thinking" }, "Reasoning withheld by the provider.") + : el("details", { class: "thinking" }, el("summary", {}, "Thinking"), el("div", {}, e.text)); + case "plan": + return el("div", { class: "block" }, el("div", { class: "block-head" }, "Plan"), markdown(e.text)); + case "tool_call": { + const result = ctx.results.get(e.callId); + const diff = ctx.diffs.get(e.callId); + const tone = result ? (result.isError ? "bad" : "ok") : "busy"; + return el("details", { class: "tool" }, + el("summary", {}, el("span", { class: `state ${tone}` }, KIND_WORDS[e.kind] || e.toolName), " ", el("span", { class: "tool-title" }, e.title || e.toolName)), + e.input ? el("pre", { class: "tool-io" }, e.input) : null, + diff ? diffView(diff) : null, + result?.text ? el("pre", { class: `tool-io${result.isError ? " error" : ""}` }, result.text) : null); + } + case "tool_result": + return null; + case "diff": + return e.callId ? null : diffView(e); + case "todos": + return el("div", { class: "block" }, el("div", { class: "block-head" }, "To do"), + el("ul", { class: "todos" }, ...e.items.map((i) => el("li", { class: `todo ${i.status}` }, i.status === "in_progress" && i.activeText ? i.activeText : i.text)))); + case "background_task": + return el("div", { class: "line" }, el("span", { class: `state ${e.status === "running" ? "busy" : e.status === "failed" ? "bad" : "ok"}` }, e.status), ` ${e.title}`, e.summary ? el("span", { class: "dim" }, ` — ${e.summary}`) : null); + case "permission_request": + return permissionCard(e, ctx); + case "question": + return questionCard(e, ctx); + case "plan_approval": + return planCard(e, ctx); + case "resolved": + case "turn_complete": + return null; + case "notice": + return el("div", { class: "line dim" }, e.text || e.kind); + case "status": + return el("div", { class: "line dim" }, e.text); + case "error": + return el("div", { class: "line error" }, e.text); + default: + return null; + } +} + +/** A card's answer, sent; the card waits for its `resolved` entry. */ +const answered = new Set(); + +async function answer(ctx, requestId, msg) { + answered.add(requestId); + redrawTranscript(); + const result = await link.command({ sessionId: ctx.session, requestId, ...msg }); + if (!result.accepted) { + answered.delete(requestId); + redrawTranscript(); + notify(result.message || "The answer did not reach the bridge."); + } +} + +function cardFrame(title, ctx, requestId, ...body) { + const summary = ctx.resolved.get(requestId); + return el("div", { class: `card-entry${summary != null ? " done" : ""}` }, + el("div", { class: "block-head" }, title), + ...body.filter(() => summary == null), + summary != null ? el("div", { class: "dim" }, summary) : answered.has(requestId) ? el("div", { class: "dim" }, "Sent…") : null); +} + +function permissionCard(e, ctx) { + const open = !ctx.resolved.has(e.requestId) && !answered.has(e.requestId); + return cardFrame("Permission", ctx, e.requestId, + el("div", {}, el("strong", {}, e.title || e.toolName)), + e.description ? el("div", { class: "dim" }, e.description) : null, + e.reason ? el("div", { class: "dim small" }, e.reason) : null, + (e.locations || []).length ? el("div", { class: "mono small" }, e.locations.join("\n")) : null, + open ? el("div", { class: "card-actions" }, ...(e.options || []).map((o) => + button(o.label, () => answer(ctx, e.requestId, { type: "permission-response", optionId: o.id }), o.kind.startsWith("allow") ? "primary small-btn" : "quiet small-btn"))) : null); +} + +function questionCard(e, ctx) { + const key = `${e.requestId}#${e.index}`; + const open = !ctx.resolved.has(e.requestId) && !answered.has(key); + const choices = (e.options || []).map((o, i) => el("label", { class: "choice" }, + el("input", { type: e.multiSelect ? "checkbox" : "radio", name: key, value: String(i) }), + el("span", {}, o.label, o.description ? el("span", { class: "dim small" }, ` — ${o.description}`) : null))); + const other = el("input", { type: "text", class: "other", placeholder: "Or answer in your own words" }); + const send = button("Answer", () => { + if (other.value.trim()) return answerQuestion(ctx, e, key, { kind: "text", text: other.value.trim() }); + const selectedOptions = choices.map((c, i) => (c.querySelector("input").checked ? i : -1)).filter((i) => i >= 0); + if (selectedOptions.length) answerQuestion(ctx, e, key, { kind: "options", selected: selectedOptions }); + }, "primary small-btn"); + const count = e.count > 1 ? ` ${e.index + 1} of ${e.count}` : ""; + return cardFrame(`Question${count}`, ctx, e.requestId, + e.header ? el("div", { class: "dim small" }, e.header) : null, + el("div", {}, el("strong", {}, e.question)), + open ? el("div", { class: "choices" }, ...choices, other, el("div", { class: "card-actions" }, send)) : answered.has(key) ? el("div", { class: "dim" }, "Sent…") : null); +} + +function answerQuestion(ctx, e, key, value) { + answered.add(key); + redrawTranscript(); + link.command({ type: "question-response", sessionId: ctx.session, requestId: e.requestId, index: e.index, answer: value }).then((r) => { + if (!r.accepted) { + answered.delete(key); + redrawTranscript(); + notify(r.message || "The answer did not reach the bridge."); + } + }); +} + +function planCard(e, ctx) { + const open = !ctx.resolved.has(e.requestId) && !answered.has(e.requestId); + const feedback = e.revise ? el("textarea", { rows: "2", placeholder: "What to change (optional)" }) : null; + return cardFrame("Plan approval", ctx, e.requestId, + open ? feedback : null, + open ? el("div", { class: "card-actions" }, ...(e.options || []).map((o) => button(o.label, () => { + const msg = { type: "plan-response", optionId: o.id }; + if (o.id === e.revise && feedback.value.trim()) msg.feedback = feedback.value.trim(); + answer(ctx, e.requestId, msg); + }, o.id === e.revise ? "quiet small-btn" : "primary small-btn"))) : null); +} + +// --- the other tabs ------------------------------------------------------ + +function overview(hb) { facts($("bridge-facts"), [ ["Machine", hb.machine || "—"], ["Runs as", hb.host || "—"], - ["Identity", el("span", { class: "mono" }, body.machine)], + ["Identity", el("span", { class: "mono" }, me?.machine || "—")], ["Capabilities", el("span", { class: "chips" }, ...(hb.capabilities || []).map((c) => el("span", { class: "chip" }, c)))], ["Workspace", (hb.roots || []).join(", ") || "—"], ...((hb.credentials || []).length ? [["Credentials", el("span", { class: "chips" }, ...hb.credentials.map(credentialOf))]] : []), @@ -194,18 +882,6 @@ function overview(body, hb) { el("div", { class: "agent-head" }, el("span", { class: "agent-name" }, agent.displayName), installOf(agent)), el("div", { class: "creds" }, ...(agent.credentials || []).map(credentialOf)), ))); - - const sessions = [...(hb.sessions || [])].sort((a, b) => Date.parse(b.lastActivity) - Date.parse(a.lastActivity)); - const agentName = Object.fromEntries((hb.agents || []).map((a) => [a.id, a.displayName])); - $("session-count").textContent = sessions.length ? String(sessions.length) : ""; - $("no-sessions").hidden = sessions.length > 0; - $("sessions").replaceChildren(...sessions.map((s) => el("tr", {}, - el("td", { class: "title", title: s.title || s.slug }, s.title || s.slug), - el("td", {}, agentName[s.agent] || s.agent), - el("td", {}, stateOf(s)), - el("td", { class: "folder", title: s.cwd }, s.project || s.cwd), - el("td", { class: "when" }, relative(s.lastActivity)), - ))); } /** How many of `values` there are of each, most first. */ @@ -217,7 +893,6 @@ function tally(values) { function usage(hb) { const sessions = hb.sessions || []; - const agentName = Object.fromEntries((hb.agents || []).map((a) => [a.id, a.displayName])); const byAgent = tally(sessions.map((s) => s.agent)); $("usage-empty").hidden = byAgent.length > 0; $("usage-agents").replaceChildren(...byAgent.map(([agent, count]) => { @@ -227,7 +902,7 @@ function usage(hb) { const lines = own.reduce((sum, s) => sum + (s.lineCount || 0), 0); const models = tally(own.map((s) => s.model)); return el("div", { class: "agent" }, - el("div", { class: "agent-head" }, el("span", { class: "agent-name" }, agentName[agent] || agent), el("span", { class: "dim small" }, `${count} session${count === 1 ? "" : "s"}`)), + el("div", { class: "agent-head" }, el("span", { class: "agent-name" }, agentName(agent)), el("span", { class: "dim small" }, `${count} session${count === 1 ? "" : "s"}`)), el("dl", { class: "facts small" }, el("dt", {}, "Now"), el("dd", {}, running || waiting ? [running && `${running} running`, waiting && `${waiting} waiting`].filter(Boolean).join(" · ") : "idle"), el("dt", {}, "Transcripts"), el("dd", {}, `${lines.toLocaleString()} lines`), @@ -249,7 +924,7 @@ function usage(hb) { return el("div", { class: "meter" }, el("div", { class: "meter-head" }, el("span", { class: "meter-title", title: s.title || s.slug }, s.title || s.slug), - el("span", { class: "dim small" }, `${agentName[s.agent] || s.agent} · ${Math.round(pct)}%${size}`)), + el("span", { class: "dim small" }, `${agentName(s.agent)} · ${Math.round(pct)}%${size}`)), el("div", { class: "meter-track" }, fill), ); })); @@ -265,30 +940,41 @@ function browserName(agent) { return name ? (os ? `${name} on ${os}` : name) : agent; } -async function browsers() { - const { status, body } = await api("/api/browsers"); - if (status !== 200) return; - $("browsers").replaceChildren(...(body.browsers || []).map((b) => { - const out = el("button", { class: "quiet danger", type: "button" }, "Sign out"); - out.addEventListener("click", async () => { - if (!confirm(b.current ? "Sign this browser out?" : `Sign out ${browserName(b.agent)} at ${b.peer}?`)) return; - const answer = await api("/api/browsers/sign-out", "POST", { id: b.id }); - $("browsers-error").hidden = answer.status === 200; +let browsersAsked = false; + +function renderBrowsers() { + if (browserList === null || !browsersAsked) { + browsersAsked = true; + if (link.ready) link.command({ type: "web-browsers-request" }); + if (browserList === null) return; + } + $("browsers").replaceChildren(...browserList.map((b) => { + const current = b.id === me?.id; + const out = button("Sign out", async () => { + if (!confirm(current ? "Sign this browser out?" : `Sign out ${browserName(b.agent)} at ${b.peer}?`)) return; + if (current) return signOut(); + const answer = await link.command({ type: "web-browser-sign-out", id: b.id }); + $("browsers-error").hidden = answer.accepted; $("browsers-error").textContent = "The bridge did not sign it out."; - if (b.current && answer.status === 200) return refresh(); - browsers(); - }); + }, "quiet danger"); return el("div", { class: "row" }, el("div", { class: "row-main" }, - el("div", { class: "row-title" }, browserName(b.agent), b.current ? el("span", { class: "chip" }, "this browser") : null), - el("div", { class: "dim small" }, `${b.peer} · signed in ${relative(b.sinceMs)} · seen ${relative(b.lastSeenMs)} · by ${b.by.slice(0, 16)}…`)), + el("div", { class: "row-title" }, browserName(b.agent), current ? el("span", { class: "chip" }, "this browser") : null), + el("div", { class: "dim small" }, `${b.peer} · signed in ${relative(b.sinceMs)} · seen ${relative(b.lastSeenMs)} · until ${new Date(b.expiresMs).toLocaleDateString()} · by ${b.by.slice(0, 16)}…`)), out); })); } +let devicesShown = false; + async function devices() { - const { status, body } = await api("/api/devices"); - if (status !== 200) return; + if (devicesShown) return; + devicesShown = true; + const { status, body } = await link.page({ type: "devices" }); + if (status !== 200) { + devicesShown = false; + return; + } const list = body.devices || []; $("no-devices").hidden = list.length > 0; const now = Date.now(); @@ -317,8 +1003,8 @@ const FIXED_LABELS = { workspaceRoots: "Workspace", torProxyUrl: "Tor proxy", nodePath: "Node", agentHostPath: "Agent host", testMode: "Test mode", "direct.listen": "Direct link listens on", "direct.onionListen": "Onion listener", }; -// The form is built once per visit to the tab, so a poll does not wipe what -// is being typed. +// The form is built once per visit to the tab, so a heartbeat does not wipe +// what is being typed. let settingsShown = false; function shownValue(v) { @@ -329,9 +1015,12 @@ function shownValue(v) { async function settings() { if (settingsShown) return; - const { status, body } = await api("/api/config"); - if (status !== 200) return; settingsShown = true; + const { status, body } = await link.page({ type: "config" }); + if (status !== 200) { + settingsShown = false; + return; + } const fields = body.fields || []; const editable = fields.filter((f) => f.editable && SETTINGS[f.key]); $("settings-fields").replaceChildren(...editable.map((f) => { @@ -371,24 +1060,24 @@ $("settings-form").addEventListener("submit", async (event) => { } } const result = $("settings-result"); - const answer = await api("/api/config", "POST", { set }); + const answer = await link.page({ type: "config-set", set }); if (answer.status === 200) { result.className = "small ok"; result.textContent = "Saved. Restart the bridge to apply it."; } else { result.className = "small error"; - result.textContent = answer.body.error ? `${SETTINGS[answer.body.key]?.label || answer.body.key}: ${answer.body.error}` : "The bridge did not save it."; + const body = answer.body || {}; + result.textContent = body.error ? `${SETTINGS[body.key]?.label || body.key}: ${body.error}` : "The bridge did not save it."; } }); window.addEventListener("hashchange", () => { settingsShown = false; + devicesShown = false; + browsersAsked = false; render(); }); $("start").addEventListener("click", start); -$("sign-out").addEventListener("click", async () => { - await api("/api/sign-out", "POST"); - show("signed-out"); -}); +$("sign-out").addEventListener("click", () => signOut()); refresh(); diff --git a/crates/bridge-runtime/web/index.html b/crates/bridge-runtime/web/index.html index bd7d1341..a8ab5f6a 100644 --- a/crates/bridge-runtime/web/index.html +++ b/crates/bridge-runtime/web/index.html @@ -11,7 +11,7 @@
CodeDeck+
- +
@@ -20,7 +20,7 @@

Sign in with your phone

-

This page shows what your bridge is doing. Only a phone paired with it can let a browser in — there is no password.

+

Drive your bridge's sessions from this browser. Only a phone paired with it can let a browser in — there is no password.

@@ -35,6 +35,7 @@

Sign in with your phone

  • Open CodeDeck+ on a phone paired with this bridge.
  • On the machine's page, under Web page, choose Browsers.
  • Scan this code, or type it.
  • +
  • The phone shows this page's certificate fingerprint. Check that the certificate your browser accepted for this page shows the same SHA-256 before you sign in.
  • @@ -42,6 +43,7 @@

    Sign in with your phone

    -
    + + +
    + diff --git a/crates/client-ffi/src/views.rs b/crates/client-ffi/src/views.rs index 842043cc..37ef5754 100644 --- a/crates/client-ffi/src/views.rs +++ b/crates/client-ffi/src/views.rs @@ -640,6 +640,10 @@ pub struct UniffiMachineSummary { /// Whether the bridge advertised a certificate pin (without one no /// `wss://` endpoint is dialled). pub direct_pinned: bool, + /// The SHA-256 of the certificate the bridge's `wss://` listener serves + /// (lowercase hex), as its signed heartbeat pins it: what a browser + /// opening the web page must be shown, checked before a sign-in. + pub direct_cert_sha256: Option, /// The direct endpoints the user added, tried after the advertised ones. pub direct_endpoints: Vec, /// The endpoint the direct link is up on; `None` means the relays. @@ -1164,6 +1168,7 @@ pub fn build_uniffi_machines_view(v: &MachinesView) -> UniffiMachinesView { accounts: m.accounts.iter().map(|(agent, a)| to_uniffi_agent_accounts(agent, a)).collect(), direct_advertised: m.direct.as_ref().map(|d| d.endpoints.clone()).unwrap_or_default(), direct_pinned: m.direct.as_ref().is_some_and(|d| d.cert_sha256.is_some()), + direct_cert_sha256: m.direct.as_ref().and_then(|d| d.cert_sha256.clone()), direct_endpoints: m.direct_endpoints.clone(), direct_up: v.direct_up.get(&m.pubkey_hex).cloned(), npub: protocol::crypto::npub_from_hex(&m.pubkey_hex).unwrap_or_else(|_| m.pubkey_hex.clone()), diff --git a/crates/protocol/Cargo.toml b/crates/protocol/Cargo.toml index 63a2c2cf..f1f8d116 100644 --- a/crates/protocol/Cargo.toml +++ b/crates/protocol/Cargo.toml @@ -21,6 +21,10 @@ serde_json = "1" # Packing a message before it is encrypted (`packing.rs`): raw deflate, # pure Rust, and the base64 the rest of the workspace already uses. miniz_oxide = { version = "0.8", features = ["with-alloc"] } +# The web page's browser key (`web.rs`): WebCrypto's ECDSA P-256 over +# SHA-256, verified in pure Rust (RustCrypto), nothing to cross-compile. +p256 = { version = "0.13", default-features = false, features = ["ecdsa", "std"] } +sha2 = "0.10" base64 = "0.22" # The agent host's TypeScript types are generated FROM these types (the # driver protocol reuses them; see agent-protocol's gen_ts_bindings test), diff --git a/crates/protocol/fixtures/corpus.json b/crates/protocol/fixtures/corpus.json index 18ff848e..e5a6b055 100644 --- a/crates/protocol/fixtures/corpus.json +++ b/crates/protocol/fixtures/corpus.json @@ -283,6 +283,35 @@ ["OK", "aa", true] ] }, + "webFrames": { + "valid": [ + ["CHALLENGE", "q3Jv8c1Ew7Xh2mY0aZ5tUe9kQnB4sLfD6pR1oG8iVxM"], + ["HELLO", "w_qyb5iAhcG-HSkLYHw3VlPFGm-W3hwPwMyJ0kKbvItoSB6Ml-lqPy5PkVOWj4QCZnYi8IbgUTBwim6pcXFklQ"], + ["READY"], + ["CLOSED", "expired"], + ["CMD", 1, "{\"v\":12,\"type\":\"input\",\"sessionId\":\"s\",\"text\":\"hi\",\"inputId\":\"i1\"}", "w_qyb5iAhcG-HSkLYHw3VlPFGm-W3hwPwMyJ0kKbvItoSB6Ml-lqPy5PkVOWj4QCZnYi8IbgUTBwim6pcXFklQ"], + ["OK", 1, false, "not from a browser"], + ["MSG", { "v": 12, "type": "input-ack", "sessionId": "s", "inputId": "i1" }], + ["PAGE", 2, "{\"type\":\"config\"}", "w_qyb5iAhcG-HSkLYHw3VlPFGm-W3hwPwMyJ0kKbvItoSB6Ml-lqPy5PkVOWj4QCZnYi8IbgUTBwim6pcXFklQ"], + ["REPLY", 2, { "fields": [] }] + ], + "rejected": [ + "not json", + {}, + [], + ["EVENT", {}], + ["HELLO"], + ["HELLO", 1], + ["CMD", 1, { "v": 12, "type": "input" }, "s"], + ["CMD", -1, "{}", "s"], + ["CMD", 9007199254740992, "{}", "s"], + ["CMD", 1, "{}"], + ["OK", 1, "yes", ""], + ["MSG", "{}"], + ["REPLY", 2], + ["READY", 1] + ] + }, "forwardCompatible": [ { "dir": "b2p", "msg": { "v": 12, "type": "agent-style", "agent": "x", "style": { "userMessage": { "shape": "card", "corner": 3 }, "futureKnob": 1 } } }, { "dir": "p2b", "msg": { "v": 12, "type": "input", "sessionId": "s", "text": "hi", "unknownFutureField": 1 } }, diff --git a/crates/protocol/src/lib.rs b/crates/protocol/src/lib.rs index 74cacf32..1a7d715a 100644 --- a/crates/protocol/src/lib.rs +++ b/crates/protocol/src/lib.rs @@ -28,6 +28,7 @@ pub mod ranges; pub mod recipients; pub mod relays; pub mod tristate; +pub mod web; pub use codec::{ decode_bridge_to_phone, decode_phone_to_bridge, encode_bridge_to_phone, encode_phone_to_bridge, diff --git a/crates/protocol/src/web.rs b/crates/protocol/src/web.rs new file mode 100644 index 00000000..a107560c --- /dev/null +++ b/crates/protocol/src/web.rs @@ -0,0 +1,321 @@ +//! The browser's stream: how the bridge's web page drives sessions. +//! +//! The page is served only on the direct link's `wss://` listener, so a +//! browser reaches the bridge over TLS and never through a relay. It needs +//! no Nostr event and no NIP-44: it sends the protocol's own messages +//! ([`crate::commands::PhoneToBridge`] up, [`crate::events::BridgeToPhone`] +//! down) as JSON over one WebSocket. What TLS does not give is who sent a +//! command — the page's cookie is a bearer token — so every frame the +//! browser sends is signed by a key of its own: a WebCrypto ECDSA P-256 key +//! whose private half the page can use but never read, bound to the browser +//! when a paired phone approved its sign-in. +//! +//! Each frame is one WebSocket text message, a JSON array: +//! +//! ```text +//! bridge → browser ["CHALLENGE", ] on connect +//! browser → bridge ["HELLO", ] signs seq 0, empty body +//! bridge → browser ["READY"] | ["CLOSED", ] +//! browser → bridge ["CMD", , , ] body: a PhoneToBridge, as JSON text +//! bridge → browser ["OK", , , ] +//! bridge → browser ["MSG", ] a BridgeToPhone, as a JSON object +//! browser → bridge ["PAGE", , , ] a page request, as JSON text +//! bridge → browser ["REPLY", , ] its answer, a JSON value +//! ``` +//! +//! A signature is over [`signed_input`]: the machine, the browser, the +//! connection's challenge, the frame's `seq` and its body exactly as sent — +//! so neither side canonicalizes JSON, and a signature is good once, on one +//! connection to one bridge. `seq` grows on every signed frame of a +//! connection; several tabs are several connections, each with its own +//! challenge. + +use base64::Engine as _; +use p256::ecdsa::signature::Verifier as _; +use p256::ecdsa::{Signature, VerifyingKey}; +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; + +/// What every signed input starts with, so a signature made for this stream +/// can be nothing else. +pub const SIGNING_CONTEXT: &str = "codedeck-web-v1"; +/// A public key on the wire: the raw uncompressed P-256 point. +pub const PUBLIC_KEY_LEN: usize = 65; +/// A signature on the wire: WebCrypto's `r‖s`. +pub const SIGNATURE_LEN: usize = 64; +/// The largest `seq`: a JavaScript number holds integers exactly up to it. +pub const MAX_SEQ: u64 = (1 << 53) - 1; +/// How many hex characters of the key's SHA-256 are a browser's public id. +pub const BROWSER_ID_LEN: usize = 16; + +/// One frame on the browser's stream. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WebFrame { + Challenge(String), + Hello { sig: String }, + Ready, + Closed(String), + /// `body`: the JSON text of one `PhoneToBridge`, exactly as signed. + Cmd { seq: u64, body: String, sig: String }, + Ok { seq: u64, accepted: bool, message: String }, + /// `message`: the JSON text of one `BridgeToPhone`, sent as an object. + /// Decoding re-serializes it, so its keys come back sorted: only a + /// browser reads these, and it reads them as JSON, not as text. + Msg(String), + /// `body`: the JSON text of a page request, exactly as signed. + Page { seq: u64, body: String, sig: String }, + /// `reply`: the JSON text of the answer, sent as a value. + Reply { seq: u64, reply: String }, +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("bad web frame: {0}")] +pub struct WebDecodeError(pub String); + +/// Why the bridge closed a stream: the `reason` of `["CLOSED", reason]`. +pub mod closed { + /// The `HELLO` or a later frame did not verify, or its `seq` did not grow. + pub const BAD_SIGNATURE: &str = "bad-signature"; + /// The browser's sign-in lapsed (30 days, or 7 idle). + pub const EXPIRED: &str = "expired"; + /// It was signed out, or revoked by a phone or another browser. + pub const SIGNED_OUT: &str = "signed-out"; + /// It fell behind on what the bridge sends, or too many streams are open. + pub const BUSY: &str = "busy"; + /// A frame that is not one the browser may send. + pub const BAD_FRAME: &str = "bad-frame"; +} + +pub fn encode_web_frame(frame: &WebFrame) -> String { + match frame { + WebFrame::Challenge(c) => json!(["CHALLENGE", c]).to_string(), + WebFrame::Hello { sig } => json!(["HELLO", sig]).to_string(), + WebFrame::Ready => json!(["READY"]).to_string(), + WebFrame::Closed(reason) => json!(["CLOSED", reason]).to_string(), + WebFrame::Cmd { seq, body, sig } => json!(["CMD", seq, body, sig]).to_string(), + WebFrame::Ok { seq, accepted, message } => json!(["OK", seq, accepted, message]).to_string(), + // The message is already JSON: it goes in as it is, not re-parsed. + WebFrame::Msg(message) => format!("[\"MSG\",{message}]"), + WebFrame::Page { seq, body, sig } => json!(["PAGE", seq, body, sig]).to_string(), + WebFrame::Reply { seq, reply } => format!("[\"REPLY\",{seq},{reply}]"), + } +} + +/// Decode one frame. Total: anything malformed is an error, never a panic. +pub fn decode_web_frame(text: &str) -> Result { + let bad = |why: &str| WebDecodeError(why.to_string()); + let value: Value = serde_json::from_str(text).map_err(|e| bad(&e.to_string()))?; + let items = value.as_array().ok_or_else(|| bad("not an array"))?; + let label = items.first().and_then(Value::as_str).ok_or_else(|| bad("no label"))?; + let string = |i: usize, what: &str| items.get(i).and_then(Value::as_str).map(str::to_string).ok_or_else(|| bad(what)); + let seq = || items.get(1).and_then(Value::as_u64).filter(|s| *s <= MAX_SEQ).ok_or_else(|| bad("bad seq")); + let arity = |n: usize| if items.len() == n { Ok(()) } else { Err(bad("wrong length")) }; + match label { + "CHALLENGE" => { + arity(2)?; + Ok(WebFrame::Challenge(string(1, "bad challenge")?)) + } + "HELLO" => { + arity(2)?; + Ok(WebFrame::Hello { sig: string(1, "bad signature")? }) + } + "READY" => { + arity(1)?; + Ok(WebFrame::Ready) + } + "CLOSED" => { + arity(2)?; + Ok(WebFrame::Closed(string(1, "bad reason")?)) + } + "CMD" => { + arity(4)?; + Ok(WebFrame::Cmd { seq: seq()?, body: string(2, "bad body")?, sig: string(3, "bad signature")? }) + } + "OK" => { + arity(4)?; + Ok(WebFrame::Ok { + seq: seq()?, + accepted: items.get(2).and_then(Value::as_bool).ok_or_else(|| bad("bad accepted"))?, + message: string(3, "bad message")?, + }) + } + "MSG" => { + arity(2)?; + let message = items.get(1).filter(|m| m.is_object()).ok_or_else(|| bad("bad message"))?; + Ok(WebFrame::Msg(message.to_string())) + } + "PAGE" => { + arity(4)?; + Ok(WebFrame::Page { seq: seq()?, body: string(2, "bad body")?, sig: string(3, "bad signature")? }) + } + "REPLY" => { + arity(3)?; + let reply = items.get(2).ok_or_else(|| bad("no reply"))?; + Ok(WebFrame::Reply { seq: seq()?, reply: reply.to_string() }) + } + _ => Err(bad("unknown label")), + } +} + +/// A browser's public key, checked: base64url of the raw uncompressed point, +/// and a point on the curve. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BrowserKey { + raw: Vec, + key: VerifyingKey, +} + +impl BrowserKey { + /// Read a key as the page sends it; `None` for anything that is not an + /// uncompressed P-256 point on the curve. + pub fn parse(base64url: &str) -> Option { + let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(base64url.trim_end_matches('=')).ok()?; + if raw.len() != PUBLIC_KEY_LEN || raw[0] != 0x04 { + return None; + } + let key = VerifyingKey::from_sec1_bytes(&raw).ok()?; + Some(Self { raw, key }) + } + + /// The key as the page sent it: base64url, no padding. + pub fn to_base64url(&self) -> String { + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&self.raw) + } + + /// The browser's public id: the first [`BROWSER_ID_LEN`] hex characters + /// of the SHA-256 of the raw key. What `web-browsers` lists and + /// `web-browser-sign-out` names; it proves nothing by itself. + pub fn id(&self) -> String { + let mut id = hex::encode(Sha256::digest(&self.raw)); + id.truncate(BROWSER_ID_LEN); + id + } + + /// Whether `sig` (base64url `r‖s`) is this key's signature over `input`. + pub fn verifies(&self, input: &[u8], sig: &str) -> bool { + let Ok(bytes) = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(sig.trim_end_matches('=')) else { return false }; + if bytes.len() != SIGNATURE_LEN { + return false; + } + let Ok(signature) = Signature::from_slice(&bytes) else { return false }; + self.key.verify(input, &signature).is_ok() + } +} + +/// What a frame's signature is over: the UTF-8 of +/// `codedeck-web-v1\n\n\n\n\n`, with +/// `seq` in decimal. `HELLO` is seq 0 with an empty body. +pub fn signed_input(machine_npub: &str, browser_id: &str, challenge: &str, seq: u64, body: &str) -> Vec { + format!("{SIGNING_CONTEXT}\n{machine_npub}\n{browser_id}\n{challenge}\n{seq}\n{body}").into_bytes() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Made by WebCrypto (Node's, the same API the page uses): + /// `generateKey({name: "ECDSA", namedCurve: "P-256"})`, then `sign` with + /// SHA-256 over [`VECTOR_INPUT`]. Proves the bridge reads what a browser + /// writes: the raw point, and `r‖s` rather than DER. + const VECTOR_KEY: &str = "BFl8gfTaV0Lvl6YQA7eW4XLPT_Fjrid-TAPYwqFzPeNymcU9tbDYtN0tnATTjXLtL4aKeMaf4RhN6Kx2js17LaE"; + const VECTOR_SIG: &str = "w_qyb5iAhcG-HSkLYHw3VlPFGm-W3hwPwMyJ0kKbvItoSB6Ml-lqPy5PkVOWj4QCZnYi8IbgUTBwim6pcXFklQ"; + const VECTOR_BODY: &str = r#"{"v":12,"type":"refresh-sessions"}"#; + + fn vector_input() -> Vec { + signed_input("npub1machine", "0123456789abcdef", "challenge", 1, VECTOR_BODY) + } + + #[test] + fn a_webcrypto_signature_verifies() { + let key = BrowserKey::parse(VECTOR_KEY).expect("a WebCrypto raw key"); + assert!(key.verifies(&vector_input(), VECTOR_SIG)); + } + + #[test] + fn a_signature_is_good_only_for_what_it_signed() { + let key = BrowserKey::parse(VECTOR_KEY).unwrap(); + for (machine, browser, challenge, seq, body) in [ + ("npub1other", "0123456789abcdef", "challenge", 1, VECTOR_BODY), + ("npub1machine", "fedcba9876543210", "challenge", 1, VECTOR_BODY), + ("npub1machine", "0123456789abcdef", "another", 1, VECTOR_BODY), + ("npub1machine", "0123456789abcdef", "challenge", 2, VECTOR_BODY), + ("npub1machine", "0123456789abcdef", "challenge", 1, r#"{"v":12,"type":"refresh-sessions" }"#), + ] { + assert!(!key.verifies(&signed_input(machine, browser, challenge, seq, body), VECTOR_SIG), "{machine} {browser} {challenge} {seq} {body}"); + } + } + + #[test] + fn another_key_or_a_mangled_signature_does_not_verify() { + let mut other = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(VECTOR_KEY).unwrap(); + // The generator point: on the curve, but not the signer. + other[1..33].copy_from_slice(&hex::decode("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296").unwrap()); + other[33..].copy_from_slice(&hex::decode("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5").unwrap()); + let other = BrowserKey::parse(&base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(other)).expect("on the curve"); + assert!(!other.verifies(&vector_input(), VECTOR_SIG)); + + let key = BrowserKey::parse(VECTOR_KEY).unwrap(); + assert!(!key.verifies(&vector_input(), "not base64!")); + assert!(!key.verifies(&vector_input(), &VECTOR_SIG[..40]), "short"); + let mut flipped = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(VECTOR_SIG).unwrap(); + flipped[10] ^= 1; + assert!(!key.verifies(&vector_input(), &base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(flipped))); + } + + #[test] + fn only_an_uncompressed_point_on_the_curve_is_a_key() { + let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(VECTOR_KEY).unwrap(); + let enc = |b: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b); + assert!(BrowserKey::parse(&enc(&raw[..64])).is_none(), "short"); + let mut compressed = vec![0x02 | (raw[64] & 1)]; + compressed.extend_from_slice(&raw[1..33]); + assert!(BrowserKey::parse(&enc(&compressed)).is_none(), "compressed"); + let mut off_curve = raw.clone(); + off_curve[64] ^= 1; + assert!(BrowserKey::parse(&enc(&off_curve)).is_none(), "not on the curve"); + assert!(BrowserKey::parse("%%%").is_none()); + assert_eq!(BrowserKey::parse(VECTOR_KEY).unwrap().to_base64url(), VECTOR_KEY); + } + + #[test] + fn the_id_is_the_keys_hash_prefix() { + let key = BrowserKey::parse(VECTOR_KEY).unwrap(); + let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(VECTOR_KEY).unwrap(); + assert_eq!(key.id(), hex::encode(Sha256::digest(&raw))[..BROWSER_ID_LEN]); + } + + #[test] + fn frames_round_trip() { + for frame in [ + WebFrame::Challenge("c1".into()), + WebFrame::Hello { sig: "s".into() }, + WebFrame::Ready, + WebFrame::Closed(closed::EXPIRED.into()), + WebFrame::Cmd { seq: 1, body: VECTOR_BODY.into(), sig: "s".into() }, + WebFrame::Ok { seq: 1, accepted: false, message: "not from a browser".into() }, + WebFrame::Msg(r#"{"inputId":"i","sessionId":"s","type":"input-ack","v":12}"#.into()), + WebFrame::Page { seq: 2, body: r#"{"type":"devices"}"#.into(), sig: "s".into() }, + WebFrame::Reply { seq: 2, reply: r#"{"devices":[]}"#.into() }, + ] { + assert_eq!(decode_web_frame(&encode_web_frame(&frame)), Ok(frame)); + } + } + + #[test] + fn malformed_frames_are_errors() { + for text in [ + "", + "{}", + "[]", + r#"["NOPE"]"#, + r#"["HELLO"]"#, + r#"["CMD", -1, "{}", "s"]"#, + r#"["CMD", 9007199254740992, "{}", "s"]"#, + r#"["CMD", 1, {}, "s"]"#, + r#"["MSG", "text"]"#, + r#"["READY", 1]"#, + ] { + assert!(decode_web_frame(text).is_err(), "{text}"); + } + } +} diff --git a/crates/protocol/tests/codec_conformance.rs b/crates/protocol/tests/codec_conformance.rs index ad15fe82..1dc68c04 100644 --- a/crates/protocol/tests/codec_conformance.rs +++ b/crates/protocol/tests/codec_conformance.rs @@ -252,3 +252,19 @@ fn direct_frames_decode_round_trip_and_rejections_stay_rejected() { assert!(decode_direct_frame(&text).is_err(), "directFrames.rejected[{i}] {text} decoded but should not have"); } } + +#[test] +fn web_frames_decode_round_trip_and_rejections_stay_rejected() { + use protocol::web::{decode_web_frame, encode_web_frame}; + let corpus = corpus(); + for (i, frame) in corpus["webFrames"]["valid"].as_array().unwrap().iter().enumerate() { + let text = frame.to_string(); + let decoded = decode_web_frame(&text).unwrap_or_else(|e| panic!("webFrames.valid[{i}] {text} -> {e}")); + assert_eq!(decode_web_frame(&encode_web_frame(&decoded)), Ok(decoded), "webFrames.valid[{i}] not a round-trip"); + } + for (i, frame) in corpus["webFrames"]["rejected"].as_array().unwrap().iter().enumerate() { + // A string fixture is the raw frame text, anything else its JSON. + let text = frame.as_str().map(str::to_string).unwrap_or_else(|| frame.to_string()); + assert!(decode_web_frame(&text).is_err(), "webFrames.rejected[{i}] {text} decoded but should not have"); + } +} diff --git a/crates/protocol/tests/totality_props.rs b/crates/protocol/tests/totality_props.rs index 459d2d8b..e2ba5a1e 100644 --- a/crates/protocol/tests/totality_props.rs +++ b/crates/protocol/tests/totality_props.rs @@ -12,6 +12,7 @@ use proptest::prelude::*; use protocol::chunking::{frame_encoded_message, parse_chunk_envelope, ChunkAssembler}; use protocol::direct::decode_direct_frame; +use protocol::web::{decode_web_frame, BrowserKey}; use protocol::{decode_bridge_to_phone, decode_phone_to_bridge}; use serde_json::Value; @@ -35,6 +36,8 @@ fn exercise_ingest(text: &str) { let _ = decode_phone_to_bridge(text); let _ = decode_bridge_to_phone(text); let _ = decode_direct_frame(text); + let _ = decode_web_frame(text); + let _ = BrowserKey::parse(text); let _ = parse_chunk_envelope(text); let mut assembler = ChunkAssembler::new(); let _ = assembler.offer(text, 0); @@ -55,8 +58,10 @@ fn valid_wire_messages() -> &'static [String] { out.push(msg.as_str().map(str::to_string).unwrap_or_else(|| msg.to_string())); } } - for frame in corpus["directFrames"]["valid"].as_array().expect("a valid list") { - out.push(frame.to_string()); + for list in ["directFrames", "webFrames"] { + for frame in corpus[list]["valid"].as_array().expect("a valid list") { + out.push(frame.to_string()); + } } let large = format!(r#"{{"type":"output","sessionId":"s","seq":1,"content":"{}"}}"#, "x".repeat(200_000)); out.extend(frame_encoded_message(&large, || "cid-property".to_string())); diff --git a/docs/BRIDGE.md b/docs/BRIDGE.md index 832a8521..d41f6dd7 100644 --- a/docs/BRIDGE.md +++ b/docs/BRIDGE.md @@ -268,43 +268,50 @@ phone, in the machine's settings. To turn the link off, remove `direct` from With the direct link listening on `wss://`, the same port serves a web page for a browser: open `https://
    :7447/` (the bridge logs it at start, -`[Web] The bridge's web page: …`). The browser gets the same self-signed -certificate as the phone, so it shows a certificate warning; compare the -SHA-256 it shows with the one `[Direct] Listening on …` logs before -accepting it. Plain `http://` on the port redirects to -`https://`; the onion listener serves no page. +`[Web] The bridge's web page: …`). From it a browser drives the bridge's +sessions as the phone does — the list, a transcript with live text, input, +permission, question and plan cards, Stop, the mode, a new session — and +sees the bridge, its agents, usage, the signed-in browsers, the paired phones +and the settings. The browser gets the same self-signed certificate as the +phone, so it shows a certificate warning: the phone shows the fingerprint to +compare it with while it signs the browser in (and `[Direct] Listening on …` +logs it). Plain `http://` on the port redirects to `https://`; the onion +listener serves no page. A browser signs in with a paired phone: the page shows a code and a QR, and -on the phone the machine's page, "Browsers", scans or types it (the same -page lists the signed-in browsers and signs one out). The -browser then stays signed in for 30 days (a cookie only the bridge can read, -sent only over HTTPS), and it survives a restart: signed-in browsers are kept -in `/web-sessions.json`, keyed by the cookie's SHA-256 so the file -holds no token a copy could be replayed from. Signing out, or revoking one -from the page, ends it; a pending sign-in is never written. Until signed in -it sees only the sign-in page. The page shows what the heartbeat carries — -the bridge, the direct link, the agents and their credential status, the -sessions — and never a secret. - -Signed in, the page also has a few JSON APIs: `GET /api/browsers` lists the -signed-in browsers (each with its id, approver, sign-in and last-seen times, -expiry, address and User-Agent, and which is the caller) and -`POST /api/browsers/sign-out` ends one — the same list a paired phone reads -with `web-browsers-request` and ends one of with `web-browser-sign-out`, both -served from one place so the two paths never disagree; `GET /api/devices` -shows the paired identities and their clients (labels and key expiries, never -a key); -`GET /api/config` shows the config as it is in effect (and each field whether -a flag or environment variable overrides the file) and `POST /api/config` +on the phone the machine's page, "Browsers", scans or types it, shows the +certificate fingerprint to check, and sends it (the same page lists the +signed-in browsers and signs one out). When it starts, the browser makes a +signing key of its own that its page can use but never read, and sends the +public half with the request; every command it sends afterwards, over one +WebSocket, is signed with it, so the cookie the bridge also sets (readable +only by the bridge, sent only over HTTPS) is worth nothing to whoever copies +it. A browser stays signed in while it is used: 7 days without signing +anything, or 30 days after its sign-in, end it. Signed-in browsers survive a +restart: they are kept in `/web-sessions.json` with their public key, +keyed by the cookie's SHA-256, so the file holds no token a copy could be +replayed from. Signing out, revoking one from the page or the phone, or +unpairing the phone that let it in, ends it at once. A pending sign-in is +never written. [`WEB-CLIENT.md`](WEB-CLIENT.md) is the whole design: the +threat model, the stream, what a browser may send. + +Over plain HTTPS the page answers only its own files, the sign-in (`GET +/api/me`, `POST /api/sign-in`, the QR) and `POST /api/sign-out`; everything +else goes through the signed stream (`/api/stream`). There the config editor changes the safe set — the machine name, the relays, the direct endpoints and the transcript retention — validating each and rewriting `config.json` -keeping every other key. +keeping every other key, and the paired phones are shown with their labels +and key expiries, never a key. What the page shows is what the bridge sends +a phone, which by protocol never holds a secret. Because a LAN or VPN is not a trusted place, the page refuses a `Host` that is not an IP address, `localhost` or a host the direct endpoints name, -requires an `Origin` equal to its own on every `POST`, forbids framing, -caching and any script or connection not its own, rate-limits sign-in starts -to 10 a minute per address, and caps pending codes and signed-in browsers. +requires an `Origin` equal to its own on every `POST` and on its stream, +forbids framing, caching and any script or connection not its own, +rate-limits sign-in starts to 10 a minute per address, and caps pending +codes, signed-in browsers and open streams (4 per browser, 16 in all). A +browser that stops reading its stream is closed rather than waited on, so the +page never slows a phone's link. ## Terminal diff --git a/docs/CLIENT.md b/docs/CLIENT.md index fe79908e..c4396732 100644 --- a/docs/CLIENT.md +++ b/docs/CLIENT.md @@ -433,6 +433,13 @@ the UI view's `webBrowsers` (by machine). Ending one dispatches `SignOutWebBrowser`, which drops the row at once and lets the bridge's fresh list — the same message a request is answered with — confirm it. +A scanned or typed code is not sent at once: "Check the page" shows the +certificate fingerprint the machine's heartbeat pins (the summary's +`directCertSha256`, written as browsers' certificate viewers write it) beside +the code, and only "They match: sign in" sends it. The browser's warning is +the one place a page served by someone else shows itself +([`WEB-CLIENT.md`](WEB-CLIENT.md#sign-in)). + ## Conventions - A UniFFI error variant must not have a field named `message` (it collides diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 3bd0ba26..45841ac1 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -806,12 +806,14 @@ the page's own `GET /api/browsers` and `POST /api/browsers/sign-out` do: never on a timer: the list changes only when a browser signs in or out, so nothing else would make it stale. - `web-browsers {browsers}` to the asking client. Each entry is `{id, by, - sinceMs, lastSeenMs, expiresMs, peer, agent}`: `id` is the page's short - public id — the first 16 hex characters of the stored key's SHA-256, never - the key and never the session token — `by` is the npub that signed it in, - the three times are ms since the Unix epoch, `peer` the address it came - from and `agent` its `User-Agent` (cleaned and bounded). Oldest signed in - first; empty when the bridge runs no web page. + sinceMs, lastSeenMs, expiresMs, peer, agent}`: `id` is the browser's short + public id — the first 16 hex characters of the SHA-256 of its signing key, + never the session token — `by` is the npub that signed it in, the three + times are ms since the Unix epoch (`expiresMs` the moment it lapses: the + sooner of 30 days after its sign-in and 7 days after it last signed + anything), `peer` the address it came from and `agent` its `User-Agent` + (cleaned and bounded). Oldest signed in first; empty when the bridge runs + no web page. - `web-browser-sign-out {id}` (phone → bridge). Ends the browser whose page id is `id`; any paired client may end any of the owner's browsers. Answered with `web-browsers`, the fresh list — a sign-out is confirmed by the list it @@ -822,6 +824,23 @@ Cost: two small command-class events per sign-in, one request and one response per screen opening, and the same again per sign-out; nothing while the screen is closed. +### The browser's stream + +A signed-in browser drives sessions over a wire of its own, not Nostr: the +page is reached only over TLS on the direct listener, so the browser sends +the same `PhoneToBridge` messages as JSON and gets the same `BridgeToPhone` +ones, unencrypted, on one WebSocket (`/api/stream`). Each frame it sends is +signed by a WebCrypto P-256 key the browser made at sign-in, whose public +half `POST /api/sign-in` bound to the code before the phone approved it. +`crates/protocol/src/web.rs` is the spec (frames, the signed input, the key +and signature checks), its frames are in the corpus (`webFrames`), and +[`WEB-CLIENT.md`](WEB-CLIENT.md) is the design: the threat model, what a +browser may send (`bridge_core::browser_may_send`), the lifetimes. + +Cost: none on the relays and none for a phone. A browser's copies are neither +encrypted nor signed, live text goes only to the session on its screen, and a +browser that stops reading is closed, never waited on. + ### Version and capabilities Every message, both ways, carries `v`: its sender's protocol version (12), diff --git a/docs/WEB-CLIENT.md b/docs/WEB-CLIENT.md new file mode 100644 index 00000000..91493bdd --- /dev/null +++ b/docs/WEB-CLIENT.md @@ -0,0 +1,231 @@ +# The web client + +The bridge's web page is a client: a browser drives the bridge's sessions +from it, as the phone does. This page is its design: why it is built the way +it is, what it defends against, and what a browser may do. +[`BRIDGE.md`](BRIDGE.md#web-page) has how to open it; +`crates/protocol/src/web.rs` is the spec of its stream. + +## In one paragraph + +A browser makes a key of its own when it signs in: a WebCrypto ECDSA P-256 +key whose private half the page can use but never read. It sends the public +half with its sign-in request, so the code the phone approves names exactly +one key. After that, every frame the browser sends, on one WebSocket stream, +carries a signature by that key. The 30-day cookie stays, but by itself it +opens nothing beyond the sign-in state. A browser that has signed nothing for +7 days is signed out. While the phone approves, it shows the SHA-256 +fingerprint of the bridge's certificate, so the user can check the +browser's certificate warning against it. + +## Why not Nostr in the browser + +The page is served only on the direct link's `wss://` listener, so a browser +reaches the bridge over TLS and never through a relay. The phone's commands +are Nostr events with NIP-44 payloads because the same events also travel +through relays, and one format means one ingest path. A browser has no +relays, and TLS already encrypts its one hop once the certificate checks +out. So the browser sends the protocol's own JSON messages (`PhoneToBridge` +up, `BridgeToPhone` down) as they are, with no event wrapper and no +encryption of its own. + +TLS does not tell the bridge **who** sent a command. A phone command is +signed by the identity key; a cookie is a bearer token, and whoever holds a +copy holds the browser. Prompting an agent is running commands on the +machine, so the browser signs with a key of its own. + +## Threat model + +What is at stake: commands to agents (code execution on the machine) and +transcripts (code, tool output). + +| Threat | What stops it | +| --- | --- | +| Someone on the LAN or VPN | TLS, the `Host` allowlist, the `Origin` check, and the sign-in itself (only a paired phone approves a code) | +| A copied cookie (profile backup, proxy log, devtools export) | Every frame on the stream needs a signature by the browser's key, which cannot be exported. The cookie alone reads only `/api/me` and cannot keep the session alive. | +| Script injected into the page | The strict CSP (no inline script, nothing from another origin, no `eval`): the key can be *used* by any script on the page, so keeping foreign script out is what protects it. Transcripts are rendered as text only (below). | +| An active MITM whose certificate the user accepts | The fingerprint on the phone. A MITM serves its own page and its own key, and the code it shows is bound to that key; only the user comparing the browser's certificate with the phone's pin catches it. | +| A forgotten signed-in browser | The 7-day idle limit, the 30-day limit, and sign-out from the phone or another browser | +| A browser approved by an identity that is later unpaired | Unpairing ends that identity's browsers | +| A pending sign-in code read off the screen | It is useless without a paired phone, works once, for 5 minutes | + +Out of reach by design: malware running as the user inside that browser +profile (it can drive the page, and so the key); a user who approves a code +they did not start themselves. + +**Transcripts are attacker-controlled text.** An agent's output can contain +anything a tool read, such as a fetched web page. The page builds every +transcript element from text nodes and never assigns `innerHTML`; its light +markdown (fences, paragraphs, inline code, bold) is built as elements. The +CSP is the second line of defence, never the first. + +## Sign-in + +1. **The key.** On "Show a sign-in code" the page makes a fresh pair with + `crypto.subtle.generateKey({name: "ECDSA", namedCurve: "P-256"}, false, + ["sign", "verify"])` and stores the `CryptoKey` objects in IndexedDB, + where they stay non-extractable. P-256 rather than Ed25519, because every + browser has had it for years. A page whose certificate the user accepted + is a secure context (its scheme is `https`), so WebCrypto works there — + checked in Chrome over a LAN address. +2. **Start.** `POST /api/sign-in {key}`: the public key's raw uncompressed + point (65 bytes, base64url). The bridge refuses a point off the curve. + The browser's **id** is the first 16 hex characters of the point's + SHA-256: what `web-browsers` lists and `web-browser-sign-out` names. The + key is bound to the pending sign-in **here, before any phone sees the + code**, so the code an identity approves names exactly one key. The answer + is the code, its lifetime, and the `__Host-` cookie. +3. **The page** shows the code and its QR, and tells the user that the phone + will show the certificate fingerprint to compare. It never shows a + fingerprint itself: a MITM's page would show whatever matches. +4. **The phone** (Browsers) scans the QR or takes the typed code, then shows + "Check the page": the certificate fingerprint it pins from the heartbeat + (`direct.certSha256`), written as browsers' certificate viewers write it + (uppercase pairs, colon-separated, eight to a line), and the code. Only + "They match: sign in" sends `web-sign-in {code}`. The wire is the one it + was: the identity's signature covers the code, and the code names one key. +5. **The bridge** matches the code and signs the browser in with that key. + The page, polling `/api/me`, sees `signed-in` with its own `id` and the + machine's npub — and opens the stream only if the key it holds has that + id (site data cleared means a new sign-in). + +The key lives as long as the sign-in: signing out, a revocation or a lapse +deletes it, and the next sign-in makes a fresh one, so a revoked key is +never used again. + +## The stream + +`GET /api/stream` with `Upgrade: websocket`; every other upgrade on the port +is a phone's direct link. The upgrade is refused unless the `Host` is +allowed, the `Origin` is the page's own (browsers send cookies on +cross-site WebSocket handshakes, and `SameSite` alone is not relied on), and +the cookie names a signed-in browser — a check that costs one hash, before +any signature work. + +Frames are JSON arrays, one per text message, like the direct link's: + +``` +bridge ["CHALLENGE", c] 32 random bytes, base64url, new per connection +browser ["HELLO", sig] within 10 s; signs seq 0 with an empty body +bridge ["READY"] | ["CLOSED", reason] bad-signature | expired | signed-out | busy | bad-frame +browser ["CMD", seq, body, sig] body: one PhoneToBridge, as JSON text +bridge ["OK", seq, accepted, message] per CMD +bridge ["MSG", message] one BridgeToPhone, as a JSON object +browser ["PAGE", seq, body, sig] a page request, as JSON text +bridge ["REPLY", seq, {status, body}] its answer +``` + +**The signed input** is the UTF-8 of +`codedeck-web-v1\n\n\n\n\n` +with `seq` in decimal; `sig` is WebCrypto's ECDSA signature over it with +SHA-256 (64 bytes, `r‖s`, base64url). It is over the exact text sent, so +neither side canonicalizes JSON, and binding the machine, the browser and the +connection's challenge makes a signature good once, on one connection to one +bridge. `seq` grows on every signed frame (gaps allowed); a frame that does +not verify, or whose `seq` does not grow, closes the stream. Several tabs are +several connections, each with its own challenge. + +**Page requests** are what only the page asks: `{type: "devices"}`, +`{type: "config"}` and `{type: "config-set", set}`. The heartbeat +(`sessions`) arrives as a `MSG`, and the browser list through the phone's own +`web-browsers-request` and `web-browser-sign-out`. Over plain HTTPS a cookie +reaches only the page's files, `GET /api/me`, `POST /api/sign-in`, the QR and +`POST /api/sign-out` (ending its own sign-in, which a cookie may always do). + +**No automatic resend.** A `CMD` whose `OK` never came before the connection +dropped is reported as "may not have arrived" and not sent again: a browser's +command has no event id for the engine to drop a duplicate by, and the +transcript shows whether an input landed. + +## The browser in the engine + +A browser is a principal of `bridge-core`: **a client of the identity that +let it in**, addressed as `Addressee::browser(identity, id)`. The runtime +verifies each frame and hands the engine `Input::WebCommand`; the engine +runs it as that identity's, with the reply going to the browser alone. Its +copies are neither encrypted nor signed: the runtime writes them down its +streams. It has presence and watch state like a phone's client, so it gets +live text only for the session on screen; it is present while a stream is +open. Unpairing an identity ends the browsers it let in. + +**What a browser may send** (`bridge_core::browser_may_send`, which names +every command so a new one is decided rather than let through): `input`, the +three card responses, `set-option`, `sync-request`/`sync-ack`, +`create-session`, `refresh-sessions`, `close-session`, `interrupt`, +`stop-task`, `create-folder`, `presence`, the read-only requests (usage, +models, agent style, commands, personas, plugins, MCP, session MCP, +permission rules, accounts, provider profiles), `web-browsers-request` and +`web-browser-sign-out`. Refused, with `OK false`: + +- `session-key`, `pair-request` and `web-sign-in` belong to an identity: a + browser never lets in another browser. +- `set-credentials`, `set-provider-profile` and `account-action` move + secrets and sign-ins. +- `terminal-*`: the terminal allowlist names devices, and a browser is none. +- `upload-file`, and the agent-configuration writes: `plugin-action`, + `mcp-action`, `agent-action`, `session-mcp-toggle`, + `permission-rules-remove`. + +These can be opened one at a time later, each with its own reasoning. + +## Lifetimes + +- **30 days** from sign-in at most (the cookie's `Max-Age` is set at the + start; the bridge's record, which decides, counts from the approval). +- **7 idle days:** only a verified signature (`HELLO`, `CMD`, `PAGE`) moves + `lastSeenMs` — a request carrying the cookie does not, so a copied cookie + cannot keep a session alive. It is written to disk at most once a minute, + so the limit holds to a minute and survives a restart. An open tab renews + its presence every 5 minutes, which keeps it signed in while open. +- `expiresMs` in `web-browsers` is when it actually lapses: + `min(sinceMs + 30 d, lastSeenMs + 7 d)`. +- A lapse, sign-out or revocation closes the browser's streams at once with + `["CLOSED", reason]`; the page returns to sign-in and deletes its key. + +## Rendering + +The page renders the protocol's messages itself, in plain JavaScript with no +build step, about 60 KB in all. Reusing the phone's core instead +(`crates/client-core` in wasm) was considered: it is pure, but it and +`crates/protocol` depend on `nostr`, which pulls `secp256k1-sys`, a C +library — a wasm build needs the Nostr parts behind a feature or a C +compiler for wasm, a wasm build in every release, and `'wasm-unsafe-eval'` +in the CSP. The browser needs none of the Nostr parts, and a renderer of the +wire's entry types is small, so the page keeps its own; the corpora and +`PROTOCOL.md` are what it follows. + +## Cost + +- No relay traffic, no NIP-44 and no event signing for a browser's copies: a + copy for a browser costs the bridge less than one for a phone. +- Live text only for the session on screen, nothing for a closed tab. +- **The phones' links never wait for a browser.** A stream goes through the + direct link's lane: queued, never waited on, and a browser that stops + reading is closed (`busy`) and reconnects with a sync. Caps: 4 streams per + browser, 16 in all, 64 signed-in browsers. An open stream does not count + against its host's direct-link connections (8 per address, or per /64 on + IPv6, where a whole LAN shares one), so tabs never lock a phone out. +- One ECDSA P-256 verify per browser frame, at human rates. + +## Tests + +- `crates/protocol/src/web.rs`: the frames, and the key and signature checks + against a vector made by WebCrypto. +- `crates/bridge-core/tests/web_client.rs`: the engine's side — copies, + replies, live text, the allowlist, unpairing. +- `crates/bridge-runtime/src/web.rs`, `web_stream.rs`: the page and the + stream over a real WebSocket — the cookie alone, the limits on an injected + clock, the gate, a replayed `seq`, another key, another connection's + challenge. +- `crates/bridge-runtime/tests/web_page.rs` (ignored; `./codedeck e2e` and + CI run it): the real runtime and agent host, a paired phone core, and a + browser over pinned TLS, from sign-in to a session answered and the phone's + sign-out closing the stream. Its `hold_a_bridge_for_a_real_browser` holds + such a bridge for a real browser: with `CODEDECK_WEB_HOLD=` (and + `CODEDECK_WEB_HOLD_PORT`, `CODEDECK_WEB_HOLD_SECS`) the phone approves + every code written to ``, so headless Chrome — or a person — can + drive the page. + +Later, optionally: signing as the real identity through a NIP-07 browser +extension, for users who have one; a real certificate through Tailscale, +which removes the warning.