diff --git a/.agents/skills/verify-deepseekbot/features/phone-pairing.md b/.agents/skills/verify-deepseekbot/features/phone-pairing.md index 32389b04ed..9bd0bd76c6 100644 --- a/.agents/skills/verify-deepseekbot/features/phone-pairing.md +++ b/.agents/skills/verify-deepseekbot/features/phone-pairing.md @@ -1,5 +1,15 @@ # Phone pairing and paired devices +## Encrypted LAN (#2599) + +Reserve the native QA lane before starting a Host, build or device. New native builds are required for `LanChannel`; record iOS and Android separately. + +1. Devices starts with local access off. `device-lan enable` without `--confirm` refuses. Capture the matched base/candidate Devices states. +2. Enable local access visibly. Choose **Use the same Wi-Fi** in the installed app, scan the computer QR and approve the exact phone key on the computer. Capture both themes and default/intermediate/maximum text. Exclude QR payloads and private addresses from public evidence. +3. Without WAN, read the real Host Feed over LAN. Separately, with a reachable model, send a marked DM and verify the visible reply and canonical timeline. A model failure is not a LAN failure. +4. Restart both peers; trust and the logical Host remain. Revoke the phone; streams close and reconnect refuses. Disable LAN and verify port release while independent remote access remains. +5. Wrong Host pins, legacy pairings without keys, reused and expired offers refuse. Denied local-network permission shows recovery guidance. This slice does not add mutation replay or proactive handover. + A Human pairs the phone app with their Host by a one-time QR code, and the phone keeps working across Host restarts until the Human revokes it. The phone holds a per-device credential and talks only to the device gateway (`/botharness-device/*`, [ADR-0199](../../../../docs/adr/0199-paired-devices-reach-the-host-through-a-same-listener-device-gateway.md)). ## Sub-features @@ -11,7 +21,7 @@ A Human pairs the phone app with their Host by a one-time QR code, and the phone - `link-errors` words a refusal by how the phone got the offer: a pasted or opened link that is broken, expired or already used says the link is wrong, and a pasted one empties the field; a scan keeps the code wording. - `manual-input` keeps the empty link field and Pair button above the Android keyboard. A manually scanned or pasted offer registers the phone, loads the Host roster and survives app process restart. - `cloud-exit` leaves the native pairing modal before opening Cloud services, so Workspaces exposes a visible, operable drawer. -- `fingerprint-steps` opens a fresh encrypted invitation. The scan/link form is replaced by a focused computer verification page with all 64 fingerprint digits, selectable grouped text and native actions. Expand/collapse the explanation without granting trust. A mismatch or Back must cancel without opening a channel; a fresh invitation still works. Explicitly compare with the trusted Host, tap Fingerprints match, then compare the full phone fingerprint with Host Devices and approve only that key. The phone waits without a second trust action and remains cancellable. Check light/dark and default/intermediate/maximum text; compare full fingerprints before scrolling to reachable actions. Both account and direct-link routes use the same verification view. +- `fingerprint-steps` opens a fresh encrypted invitation. For pasted and opened links, the link form is replaced by a focused computer verification page with all 64 fingerprint digits, selectable grouped text and native actions. Expand/collapse the explanation without granting trust. A mismatch or Back must cancel without opening a channel; a fresh invitation still works. Explicitly compare with the trusted Host, tap Fingerprints match, then compare the full phone fingerprint with Host Devices and approve only that key. The phone waits without a second trust action and remains cancellable. Check light/dark and default/intermediate/maximum text; compare full fingerprints before scrolling to reachable actions. Both account and direct-link routes use the same verification view. - `pair-return` uses the existing assigned iOS Simulator: compare the real Connect Host fingerprint, approve the exact displayed device key, then immediately open Chats, Settings (close and reopen) and Activity without restarting/reloading the app. Require no `sheetPresentationController` error or blocked taps. Repeat with the first-use notice unread/read, light/dark and default/intermediate/maximum system text. `apps/mobile/.maestro/sim/pairing-return.yaml` runs the post-approval interaction check without launching or clearing the app; keep native approval and capture evidence alongside it. - `roster` shows the Host's PersonaBots in the app through the gateway, with the live stream. - `restart` keeps the phone connected after a Host restart without pairing again. diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index ab6c4d3bc0..e352a63628 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -138,7 +138,7 @@ jobs: env: CI: '1' EXPO_OFFLINE: '1' - - run: bash apps/mobile/android/gradlew -p apps/mobile/android :stream-reveal:testDebugUnitTest :hardware-send:testDebugUnitTest :conversation-notifications:compileDebugKotlin -PreactNativeArchitectures=x86_64 --max-workers=2 --console=plain + - run: bash apps/mobile/android/gradlew -p apps/mobile/android :stream-reveal:testDebugUnitTest :hardware-send:testDebugUnitTest :conversation-notifications:compileDebugKotlin :lan-channel:testDebugUnitTest -PreactNativeArchitectures=x86_64 --max-workers=2 --console=plain test-full: name: test (shard ${{ matrix.shard }}) diff --git a/apps/mobile/AGENTS.md b/apps/mobile/AGENTS.md index 95e7256fd1..bd0cf50b35 100644 --- a/apps/mobile/AGENTS.md +++ b/apps/mobile/AGENTS.md @@ -35,7 +35,7 @@ Screens follow the shared [UI design standard](../../docs/agents/ui-design.md) a - **File writes are explicit.** SDK 58 `File.write()` is asynchronous. The existing synchronous persistence adapters use `File.writeSync()` so their failure handling and callers retain the same contract. - **A native change needs a new development build.** Adding a package with native code, a config plugin, or an `app.json` native field change means the installed dev build is stale; say so in the PR. JavaScript-only changes reload through Metro. - **No secrets in the bundle.** Anything in `EXPO_PUBLIC_*` variables or `app.json` ships inside the app. Tokens live only in `expo-secure-store` and are never logged. -- **HTTPS only.** iOS App Transport Security and Android cleartext rules block plain `http://` on device; the Host is reached over Tailscale HTTPS. +- **HTTPS for ordinary requests.** LAN uses only the restricted native `LanChannel` carrier for pinned-key Noise frames; it never sends ordinary HTTP or device credentials in plaintext. Keep general cleartext disabled. Tailscale uses HTTPS and Connect retains its encrypted carrier. See `docs/architecture/lan-phone-v1.md` at the repo root. - **Long lists virtualize.** Use `FlatList`/`SectionList` (or FlashList if measured), never `ScrollView` over `.map()`. - **Web is a preview target, not a product.** The web export exists for screenshots in cloud sessions (see `README.md`); do not add web-only code paths to make it work. diff --git a/apps/mobile/app.config.js b/apps/mobile/app.config.js index f6611474d2..5211dfc534 100644 --- a/apps/mobile/app.config.js +++ b/apps/mobile/app.config.js @@ -59,6 +59,7 @@ module.exports = ({ config }) => { bundleIdentifier, infoPlist: { ...config.ios.infoPlist, + NSAppTransportSecurity: { NSAllowsLocalNetworking: true }, ITSAppUsesNonExemptEncryption: false, NSUserActivityTypes: ['INSendMessageIntent'], }, diff --git a/apps/mobile/app.json b/apps/mobile/app.json index c398664d07..e28e3ed62a 100644 --- a/apps/mobile/app.json +++ b/apps/mobile/app.json @@ -19,6 +19,7 @@ "tinted": "./assets/app-icons/deepseekbot-tinted.png" }, "infoPlist": { + "NSLocalNetworkUsageDescription": "DeepSeekBot connects to your computer on this network using an encrypted connection.", "CFBundleDevelopmentRegion": "en", "CFBundleLocalizations": ["en", "zh-Hans"] } @@ -31,6 +32,7 @@ } }, "plugins": [ + "./with-lan-channel", "expo-router", [ "expo-splash-screen", diff --git a/apps/mobile/app/pair/index.tsx b/apps/mobile/app/pair/index.tsx index a2ad391e86..0d42f45eb0 100644 --- a/apps/mobile/app/pair/index.tsx +++ b/apps/mobile/app/pair/index.tsx @@ -43,6 +43,15 @@ export default function PairChoiceScreen() { router.back()} /> {t.pairChoice.intro} + } + disclosure + onPress={() => router.push({ pathname: '/pair/tailscale', params: { mode: 'lan' } })} + /> (); + const params = useLocalSearchParams<{ p?: string; mode?: string }>(); const [permission, requestPermission] = useCameraPermissions(); const [link, setLink] = useState(''); const [focused, setFocused] = useState(false); @@ -56,7 +56,12 @@ export default function PairTailscaleScreen() { style={{ flex: 1, backgroundColor: theme.overlay.fill }} contentContainerStyle={{ padding: space.x5, gap: space.x4 }} > - {t.pairChoice.tailscaleHint} + + + {params.mode === 'lan' ? t.pairChoice.lanHint : t.pairChoice.tailscaleHint} + diff --git a/apps/mobile/modules/lan-channel/android/src/main/java/expo/modules/lanchannel/BoundedChannelInput.kt b/apps/mobile/modules/lan-channel/android/src/main/java/expo/modules/lanchannel/BoundedChannelInput.kt new file mode 100644 index 0000000000..9622be1851 --- /dev/null +++ b/apps/mobile/modules/lan-channel/android/src/main/java/expo/modules/lanchannel/BoundedChannelInput.kt @@ -0,0 +1,83 @@ +package expo.modules.lanchannel + +import java.io.IOException +import java.io.InputStream + +internal class BoundedChannelInput(private val source: InputStream) : InputStream() { + private var upgraded = false + private var headerBytes = 0 + private var delimiter = 0 + private val header = ByteArray(10) + private var headerSize = 0 + private var headerTarget = 2 + private var remaining = 0L + private var messageBytes = 0L + private var fragments = 0 + private var fragmented = false + + override fun read(): Int { + val value = source.read() + if (value >= 0) accept(value) + return value + } + + override fun read(buffer: ByteArray, offset: Int, length: Int): Int { + val count = source.read(buffer, offset, minOf(length, 8192)) + for (index in offset until offset + maxOf(count, 0)) accept(buffer[index].toInt() and 255) + return count + } + + override fun close() = source.close() + + private fun accept(value: Int) { + if (!upgraded) { + if (++headerBytes > 8192) refuse() + delimiter = (delimiter shl 8) or value + if (delimiter == 0x0d0a0d0a) upgraded = true + return + } + if (remaining > 0) { + remaining-- + return + } + header[headerSize++] = value.toByte() + if (headerSize == 2) { + val length = value and 127 + headerTarget = when (length) { 126 -> 4; 127 -> 10; else -> 2 } + } + if (headerSize != headerTarget) return + val first = header[0].toInt() and 255 + val opcode = first and 15 + val final = first and 128 != 0 + if (first and 112 != 0 || header[1].toInt() and 128 != 0) refuse() + var length = (header[1].toInt() and 127).toLong() + if (length >= 126) { + length = 0 + for (index in 2 until headerTarget) { + length = (length shl 8) or (header[index].toLong() and 255) + if (length > 70_000) refuse() + } + } + when (opcode) { + 1 -> { + if (fragmented) refuse() + messageBytes = length + fragments = 1 + fragmented = !final + } + 0 -> { + if (!fragmented || ++fragments > 1024) refuse() + messageBytes += length + fragmented = !final + } + 8, 9, 10 -> if (!final || length > 125) refuse() + else -> refuse() + } + if (messageBytes > 70_000) refuse() + remaining = length + headerSize = 0 + headerTarget = 2 + } + + private fun refuse(): Nothing = throw IOException("channel-frame-invalid") +} diff --git a/apps/mobile/modules/lan-channel/android/src/main/java/expo/modules/lanchannel/LanChannelModule.kt b/apps/mobile/modules/lan-channel/android/src/main/java/expo/modules/lanchannel/LanChannelModule.kt new file mode 100644 index 0000000000..993dccc1d7 --- /dev/null +++ b/apps/mobile/modules/lan-channel/android/src/main/java/expo/modules/lanchannel/LanChannelModule.kt @@ -0,0 +1,115 @@ +package expo.modules.lanchannel + +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition +import okhttp3.ConnectionPool +import okhttp3.Dns +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.Response +import okhttp3.WebSocket +import okhttp3.WebSocketListener +import java.net.InetAddress +import java.net.Proxy +import java.net.Socket +import javax.net.SocketFactory +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.TimeUnit + +private const val CARRIER_HOST = "encrypted-lan.invalid" +private const val CHANNEL_PATH = "/botharness-device/channel" +private const val FRAME_LIMIT = 70_000 + +class LanChannelModule : Module() { + private data class Channel(val client: OkHttpClient, var socket: WebSocket? = null) + private val channels = ConcurrentHashMap() + + override fun definition() = ModuleDefinition { + Name("LanChannel") + Events("channel") + + Function("open") { id: String, address: String, port: Int -> + require(port in 1..65535 && channels.size < 8 && !channels.containsKey(id)) { "lan-route-invalid" } + val bytes = privateAddress(address) + val client = OkHttpClient.Builder() + .socketFactory(object : SocketFactory() { + override fun createSocket(): Socket = object : Socket() { + private val bounded by lazy { BoundedChannelInput(super.getInputStream()) } + override fun getInputStream() = bounded + } + override fun createSocket(host: String, port: Int): Socket = error("lan-route-invalid") + override fun createSocket(host: String, port: Int, local: InetAddress, localPort: Int): Socket = error("lan-route-invalid") + override fun createSocket(host: InetAddress, port: Int): Socket = error("lan-route-invalid") + override fun createSocket(host: InetAddress, port: Int, local: InetAddress, localPort: Int): Socket = error("lan-route-invalid") + }) + .proxy(Proxy.NO_PROXY) + .dns(object : Dns { + override fun lookup(hostname: String): List { + require(hostname == CARRIER_HOST) { "lan-route-invalid" } + return listOf(InetAddress.getByAddress(bytes)) + } + }) + .connectionPool(ConnectionPool(0, 1, TimeUnit.SECONDS)) + .followRedirects(false).followSslRedirects(false) + .connectTimeout(10, TimeUnit.SECONDS) + .readTimeout(0, TimeUnit.SECONDS) + .build() + val channel = Channel(client) + channels[id] = channel + channel.socket = client.newWebSocket( + Request.Builder().url("ws://$CARRIER_HOST:$port$CHANNEL_PATH").build(), + object : WebSocketListener() { + override fun onOpen(socket: WebSocket, response: Response) { + if (channels[id] !== channel) socket.cancel() + else emit(id, "open") + } + override fun onMessage(socket: WebSocket, text: String) { + if (!validFrame(text)) finish(id, "channel-frame-invalid") + else if (channels[id] === channel) emit(id, "message", text) + } + override fun onMessage(socket: WebSocket, bytes: okio.ByteString) { finish(id, "channel-frame-invalid") } + override fun onClosing(socket: WebSocket, code: Int, reason: String) { finish(id, "channel-disconnected") } + override fun onFailure(socket: WebSocket, error: Throwable, response: Response?) { finish(id, "lan-unreachable") } + override fun onClosed(socket: WebSocket, code: Int, reason: String) { finish(id, "channel-disconnected") } + } + ) + if (channels[id] !== channel) channel.socket?.cancel() + } + Function("send") { id: String, text: String -> + val socket = channels[id]?.socket ?: error("channel-disconnected") + require(validFrame(text)) { "channel-frame-invalid" } + if (socket.queueSize() + text.length > 20 * 1024 * 1024 || !socket.send(text)) { + finish(id, "channel-busy") + error("channel-busy") + } + } + Function("close") { id: String -> finish(id, "channel-disconnected") } + OnDestroy { channels.keys.toList().forEach { finish(it, "channel-disconnected") } } + } + + private fun emit(id: String, type: String, text: String = "") { + sendEvent("channel", mapOf("id" to id, "type" to type, "text" to text)) + } + + private fun finish(id: String, reason: String) { + val channel = channels.remove(id) ?: return + channel.socket?.cancel() + channel.client.connectionPool.evictAll() + channel.client.dispatcher.executorService.shutdown() + emit(id, "closed", reason) + } +} + +internal fun validFrame(text: String): Boolean = + text.length in 3..FRAME_LIMIT && text.length % 2 == 1 && + (text[0] == 'h' || text[0] == 'd') && text.drop(1).all { it in '0'..'9' || it in 'a'..'f' } + +internal fun privateAddress(address: String): ByteArray { + val parts = address.split('.') + require(parts.size == 4 && parts.all { it.matches(Regex("[0-9]{1,3}")) }) { "lan-route-invalid" } + val numbers = parts.map { it.toInt() } + require(numbers.all { it in 0..255 } && + (numbers[0] == 10 || (numbers[0] == 172 && numbers[1] in 16..31) || + (numbers[0] == 192 && numbers[1] == 168))) { "lan-route-invalid" } + return numbers.map { it.toByte() }.toByteArray() +} diff --git a/apps/mobile/modules/lan-channel/android/src/test/java/expo/modules/lanchannel/BoundedChannelInputTest.kt b/apps/mobile/modules/lan-channel/android/src/test/java/expo/modules/lanchannel/BoundedChannelInputTest.kt new file mode 100644 index 0000000000..63564887ca --- /dev/null +++ b/apps/mobile/modules/lan-channel/android/src/test/java/expo/modules/lanchannel/BoundedChannelInputTest.kt @@ -0,0 +1,38 @@ +package expo.modules.lanchannel + +import java.io.ByteArrayInputStream +import java.io.IOException +import org.junit.Assert.* +import org.junit.Test + +class BoundedChannelInputTest { + private val upgrade = "HTTP/1.1 101 Switching Protocols\r\n\r\n".toByteArray() + private fun read(vararg frames: ByteArray): ByteArray = BoundedChannelInput( + ByteArrayInputStream(upgrade + frames.reduce { first, next -> first + next }) + ).readBytes() + + @Test fun acceptsBoundedTextWithFragmentationAndPing() { + val frames = byteArrayOf(1, 2, 100, 97, 137.toByte(), 0, 128.toByte(), 1, 98) + assertArrayEquals(upgrade + frames, read(frames)) + } + + @Test fun refusesDeclaredLengthBeforeReadingPayload() { + assertThrows(IOException::class.java) { + read(byteArrayOf(129.toByte(), 127, 0, 0, 0, 0, 0, 1, 17, 113)) + } + } + + @Test fun refusesAggregateFragmentsAndFragmentCount() { + val first = byteArrayOf(1, 126, 0x9c.toByte(), 0x40) + ByteArray(40_000) + val second = byteArrayOf(128.toByte(), 126, 0x9c.toByte(), 0x40) + assertThrows(IOException::class.java) { read(first, second) } + assertThrows(IOException::class.java) { read(byteArrayOf(1, 0), *Array(1024) { byteArrayOf(0, 0) }) } + } + + @Test fun refusesBinaryCompressionAndOversizedUpgrade() { + for (frame in listOf(byteArrayOf(130.toByte(), 0), byteArrayOf(193.toByte(), 0))) { + assertThrows(IOException::class.java) { read(frame) } + } + assertThrows(IOException::class.java) { BoundedChannelInput(ByteArrayInputStream(ByteArray(8193))).readBytes() } + } +} diff --git a/apps/mobile/modules/lan-channel/android/src/test/java/expo/modules/lanchannel/LanChannelTest.kt b/apps/mobile/modules/lan-channel/android/src/test/java/expo/modules/lanchannel/LanChannelTest.kt new file mode 100644 index 0000000000..30c075035c --- /dev/null +++ b/apps/mobile/modules/lan-channel/android/src/test/java/expo/modules/lanchannel/LanChannelTest.kt @@ -0,0 +1,20 @@ +package expo.modules.lanchannel + +import org.junit.Assert.* +import org.junit.Test + +class LanChannelTest { + @Test fun acceptsOnlyPrivateIpv4WithoutDns() { + assertArrayEquals(byteArrayOf(192.toByte(), 168.toByte(), 1, 20), privateAddress("192.168.1.20")) + for (address in listOf("127.0.0.1", "8.8.8.8", "169.254.169.254", "172.32.1.1", "10.0.0.256", "host.local", "::1", "1.2.3")) { + assertThrows(IllegalArgumentException::class.java) { privateAddress(address) } + } + } + @Test fun refusesRawMessagesAndOversizedFrames() { + assertTrue(validFrame("h" + "ab".repeat(48))) + assertTrue(validFrame("d" + "ab".repeat(64))) + for (frame in listOf("Device token", "{\"text\":\"private\"}", "hzz", "daa0", "d" + "ab".repeat(35_000))) { + assertFalse(validFrame(frame)) + } + } +} diff --git a/apps/mobile/modules/lan-channel/expo-module.config.json b/apps/mobile/modules/lan-channel/expo-module.config.json new file mode 100644 index 0000000000..6cea20fc04 --- /dev/null +++ b/apps/mobile/modules/lan-channel/expo-module.config.json @@ -0,0 +1,5 @@ +{ + "platforms": ["android", "apple"], + "apple": { "modules": ["LanChannelModule"] }, + "android": { "modules": ["expo.modules.lanchannel.LanChannelModule"] } +} diff --git a/apps/mobile/modules/lan-channel/ios/LanChannel.podspec b/apps/mobile/modules/lan-channel/ios/LanChannel.podspec new file mode 100644 index 0000000000..51f516fe78 --- /dev/null +++ b/apps/mobile/modules/lan-channel/ios/LanChannel.podspec @@ -0,0 +1,15 @@ +Pod::Spec.new do |s| + s.name = 'LanChannel' + s.version = '0.1.0' + s.summary = 'Restricted encrypted LAN WebSocket carrier' + s.description = 'Carries Noise frames to private IPv4 device gateways.' + s.author = 'BotHarness' + s.homepage = 'https://github.com/BotHarness/DeepSeekBot' + s.license = { :type => 'MIT' } + s.platforms = { :ios => '17.0' } + s.source = { :git => '' } + s.static_framework = true + s.dependency 'ExpoModulesCore' + s.source_files = '**/*.{h,m,mm,swift}' + s.swift_version = '5.9' +end diff --git a/apps/mobile/modules/lan-channel/ios/LanChannelModule.swift b/apps/mobile/modules/lan-channel/ios/LanChannelModule.swift new file mode 100644 index 0000000000..7dfb1e8e7f --- /dev/null +++ b/apps/mobile/modules/lan-channel/ios/LanChannelModule.swift @@ -0,0 +1,117 @@ +import ExpoModulesCore +import Foundation + +private final class LanSessionDelegate: NSObject, URLSessionTaskDelegate { + func urlSession(_ session: URLSession, task: URLSessionTask, + willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, + completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } +} + +public final class LanChannelModule: Module { + private var channels: [String: URLSessionWebSocketTask] = [:] + private let lock = NSLock() + private let delegate = LanSessionDelegate() + private var queued: [String: Int] = [:] + private lazy var session: URLSession = { + let config = URLSessionConfiguration.ephemeral + config.httpCookieStorage = nil + config.httpShouldSetCookies = false + config.urlCredentialStorage = nil + config.timeoutIntervalForRequest = 10 + config.connectionProxyDictionary = [:] + return URLSession(configuration: config, delegate: delegate, delegateQueue: nil) + }() + + public func definition() -> ModuleDefinition { + Name("LanChannel") + Events("channel") + Function("open") { (id: String, address: String, port: Int) in + let parts = address.split(separator: ".", omittingEmptySubsequences: false) + let numbers = parts.compactMap { Int($0) } + guard parts.count == 4, numbers.count == 4, + parts.allSatisfy({ $0.count <= 3 && $0.allSatisfy({ $0.isASCII && $0.isNumber }) }), + numbers.allSatisfy({ (0...255).contains($0) }), + (numbers[0] == 10 || (numbers[0] == 172 && (16...31).contains(numbers[1])) || + (numbers[0] == 192 && numbers[1] == 168)), (1...65535).contains(port), + let url = URL(string: "ws://\(address):\(port)/botharness-device/channel") + else { throw NSError(domain: "lan-route-invalid", code: 1) } + self.lock.lock() + guard self.channels.count < 8, self.channels[id] == nil else { + self.lock.unlock() + throw NSError(domain: "channel-busy", code: 1) + } + let socket = self.session.webSocketTask(with: url) + socket.maximumMessageSize = 70_000 + self.channels[id] = socket + self.queued[id] = 0 + self.lock.unlock() + socket.resume() + // send() queues until the WebSocket upgrade completes; no application data precedes Noise. + self.emit(id, "open") + self.receive(id, socket) + } + Function("send") { (id: String, text: String) in + guard self.valid(text), let socket = self.socket(id) else { + throw NSError(domain: "channel-frame-invalid", code: 1) + } + self.lock.lock() + let size = (self.queued[id] ?? 0) + text.utf8.count + if size > 20 * 1024 * 1024 { + self.lock.unlock() + self.finish(id, "channel-busy") + throw NSError(domain: "channel-busy", code: 1) + } + self.queued[id] = size + self.lock.unlock() + socket.send(.string(text)) { error in + self.lock.lock() + if let pending = self.queued[id] { self.queued[id] = pending - text.utf8.count } + self.lock.unlock() + if error != nil { self.finish(id, "channel-send-failed") } + } + } + Function("close") { (id: String) in self.finish(id, "channel-disconnected") } + OnDestroy { + self.lock.lock() + let ids = Array(self.channels.keys) + self.lock.unlock() + ids.forEach { self.finish($0, "channel-disconnected") } + self.session.invalidateAndCancel() + } + } + + private func socket(_ id: String) -> URLSessionWebSocketTask? { + lock.lock() + defer { lock.unlock() } + return channels[id] + } + private func valid(_ text: String) -> Bool { + let bytes = text.utf8 + return (3...70_000).contains(bytes.count) && bytes.count % 2 == 1 && + (bytes.first == 104 || bytes.first == 100) && + bytes.dropFirst().allSatisfy { (48...57).contains($0) || (97...102).contains($0) } + } + private func receive(_ id: String, _ socket: URLSessionWebSocketTask) { + socket.receive { result in + guard self.socket(id) === socket else { return } + switch result { + case .success(.string(let text)) where self.valid(text): + self.emit(id, "message", text) + self.receive(id, socket) + default: self.finish(id, "lan-unreachable") + } + } + } + private func emit(_ id: String, _ type: String, _ text: String = "") { + sendEvent("channel", ["id": id, "type": type, "text": text]) + } + private func finish(_ id: String, _ reason: String) { + lock.lock() + let socket = channels.removeValue(forKey: id) + queued.removeValue(forKey: id) + lock.unlock() + guard let socket else { return } + socket.cancel(with: .goingAway, reason: nil) + emit(id, "closed", reason) + } +} diff --git a/apps/mobile/package.json b/apps/mobile/package.json index fcaeda6d23..137b23c2bf 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -73,7 +73,7 @@ "@bacons/apple-targets": "5.0.0", "@deepseek-ai/dsh-api-gateway": "0.2.1-rc.2", "@types/react": "~19.3.0", - "@types/react-dom": "~19.2.7", + "@types/react-dom": "~19.3.0", "expo-doctor": "1.21.4" }, "enriched-markdown": { diff --git a/apps/mobile/src/host/client.ts b/apps/mobile/src/host/client.ts index d2446df800..13f613dcd8 100644 --- a/apps/mobile/src/host/client.ts +++ b/apps/mobile/src/host/client.ts @@ -5,7 +5,7 @@ import { ActivitySmoother } from '../../../../packages/client/src/client/activit import type { BotPrimaryColor } from '../../../../packages/core/src/bots/primary-color'; import type { HostCarrier, HostSocket } from './carrier'; import { DEVICE_PREFIX } from './pairing'; -import { checkRoute, isConnectRoute, socketOrigin } from './route'; +import { checkRoute, isConnectRoute, isEncryptedRoute, socketOrigin } from './route'; import { secretRouteRefusal } from '../../../../packages/core/src/bridge/secret-route'; import { REMOTE_STREAM_MUX_PATH, @@ -355,8 +355,8 @@ export function createHostClient(options: HostClientOptions): HostClient { ...(bot.primaryColor === undefined ? {} : { primaryColor: bot.primaryColor }), roles: bot.roles ?? [], ...(bot.description === undefined ? {} : { description: bot.description }), - computerAccess: bot.computerAccess === true && !isConnectRoute(route), - browserAccess: bot.browserAccess === true && !isConnectRoute(route), + computerAccess: bot.computerAccess === true && !isEncryptedRoute(route), + browserAccess: bot.browserAccess === true && !isEncryptedRoute(route), state: live?.state ?? bot.aggregateState, ...(live?.activity === undefined ? {} : { activity: live.activity }), ...(live?.sessions === undefined ? {} : { sessions: live.sessions }), @@ -375,7 +375,7 @@ export function createHostClient(options: HostClientOptions): HostClient { path.startsWith('/') ? `${route}${DEVICE_PREFIX}${path}` : path; const resource = (path: string): RemoteSource => { - if (checkRoute(route).ok && !isConnectRoute(route)) + if (checkRoute(route).ok && !isEncryptedRoute(route)) return { uri: absolute(path), headers: authorization }; const origin = route; return { @@ -398,7 +398,8 @@ export function createHostClient(options: HostClientOptions): HostClient { }; const avatar = (path: string): { avatarUrl?: string; avatarHeaders?: Record } => { if (!checkRoute(route).ok) return {}; - if (!isConnectRoute(route)) return { avatarUrl: absolute(path), avatarHeaders: authorization }; + if (!isEncryptedRoute(route)) + return { avatarUrl: absolute(path), avatarHeaders: authorization }; const key = route + path; const cached = avatars.get(key); if (cached) return { avatarUrl: cached, avatarHeaders: {} }; @@ -472,7 +473,7 @@ export function createHostClient(options: HostClientOptions): HostClient { withDeadline(async (signal) => { const name = method.includes('/') ? method : `botharness/${method}`; const refusal = - isConnectRoute(via) && options.encryption === undefined + isEncryptedRoute(via) && options.encryption === undefined ? secretRouteRefusal(name) : undefined; if (refusal !== undefined) throw new MethodRefused(refusal.code, refusal.message); @@ -541,7 +542,7 @@ export function createHostClient(options: HostClientOptions): HostClient { const api = (path: string, init: HostApiInit = {}): Promise => withDeadline(async (signal) => { - if (isConnectRoute(route) && /^\/api\/(?:browser|computer)\//u.test(path)) + if (isEncryptedRoute(route) && /^\/api\/(?:browser|computer)\//u.test(path)) throw new MethodRefused( 'connect-viewer-unavailable', 'Use the Host or Tailscale for Browser and Computer viewers.', @@ -669,6 +670,7 @@ export function createHostClient(options: HostClientOptions): HostClient { } catch (error) { if ( isConnectRoute(candidate) || + error instanceof ConnectRefused || error instanceof CredentialRefused || error instanceof MethodRefused ) @@ -927,7 +929,7 @@ export function createHostClient(options: HostClientOptions): HostClient { upload, resource, secretInputAllowed: () => - checkRoute(route).ok && (!isConnectRoute(route) || options.encryption !== undefined), + checkRoute(route).ok && (!isEncryptedRoute(route) || options.encryption !== undefined), onLive(listener) { liveListeners.add(listener); return () => liveListeners.delete(listener); diff --git a/apps/mobile/src/host/encrypted-carrier.ts b/apps/mobile/src/host/encrypted-carrier.ts index a3592cdd03..aee45b5a2c 100644 --- a/apps/mobile/src/host/encrypted-carrier.ts +++ b/apps/mobile/src/host/encrypted-carrier.ts @@ -4,7 +4,7 @@ import { } from '../../../../packages/core/src/devices/noise/channel'; import type { HostCarrier, HostResponse, HostSocket, HostSocketEvents } from './carrier'; import type { HostEncryption } from './hosts'; -import { checkRoute, isConnectRoute, socketOrigin } from './route'; +import { checkRoute, isEncryptedRoute, isLanRoute, socketOrigin } from './route'; export class ConnectRefused extends Error { constructor(readonly code: string) { @@ -85,6 +85,7 @@ export function openNoiseSocket(options: { hostId: string; encryption: HostEncryption; raw: HostCarrier; + timeoutMs?: number; message(value: Record): void; closed(reason: string): void; }) { @@ -95,6 +96,7 @@ export function openNoiseSocket(options: { hostKey: keyBytes(options.encryption.hostKey), staticKey: keyBytes(options.encryption.deviceKey), ephemeralKey: secureRandom(options.raw), + route: isLanRoute(options.origin) ? 'lan' : 'connect', }); let done = false; let nextCredit = 0, @@ -116,42 +118,49 @@ export function openNoiseSocket(options: { reject(new Error(reason)); options.closed(reason); }; - const timer = setTimeout(() => fail('channel-timeout'), 10_000); - const socket = options.raw.openSocket(`${socketOrigin(options.origin)}${CONNECT_CHANNEL_PATH}`, { - open: () => { - try { - socket.send(channel.start()); - } catch { - fail('channel-handshake-failed'); - } - }, - message: (wire) => { - try { - const result = channel.receive(wire); - if (result.reply) socket.send(result.reply); - if (result.ready) { - clearTimeout(timer); - resolve(); + const timer = setTimeout(() => fail('channel-timeout'), options.timeoutMs ?? 10_000); + let socket: HostSocket; + try { + socket = options.raw.openSocket(`${socketOrigin(options.origin)}${CONNECT_CHANNEL_PATH}`, { + open: () => { + try { + socket.send(channel.start()); + } catch { + fail('channel-handshake-failed'); } - if (result.message !== undefined) { - const value: unknown = JSON.parse(result.message); - if (!value || typeof value !== 'object' || Array.isArray(value)) - throw new Error('channel-message-invalid'); - const message = value as Record; - if (message['type'] === 'ack') { - const credit = message['credit']; - const bytes = typeof credit === 'number' ? credits.get(credit) : undefined; - if (bytes === undefined) throw new Error('channel-credit-invalid'); - credits.delete(credit as number); - outstandingBytes -= bytes; - } else options.message(message); + }, + message: (wire) => { + try { + const result = channel.receive(wire); + if (result.reply) socket.send(result.reply); + if (result.ready) { + clearTimeout(timer); + resolve(); + } + if (result.message !== undefined) { + const value: unknown = JSON.parse(result.message); + if (!value || typeof value !== 'object' || Array.isArray(value)) + throw new Error('channel-message-invalid'); + const message = value as Record; + if (message['type'] === 'ack') { + const credit = message['credit']; + const bytes = typeof credit === 'number' ? credits.get(credit) : undefined; + if (bytes === undefined) throw new Error('channel-credit-invalid'); + credits.delete(credit as number); + outstandingBytes -= bytes; + } else options.message(message); + } + } catch { + fail('channel-authentication-failed'); } - } catch { - fail('channel-authentication-failed'); - } - }, - closed: (reason) => fail(reason || 'channel-disconnected'), - }); + }, + closed: (reason) => fail(reason || 'channel-disconnected'), + }); + } catch (error) { + clearTimeout(timer); + channel.close(); + throw error; + } return { ready, send(value: unknown): void { @@ -308,7 +317,7 @@ export function encryptedCarrier(options: { }, async request(url, init) { const parsed = requestUrl(url); - if (!isConnectRoute(parsed.origin)) return options.raw.request(url, init); + if (!isEncryptedRoute(parsed.origin)) return options.raw.request(url, init); if (init.signal.aborted) throw new Error('request-cancelled'); const current = session(parsed.origin); await current.ready; @@ -372,7 +381,7 @@ export function encryptedCarrier(options: { }, openSocket(url, events, headers): HostSocket { const parsed = requestUrl(url.replace(/^ws/u, 'http')); - if (!isConnectRoute(parsed.origin)) return options.raw.openSocket(url, events, headers); + if (!isEncryptedRoute(parsed.origin)) return options.raw.openSocket(url, events, headers); let current: Session | undefined, done = false; const id = String(++next); diff --git a/apps/mobile/src/host/native-carrier.ts b/apps/mobile/src/host/native-carrier.ts index 548abd24fa..d688efa7d4 100644 --- a/apps/mobile/src/host/native-carrier.ts +++ b/apps/mobile/src/host/native-carrier.ts @@ -1,5 +1,7 @@ import { getRandomBytes } from 'expo-crypto'; import type { HostCarrier } from './carrier'; +import { isLanRoute } from './route'; +import { openLanSocket } from './native-lan-socket'; type NativeWebSocket = new ( url: string, @@ -11,6 +13,7 @@ export function nativeCarrier(): HostCarrier { return { randomBytes: () => getRandomBytes(32), async request(url, init) { + if (isLanRoute(new URL(url).origin)) throw new Error('encrypted-channel-required'); const response = await fetch(url, { method: init.method, signal: init.signal, @@ -29,6 +32,10 @@ export function nativeCarrier(): HostCarrier { }; }, openSocket(url, events, headers = {}) { + if (isLanRoute(url.replace(/^ws:/u, 'http:'))) { + if (Object.keys(headers).length > 0) throw new Error('encrypted-channel-required'); + return openLanSocket(url, events); + } const socket = new (WebSocket as unknown as NativeWebSocket)(url, undefined, { headers }); let done = false; const closed = (reason: string): void => { diff --git a/apps/mobile/src/host/native-lan-socket.ts b/apps/mobile/src/host/native-lan-socket.ts new file mode 100644 index 0000000000..daae36bebc --- /dev/null +++ b/apps/mobile/src/host/native-lan-socket.ts @@ -0,0 +1,50 @@ +import { requireOptionalNativeModule } from 'expo'; +import type { HostSocket, HostSocketEvents } from './carrier'; +import { isLanRoute } from './route'; + +interface LanModule { + open(id: string, address: string, port: number): void; + send(id: string, text: string): void; + close(id: string): void; + addListener( + name: 'channel', + listener: (event: { id: string; type: string; text: string }) => void, + ): { remove(): void }; +} +let sequence = 0; +export function openLanSocket(url: string, events: HostSocketEvents): HostSocket { + const parsed = new URL(url.replace(/^ws:/u, 'http:')); + if ( + !isLanRoute(parsed.origin) || + parsed.pathname !== '/botharness-device/channel' || + parsed.username || + parsed.password || + parsed.search || + parsed.hash + ) + throw new Error('lan-route-invalid'); + const native = requireOptionalNativeModule('LanChannel'); + if (!native) throw new Error('lan-build-required'); + const id = `lan-${++sequence}`; + let done = false; + const finish = (reason: string) => { + if (done) return; + done = true; + subscription.remove(); + native.close(id); + events.closed(reason); + }; + const subscription = native.addListener('channel', (event) => { + if (event.id !== id || done) return; + if (event.type === 'open') events.open(); + else if (event.type === 'message') events.message(event.text); + else if (event.type === 'closed') finish(event.text); + }); + try { + native.open(id, parsed.hostname, Number(parsed.port)); + } catch (error) { + subscription.remove(); + throw error; + } + return { send: (text) => native.send(id, text), close: () => finish('channel-disconnected') }; +} diff --git a/apps/mobile/src/host/pairing.ts b/apps/mobile/src/host/pairing.ts index 4d7c4dd7ef..6cb121af65 100644 --- a/apps/mobile/src/host/pairing.ts +++ b/apps/mobile/src/host/pairing.ts @@ -7,7 +7,7 @@ import { openNoiseSocket, secureRandom, } from './encrypted-carrier'; -import { isConnectRoute } from './route'; +import { isConnectRoute, isEncryptedRoute, isLanRoute } from './route'; import type { HostEncryption } from './hosts'; import type { HostCarrier } from './carrier'; import { checkRoute } from './route'; @@ -27,6 +27,8 @@ export interface PairingPayload { } export type PairingRefusal = + | 'lan-build-required' + | 'lan-unreachable' | 'already-paired' | 'host-key-required' | 'host-key-confirmation-required' @@ -127,7 +129,7 @@ export async function redeemPairing(options: { return { ok: false, code: 'no-route' }; if (payload.encryption !== undefined) return redeemEncrypted(options); for (const route of payload.routes) { - if (isConnectRoute(route)) return { ok: false, code: 'host-key-required' }; + if (isEncryptedRoute(route)) return { ok: false, code: 'host-key-required' }; let status: number; let body: Record; const controller = new AbortController(); @@ -295,9 +297,11 @@ export async function pairHost(options: { deviceName: options.deviceName, carrier: options.carrier, ...(options.onPending === undefined ? {} : { onPending: options.onPending }), - ...(options.confirmFingerprint === undefined - ? {} - : { confirmFingerprint: options.confirmFingerprint }), + ...(options.method === 'qr' + ? { confirmFingerprint: async () => true } + : options.confirmFingerprint === undefined + ? {} + : { confirmFingerprint: options.confirmFingerprint }), ...(options.signal === undefined ? {} : { signal: options.signal }), }); if (options.signal?.aborted) return { ok: false, code: 'cancelled' }; @@ -313,9 +317,13 @@ export async function pairHost(options: { } observation.finish('success'); return { ok: true }; - } catch { - observation.finish('failed', 'unknown'); - return { ok: false, code: 'unknown' }; + } catch (error) { + const code = + error instanceof Error && error.message === 'lan-build-required' + ? 'lan-build-required' + : 'unknown'; + observation.finish('failed', code); + return { ok: false, code }; } finally { options.signal?.removeEventListener('abort', cancelled); } @@ -344,8 +352,31 @@ async function redeemEncrypted(options: { hostKey: advertised.publicKey, deviceKey: keyHex(secureRandom(options.carrier)), }; - const route = payload.routes.find(isConnectRoute) ?? payload.routes[0]!; + const lan = payload.routes.filter(isLanRoute); + const remote = payload.routes.filter((route) => !isLanRoute(route)); + const preferred = remote.find(isConnectRoute) ?? remote[0]; + const routes = [ + ...lan, + ...(preferred ? [preferred] : []), + ...remote.filter((route) => route !== preferred), + ]; + let result: Redemption = { ok: false, code: 'no-route' }; + for (const route of routes) { + if (options.signal?.aborted) return { ok: false, code: 'unreachable' }; + result = await redeemEncryptedRoute(options, encryption, route); + if (result.ok || result.code !== 'lan-unreachable') return result; + } + return result; +} + +function redeemEncryptedRoute( + options: Parameters[0], + encryption: HostEncryption, + route: string, +): Promise { + const { payload } = options; return new Promise((resolve) => { + let authenticated = false; let done = false, poll: ReturnType | undefined; const finish = (result: Redemption) => { @@ -363,7 +394,22 @@ async function redeemEncrypted(options: { hostId: payload.host.id, encryption, raw: options.carrier, - closed: () => finish({ ok: false, code: 'channel-authentication-failed' }), + timeoutMs: isLanRoute(route) ? 2000 : 10_000, + closed: (reason) => + finish({ + ok: false, + code: + isLanRoute(route) && + !authenticated && + [ + 'lan-unreachable', + 'channel-timeout', + 'channel-send-failed', + 'channel-disconnected', + ].includes(reason) + ? 'lan-unreachable' + : 'channel-authentication-failed', + }), message: (value) => { if (value['type'] === 'pair-pending') { options.onPending?.(noiseFingerprint(noisePublicKey(keyBytes(encryption.deviceKey)))); @@ -413,8 +459,12 @@ async function redeemEncrypted(options: { Math.max(1, Math.min(600_000, Date.parse(payload.expiresAt) - Date.now())), ); options.signal?.addEventListener('abort', abort, { once: true }); - void socket.ready.then(submit, () => - finish({ ok: false, code: 'channel-authentication-failed' }), + void socket.ready.then( + () => { + authenticated = true; + submit(); + }, + () => finish({ ok: false, code: 'channel-authentication-failed' }), ); }); } diff --git a/apps/mobile/src/host/route.ts b/apps/mobile/src/host/route.ts index 94b26b807f..2db806a31e 100644 --- a/apps/mobile/src/host/route.ts +++ b/apps/mobile/src/host/route.ts @@ -1,3 +1,4 @@ +import { isLanAddress } from '../../../../packages/core/src/devices/lan-address'; export type RouteCheck = { ok: true; origin: string } | { ok: false; reason: string }; export function checkRoute(input: string): RouteCheck { @@ -16,6 +17,7 @@ export function checkRoute(input: string): RouteCheck { name.endsWith('.ts.net') || /^100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d+\.\d+$/u.test(name); const connect = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.deepseekbot\.dev$/u.test(name); const allowed = + (isLanAddress(name) && url.protocol === 'http:' && url.port !== '') || (loopback && (url.protocol === 'http:' || url.protocol === 'https:')) || ((tailnet || (connect && url.port === '')) && url.protocol === 'https:'); if ( @@ -47,3 +49,16 @@ export function isConnectRoute(route: string): boolean { return false; } } + +export function isLanRoute(route: string): boolean { + try { + const url = new URL(route); + return url.protocol === 'http:' && isLanAddress(url.hostname) && url.port !== ''; + } catch { + return false; + } +} + +export function isEncryptedRoute(route: string): boolean { + return isConnectRoute(route) || isLanRoute(route); +} diff --git a/apps/mobile/src/telemetry/schema.ts b/apps/mobile/src/telemetry/schema.ts index d695b11567..f6c80d9157 100644 --- a/apps/mobile/src/telemetry/schema.ts +++ b/apps/mobile/src/telemetry/schema.ts @@ -3,6 +3,8 @@ import { isDeviceYearClass, isPublicModelId, type DeviceTelemetryContext } from export type PairingMethod = 'qr' | 'paste' | 'deep_link' | 'account'; export type PairingOutcome = 'success' | 'refused' | 'failed' | 'cancelled'; export type PairingReason = + | 'lan-build-required' + | 'lan-unreachable' | 'already-paired' | 'none' | 'host-key-required' @@ -114,6 +116,8 @@ const fields: Record b attempt_id: isUuid, outcome: member('success', 'refused', 'failed', 'cancelled'), reason: member( + 'lan-build-required', + 'lan-unreachable', 'none', 'host-key-required', 'host-key-confirmation-required', diff --git a/apps/mobile/src/ui/strings.ts b/apps/mobile/src/ui/strings.ts index 84895b0601..287425acd1 100644 --- a/apps/mobile/src/ui/strings.ts +++ b/apps/mobile/src/ui/strings.ts @@ -460,7 +460,7 @@ const en = { title: 'Before you pair', steps: [ 'On your computer, install DeepSeek Harness (DSH) and the DeepSeekBot plugin.', - 'Choose how they connect: sign in to the same DeepSeekBot account on both (no Tailscale needed; on the computer, Settings → Devices → DeepSeekBot Connect), or install Tailscale on both and sign in to the same Tailscale account.', + 'On the same Wi-Fi, enable local access in the computer’s Settings → Devices. For remote access, use a DeepSeekBot account or Tailscale.', 'Pair: pick the computer under your DeepSeekBot account, or show the pairing code on the computer and scan it here.', ], open: 'Open the setup guide', @@ -505,6 +505,10 @@ const en = { accountDetail: 'Pair the computers on your account. No Tailscale needed.', accountComputer: 'On your computer, open DeepSeekBot Settings → Devices → DeepSeekBot Connect and sign in to the same account.', + lan: 'Use the same Wi-Fi', + lanDetail: 'Scan your computer’s code. No account needed.', + lanHint: + 'Join the same network. On your computer, open Settings → Devices, enable local access, then scan its pairing code. Approve this phone on the computer.', tailscale: 'Use Tailscale', tailscaleDetail: 'Scan the pairing code or paste a pairing link.', tailscaleHint: @@ -514,6 +518,9 @@ const en = { emptyAction: 'Pair a computer', }, pairRefused: { + 'lan-build-required': 'Update the phone app to use local access.', + 'lan-unreachable': + 'Check that both devices use the same network, allow Local Network access, and enable local access on your computer.', 'already-paired': 'This computer is already added.', 'host-key-required': 'Pair again using a new code from your computer.', 'host-key-confirmation-required': 'Compare the fingerprint on your computer before pairing.', @@ -523,7 +530,7 @@ const en = { 'link-invalid': 'This is not a DeepSeekBot pairing code.', 'link-expired': 'This code has expired. Show a new code on your computer.', 'no-route': - 'Your computer offered no address this phone can use. Set up Tailscale on it first.', + 'Enable local access on your computer, or set up Tailscale or Connect, then get a new code.', 'offer-invalid': 'This code was already used. Show a new code on your computer.', 'offer-expired': 'This code has expired. Show a new code on your computer.', 'storage-failure': 'Could not save the pairing on this phone. Show a new code and try again.', @@ -1759,7 +1766,7 @@ const zh: typeof en = { title: '配对前的准备', steps: [ '在电脑上安装 DSH(DeepSeek Harness)和 DeepSeekBot 插件。', - '选一种连接方式:在手机和电脑上登录同一个 DeepSeekBot 账号(不需要 Tailscale;电脑上在设置 → 设备 → DeepSeekBot Connect 登录),或者都安装 Tailscale 并登录同一个 Tailscale 账号。', + '使用同一 Wi-Fi 时,在电脑的设置 → 设备中开启局域网连接。远程连接可选 DeepSeekBot 账号或 Tailscale。', '配对:在 DeepSeekBot 账号里选择这台电脑,或者在电脑上显示配对二维码,然后在这里扫码。', ], open: '查看安装与配对教程', @@ -1802,6 +1809,10 @@ const zh: typeof en = { account: '登录 DeepSeekBot 账号', accountDetail: '直接配对账号下的电脑,不用 Tailscale。', accountComputer: '在电脑上打开 DeepSeekBot 设置 → 设备 → DeepSeekBot Connect,登录同一个账号。', + lan: '使用同一 Wi-Fi', + lanDetail: '扫描电脑上的二维码,不需要账号。', + lanHint: + '手机和电脑连到同一网络。在电脑的设置 → 设备中开启局域网连接,扫码后在电脑上批准这台手机。', tailscale: '使用 Tailscale', tailscaleDetail: '扫描配对二维码,或粘贴配对链接。', tailscaleHint: '在手机和电脑上都安装 Tailscale,并登录同一个 Tailscale 账号。', @@ -1810,6 +1821,8 @@ const zh: typeof en = { emptyAction: '配对电脑', }, pairRefused: { + 'lan-build-required': '请更新手机 App 后再使用局域网连接。', + 'lan-unreachable': '请确认手机和电脑在同一网络,允许本地网络权限,并在电脑上开启局域网连接。', 'already-paired': '这台电脑已添加。', 'host-key-required': '请使用电脑上的新二维码重新配对。', 'host-key-confirmation-required': '请先核对电脑上的指纹,再继续配对。', @@ -1817,7 +1830,7 @@ const zh: typeof en = { 'link-invalid': '这不是 DeepSeekBot 的配对二维码。', 'link-expired': '二维码已失效,请在电脑上换一个。', - 'no-route': '电脑没有提供手机能用的地址,请先在电脑上设置 Tailscale。', + 'no-route': '请在电脑上开启局域网连接,或设置 Tailscale、Connect,然后获取新二维码。', 'offer-invalid': '这个二维码已经用过了,请在电脑上换一个。', 'offer-expired': '二维码已失效,请在电脑上换一个。', 'storage-failure': '无法在手机上保存配对,请在电脑上换一个二维码后重试。', diff --git a/apps/mobile/test/encrypted-carrier.test.ts b/apps/mobile/test/encrypted-carrier.test.ts index 3a9e9c5dc4..322df97602 100644 --- a/apps/mobile/test/encrypted-carrier.test.ts +++ b/apps/mobile/test/encrypted-carrier.test.ts @@ -5,25 +5,28 @@ import { decideApproval } from '../src/host/requests'; import { redeemPairing } from '../src/host/pairing'; import { encryptedCarrier } from '../src/host/encrypted-carrier'; -it('refuses a legacy Connect pairing before any credential reaches the raw carrier', async () => { - const request = vi.fn(), - openSocket = vi.fn(); - const carrier = encryptedCarrier({ - raw: { request, openSocket }, - hostId: 'host', - credential: 'private-credential', - }); - await expect( - carrier.request('https://host.deepseekbot.dev/botharness-device/api/botharness/list', { - method: 'POST', - signal: new AbortController().signal, - headers: { authorization: 'Device private-credential' }, - body: '{}', - }), - ).rejects.toThrow('host-key-required'); - expect(request).not.toHaveBeenCalled(); - expect(openSocket).not.toHaveBeenCalled(); -}); +it.each(['https://host.deepseekbot.dev', 'http://192.168.1.20:39101'])( + 'refuses a legacy pairing at %s before any credential reaches the raw carrier', + async (origin) => { + const request = vi.fn(), + openSocket = vi.fn(); + const carrier = encryptedCarrier({ + raw: { request, openSocket }, + hostId: 'host', + credential: 'private-credential', + }); + await expect( + carrier.request(`${origin}/botharness-device/api/botharness/list`, { + method: 'POST', + signal: new AbortController().signal, + headers: { authorization: 'Device private-credential' }, + body: '{}', + }), + ).rejects.toThrow('host-key-required'); + expect(request).not.toHaveBeenCalled(); + expect(openSocket).not.toHaveBeenCalled(); + }, +); import { parseSavedHost, withHost } from '../src/host/hosts'; it('persists the complete trust record and refuses a silent pin change or removal', () => { diff --git a/apps/mobile/test/host-client.test.ts b/apps/mobile/test/host-client.test.ts index 25da540ac1..89bae578c7 100644 --- a/apps/mobile/test/host-client.test.ts +++ b/apps/mobile/test/host-client.test.ts @@ -50,6 +50,41 @@ async function until( } describe('Host client', () => { + it.each(['lan-unreachable', 'channel-authentication-failed'])( + 'falls through an unavailable LAN route but stops on a Host key refusal: %s', + async (reason) => { + const host = new FakeHost(); + client = createHostClient({ + routes: ['http://192.168.1.20:4567', ROUTE], + hostId: 'test-host', + encryption: { + protocol: 'connect-noise-xk-v1', + hostKey: '11'.repeat(32), + deviceKey: '22'.repeat(32), + }, + credential: host.credential, + carrier: { + ...host.carrier, + openSocket: (url, events, headers) => { + if (!url.startsWith('ws://192.168.1.20:4567/')) + return host.carrier.openSocket(url, events, headers); + queueMicrotask(() => events.closed(reason)); + return { send: () => {}, close: () => {} }; + }, + }, + backoff: () => 5, + }); + client.start(); + const state = await until( + client, + (snapshot) => + snapshot.connection.status === + (reason === 'lan-unreachable' ? 'connected' : 'unreachable'), + ); + if (reason === 'lan-unreachable') expect(state.connection).toMatchObject({ route: ROUTE }); + else expect(host.requests).toEqual([]); + }, + ); it('retains Bot DM metadata for activity links without listing it as a group', async () => { const host = new FakeHost(); host.methods.set('channels', () => ({ channels: wire.activityJournal.channels })); @@ -295,7 +330,7 @@ describe('pairing', () => { ok: false, code: 'link-expired', }); - expect(parsePairingLink(link({ ...payload, routes: ['http://10.0.0.2:3000'] }))).toEqual({ + expect(parsePairingLink(link({ ...payload, routes: ['http://8.8.8.8:3000'] }))).toEqual({ ok: false, code: 'no-route', }); diff --git a/apps/mobile/test/localization.test.ts b/apps/mobile/test/localization.test.ts index b7a719c796..ca0916c60d 100644 --- a/apps/mobile/test/localization.test.ts +++ b/apps/mobile/test/localization.test.ts @@ -22,7 +22,9 @@ describe('system language', () => { photosPermission: 'NSPhotoLibraryUsageDescription', speechRecognitionPermission: 'NSSpeechRecognitionUsageDescription', }; - const declared = new Set(); + const declared = new Set( + Object.keys(expo.ios.infoPlist).filter((key) => /^NS.*UsageDescription$/u.test(key)), + ); for (const plugin of expo.plugins) { if (!Array.isArray(plugin)) continue; for (const option of Object.keys(plugin[1])) { diff --git a/apps/mobile/test/native-lan-socket.test.ts b/apps/mobile/test/native-lan-socket.test.ts new file mode 100644 index 0000000000..bb61813df4 --- /dev/null +++ b/apps/mobile/test/native-lan-socket.test.ts @@ -0,0 +1,58 @@ +import { afterEach, expect, it, vi } from 'vitest'; +const state = vi.hoisted(() => ({ + available: true, + listener: undefined as ((value: { id: string; type: string; text: string }) => void) | undefined, + open: vi.fn(), + send: vi.fn(), + close: vi.fn(), + remove: vi.fn(), +})); +vi.mock('expo', () => ({ + requireOptionalNativeModule: () => + state.available + ? { + open: state.open, + send: state.send, + close: state.close, + addListener: (_name: string, listener: typeof state.listener) => { + state.listener = listener; + return { remove: state.remove }; + }, + } + : null, +})); +import { openLanSocket } from '../src/host/native-lan-socket'; +afterEach(() => { + vi.clearAllMocks(); + state.available = true; +}); +it('keeps each native channel scoped and removes its event subscription on close', () => { + const events = { open: vi.fn(), message: vi.fn(), closed: vi.fn() }; + const socket = openLanSocket('ws://192.168.1.20:39101/botharness-device/channel', events); + const id = state.open.mock.calls[0]![0] as string; + expect(state.open).toHaveBeenCalledWith(id, '192.168.1.20', 39101); + state.listener!({ id: 'other', type: 'message', text: 'ignored' }); + expect(events.message).not.toHaveBeenCalled(); + state.listener!({ id, type: 'open', text: '' }); + expect(events.open).toHaveBeenCalledOnce(); + socket.send('h00'); + expect(state.send).toHaveBeenCalledWith(id, 'h00'); + socket.close(); + socket.close(); + expect(state.remove).toHaveBeenCalledOnce(); + expect(state.close).toHaveBeenCalledOnce(); +}); +it('refuses public addresses, other paths and stale native builds', () => { + const events = { open: vi.fn(), message: vi.fn(), closed: vi.fn() }; + for (const url of [ + 'ws://8.8.8.8:90/botharness-device/channel', + 'ws://192.168.1.1:90/api', + 'ws://192.168.1.1:90/botharness-device/channel?token=x', + ]) + expect(() => openLanSocket(url, events)).toThrow('lan-route-invalid'); + state.available = false; + expect(() => openLanSocket('ws://192.168.1.20:39101/botharness-device/channel', events)).toThrow( + 'lan-build-required', + ); + expect(state.open).not.toHaveBeenCalled(); +}); diff --git a/apps/mobile/test/pair-choice.test.tsx b/apps/mobile/test/pair-choice.test.tsx index ab6b632254..48d209f2bc 100644 --- a/apps/mobile/test/pair-choice.test.tsx +++ b/apps/mobile/test/pair-choice.test.tsx @@ -41,12 +41,20 @@ async function render(): Promise { return host; } -it('offers account sign-in and Tailscale as separate ways to pair', async () => { +it('offers LAN, account sign-in and Tailscale through the existing pairing flow', async () => { const view = await render(); expect(view.textContent).toContain(t.pairChoice.account); expect(view.textContent).toContain(t.pairChoice.tailscale); expect(view.textContent).not.toContain(t.cloud.title); - expect(view.textContent).not.toContain(t.pasteLink); + expect(view.querySelector('input')).toBeNull(); + expect(view.textContent).toContain(t.pairChoice.lan); + await act(async () => + view.querySelector('[data-testid="pair-choice-lan"]')!.click(), + ); + expect(router.push).toHaveBeenLastCalledWith({ + pathname: '/pair/tailscale', + params: { mode: 'lan' }, + }); await act(async () => view.querySelector('[data-testid="pair-choice-account"]')!.click(), diff --git a/apps/mobile/with-lan-channel.js b/apps/mobile/with-lan-channel.js new file mode 100644 index 0000000000..6ca92b1380 --- /dev/null +++ b/apps/mobile/with-lan-channel.js @@ -0,0 +1,33 @@ +const { withAndroidManifest, withDangerousMod } = require('expo/config-plugins'); +const { mkdir, writeFile } = require('node:fs/promises'); +const path = require('node:path'); + +module.exports = (config) => { + config = withAndroidManifest(config, (mod) => { + const application = mod.modResults.manifest.application[0]; + application.$['android:networkSecurityConfig'] = '@xml/lan_channel_security'; + return mod; + }); + return withDangerousMod(config, [ + 'android', + async (mod) => { + const directory = path.join(mod.modRequest.platformProjectRoot, 'app/src/main/res/xml'); + await mkdir(directory, { recursive: true }); + await writeFile( + path.join(directory, 'lan_channel_security.xml'), + ` + + + + encrypted-lan.invalid + localhost + 127.0.0.1 + 10.0.2.2 + + +`, + ); + return mod; + }, + ]); +}; diff --git a/changes/2599-encrypted-lan.md b/changes/2599-encrypted-lan.md new file mode 100644 index 0000000000..58e8eb00cf --- /dev/null +++ b/changes/2599-encrypted-lan.md @@ -0,0 +1,11 @@ +--- +section: Added +--- + +## en + +- Added opt-in encrypted local-network phone pairing through the existing Devices controls and CLI, with computer approval and immediate device revocation ([#2599](https://github.com/BotHarness/DeepSeekBot/issues/2599)). + +## zh + +- 设备页和 CLI 新增默认关闭的加密局域网手机配对,手机经电脑批准后访问,撤销立即生效([#2599](https://github.com/BotHarness/DeepSeekBot/issues/2599))。 diff --git a/docs/adr/0244-connect-encrypts-device-traffic-against-pinned-host-keys.md b/docs/adr/0244-connect-encrypts-device-traffic-against-pinned-host-keys.md index 0be22fe446..dee65a4624 100644 --- a/docs/adr/0244-connect-encrypts-device-traffic-against-pinned-host-keys.md +++ b/docs/adr/0244-connect-encrypts-device-traffic-against-pinned-host-keys.md @@ -7,6 +7,10 @@ Amends: ADR-0241 and ADR-0242 # Connect encrypts device traffic against pinned Host keys +## LAN extension — 2026-10-23 + +The accepted [#2598](https://github.com/BotHarness/DeepSeekBot/issues/2598) design reuses this authority and Noise profile for opt-in LAN phone access. A trusted computer QR scanned in the installed app supplies the Host pin; pasted and external links retain independent comparison. Exact phone-key approval still occurs on the Host. LAN binds the final prologue field to `lan`; Connect stays `connect`. This restricted adapter refines ADR-0199's same-listener choice without moving DSH's operator listener off loopback. See [the LAN contract](../architecture/lan-phone-v1.md) for lifecycle, native policy and qualification limits. + Reported by Vain. On 2026-10-21 Vain rejected Cloudflare's ability to read Connect traffic. Connect has not shipped, so its protocol and pairing experience can change. Vain approved this ADR and its stacked implementation above Track A PR #2546 on 2026-10-22. It replaces ADR-0241's plaintext application channel; acceptance of this design is not evidence of runtime or native qualification. ADR-0199 remains the device-authority owner, ADR-0242 remains the browser pairing owner, and ADR-0243 remains the Host Feed contract. ## Decisions confirmed by Vain on 2026-10-22 diff --git a/docs/agents/development-scripts.md b/docs/agents/development-scripts.md index a9f549f8f0..653ba2c72f 100644 --- a/docs/agents/development-scripts.md +++ b/docs/agents/development-scripts.md @@ -85,6 +85,7 @@ Run `node scripts/ci-plan.mjs --base origin/main` to print the plan and the exac | `apps/mobile/modules/**` | No tests of its own | | Local Expo modules, checked by Android native unit tests | | `apps/mobile/targets/**` | No tests of its own | | Apple extension targets, built on a Mac by Expo prebuild | | `apps/mobile/{app.json,app.config.js,eas.json,metro.config.js}` | Related tests | | Mobile app config | +| `apps/mobile/with-*.js` | Related tests | | Mobile native config plugins | | `apps/mobile/locales/**` | Related tests | | Translated iOS permission prompts | | `apps/mobile/assets/**` | Related tests | | Mobile app icons and bundled images | | `apps/mobile/.maestro/**` | No tests of its own | | Maestro flows, run on a Mac simulator | diff --git a/docs/architecture/botharness-architecture.md b/docs/architecture/botharness-architecture.md index 3267422756..fdafae9995 100644 --- a/docs/architecture/botharness-architecture.md +++ b/docs/architecture/botharness-architecture.md @@ -1227,7 +1227,9 @@ and returns focus after dismissal. No second shortcut router or Panel state is i ### Connect encryption and full WebView removal (#2541, #2542) -The application-defined Connect Channel uses the fixed Noise XK profile and authenticated, bounded frames defined in [Connect Channel v1](connect-channel-v1.md). The Host identity lives in the native Credentials Provider; the existing Device Pairing authority persists approved device public keys and closes their channels on revocation. A successful handshake alone grants no application access. Account relay requests and QR offers are redeemed only inside the channel after independent Host fingerprint comparison and exact device-key approval. +The application-defined Connect Channel uses the fixed Noise XK profile and authenticated, bounded frames defined in [Connect Channel v1](connect-channel-v1.md). The Host identity lives in the native Credentials Provider; the existing Device Pairing authority persists approved device public keys and closes their channels on revocation. A successful handshake alone grants no application access. Offers are redeemed only inside the channel after independent Host fingerprint comparison or a trusted computer QR scan, and exact device-key approval. + +[Encrypted LAN phone access](lan-phone-v1.md) adds a default-off, restricted listener owned by the device-access Plugin lifecycle. It exposes only the Noise channel upgrade and reuses the same Host key, Device Pairing records and loopback gateway. DSH's operator surface remains loopback-bound. LAN has an explicit handshake context and native carrier; disabling it releases only LAN resources. Address rediscovery, safe route handover and legacy upgrades follow later slices of #2598. The cloudflared-only origin accepts `/botharness-device/channel` and refuses legacy application HTTP, stream tickets and WebView paths. The shared phone/browser Host client carries unary RPCs, logical `remote.mux`, uploads, downloads, avatars, private input and push registration inside ciphertext. The encrypted adapter forwards to the existing Device Gateway on loopback; native DSH Typert/API Gateway remains the sole dispatcher. Loopback/Tailscale retain their contract. Legacy Connect pairings without pins fail closed and must be paired again; no failure clears a pin or retries plaintext through Connect. diff --git a/docs/architecture/lan-phone-v1.md b/docs/architecture/lan-phone-v1.md new file mode 100644 index 0000000000..b33fd3264c --- /dev/null +++ b/docs/architecture/lan-phone-v1.md @@ -0,0 +1,34 @@ +# Encrypted LAN phone access + +[#2599](https://github.com/BotHarness/DeepSeekBot/issues/2599) is the first slice of the accepted [#2598](https://github.com/BotHarness/DeepSeekBot/issues/2598) design. Native qualification and Human acceptance are separate from source tests. + +## Authority and lifecycle + +LAN starts off. Devices → Local network access, or `deepseekbot device-lan enable --confirm`, opens a restricted IPv4 listener. The Profile's Credentials Provider stores its port for restart. Disabling closes LAN sockets and removes the preference; Connect remains independent. + +This refines ADR-0199's same-listener transport decision. DSH stays loopback-bound; the application-defined adapter exposes only WebSocket upgrade at `/botharness-device/channel`. All ordinary HTTP paths return 404. Authorization, cookie, browser Origin and subprotocol headers are refused before upgrade. No operator API, general proxy or Web Client is exposed. + +The adapter instantiates the existing encrypted gateway against the same Host key and Device Pairing owner. Admitted requests traverse the existing loopback device gateway and its normal authorization checks. There is no second device store or business dispatcher. Revocation closes that device's channels across transports. + +## Trust and compatibility + +A computer QR includes an expiring one-use offer, Host key and candidate addresses. Scanning it in the installed app pins that key; pasted and external links retain fingerprint comparison. The computer still approves the exact phone key. Handshake success alone grants no authority. + +LAN uses the existing Noise XK profile and framing with the final prologue field `lan`. Connect retains `connect`. Credentials follow authentication; LAN never falls back to plaintext. Missing keys refuse until the later legacy-upgrade slice. This slice advertises RFC 1918 IPv4 routes, prefers LAN for encrypted enrollment, and retains the encrypted carrier's viewer restrictions. IPv6, changed-address discovery and safe proactive handover are not implemented here. + +## Native carrier + +The local Expo `LanChannel` module accepts only a private IPv4 address and port, fixes the channel path, and carries bounded hexadecimal Noise frames. It has no general HTTP or header API. A missing module refuses with `lan-build-required`; new native builds are required. + +- iOS uses an ephemeral `URLSessionWebSocketTask`, no cookies, credentials or redirects, bounded receive size, and `NSAllowsLocalNetworking`. It does not enable arbitrary loads. See [Apple's ATS contract](https://developer.apple.com/documentation/bundleresources/information-property-list/nsapptransportsecurity/nsallowslocalnetworking). +- Android uses a private OkHttp client with redirects and proxies disabled. Only `encrypted-lan.invalid` receives the carrier exception; per-connection DNS maps that reserved name directly to validated private IPv4 bytes, without external resolution. Separate pools prevent alias reuse across Hosts. General HTTP stays denied; loopback and the emulator Host alias retain development access. See [Android's domain policy](https://developer.android.com/privacy-and-security/security-config). + +The reserved name is neither discovery nor trust. Noise authenticates the Host. Permission denial, network isolation and firewalls can still prevent access. + +Android validates the HTTP upgrade header and WebSocket frame headers in a bounded Socket input wrapper before OkHttp assembles messages. It caps a frame and accumulated fragments at 70,000 bytes, refuses binary or compressed messages, and permits at most 1,024 fragments per message. Each source read is at most 8 KiB. The gateway does not negotiate WebSocket compression. + +The Host advertises at most eight private addresses. Enrollment tries them with a two-second handshake deadline per address; pre-authentication transport failure may try the next candidate. A Host-key refusal stops enrollment. After pairing, an unavailable LAN route may fall through to saved remote routes, while identity and admission refusals stop selection. LAN lifecycle logs contain the initiator, phase, elapsed duration and a coded refusal without addresses or enrollment material. + +## Qualification + +`device-lan.test.ts` exercises opt-in, HTTP refusal, scanned enrollment, exact approval, encrypted requests, revocation, restart and shutdown through the actual pairing and mobile carrier owners. Native compilation, camera scanning, real Host Feed, offline state, model replies and visual acceptance require the assigned device QA batch. Record each platform separately and do not infer native success from source tests. diff --git a/docs/bot-cli.md b/docs/bot-cli.md index 9402c9a1b7..a5b66b27e5 100644 --- a/docs/bot-cli.md +++ b/docs/bot-cli.md @@ -613,6 +613,14 @@ deepseekbot idle-compaction-cache-set deepseek/ auto All three return `{enabled, settingReadable, minimumIdleSeconds, scheduled, routes}`. Each route lists `cacheLifetimeSeconds`, its `source` and `compactAfterSeconds` (`null` when the route is skipped). The lifetime comes from the per-route value set here (`setting`), the model catalog (`catalog`, Anthropic's short tier), the observed gaps before requests that still read most of their input from the cache (`observed`; a warm gap never shortens the default, and a longer cold gap caps it), or 2 hours for DeepSeek routes (`default`); other routes with nothing known are `unknown` and skipped, as are lifetimes under 15 minutes. `idle-compaction-cache-set ... auto` removes the per-route value. Each run is recorded under `idleCompactions` in `deepseekbot bot-activity-history ` with the route, idle gap, tokens before and after, and the compaction request's input, cache-read and output tokens. Refusals carry a code: `usage` (a missing `on`/`off`, `/` or whole seconds) and `invalid-input`. +### Encrypted LAN phone access + +For model-free device-side qualification, `device-pair --link-file --out --confirm` runs the same encrypted enrollment as the phone. While waiting, the pairing process writes one `device-key-confirmation-required` JSON status to stderr containing only its public-key fingerprint. In another CLI process, compare all digits with `devices.pendingKeys[].fingerprint`, then approve the matching exact public key with `device-approve-key`; never approve merely by device name or list position. The final stdout contains only Host/device IDs and the output path; keys and credentials go only to the new private file. `device-probe --device-file ` then reads the real Host Feed through the mobile connection owner and reports only route kind and roster counts. It sends no DM and requires no model. Never pass a pairing link or device credential as a command argument. + +`deepseekbot device-lan enable --confirm` opens the restricted encrypted entry. `device-lan disable` closes LAN sockets and removes the opt-in; it does not revoke devices or disable Connect. Both return one JSON status (`off` or `listening`, with the port). `devices` includes `lan` status and eligible routes. Refusals include `confirm-required`, `lan-action-invalid`, `lan-listen-failed` and `lan-storage-unavailable`. LAN starts disabled; its enabled port survives ordinary Host restart. + +Use `device-offer --out ` and `device-approve-key --confirm` through the existing pairing owner. The installed app scans the trusted computer code and waits for exact phone-key approval. Public keys are safe arguments; links and credentials stay in protected files. See [the LAN contract](architecture/lan-phone-v1.md) for native build and network requirements. + ### Phone route (Tailscale) Bot settings → Devices → Pair a phone shows a three-step guide while a phone cannot reach this Host: install Tailscale, start and sign in, then publish the Host on the tailnet. The last step can run `tailscale serve --bg ` for you after a confirmation, or you copy the command and run it yourself. The same two operations from the CLI: @@ -631,6 +639,8 @@ Bot settings → Devices lists paired phones, shows a pairing QR code and revoke ```bash deepseekbot devices deepseekbot device-offer --out /absolute/new-private-file +deepseekbot device-lan enable --confirm +deepseekbot device-lan disable deepseekbot device-offer-status deepseekbot device-revoke --confirm ``` diff --git a/docs/bot-cli.zh.md b/docs/bot-cli.zh.md index 10b04316ee..9045658d6d 100644 --- a/docs/bot-cli.zh.md +++ b/docs/bot-cli.zh.md @@ -597,6 +597,14 @@ deepseekbot idle-compaction-cache-set deepseek/ auto 三个命令都返回 `{enabled, settingReadable, minimumIdleSeconds, scheduled, routes}`。每条线路列出 `cacheLifetimeSeconds`、来源 `source` 和 `compactAfterSeconds`(跳过时为 `null`)。缓存寿命依次取自这里为该线路设置的值(`setting`)、模型目录(`catalog`,Anthropic 的短档)、观测到的请求前空闲间隔中仍大部分命中缓存的最长值(`observed`;命中的间隔不会缩短默认值,更长的未命中间隔会把它封顶),或 DeepSeek 线路的 2 小时(`default`);其它没有任何信息的线路为 `unknown` 并跳过,寿命不足 15 分钟的也跳过。`idle-compaction-cache-set ... auto` 删除该线路的设置值。每次执行都记录在 `deepseekbot bot-activity-history ` 的 `idleCompactions` 中,包含线路、空闲时长、压缩前后 token 数,以及压缩请求的输入、缓存读取和输出 token。拒绝时带错误码:`usage`(缺少 `on`/`off`、`/` 或整数秒)和 `invalid-input`。 +### 加密局域网手机连接 + +无需模型的设备侧验收使用 `device-pair --link-file <可信私有链接文件> --out <新私有配对.json> --confirm`,执行与手机相同的加密注册。等待批准时,配对进程向标准错误输出一条 `device-key-confirmation-required` JSON 状态,只包含本端公钥指纹。在另一个 CLI 进程将其与 `devices.pendingKeys[].fingerprint` 完整逐位比较,再用 `device-approve-key` 批准该条目的准确公钥;不得只按设备名或列表位置批准。最终标准输出只有 Host/设备 ID 和输出路径,密钥及凭据只写入新私有文件。之后用 `device-probe --device-file <私有配对.json>` 通过手机连接模块读取真实 Host Feed,只报告路由类型与列表数量,不发送 DM,也不需要模型。配对链接和凭据不得放入命令参数。 + +`deepseekbot device-lan enable --confirm` 开启受限的加密入口。`device-lan disable` 关闭 LAN 连接并移除启用记录,不撤销设备,也不关闭 Connect。两者只返回一个 JSON 状态(`off` 或带端口的 `listening`)。`devices` 增加 `lan` 状态和可用路由。拒绝码包括 `confirm-required`、`lan-action-invalid`、`lan-listen-failed`、`lan-storage-unavailable`。LAN 默认关闭;启用后端口在普通 Host 重启时保留。 + +继续使用现有配对命令 `device-offer --out <新私有文件>` 和 `device-approve-key <公钥> --confirm`。已安装的 App 扫描可信电脑上的二维码,然后等待电脑批准准确的手机公钥。公钥可作为参数;链接和凭据只放在受保护文件中。原生构建与网络要求见 [LAN 协议](architecture/lan-phone-v1.md)。 + ### 手机连接(Tailscale) 手机连不上这台 Host 时,Bot 设置 → 设备 → 配对手机会显示三步指引:安装 Tailscale、启动并登录、把 Host 发布到 tailnet。最后一步可以确认后由 DeepSeekBot 代为运行 `tailscale serve --bg `,也可以复制命令自己运行。CLI 中的对应操作: @@ -615,6 +623,8 @@ Bot 设置 → 设备 会列出已配对的手机、显示配对二维码并撤 ```bash deepseekbot devices deepseekbot device-offer --out /absolute/new-private-file +deepseekbot device-lan enable --confirm +deepseekbot device-lan disable deepseekbot device-offer-status deepseekbot device-revoke --confirm ``` diff --git a/packages/client/src/client/locale.ts b/packages/client/src/client/locale.ts index dea99127c3..d00e09f9f5 100644 --- a/packages/client/src/client/locale.ts +++ b/packages/client/src/client/locale.ts @@ -4028,6 +4028,11 @@ export const zh = { 'remoteHosts.error.unreachable': '连不上这个远程,请确认它开着并在同一个 Tailscale 网络里', 'remoteHosts.error.already-paired': '这个远程已经添加过了', 'remoteHosts.error.this-host': '这是本机的链接', + 'devices.lan.title': '局域网连接', + 'devices.lan.notice': '允许手机通过当前网络加密连接。新手机需要你批准。', + 'devices.lan.enabled': '已开启。手机连到同一网络后,扫描下方配对码。', + 'devices.lan.enable': '开启局域网连接', + 'devices.lan.disable': '关闭局域网连接', 'devices.pair.title': '配对手机', 'devices.pair.description': '用 DeepSeekBot App 扫码。二维码只能用一次,10 分钟后失效。', 'devices.pair.open': '配对手机', @@ -8461,6 +8466,13 @@ My relationship with you, established lore and topics to avoid: [fill in]. "Can't reach that remote. Check that it's on and on the same Tailscale network.", 'remoteHosts.error.already-paired': 'That remote is already added.', 'remoteHosts.error.this-host': 'That link is for this host.', + 'devices.lan.title': 'Local network access', + 'devices.lan.notice': + 'Allow encrypted phone connections on this network. You approve each new phone.', + 'devices.lan.enabled': + 'On. Join the same network on your phone, then scan the pairing code below.', + 'devices.lan.enable': 'Enable local access', + 'devices.lan.disable': 'Disable local access', 'devices.pair.title': 'Pair a phone', 'devices.pair.description': 'Scan a QR code with the DeepSeekBot app. The code works once and expires after 10 minutes.', diff --git a/packages/client/src/client/paired-devices.tsx b/packages/client/src/client/paired-devices.tsx index 1f19239ef8..31d72772e9 100644 --- a/packages/client/src/client/paired-devices.tsx +++ b/packages/client/src/client/paired-devices.tsx @@ -50,6 +50,7 @@ interface ConnectStatus { } interface DevicesSnapshot { + lan?: { state: 'off' | 'listening' | 'error'; issue?: string }; host: { id: string; name: string }; devices: PairedDevice[]; pendingKeys?: { receipt: string; publicKey: string; name: string; approved: boolean }[]; @@ -221,6 +222,27 @@ export function PairedDevicesSettings({ t }: PropsLocale<'botharness'>): ReactEl void createOffer(); }; + const setLan = async (action: 'enable' | 'disable'): Promise => { + setBusy('lan'); + setError(false); + try { + await json( + await fetch(`${PATH}/lan`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ action, confirm: true }), + }), + ); + await load(); + if (action === 'enable') setGuided(false); + setOffer(undefined); + } catch { + if (mounted.current) setError(true); + } finally { + if (mounted.current) setBusy(undefined); + } + }; + const close = (): void => { setPairing(false); setOffer(undefined); @@ -344,6 +366,29 @@ export function PairedDevicesSettings({ t }: PropsLocale<'botharness'>): ReactEl return (
+ {snapshot?.lan ? ( + + void setLan(snapshot.lan?.state === 'listening' ? 'disable' : 'enable') + } + > + {t( + snapshot.lan.state === 'listening' ? 'devices.lan.disable' : 'devices.lan.enable', + )} + + } + /> + ) : null} void = (line) => { + process.stderr.write(line); + }, +): Promise { + if (rest.length) throw new CliLiveError('usage', `${command} takes no positional arguments.`); + if (command === 'device-pair') { + if (!values['link-file'] || !values.out || !isAbsolute(values.out)) + throw new CliLiveError('usage', 'Provide --link-file and a new absolute --out file.'); + if (!values.confirm) + throw new CliLiveError( + 'confirm-required', + 'Confirm this file came from the trusted computer with --confirm.', + ); + if (existsSync(values.out)) throw new CliLiveError('output-exists', 'Choose a new --out file.'); + let text: string; + try { + text = readFileSync(values['link-file'], 'utf8'); + } catch { + throw new CliLiveError('invalid-input', 'Cannot read the trusted pairing file.'); + } + let summary: unknown; + let reported = false; + const result = await pairHost({ + text, + method: 'paste', + deviceName: 'CLI device', + carrier: nodeDeviceCarrier(), + confirmFingerprint: async () => true, + onPending: (fingerprint) => { + if (reported) return; + reported = true; + writeStatus( + `${JSON.stringify({ type: 'device-key-confirmation-required', fingerprint })}\n`, + ); + }, + telemetry: { pairing: () => ({ finish: () => {} }) }, + save: async (host) => { + writeFileSync(values.out!, `${JSON.stringify(host)}\n`, { flag: 'wx', mode: 0o600 }); + summary = { + hostId: host.hostId, + deviceId: host.deviceId, + encrypted: !!host.encryption, + pairing: { path: values.out }, + }; + }, + }); + if (!result.ok) + throw new CliLiveError( + result.code, + 'Device pairing refused. Approve the pending exact key on the trusted Host.', + ); + return summary; + } + if (!values['device-file']) throw new CliLiveError('usage', 'Provide --device-file.'); + let host; + try { + host = parseSavedHost(JSON.parse(readFileSync(values['device-file'], 'utf8'))); + } catch { + throw new CliLiveError('invalid-input', 'Cannot read the saved pairing.'); + } + if (!host) throw new CliLiveError('invalid-input', 'Invalid saved pairing.'); + if (!host.encryption && host.routes.some(isEncryptedRoute)) + throw new CliLiveError('host-key-required', 'Upgrade this pairing from the trusted computer.'); + const client = createHostClient({ ...host, carrier: nodeDeviceCarrier() }); + let unsubscribe = () => {}; + let timer: ReturnType | undefined; + try { + return await new Promise((resolve, reject) => { + timer = setTimeout( + () => reject(new CliLiveError('unreachable', 'Device Host Feed did not become ready.')), + 15_000, + ); + unsubscribe = client.subscribe(() => { + const snapshot = client.getSnapshot(); + if (snapshot.connection.status === 'connected' && snapshot.roster) + resolve({ + hostId: host.hostId, + deviceId: host.deviceId, + route: isLanRoute(snapshot.connection.route) ? 'lan' : 'remote', + encrypted: isEncryptedRoute(snapshot.connection.route), + bots: snapshot.roster.bots.length, + channels: snapshot.roster.channels.length, + }); + else if (snapshot.connection.status === 'refused') + reject(new CliLiveError(snapshot.connection.code, 'Device access was refused.')); + }); + client.start(); + }); + } finally { + clearTimeout(timer); + unsubscribe(); + client.stop(); + } +} diff --git a/packages/core/src/bots/cli-devices.ts b/packages/core/src/bots/cli-devices.ts index d12bebdd8f..69066c55e6 100644 --- a/packages/core/src/bots/cli-devices.ts +++ b/packages/core/src/bots/cli-devices.ts @@ -1,8 +1,13 @@ import { existsSync, writeFileSync } from 'node:fs'; import { CliLiveError } from './cli-live-error.js'; +import { noiseFingerprint } from '../devices/noise/xk.js'; export const DEVICES_COMMANDS = [ + { + command: 'device-lan', + description: 'enable --confirm or disable encrypted phone access on the local network', + }, { command: 'device-approve-key', description: @@ -50,7 +55,7 @@ export async function runDevicesCommand( const takes = command === 'device-approve-key' ? 2 - : command === 'device-offer-status' || command === 'device-revoke' + : command === 'device-offer-status' || command === 'device-revoke' || command === 'device-lan' ? 1 : 0; if (rest.length !== takes) @@ -64,6 +69,15 @@ export async function runDevicesCommand( ); if (values.out !== undefined && command !== 'device-offer') throw new CliLiveError('usage', '--out requires device-offer.'); + if (command === 'device-lan') { + if (rest[0] !== 'enable' && rest[0] !== 'disable') + throw new CliLiveError('usage', 'device-lan takes enable --confirm or disable.'); + if (rest[0] === 'enable' && values.confirm !== true) + throw new CliLiveError( + 'confirm-required', + 'LAN access opens an encrypted phone entry on this network. Pass --confirm.', + ); + } if (command === 'device-offer') { if (values.out === undefined) throw new CliLiveError( @@ -102,13 +116,33 @@ export async function runDevicesCommand( }; if (command === 'devices') { const snapshot = decode((await host.http(DEVICES)).bytes); + const pending = snapshot['pendingKeys']; + const pendingKeys = Array.isArray(pending) + ? pending.map((entry: unknown) => { + if ( + !entry || + typeof entry !== 'object' || + !('publicKey' in entry) || + typeof entry.publicKey !== 'string' || + !/^[0-9a-f]{64}$/u.test(entry.publicKey) + ) + return entry; + return { ...entry, fingerprint: noiseFingerprint(Buffer.from(entry.publicKey, 'hex')) }; + }) + : pending; return { host: snapshot['host'], devices: snapshot['devices'], - ...(snapshot['pendingKeys'] === undefined ? {} : { pendingKeys: snapshot['pendingKeys'] }), + ...(pendingKeys === undefined ? {} : { pendingKeys }), routes: snapshot['routes'], + ...(snapshot['lan'] === undefined ? {} : { lan: snapshot['lan'] }), }; } + if (command === 'device-lan') + return decode( + (await host.http(`${DEVICES}/lan`, { action: rest[0], confirm: values.confirm === true })) + .bytes, + ); if (command === 'device-approve-key') return decode( ( diff --git a/packages/core/src/bots/cli-live.ts b/packages/core/src/bots/cli-live.ts index 0e5e0d8f5e..0bcfbb03c5 100644 --- a/packages/core/src/bots/cli-live.ts +++ b/packages/core/src/bots/cli-live.ts @@ -7,6 +7,7 @@ import { } from './cli-window-zoom.js'; import { PHONE_ROUTE_COMMANDS, runPhoneRouteCommand } from './cli-phone-route.js'; import { DEVICES_COMMANDS, isDevicesCommand, runDevicesCommand } from './cli-devices.js'; +import { DEVICE_CLIENT_COMMANDS, runDeviceClientCommand } from './cli-device-client.js'; import { DEVICE_NOTIFICATION_COMMANDS, DEVICE_NOTIFICATION_OPTIONS, @@ -133,6 +134,7 @@ import { export { CliLiveError } from './cli-live-error.js'; export const LIVE_OPTIONS = { + 'link-file': { type: 'string' }, 'remote-host-id': { type: 'string' }, 'host-id': { type: 'string' }, ...DEVICE_NOTIFICATION_OPTIONS, @@ -238,6 +240,7 @@ export const LIVE_COMMANDS = [ ...WINDOW_ZOOM_COMMANDS, ...PHONE_ROUTE_COMMANDS, ...DEVICES_COMMANDS, + ...DEVICE_CLIENT_COMMANDS, ...CONNECT_COMMANDS, ...IM_COMMANDS, ...MESSAGING_COMMANDS, @@ -432,6 +435,7 @@ interface LiveValues ApprovalReviewerValues { 'client-id'?: string; 'device-file'?: string; + 'link-file'?: string; 'remote-host-id'?: string; 'host-id'?: string; 'preferences-stdin'?: boolean; @@ -808,6 +812,8 @@ export async function runLiveCli( return runDevicesCommand(command, rest, values, () => connectLiveHost(values, io, AbortSignal.timeout(timeoutMs(values.timeout))), ); + if (DEVICE_CLIENT_COMMANDS.some((entry) => entry.command === command)) + return runDeviceClientCommand(command, rest, values); if (command === 'cloud-work') { const input = await prepareCloudWork(rest, values, io); const host = await connectLiveHost(values, io, AbortSignal.timeout(timeoutMs(values.timeout))); diff --git a/packages/core/src/devices/encrypted-gateway.ts b/packages/core/src/devices/encrypted-gateway.ts index ab7e413208..acc511b962 100644 --- a/packages/core/src/devices/encrypted-gateway.ts +++ b/packages/core/src/devices/encrypted-gateway.ts @@ -38,6 +38,7 @@ function pathAllowed(path: string): boolean { export function createEncryptedGateway(options: { pairing: DevicePairing; + route?: 'connect' | 'lan'; key(): Promise; port(): number; changed?: (state: { negotiating: number; encrypted: number }) => void; @@ -65,6 +66,7 @@ export function createEncryptedGateway(options: { staticKey: key, ephemeralKey: randomBytes(32), hostKey: noisePublicKey(key), + route: options.route ?? 'connect', }); key.fill(0); let credential: string | undefined, diff --git a/packages/core/src/devices/http.ts b/packages/core/src/devices/http.ts index 86609a2edc..3196460c64 100644 --- a/packages/core/src/devices/http.ts +++ b/packages/core/src/devices/http.ts @@ -1,5 +1,6 @@ import type { EncryptionIdentity } from './noise-identity.js'; import { encode } from 'uqr'; +import type { DeviceLan, LanStatus } from './lan.js'; import type { AccountStatus, ConnectAccount } from './connect-account.js'; import type { ConnectStatus, DeviceConnect } from './connect.js'; @@ -30,6 +31,7 @@ export interface PairingPayload { } export interface DevicesSnapshot { + lan?: LanStatus; host: HostIdentity; devices: PairedDevice[]; pendingKeys?: ReturnType; @@ -74,7 +76,8 @@ function qrPath(text: string): { size: number; path: string } { } export function offeredRoutes(status: RouteStatus, clientOrigin: string | undefined): PhoneRoute[] { - const routes = status.routes.filter((route) => route.ready && route.kind === 'tailscale'); + const routes = status.routes.filter((route) => route.ready && route.kind === 'lan'); + routes.push(...status.routes.filter((route) => route.ready && route.kind === 'tailscale')); const own = clientOrigin === undefined ? undefined : phoneRoute(clientOrigin); if (own?.kind === 'tailscale' && !routes.some((route) => route.url === own.url)) routes.push(own); routes.push(...status.routes.filter((route) => route.ready && route.kind === 'connect')); @@ -106,12 +109,14 @@ export function createDevicesHttp(options: { publish?: () => Promise; connect?: DeviceConnect; account?: ConnectAccount; + lan?: DeviceLan; }): (request: Request) => Promise { const { pairing, connect, account } = options; return async (request) => { const path = new URL(request.url).pathname; if (request.method === 'GET' && path === DEVICES_PATH) { const snapshot: DevicesSnapshot = { + ...(options.lan ? { lan: options.lan.status() } : {}), host: pairing.host(), devices: pairing.list(), pendingKeys: pairing.pendingKeys(), @@ -145,7 +150,7 @@ export function createDevicesHttp(options: { routes, reachable: routes.some((route) => { const kind = phoneRoute(route)?.kind; - return kind === 'tailscale' || kind === 'connect'; + return kind === 'lan' || kind === 'tailscale' || kind === 'connect'; }), }; return json(view); @@ -197,6 +202,15 @@ export function createDevicesHttp(options: { 409, ); } + if (request.method === 'POST' && path === `${DEVICES_PATH}/lan` && options.lan) { + const input = await body(request); + if (input['action'] !== 'enable' && input['action'] !== 'disable') + return json({ code: 'lan-action-invalid' }, 400); + if (input['action'] === 'enable' && input['confirm'] !== true) + return json({ code: 'confirm-required' }, 400); + const result = await options.lan[input['action']](); + return result.ok ? json(result.status) : json({ code: result.code }, 503); + } if (request.method === 'POST' && path === `${DEVICES_PATH}/connect` && connect !== undefined) { const input = await body(request); if ( diff --git a/packages/core/src/devices/lan-address.ts b/packages/core/src/devices/lan-address.ts new file mode 100644 index 0000000000..6d3be19a6b --- /dev/null +++ b/packages/core/src/devices/lan-address.ts @@ -0,0 +1,7 @@ +export function isLanAddress(address: string): boolean { + const parts = address.split('.'); + if (parts.length !== 4 || parts.some((part) => !/^\d{1,3}$/u.test(part) || Number(part) > 255)) + return false; + const [a, b] = parts.map(Number); + return a === 10 || (a === 172 && b! >= 16 && b! <= 31) || (a === 192 && b === 168); +} diff --git a/packages/core/src/devices/lan.ts b/packages/core/src/devices/lan.ts new file mode 100644 index 0000000000..81a90d9807 --- /dev/null +++ b/packages/core/src/devices/lan.ts @@ -0,0 +1,197 @@ +import { createServer, type IncomingMessage } from 'node:http'; +import { networkInterfaces } from 'node:os'; +import type { AddressInfo, Socket } from 'node:net'; +import type { Duplex } from 'node:stream'; +import type { PhoneRoute } from './routes.js'; +import { CONNECT_CHANNEL_PATH } from './noise/channel.js'; +import { isLanAddress } from './lan-address.js'; + +export interface LanStatus { + state: 'off' | 'listening' | 'error'; + port?: number; + issue?: 'lan-listen-failed' | 'lan-storage-unavailable'; +} +export type LanResult = + | { ok: true; status: LanStatus } + | { ok: false; code: NonNullable }; +interface Gateway { + upgrade(request: IncomingMessage, socket: Duplex, head: Buffer): void; + close(): void; +} + +export function createDeviceLan(options: { + read(): Promise; + write(port: number | undefined): Promise; + gateway(): Gateway; + addresses?: () => string[]; + log?: (event: { + initiator: 'startup' | 'operator' | 'shutdown' | 'listener'; + phase: 'restore' | 'enable' | 'disable' | 'close' | 'error'; + durationMs: number; + refusal?: NonNullable; + }) => void; +}) { + let status: LanStatus = { state: 'off' }; + let current: + | { server: ReturnType; gateway: Gateway; sockets: Set } + | undefined; + let disposed = false; + let tail = Promise.resolve(); + function serial(action: () => Promise): Promise { + const result = tail.then(action); + tail = result.then( + () => {}, + () => {}, + ); + return result; + } + function transition( + initiator: 'startup' | 'operator' | 'shutdown' | 'listener', + phase: 'restore' | 'enable' | 'disable' | 'close' | 'error', + action: () => Promise, + ) { + return serial(async () => { + const started = performance.now(); + const result = await action(); + options.log?.({ + initiator, + phase, + durationMs: Math.round(performance.now() - started), + ...(!result.ok ? { refusal: result.code } : {}), + }); + return result; + }); + } + async function stop() { + const previous = current; + current = undefined; + status = { state: 'off' }; + if (!previous) return; + previous.gateway.close(); + for (const socket of previous.sockets) socket.destroy(); + await new Promise((resolve) => previous.server.close(() => resolve())); + } + async function listen(port: number): Promise { + if (disposed) return { ok: false, code: 'lan-listen-failed' }; + const gateway = options.gateway(); + const sockets = new Set(); + const server = createServer( + { maxHeaderSize: 8192, requestTimeout: 5000, headersTimeout: 5000 }, + (request, response) => { + request.resume(); + response.writeHead(404, { + 'content-type': 'application/json', + 'cache-control': 'no-store', + connection: 'close', + }); + response.end('{"code":"not-found"}'); + }, + ); + server.maxConnections = 64; + server.on('connection', (socket) => { + sockets.add(socket); + socket.once('close', () => sockets.delete(socket)); + socket.setTimeout(15_000, () => socket.destroy()); + }); + server.on('upgrade', (request, socket, head) => { + if ( + request.url !== CONNECT_CHANNEL_PATH || + request.method !== 'GET' || + request.headers.origin || + request.headers.authorization || + request.headers.cookie || + request.headers['sec-websocket-protocol'] + ) { + socket.destroy(); + return; + } + (socket as Socket).setTimeout(0); + gateway.upgrade(request, socket, head); + }); + current = { server, gateway, sockets }; + try { + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(port, '0.0.0.0', () => { + server.removeListener('error', reject); + resolve(); + }); + }); + server.on('error', () => { + void transition('listener', 'error', async () => { + await stop(); + status = { state: 'error', issue: 'lan-listen-failed' }; + return { ok: false, code: 'lan-listen-failed' }; + }); + }); + status = { state: 'listening', port: (server.address() as AddressInfo).port }; + return { ok: true, status: { ...status } }; + } catch { + await stop(); + status = { state: 'error', issue: 'lan-listen-failed' }; + return { ok: false, code: 'lan-listen-failed' }; + } + } + return { + status: (): LanStatus => ({ ...status }), + routes(): PhoneRoute[] { + if (status.state !== 'listening') return []; + const addresses = + options.addresses?.() ?? + Object.values(networkInterfaces()).flatMap( + (entries) => + entries + ?.filter((entry) => !entry.internal && entry.family === 'IPv4') + .map((entry) => entry.address) ?? [], + ); + return [...new Set(addresses)] + .filter(isLanAddress) + .slice(0, 8) + .map((address) => ({ url: `http://${address}:${status.port}`, kind: 'lan', ready: true })); + }, + start: () => + transition('startup', 'restore', async () => { + if (current || disposed) return { ok: true, status: { ...status } }; + try { + const port = await options.read(); + if (Number.isInteger(port) && port! > 0 && port! <= 65535) return await listen(port!); + } catch { + status = { state: 'error', issue: 'lan-storage-unavailable' }; + return { ok: false, code: 'lan-storage-unavailable' }; + } + return { ok: true, status: { ...status } }; + }), + enable: () => + transition('operator', 'enable', async (): Promise => { + if (current) return { ok: true, status: { ...status } }; + const result = await listen(0); + if (!result.ok) return result; + try { + await options.write(status.port); + } catch { + await stop(); + return { ok: false, code: 'lan-storage-unavailable' }; + } + return { ok: true, status: { ...status } }; + }), + disable: () => + transition('operator', 'disable', async (): Promise => { + await stop(); + try { + await options.write(undefined); + } catch { + return { ok: false, code: 'lan-storage-unavailable' }; + } + return { ok: true, status: { ...status } }; + }), + close: () => { + disposed = true; + return transition('shutdown', 'close', async () => { + await stop(); + return { ok: true, status: { ...status } }; + }); + }, + }; +} + +export type DeviceLan = ReturnType; diff --git a/packages/core/src/devices/mount.ts b/packages/core/src/devices/mount.ts index 5d56d0ab2b..51f411bd69 100644 --- a/packages/core/src/devices/mount.ts +++ b/packages/core/src/devices/mount.ts @@ -2,7 +2,8 @@ import { createNoiseIdentity } from './noise-identity.js'; import { createEncryptedGateway } from './encrypted-gateway.js'; import { CONNECT_CHANNEL_PATH } from './noise/channel.js'; import type { Context } from '@deepseek-ai/cordis'; -import type { CredentialProvider } from '@deepseek-ai/dsh-credentials'; +import { credentialKey, type CredentialProvider } from '@deepseek-ai/dsh-credentials'; +import { createDeviceLan } from './lan.js'; import type { IncomingMessage, ServerResponse } from 'node:http'; import { hostname } from 'node:os'; import { join } from 'node:path'; @@ -159,6 +160,45 @@ export function mountDevicePairing( const connection = (webCtx as unknown as { connection: ConnectionLike }).connection; const webServer = (webCtx as unknown as { webServer: WebServerLike }).webServer; const identity = createNoiseIdentity(options.credentials ?? (() => undefined)); + const lanKey = credentialKey('botharness-core', 'device-lan'); + const lan = createDeviceLan({ + read: async () => { + const credentials = options.credentials?.(); + if (!credentials) throw new Error('lan-storage-unavailable'); + const record = await credentials.readRecord(lanKey); + if (record?.kind !== 'grant') return undefined; + if (!record.payload || typeof record.payload !== 'object' || !('port' in record.payload)) + return undefined; + const port = record.payload.port; + return typeof port === 'number' ? port : undefined; + }, + write: async (port) => { + const credentials = options.credentials?.(); + if (!credentials) throw new Error('lan-storage-unavailable'); + if (port === undefined) await credentials.deleteRecord(lanKey); + else + await credentials.modifyRecord(lanKey, async () => ({ + kind: 'grant', + payload: { port }, + })); + }, + gateway: () => + createEncryptedGateway({ + pairing, + key: identity.key, + port: () => webServer.port, + route: 'lan', + log: (phase) => write('device-lan', phase, `device-lan phase=${phase}`), + }), + log: (event) => + write('device-lan', event.phase, JSON.stringify({ module: 'device-lan', ...event })), + }); + webCtx.effect(() => { + void lan.start(); + return () => { + void lan.close(); + }; + }, 'botharness: encrypted LAN entry'); let channels = { negotiating: 0, encrypted: 0 }; const encryption = async () => ({ ...(await identity.publicIdentity()), @@ -218,6 +258,7 @@ export function mountDevicePairing( }, 'botharness: device connect tunnel'); const routes = async () => { const status = await detectPhoneRoutes({ port: webServer.port }); + status.routes.unshift(...lan.routes()); const tunnel = connect.route(); if (tunnel === undefined) return status; const loopback = status.routes.filter((route) => route.kind === 'loopback'); @@ -230,6 +271,7 @@ export function mountDevicePairing( routes, connect, account, + lan, publish: () => publishPhoneRoute({ port: webServer.port }), }); for (const [path, methods] of [ @@ -239,6 +281,7 @@ export function mountDevicePairing( [`${DEVICES_PATH}/approve-key`, ['POST']], [`${DEVICES_PATH}/revoke`, ['POST']], [`${DEVICES_PATH}/connect`, ['POST']], + [`${DEVICES_PATH}/lan`, ['POST']], ] as const) webCtx.effect( () => diff --git a/packages/core/src/devices/node-carrier.ts b/packages/core/src/devices/node-carrier.ts new file mode 100644 index 0000000000..5e420aa651 --- /dev/null +++ b/packages/core/src/devices/node-carrier.ts @@ -0,0 +1,38 @@ +import { randomBytes } from 'node:crypto'; +import { WebSocket } from 'ws'; +import type { HostCarrier } from '../../../../apps/mobile/src/host/carrier.js'; + +export function nodeDeviceCarrier(): HostCarrier { + return { + randomBytes: () => randomBytes(32), + request: async (url, init) => { + const response = await fetch(url, { ...init, redirect: 'error', credentials: 'omit' }); + return { + status: response.status, + text: () => response.text(), + bytes: async () => new Uint8Array(await response.arrayBuffer()), + }; + }, + openSocket: (url, events, headers) => { + const socket = new WebSocket(url, { headers, maxPayload: 70_000, followRedirects: false }); + socket.on('open', events.open); + socket.on('message', (data) => events.message(data.toString())); + let done = false; + const closed = () => { + if (!done) { + done = true; + events.closed('lan-unreachable'); + } + }; + socket.on('close', closed); + socket.on('error', closed); + return { + send: (text) => socket.send(text), + close: () => socket.terminate(), + get bufferedAmount() { + return socket.bufferedAmount; + }, + }; + }, + }; +} diff --git a/packages/core/src/devices/noise/channel.ts b/packages/core/src/devices/noise/channel.ts index 48db033bbc..0d2964fcbd 100644 --- a/packages/core/src/devices/noise/channel.ts +++ b/packages/core/src/devices/noise/channel.ts @@ -34,13 +34,19 @@ export class ConnectChannel { staticKey: Uint8Array; ephemeralKey: Uint8Array; hostKey: Uint8Array; + route?: 'connect' | 'lan'; }) { this.role = options.role; this.noise = new NoiseXk({ ...options, remoteStatic: options.hostKey, prologue: utf8ToBytes( - JSON.stringify([CONNECT_PROTOCOL, NOISE_PROTOCOL, options.hostId, 'connect']), + JSON.stringify([ + CONNECT_PROTOCOL, + NOISE_PROTOCOL, + options.hostId, + options.route ?? 'connect', + ]), ), }); } diff --git a/packages/core/src/devices/routes.ts b/packages/core/src/devices/routes.ts index 68eb61e21b..73cdd5117a 100644 --- a/packages/core/src/devices/routes.ts +++ b/packages/core/src/devices/routes.ts @@ -1,8 +1,9 @@ import { execFile } from 'node:child_process'; +import { isLanAddress } from './lan-address.js'; export interface PhoneRoute { url: string; - kind: 'tailscale' | 'connect' | 'loopback'; + kind: 'lan' | 'tailscale' | 'connect' | 'loopback'; ready: boolean; issue?: 'serve-missing' | 'serve-other-target'; } @@ -65,6 +66,8 @@ export function phoneRoute(input: string): PhoneRoute | undefined { } if (url.username || url.password || url.search || url.hash || url.pathname !== '/') return; const name = url.hostname; + if (isLanAddress(name) && url.protocol === 'http:' && url.port !== '') + return { url: url.origin, kind: 'lan', ready: true }; if (name === 'localhost' || name === '[::1]' || /^127\.\d+\.\d+\.\d+$/u.test(name)) return { url: url.origin, kind: 'loopback', ready: true }; const tailnet = name.endsWith('.ts.net') || TAILNET_IPV4.test(name); diff --git a/packages/core/test/cli-device-client.test.ts b/packages/core/test/cli-device-client.test.ts new file mode 100644 index 0000000000..f56b4db9d0 --- /dev/null +++ b/packages/core/test/cli-device-client.test.ts @@ -0,0 +1,53 @@ +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { expect, it, vi } from 'vitest'; +import { createTempRoot } from './helpers.js'; +const paired = vi.hoisted(() => vi.fn()); +vi.mock('../../../apps/mobile/src/host/pairing.js', () => ({ pairHost: paired })); +import { runDeviceClientCommand } from '../src/bots/cli-device-client.js'; + +it('requires trusted-file confirmation and never returns saved device secrets on stdout', async () => { + const root = createTempRoot('lan-cli-'); + const link = join(root, 'link.txt'), + out = join(root, 'device.json'); + writeFileSync(link, 'private-pairing-link'); + const values = { 'link-file': link, out }; + const pending = vi.fn(); + const fingerprint = '1234 '.repeat(15) + '5678'; + await expect(runDeviceClientCommand('device-pair', [], values)).rejects.toThrow('confirm'); + expect(paired).not.toHaveBeenCalled(); + paired.mockImplementation(async (options) => { + expect(options.text).toBe('private-pairing-link'); + options.onPending(fingerprint); + options.onPending(fingerprint); + expect(pending).toHaveBeenCalledExactlyOnceWith( + `${JSON.stringify({ type: 'device-key-confirmation-required', fingerprint })}\n`, + ); + expect(() => readFileSync(out)).toThrow(); + await options.save({ + hostId: 'host', + deviceId: 'device', + credential: 'private-secret', + encryption: { deviceKey: 'private-key' }, + }); + return { ok: true }; + }); + const result = await runDeviceClientCommand( + 'device-pair', + [], + { ...values, confirm: true }, + pending, + ); + expect(result).toEqual({ + hostId: 'host', + deviceId: 'device', + encrypted: true, + pairing: { path: out }, + }); + expect(JSON.stringify(result)).not.toContain('private-'); + expect(JSON.parse(readFileSync(out, 'utf8')).credential).toBe('private-secret'); + await expect( + runDeviceClientCommand('device-pair', [], { ...values, confirm: true }), + ).rejects.toThrow('new --out'); + expect(paired).toHaveBeenCalledOnce(); +}); diff --git a/packages/core/test/cli-devices.test.ts b/packages/core/test/cli-devices.test.ts index ff1ae8c4e0..9b35f27cae 100644 --- a/packages/core/test/cli-devices.test.ts +++ b/packages/core/test/cli-devices.test.ts @@ -9,6 +9,43 @@ const reply = (value: unknown) => ({ const LINK = 'deepseekbot://pair?p=c2VjcmV0LW9mZmVy'; describe('devices CLI', () => { + it('shows the pending public-key fingerprint so the operator can compare it before approval', async () => { + const pending = { + receipt: 'r', + publicKey: 'ab'.repeat(32), + name: 'CLI device', + approved: false, + }; + const http = async () => reply({ pendingKeys: [pending] }); + expect(await runDevicesCommand('devices', [], {}, async () => ({ http }))).toMatchObject({ + pendingKeys: [ + { + ...pending, + fingerprint: + '9a2d b2e2 3f15 04cd 0566 0655 3ac0 49c5 e718 e8f9 ce92 3387 6df1 a7a1 821a f885', + }, + ], + }); + }); + it('requires confirmation before opening LAN and uses the same Host management route to disable it', async () => { + const http = vi.fn(async () => reply({ state: 'listening' })); + await expect( + runDevicesCommand('device-lan', ['enable'], {}, async () => ({ http })), + ).rejects.toThrow('confirm'); + expect(http).not.toHaveBeenCalled(); + expect( + await runDevicesCommand('device-lan', ['enable'], { confirm: true }, async () => ({ http })), + ).toEqual({ state: 'listening' }); + expect(http.mock.calls[0]).toEqual([ + '/api/botharness/devices/lan', + { action: 'enable', confirm: true }, + ]); + await runDevicesCommand('device-lan', ['disable'], {}, async () => ({ http })); + expect(http.mock.calls[1]).toEqual([ + '/api/botharness/devices/lan', + { action: 'disable', confirm: false }, + ]); + }); it('requires explicit confirmation and sends the exact key with its offer receipt', async () => { const http = vi.fn(async () => reply({ approved: true })); const key = 'ab'.repeat(32); diff --git a/packages/core/test/connect-encrypted-gateway.test.ts b/packages/core/test/connect-encrypted-gateway.test.ts index dd22d91db4..02668a2e26 100644 --- a/packages/core/test/connect-encrypted-gateway.test.ts +++ b/packages/core/test/connect-encrypted-gateway.test.ts @@ -12,173 +12,176 @@ import { attachOperationalModule, mountOperationalDatabase } from '../src/databa import { BOT_HARNESS_SCHEMA_PLAN } from '../src/database/schema-plan.js'; import { createTempRoot, trackTestOwner } from './helpers.js'; -it('admits only the approved Noise key, forwards private RPC and push settings, and closes on device revocation', async () => { - const owner = trackTestOwner( - mountOperationalDatabase({ - dshHome: createTempRoot('noise-gateway-'), - schemaPlan: BOT_HARNESS_SCHEMA_PLAN, - }), - ); - const pairing = createDevicePairing({ - database: attachOperationalModule(owner, 'device-pairing'), - hostName: 'Host', - }); - const hostKey = randomBytes(32), - deviceKey = randomBytes(32); - const publicKey = Buffer.from(noisePublicKey(deviceKey)).toString('hex'); - const offer = pairing.createOffer(); - pairing.requestKey({ offer: offer.offer, publicKey }); - pairing.approveKey(offer.receipt, publicKey); - const paired = pairing.redeem({ offer: offer.offer, publicKey }); - if (!paired.ok) throw new Error('pairing failed'); - const observed: string[] = []; - const server = createServer(async (request, response) => { - expect(request.headers.authorization).toBe(`Device ${paired.credential}`); - if (request.url === '/botharness-device/push') { - response.setHeader('content-type', 'application/json'); - response.end( - JSON.stringify({ - registered: false, - enabled: false, - preferences: { approval: true, question: true, 'private-input': true, reply: true }, - quietChannelIds: [], - }), - ); - return; - } - let body = ''; - for await (const chunk of request) body += String(chunk); - response.end(body); - }); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); - const port = (server.address() as AddressInfo).port; - const gateway = createEncryptedGateway({ - pairing, - key: async () => Uint8Array.from(hostKey), - port: () => port, - }); - server.on('upgrade', (req, socket, head) => gateway.upgrade(req, socket, head)); - const channel = new ConnectChannel({ - role: 'initiator', - hostId: pairing.host().id, - staticKey: deviceKey, - ephemeralKey: randomBytes(32), - hostKey: noisePublicKey(hostKey), - }); - const socket = new WebSocket(`ws://127.0.0.1:${port}/botharness-device/channel`); - const answers: Record[] = []; - let next: (() => void) | undefined; - socket.on('message', (data) => { - const wire = data.toString(); - observed.push(wire); - const result = channel.receive(wire); - if (result.reply) socket.send(result.reply); - if (result.ready) - for (const frame of channel.send( - JSON.stringify({ type: 'admit', credential: paired.credential }), - )) - socket.send(frame); - if (result.message) { - answers.push(JSON.parse(result.message)); - next?.(); - } - }); - const wait = async () => { - if (answers.length) return answers.shift()!; - await new Promise((resolve) => { - next = resolve; - }); - next = undefined; - return answers.shift()!; - }; - try { - await new Promise((resolve) => socket.once('open', resolve)); - socket.send(channel.start()); - expect(await wait()).toMatchObject({ type: 'admitted' }); - const sentinel = 'disposable-private-value'; - for (const frame of channel.send( - JSON.stringify({ - type: 'request', - id: '1', - method: 'POST', - path: '/botharness-device/api/botharness/privateInputSubmit', - body: sentinel, +it.each(['connect', 'lan'] as const)( + '%s admits only the approved Noise key, forwards private RPC and push settings, and closes on device revocation', + async (route) => { + const origin = route === 'lan' ? 'http://192.168.1.20:39101' : 'https://host.deepseekbot.dev'; + const owner = trackTestOwner( + mountOperationalDatabase({ + dshHome: createTempRoot('noise-gateway-'), + schemaPlan: BOT_HARNESS_SCHEMA_PLAN, }), - )) { - observed.push(frame); - socket.send(frame); - } - const answer = await wait(); - expect(Buffer.from(String(answer.body), 'base64').toString()).toBe(sentinel); - expect(observed.join('')).not.toContain(sentinel); - const carrier = encryptedCarrier({ + ); + const pairing = createDevicePairing({ + database: attachOperationalModule(owner, 'device-pairing'), + hostName: 'Host', + }); + const hostKey = randomBytes(32), + deviceKey = randomBytes(32); + const publicKey = Buffer.from(noisePublicKey(deviceKey)).toString('hex'); + const offer = pairing.createOffer(); + pairing.requestKey({ offer: offer.offer, publicKey }); + pairing.approveKey(offer.receipt, publicKey); + const paired = pairing.redeem({ offer: offer.offer, publicKey }); + if (!paired.ok) throw new Error('pairing failed'); + const observed: string[] = []; + const server = createServer(async (request, response) => { + expect(request.headers.authorization).toBe(`Device ${paired.credential}`); + if (request.url === '/botharness-device/push') { + response.setHeader('content-type', 'application/json'); + response.end( + JSON.stringify({ + registered: false, + enabled: false, + preferences: { approval: true, question: true, 'private-input': true, reply: true }, + quietChannelIds: [], + }), + ); + return; + } + let body = ''; + for await (const chunk of request) body += String(chunk); + response.end(body); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const port = (server.address() as AddressInfo).port; + const gateway = createEncryptedGateway({ + route, + pairing, + key: async () => Uint8Array.from(hostKey), + port: () => port, + }); + server.on('upgrade', (req, socket, head) => gateway.upgrade(req, socket, head)); + const channel = new ConnectChannel({ + route, + role: 'initiator', hostId: pairing.host().id, - credential: paired.credential, - encryption: { - protocol: 'connect-noise-xk-v1', - hostKey: Buffer.from(noisePublicKey(hostKey)).toString('hex'), - deviceKey: deviceKey.toString('hex'), - }, - raw: { - request: async () => { - throw new Error('plaintext request forbidden'); - }, - openSocket: (url, events, headers) => { - expect(headers).toBeUndefined(); - expect(url).toBe('wss://host.deepseekbot.dev/botharness-device/channel'); - const peer = new WebSocket(`ws://127.0.0.1:${port}/botharness-device/channel`); - peer.on('open', events.open); - peer.on('message', (data) => events.message(data.toString())); - peer.on('close', () => events.closed('closed')); - peer.on('error', () => events.closed('error')); - return { - send: (text) => { - observed.push(text); - peer.send(text); - }, - close: () => peer.close(), - }; - }, - }, + staticKey: deviceKey, + ephemeralKey: randomBytes(32), + hostKey: noisePublicKey(hostKey), + }); + const socket = new WebSocket(`ws://127.0.0.1:${port}/botharness-device/channel`); + const answers: Record[] = []; + let next: (() => void) | undefined; + socket.on('message', (data) => { + const wire = data.toString(); + observed.push(wire); + const result = channel.receive(wire); + if (result.reply) socket.send(result.reply); + if (result.ready) + for (const frame of channel.send( + JSON.stringify({ type: 'admit', credential: paired.credential }), + )) + socket.send(frame); + if (result.message) { + answers.push(JSON.parse(result.message)); + next?.(); + } }); + const wait = async () => { + if (answers.length) return answers.shift()!; + await new Promise((resolve) => { + next = resolve; + }); + next = undefined; + return answers.shift()!; + }; try { - const response = await carrier.request( - 'https://host.deepseekbot.dev/botharness-device/api/botharness/privateInputSubmit', - { + await new Promise((resolve) => socket.once('open', resolve)); + socket.send(channel.start()); + expect(await wait()).toMatchObject({ type: 'admitted' }); + const sentinel = 'disposable-private-value'; + for (const frame of channel.send( + JSON.stringify({ + type: 'request', + id: '1', method: 'POST', + path: '/botharness-device/api/botharness/privateInputSubmit', body: sentinel, - headers: { authorization: `Device ${paired.credential}` }, - signal: new AbortController().signal, + }), + )) { + observed.push(frame); + socket.send(frame); + } + const answer = await wait(); + expect(Buffer.from(String(answer.body), 'base64').toString()).toBe(sentinel); + expect(observed.join('')).not.toContain(sentinel); + const carrier = encryptedCarrier({ + hostId: pairing.host().id, + credential: paired.credential, + encryption: { + protocol: 'connect-noise-xk-v1', + hostKey: Buffer.from(noisePublicKey(hostKey)).toString('hex'), + deviceKey: deviceKey.toString('hex'), }, - ); - expect(await response.text()).toBe(sentinel); - const settings = await carrier.request( - 'https://host.deepseekbot.dev/botharness-device/push', - { - method: 'GET', - signal: new AbortController().signal, + raw: { + request: async () => { + throw new Error('plaintext request forbidden'); + }, + openSocket: (url, events, headers) => { + expect(headers).toBeUndefined(); + expect(url).toBe(`${origin.replace(/^http/u, 'ws')}/botharness-device/channel`); + const peer = new WebSocket(`ws://127.0.0.1:${port}/botharness-device/channel`); + peer.on('open', events.open); + peer.on('message', (data) => events.message(data.toString())); + peer.on('close', () => events.closed('closed')); + peer.on('error', () => events.closed('error')); + return { + send: (text) => { + observed.push(text); + peer.send(text); + }, + close: () => peer.close(), + }; + }, }, - ); - expect(settings.status).toBe(200); - expect(JSON.parse(await settings.text())).toMatchObject({ - registered: false, - quietChannelIds: [], }); + try { + const response = await carrier.request( + `${origin}/botharness-device/api/botharness/privateInputSubmit`, + { + method: 'POST', + body: sentinel, + headers: { authorization: `Device ${paired.credential}` }, + signal: new AbortController().signal, + }, + ); + expect(await response.text()).toBe(sentinel); + const settings = await carrier.request(`${origin}/botharness-device/push`, { + method: 'GET', + signal: new AbortController().signal, + }); + expect(settings.status).toBe(200); + expect(JSON.parse(await settings.text())).toMatchObject({ + registered: false, + quietChannelIds: [], + }); - expect(observed.join('')).not.toContain(paired.credential); + expect(observed.join('')).not.toContain(paired.credential); + } finally { + carrier.close?.(); + } + const closed = new Promise((resolve) => socket.once('close', () => resolve())); + pairing.revoke(paired.device.id); + await closed; } finally { - carrier.close?.(); + socket.terminate(); + channel.close(); + gateway.close(); + await new Promise((resolve) => server.close(() => resolve())); } - const closed = new Promise((resolve) => socket.once('close', () => resolve())); - pairing.revoke(paired.device.id); - await closed; - } finally { - socket.terminate(); - channel.close(); - gateway.close(); - await new Promise((resolve) => server.close(() => resolve())); - } -}); + }, +); async function endpointFixture() { const owner = trackTestOwner( diff --git a/packages/core/test/connect-noise.test.ts b/packages/core/test/connect-noise.test.ts index f9b6384294..501bed1ea4 100644 --- a/packages/core/test/connect-noise.test.ts +++ b/packages/core/test/connect-noise.test.ts @@ -1,6 +1,36 @@ import { describe, expect, it } from 'vitest'; import vector from './fixtures/noise/xk-cacophony.json'; import { NoiseXk } from '../src/devices/noise/xk.js'; +import { noisePublicKey } from '../src/devices/noise/xk.js'; +import { ConnectChannel } from '../src/devices/noise/channel.js'; +import { randomBytes } from 'node:crypto'; + +it('refuses a Connect handshake replayed at the LAN entry', () => { + const key = randomBytes(32); + const hostKey = noisePublicKey(key); + const phone = new ConnectChannel({ + role: 'initiator', + hostId: 'host', + staticKey: randomBytes(32), + ephemeralKey: randomBytes(32), + hostKey, + route: 'connect', + }); + const host = new ConnectChannel({ + role: 'responder', + hostId: 'host', + staticKey: key, + ephemeralKey: randomBytes(32), + hostKey, + route: 'lan', + }); + try { + expect(() => host.receive(phone.start())).toThrow(); + } finally { + phone.close(); + host.close(); + } +}); const bytes = (hex: string) => Uint8Array.from(Buffer.from(hex, 'hex')); const hex = (value: Uint8Array) => Buffer.from(value).toString('hex'); diff --git a/packages/core/test/device-lan.test.ts b/packages/core/test/device-lan.test.ts new file mode 100644 index 0000000000..450e40bff0 --- /dev/null +++ b/packages/core/test/device-lan.test.ts @@ -0,0 +1,240 @@ +import { createServer, request } from 'node:http'; +import { randomBytes } from 'node:crypto'; +import type { AddressInfo } from 'node:net'; +import { WebSocket } from 'ws'; +import { expect, it, vi } from 'vitest'; +import { createDeviceLan } from '../src/devices/lan.js'; +import { createEncryptedGateway } from '../src/devices/encrypted-gateway.js'; +import { createDevicePairing } from '../src/devices/pairing.js'; +import { createDevicesHttp } from '../src/devices/http.js'; +import { noisePublicKey } from '../src/devices/noise/xk.js'; +import { attachOperationalModule, mountOperationalDatabase } from '../src/database/owner.js'; +import { BOT_HARNESS_SCHEMA_PLAN } from '../src/database/schema-plan.js'; +import { createTempRoot, trackTestOwner } from './helpers.js'; +import { pairHost } from '../../../apps/mobile/src/host/pairing.js'; +import { encryptedCarrier } from '../../../apps/mobile/src/host/encrypted-carrier.js'; +import type { SavedHost } from '../../../apps/mobile/src/host/hosts.js'; +import type { HostCarrier } from '../../../apps/mobile/src/host/carrier.js'; + +it('opens only after opt-in, never serves operator HTTP, persists its port and releases it on disable', async () => { + let saved: number | undefined; + let closed = 0; + const log = vi.fn(); + const lan = createDeviceLan({ + log, + read: async () => saved, + write: async (port) => { + saved = port; + }, + gateway: () => ({ + upgrade: (_request, socket) => socket.destroy(), + close: () => { + closed++; + }, + }), + addresses: () => ['192.168.1.20'], + }); + try { + await lan.start(); + expect(lan.status()).toEqual({ state: 'off' }); + expect(lan.routes()).toEqual([]); + const enabled = await lan.enable(); + expect(enabled.ok).toBe(true); + expect(saved).toBeGreaterThan(0); + expect(lan.routes()).toEqual([ + { kind: 'lan', ready: true, url: `http://192.168.1.20:${saved}` }, + ]); + for (const path of ['/', '/api', '/botharness-device/pair', '/botharness-device/channel']) { + const status = await new Promise((resolve, reject) => { + const req = request({ host: '127.0.0.1', port: saved, path }, (res) => { + res.resume(); + resolve(res.statusCode); + }); + req.on('error', reject); + req.end(); + }); + expect(status).toBe(404); + } + expect((await lan.disable()).ok).toBe(true); + expect(saved).toBeUndefined(); + expect(closed).toBe(1); + expect(lan.routes()).toEqual([]); + expect(log.mock.calls.map(([event]) => event)).toEqual([ + { initiator: 'startup', phase: 'restore', durationMs: expect.any(Number) }, + { initiator: 'operator', phase: 'enable', durationMs: expect.any(Number) }, + { initiator: 'operator', phase: 'disable', durationMs: expect.any(Number) }, + ]); + } finally { + await lan.close(); + } +}); + +it('pairs a scanned LAN offer with exact key approval, encrypts a phone request, then enforces revocation', async () => { + const owner = trackTestOwner( + mountOperationalDatabase({ + dshHome: createTempRoot('lan-pair-'), + schemaPlan: BOT_HARNESS_SCHEMA_PLAN, + }), + ); + const pairing = createDevicePairing({ + database: attachOperationalModule(owner, 'device-pairing'), + hostName: 'LAN Host', + }); + const key = randomBytes(32); + const upstream = createServer((req, res) => { + expect(req.url).toBe('/botharness-device/api/botharness/list'); + expect(pairing.admit(req.headers.authorization).ok).toBe(true); + res.end('private-host-feed'); + }); + await new Promise((resolve) => upstream.listen(0, '127.0.0.1', resolve)); + const lan = createDeviceLan({ + read: async () => undefined, + write: async () => {}, + addresses: () => ['192.168.1.21', '192.168.1.20'], + gateway: () => + createEncryptedGateway({ + pairing, + key: async () => Uint8Array.from(key), + port: () => (upstream.address() as AddressInfo).port, + route: 'lan', + }), + }); + const http = createDevicesHttp({ + pairing, + lan, + encryption: async () => ({ + protocol: 'connect-noise-xk-v1', + noise: 'Noise_XK_25519_ChaChaPoly_SHA256', + required: true, + publicKey: Buffer.from(noisePublicKey(key)).toString('hex'), + fingerprint: 'test', + state: 'disconnected', + }), + routes: async () => ({ routes: lan.routes(), tailscale: 'missing', serveCommand: '' }), + }); + const wire: string[] = []; + let saved: SavedHost | undefined; + let carrier: HostCarrier | undefined; + const post = (path: string, body: object) => + http( + new Request(`http://localhost/api/botharness/devices/${path}`, { + method: 'POST', + body: JSON.stringify(body), + }), + ); + try { + expect((await post('lan', { action: 'enable' })).status).toBe(400); + expect(lan.status().state).toBe('off'); + expect((await post('lan', { action: 'enable', confirm: true })).status).toBe(200); + const raw: HostCarrier = { + request: async () => { + throw new Error('plaintext forbidden'); + }, + openSocket: (url, events, headers) => { + expect(headers).toBeUndefined(); + if (url.startsWith('ws://192.168.1.21:')) { + queueMicrotask(() => events.closed('channel-send-failed')); + return { send: () => {}, close: () => {} }; + } + const ws = new WebSocket(`ws://127.0.0.1:${lan.status().port}/botharness-device/channel`); + ws.on('open', events.open); + ws.on('message', (data) => { + wire.push(data.toString()); + events.message(data.toString()); + }); + ws.on('close', () => events.closed('closed')); + ws.on('error', () => events.closed('error')); + return { + send: (text) => { + wire.push(text); + ws.send(text); + }, + close: () => ws.terminate(), + }; + }, + }; + const offer = await (await post('offer', {})).json(); + expect(offer.reachable).toBe(true); + const result = await pairHost({ + text: offer.link, + method: 'qr', + deviceName: 'Test phone', + carrier: raw, + telemetry: { pairing: () => ({ finish: () => {} }) }, + onPending: () => { + const pending = pairing.pendingKeys()[0]!; + expect(pairing.approveKey(pending.receipt, 'ff'.repeat(32))).toBe(false); + expect(pairing.approveKey(pending.receipt, pending.publicKey)).toBe(true); + }, + save: async (host) => { + saved = host; + }, + }); + expect(result).toEqual({ ok: true }); + expect(saved?.routes[0]).toContain('192.168.1.20'); + expect(saved?.encryption).toBeDefined(); + carrier = encryptedCarrier({ raw, ...saved! }); + const read = () => + carrier!.request(`${saved!.routes[0]}/botharness-device/api/botharness/list`, { + method: 'POST', + body: 'private-phone-input', + signal: new AbortController().signal, + }); + expect(await (await read()).text()).toBe('private-host-feed'); + expect(wire.join('')).not.toContain('private-host-feed'); + expect(wire.join('')).not.toContain('private-phone-input'); + expect(wire.join('')).not.toContain(saved!.credential); + pairing.revoke(saved!.deviceId); + await expect(read()).rejects.toThrow(); + await post('lan', { action: 'disable' }); + expect(lan.status()).toEqual({ state: 'off' }); + } finally { + carrier?.close?.(); + await lan.close(); + await new Promise((resolve) => upstream.close(() => resolve())); + } +}); + +it('restores an opted-in port after restart and fails closed when persistence fails', async () => { + let saved: number | undefined; + const options = { + read: async () => saved, + write: async (port: number | undefined) => { + saved = port; + }, + gateway: () => ({ upgrade: () => {}, close: () => {} }), + }; + const first = createDeviceLan(options); + const second = createDeviceLan(options); + try { + await first.enable(); + const port = first.status().port; + await first.close(); + await second.start(); + expect(second.status()).toEqual({ state: 'listening', port }); + await second.disable(); + const log = vi.fn(); + const failed = createDeviceLan({ + ...options, + log, + write: async () => { + throw new Error('disk'); + }, + }); + try { + expect(await failed.enable()).toEqual({ ok: false, code: 'lan-storage-unavailable' }); + expect(failed.status().state).toBe('off'); + expect(log).toHaveBeenCalledWith({ + initiator: 'operator', + phase: 'enable', + durationMs: expect.any(Number), + refusal: 'lan-storage-unavailable', + }); + } finally { + await failed.close(); + } + } finally { + await first.close(); + await second.close(); + } +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 51ab0e0c9a..671adfea75 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -403,7 +403,7 @@ importers: version: 6.0.2(patch_hash=2d9cefa269045271145e1989e004232aac3c206249494311d39f49c13293dddb)(expo@58.0.17)(supports-color@10.2.2)(typescript@5.9.3) expo-router: specifier: ~58.0.25 - version: 58.0.25(acb4e9680f18e50f6637fcab920d1ed1) + version: 58.0.25(58988f3bca6bc559c6f1e94dfef101fd) expo-secure-store: specifier: ~58.0.2 version: 58.0.2(expo@58.0.17) @@ -496,8 +496,8 @@ importers: specifier: ~19.3.0 version: 19.3.0 '@types/react-dom': - specifier: ~19.2.7 - version: 19.2.7(@types/react@19.3.0) + specifier: ~19.3.0 + version: 19.3.0(@types/react@19.3.0) expo-doctor: specifier: 1.21.4 version: 1.21.4 @@ -7548,11 +7548,6 @@ packages: peerDependencies: '@types/react': ^18.0.0 - '@types/react-dom@19.2.7': - resolution: {integrity: sha512-I8bPpDLcHBv1qiIiXDCy71Rt8eQDKJP0sMSWJphDdAcdqiJ1sGpZamavoEIRZmYzjia9LuEb2HlYdDpmoENpvQ==} - peerDependencies: - '@types/react': ^19.2.0 - '@types/react-dom@19.3.0': resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} peerDependencies: @@ -18314,7 +18309,7 @@ snapshots: ws: 8.21.3 zod: 3.25.76 optionalDependencies: - expo-router: 58.0.25(acb4e9680f18e50f6637fcab920d1ed1) + expo-router: 58.0.25(58988f3bca6bc559c6f1e94dfef101fd) react-native: 0.88.0(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.87.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2) transitivePeerDependencies: - '@expo/dom-webview' @@ -18713,7 +18708,7 @@ snapshots: react: 19.3.0 optionalDependencies: '@expo/metro-runtime': 58.0.15(@expo/log-box@58.0.13)(expo@58.0.17)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.87.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0) - expo-router: 58.0.25(acb4e9680f18e50f6637fcab920d1ed1) + expo-router: 58.0.25(58988f3bca6bc559c6f1e94dfef101fd) react-dom: 19.3.0(react@19.3.0) transitivePeerDependencies: - supports-color @@ -19799,18 +19794,18 @@ snapshots: '@radix-ui/primitive@1.2.0': {} - '@radix-ui/react-collection@1.2.0(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + '@radix-ui/react-collection@1.2.0(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': dependencies: '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.3.0)(react@19.3.0) '@radix-ui/react-context': 1.3.0(@types/react@19.3.0)(react@19.3.0) - '@radix-ui/react-primitive': 2.2.0(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@radix-ui/react-slot': 1.5.0(@types/react@19.3.0)(react@19.3.0) '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.3.0)(react@19.3.0) react: 19.3.0 react-dom: 19.3.0(react@19.3.0) optionalDependencies: '@types/react': 19.3.0 - '@types/react-dom': 19.2.7(@types/react@19.3.0) + '@types/react-dom': 19.3.0(@types/react@19.3.0) '@radix-ui/react-compose-refs@1.1.5(@types/react@19.3.0)(react@19.3.0)': dependencies: @@ -19915,14 +19910,14 @@ snapshots: '@types/react': 19.3.0 '@types/react-dom': 19.3.0(@types/react@19.3.0) - '@radix-ui/react-presence@1.1.11(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + '@radix-ui/react-presence@1.1.11(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': dependencies: '@radix-ui/react-use-layout-effect': 1.1.4(@types/react@19.3.0)(react@19.3.0) react: 19.3.0 react-dom: 19.3.0(react@19.3.0) optionalDependencies: '@types/react': 19.3.0 - '@types/react-dom': 19.2.7(@types/react@19.3.0) + '@types/react-dom': 19.3.0(@types/react@19.3.0) '@radix-ui/react-primitive@2.1.10(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': dependencies: @@ -19933,24 +19928,24 @@ snapshots: '@types/react': 19.3.0 '@types/react-dom': 19.3.0(@types/react@19.3.0) - '@radix-ui/react-primitive@2.2.0(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + '@radix-ui/react-primitive@2.2.0(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': dependencies: '@radix-ui/react-slot': 1.5.0(@types/react@19.3.0)(react@19.3.0) react: 19.3.0 react-dom: 19.3.0(react@19.3.0) optionalDependencies: '@types/react': 19.3.0 - '@types/react-dom': 19.2.7(@types/react@19.3.0) + '@types/react-dom': 19.3.0(@types/react@19.3.0) - '@radix-ui/react-roving-focus@1.2.1(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + '@radix-ui/react-roving-focus@1.2.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': dependencies: '@radix-ui/primitive': 1.2.0 - '@radix-ui/react-collection': 1.2.0(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@radix-ui/react-collection': 1.2.0(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@radix-ui/react-compose-refs': 1.1.5(@types/react@19.3.0)(react@19.3.0) '@radix-ui/react-context': 1.3.0(@types/react@19.3.0)(react@19.3.0) '@radix-ui/react-direction': 1.2.0(@types/react@19.3.0)(react@19.3.0) '@radix-ui/react-id': 1.1.4(@types/react@19.3.0)(react@19.3.0) - '@radix-ui/react-primitive': 2.2.0(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@radix-ui/react-use-callback-ref': 1.1.5(@types/react@19.3.0)(react@19.3.0) '@radix-ui/react-use-controllable-state': 1.3.0(@types/react@19.3.0)(react@19.3.0) '@radix-ui/react-use-is-hydrated': 0.1.3(@types/react@19.3.0)(react@19.3.0) @@ -19959,7 +19954,7 @@ snapshots: react-dom: 19.3.0(react@19.3.0) optionalDependencies: '@types/react': 19.3.0 - '@types/react-dom': 19.2.7(@types/react@19.3.0) + '@types/react-dom': 19.3.0(@types/react@19.3.0) '@radix-ui/react-slot@1.3.3(@types/react@19.3.0)(react@19.3.0)': dependencies: @@ -19975,21 +19970,21 @@ snapshots: optionalDependencies: '@types/react': 19.3.0 - '@radix-ui/react-tabs@1.2.1(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': + '@radix-ui/react-tabs@1.2.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': dependencies: '@radix-ui/primitive': 1.2.0 '@radix-ui/react-context': 1.3.0(@types/react@19.3.0)(react@19.3.0) '@radix-ui/react-direction': 1.2.0(@types/react@19.3.0)(react@19.3.0) '@radix-ui/react-id': 1.1.4(@types/react@19.3.0)(react@19.3.0) - '@radix-ui/react-presence': 1.1.11(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) - '@radix-ui/react-primitive': 2.2.0(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) - '@radix-ui/react-roving-focus': 1.2.1(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@radix-ui/react-presence': 1.1.11(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@radix-ui/react-primitive': 2.2.0(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@radix-ui/react-roving-focus': 1.2.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@radix-ui/react-use-controllable-state': 1.3.0(@types/react@19.3.0)(react@19.3.0) react: 19.3.0 react-dom: 19.3.0(react@19.3.0) optionalDependencies: '@types/react': 19.3.0 - '@types/react-dom': 19.2.7(@types/react@19.3.0) + '@types/react-dom': 19.3.0(@types/react@19.3.0) '@radix-ui/react-use-callback-ref@1.1.4(@types/react@19.3.0)(react@19.3.0)': dependencies: @@ -20907,10 +20902,6 @@ snapshots: dependencies: '@types/react': 18.3.31 - '@types/react-dom@19.2.7(@types/react@19.3.0)': - dependencies: - '@types/react': 19.3.0 - '@types/react-dom@19.3.0(@types/react@19.3.0)': dependencies: '@types/react': 19.3.0 @@ -22834,13 +22825,13 @@ snapshots: - typescript - webpack - expo-router@58.0.25(acb4e9680f18e50f6637fcab920d1ed1): + expo-router@58.0.25(58988f3bca6bc559c6f1e94dfef101fd): dependencies: '@expo/log-box': 58.0.13(@expo/dom-webview@58.0.2)(expo@58.0.17)(react-native@0.88.0(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.87.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0) '@expo/metro-runtime': 58.0.15(@expo/log-box@58.0.13)(expo@58.0.17)(react-dom@19.3.0(react@19.3.0))(react-native@0.88.0(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.87.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0) '@expo/schema-utils': 58.0.2 '@radix-ui/react-slot': 1.5.0(@types/react@19.3.0)(react@19.3.0) - '@radix-ui/react-tabs': 1.2.1(@types/react-dom@19.2.7(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) + '@radix-ui/react-tabs': 1.2.1(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) '@react-native-masked-view/masked-view': 0.3.2(react-native@0.88.0(@babel/core@7.29.7(supports-color@10.2.2))(@react-native/metro-config@0.87.1(@babel/core@7.29.7(supports-color@10.2.2))(supports-color@10.2.2))(@types/react@19.3.0)(react@19.3.0)(supports-color@10.2.2))(react@19.3.0) '@react-native/normalize-colors': 0.88.0 client-only: 0.0.1 diff --git a/scripts/ci-plan.mjs b/scripts/ci-plan.mjs index db79b7383e..712be35e2b 100644 --- a/scripts/ci-plan.mjs +++ b/scripts/ci-plan.mjs @@ -81,6 +81,7 @@ export const RULES = [ none('apps/mobile/modules/**', 'Local Expo modules, checked by Android native unit tests'), none('apps/mobile/targets/**', 'Apple extension targets, built on a Mac by Expo prebuild'), related('apps/mobile/{app.json,app.config.js,eas.json,metro.config.js}', 'Mobile app config'), + related('apps/mobile/with-*.js', 'Mobile native config plugins'), related('apps/mobile/locales/**', 'Translated iOS permission prompts'), related('apps/mobile/assets/**', 'Mobile app icons and bundled images'), none('apps/mobile/.maestro/**', 'Maestro flows, run on a Mac simulator'), diff --git a/scripts/cli-ui-inventory.json b/scripts/cli-ui-inventory.json index 9622c60a86..4f5c4788b5 100644 --- a/scripts/cli-ui-inventory.json +++ b/scripts/cli-ui-inventory.json @@ -62,7 +62,8 @@ "description": "Device list, offers, offer status and revoke; the Connect tunnel action on the same route family has connect-status/enable/disable/sign-in/sign-out.", "scope": "Profile", "surfaces": [ - "route:packages/core/src/devices/mount.ts:path in [ [DEVICES_PATH, ['GET']], [`${DEVICES_PATH}/offer`, ['POST']], [`${DEVICES_PATH}/offer-status`, ['POST']], [`${DEVICES_PATH}/approve-key`, ['POST']], [`${DEVICES_PATH}/revoke`, ['POST']], [`${DEVICES_PATH}/connect`, ['POST']], ] as const", + "route:packages/core/src/devices/mount.ts:path in [ [DEVICES_PATH, ['GET']], [`${DEVICES_PATH}/offer`, ['POST']], [`${DEVICES_PATH}/offer-status`, ['POST']], [`${DEVICES_PATH}/approve-key`, ['POST']], [`${DEVICES_PATH}/revoke`, ['POST']], [`${DEVICES_PATH}/connect`, ['POST']], [`${DEVICES_PATH}/lan`, ['POST']], ] as const", + "setting:packages/client/src/client/paired-devices.tsx:{t('devices.lan.title')}", "setting:packages/client/src/client/paired-devices.tsx:{device.name}", "setting:packages/client/src/client/paired-devices.tsx:{item.name}", "route:packages/core/src/devices/mount.ts:CONNECT_CHANNEL_PATH", @@ -73,6 +74,7 @@ "device-offer", "device-offer-status", "device-approve-key", + "device-lan", "device-revoke", "connect-enable", "connect-disable" diff --git a/tsconfig.json b/tsconfig.json index 22ca00953a..763c493f67 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -44,6 +44,7 @@ "exclude": [ "apps/mobile/test/posthog-sender.test.ts", "apps/mobile/test/native-telemetry.test.ts", + "apps/mobile/test/native-lan-socket.test.ts", "apps/mobile/test/native-persistence.test.ts", "apps/mobile/test/native-chat-background.test.ts", "apps/mobile/test/inbox-screens.test.ts",