Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion .agents/skills/verify-deepseekbot/features/phone-pairing.md
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/verify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }})
Expand Down
2 changes: 1 addition & 1 deletion apps/mobile/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
1 change: 1 addition & 0 deletions apps/mobile/app.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ module.exports = ({ config }) => {
bundleIdentifier,
infoPlist: {
...config.ios.infoPlist,
NSAppTransportSecurity: { NSAllowsLocalNetworking: true },
ITSAppUsesNonExemptEncryption: false,
NSUserActivityTypes: ['INSendMessageIntent'],
},
Expand Down
2 changes: 2 additions & 0 deletions apps/mobile/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
}
Expand All @@ -31,6 +32,7 @@
}
},
"plugins": [
"./with-lan-channel",
"expo-router",
[
"expo-splash-screen",
Expand Down
9 changes: 9 additions & 0 deletions apps/mobile/app/pair/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ export default function PairChoiceScreen() {
<DrawerHeader title={t.pairTitle} onClose={() => router.back()} />
<Text tone="muted">{t.pairChoice.intro}</Text>
<SettingsSection on={SHEET_GROUP}>
<SettingsRow
testID="pair-choice-lan"
on={SHEET_GROUP}
title={t.pairChoice.lan}
detail={t.pairChoice.lanDetail}
leading={<RowIcon name="qr" />}
disclosure
onPress={() => router.push({ pathname: '/pair/tailscale', params: { mode: 'lan' } })}
/>
<SettingsRow
testID="pair-choice-account"
on={SHEET_GROUP}
Expand Down
11 changes: 8 additions & 3 deletions apps/mobile/app/pair/tailscale.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { CameraView, useCameraPermissions } from 'expo-camera';
import { useFocusEffect, useLocalSearchParams } from 'expo-router';
import { Stack, useFocusEffect, useLocalSearchParams } from 'expo-router';
import { useCallback, useRef, useState } from 'react';
import { Pressable, View, useWindowDimensions } from 'react-native';

Expand All @@ -21,7 +21,7 @@ export default function PairTailscaleScreen() {
const theme = useDesignTheme();
const { width } = useWindowDimensions();
const scan = Math.min(width * pairingScan.widthRatio, pairingScan.maxSize);
const params = useLocalSearchParams<{ p?: string }>();
const params = useLocalSearchParams<{ p?: string; mode?: string }>();
const [permission, requestPermission] = useCameraPermissions();
const [link, setLink] = useState('');
const [focused, setFocused] = useState(false);
Expand Down Expand Up @@ -56,7 +56,12 @@ export default function PairTailscaleScreen() {
style={{ flex: 1, backgroundColor: theme.overlay.fill }}
contentContainerStyle={{ padding: space.x5, gap: space.x4 }}
>
<Text tone="muted">{t.pairChoice.tailscaleHint}</Text>
<Stack.Screen
options={{ title: params.mode === 'lan' ? t.pairChoice.lan : t.pairChoice.tailscale }}
/>
<Text tone="muted">
{params.mode === 'lan' ? t.pairChoice.lanHint : t.pairChoice.tailscaleHint}
</Text>
<View
style={{
alignItems: 'center',
Expand Down
1 change: 1 addition & 0 deletions apps/mobile/locales/zh-Hans.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"ios": {
"NSLocalNetworkUsageDescription": "DeepSeekBot 通过加密连接访问当前网络上的电脑。",
"NSCameraUsageDescription": "DeepSeekBot 使用相机扫描电脑上显示的配对二维码,并拍摄你要发给 Bot 的照片。",
"NSMicrophoneUsageDescription": "DeepSeekBot 使用麦克风把你说的话转成消息,你可以先编辑再发给 Bot。",
"NSPhotoLibraryUsageDescription": "DeepSeekBot 打开你的照片,让你把它们发给 Bot。",
Expand Down
9 changes: 9 additions & 0 deletions apps/mobile/modules/lan-channel/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# LAN channel

Local Expo module for the authenticated Noise carrier. New Android and iOS builds are required; Expo Go and earlier dev clients cannot supply this module.

The module accepts only RFC 1918 IPv4 and an explicit port. It fixes `/botharness-device/channel`, permits no caller headers, refuses redirects, and carries bounded Noise frames. The Host pin and device authority live in the shared TypeScript Noise and pairing owners, not in this module. The Android-only reserved hostname is mapped directly to the supplied IPv4 bytes by a private DNS adapter and is never queried on the network.

Android's `BoundedChannelInput` checks wire lengths before OkHttp assembles a message, including cumulative fragments and a fragment-count budget. iOS sets `maximumMessageSize`. Both also validate the resulting Noise frame text before passing it to JavaScript.

`with-lan-channel.js` installs the scoped Android network policy; `app.config.js` supplies iOS local-network policy. See [the LAN contract](../../../../docs/architecture/lan-phone-v1.md). Use the shared device QA queue for native compilation and runtime checks. CI runs `:lan-channel:testDebugUnitTest`; JavaScript tests alone do not qualify native behavior.
15 changes: 15 additions & 0 deletions apps/mobile/modules/lan-channel/android/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
apply plugin: 'com.android.library'
apply plugin: 'expo-module-gradle-plugin'

group = 'expo.modules.lanchannel'
version = '0.1.0'

android {
namespace 'expo.modules.lanchannel'
defaultConfig { versionCode 1; versionName '0.1.0' }
}

dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.2'
testImplementation 'junit:junit:4.13.2'
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
Original file line number Diff line number Diff line change
@@ -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")
}
Original file line number Diff line number Diff line change
@@ -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<String, Channel>()

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<InetAddress> {
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()
}
Loading
Loading