feat: 控制通道权限分级(仅查看 / 查看+控制 / 全权限)

- 协议新增 msgType=10 access 应答,sessionConfig 增加 access 请求字段,三端同步
- rust_core:解码/编码 Access 事件,收到后入队给界面;send_control 支持 msgType=10
- android_receiver:新增 AccessLevel,被控端按本机上限裁剪请求并回送有效等级
- android_receiver:越权帧真正丢弃——输入/剪贴板需 control,文件子协议需 full 且回错误响应
- android_receiver:主界面增加权限单选(持久化),调整后当前连接立即生效并通知主控端
- flutter_sender:AppSettings 增加请求等级并在设置页可选,连接后自动下发
- flutter_sender:接收 msgType=10 更新有效等级,越权操作在界面禁用并提示
- docs:README/AGENTS 补充权限协议与各操作的最低等级
This commit is contained in:
tongtong committed 2026-11-27 20:55:54 +08:00
1 parent e2020ab595
commit a1c3f79cd8
17 files changed
+504 -25

No files matched your search

+2 -1
View File
@@ -53,7 +53,8 @@ flutter build windows --debug
## 关键约定(改代码前先看) ## 关键约定(改代码前先看)
- **控制帧格式**:`[version:1][msgType:1][sequence:u16][length:u32]` + payload,全小端;外层再套 AEAD(`[8B 明文头][12B nonce][密文][16B tag]`)。 - **控制帧格式**:`[version:1][msgType:1][sequence:u16][length:u32]` + payload,全小端;外层再套 AEAD(`[8B 明文头][12B nonce][密文][16B tag]`)。
- **msgType**:`0` touch / `1` mouse / `2` key / `3` wheel / `4` clipboard / `5` ping / `6` pong / `7` file(JSON 子协议,`op=prepare|chunk|progress|cancel|list`,分片用 `dataB64`) / `8` mirror(投屏请求应答) / `9` sessionConfig(UTF-8 JSON 会话配置)。 - **msgType**:`0` touch / `1` mouse / `2` key / `3` wheel / `4` clipboard / `5` ping / `6` pong / `7` file(JSON 子协议,`op=prepare|chunk|progress|cancel|list`,分片用 `dataB64`) / `8` mirror(投屏请求应答) / `9` sessionConfig(UTF-8 JSON 会话配置,含 `access` 权限请求) / `10` access(权限等级应答 JSON)。
- **权限分级**:被控端 `protocol/AccessLevel.kt` 定义 0=view / 1=control / 2=full;有效等级取「主控端请求」与「被控端上限」较小值,被控端必须真正丢弃越权帧(输入/剪贴板需 control,`msgType=7` 需 full),不能只在界面禁用。
- **中继(`/relay`)**:只承载控制帧,报文信封定义在 `rust_core/src/session/relay.rs`(`relay/1`); - **中继(`/relay`)**:只承载控制帧,报文信封定义在 `rust_core/src/session/relay.rs`(`relay/1`);
改信封必须同步 Android `session/RelayClient.kt`。中继模式禁止投屏(视频/音频仍走 UDP)。 改信封必须同步 Android `session/RelayClient.kt`。中继模式禁止投屏(视频/音频仍走 UDP)。
- **设备指纹**:被控端公布的是**应用签名证书 SHA-256**(`util/Fingerprint.kt`),主控端 TOFU 记录在 - **设备指纹**:被控端公布的是**应用签名证书 SHA-256**(`util/Fingerprint.kt`),主控端 TOFU 记录在
+16 -2
View File
@@ -183,6 +183,7 @@ struct ControlFrameHeader {
u8 version; // 当前 = 1 u8 version; // 当前 = 1
u8 msg_type; // 0=touch 1=mouse 2=key 3=wheel 4=clipboard 5=ping 6=pong u8 msg_type; // 0=touch 1=mouse 2=key 3=wheel 4=clipboard 5=ping 6=pong
// 7=file(JSON 子协议) 8=mirror(投屏请求/应答) 9=sessionConfig(会话配置) // 7=file(JSON 子协议) 8=mirror(投屏请求/应答) 9=sessionConfig(会话配置)
// 10=access(权限等级应答)
u16 sequence; // 递增序号,用于去重/重传 u16 sequence; // 递增序号,用于去重/重传
u32 payload_len; // 负载长度(不包括头部) u32 payload_len; // 负载长度(不包括头部)
}; };
@@ -405,7 +406,7 @@ GET /file/progress ?sessionId= (SSE 或轮询)
- **复用会话密钥**:文件流走已建立的 AES-256-GCM 会话,不再另起 HTTPS 自签证书 - **复用会话密钥**:文件流走已建立的 AES-256-GCM 会话,不再另起 HTTPS 自签证书
- **offset 分片**:原版是"一个文件一次请求",我们加分片 → **断点续传**天然支持 - **offset 分片**:原版是"一个文件一次请求",我们加分片 → **断点续传**天然支持
- **跨网段**:走信令服务器可达路径,不受组播限制 - **跨网段**:走信令服务器可达路径,不受组播限制
- **权限分级**:配对时选"仅投屏"就不能发文件,审计日志统一 - **权限分级**:被控端设上限,非 full 时文件子协议直接拒绝(见 §7),审计日志统一
- **秒传**:sha256 先比对,被控端已有同哈希文件直接跳过 - **秒传**:sha256 先比对,被控端已有同哈希文件直接跳过
### 6.4 并发与限速 ### 6.4 并发与限速
@@ -455,7 +456,7 @@ POST /mirror/request?token= 触发一次投屏确认(便
| 传输 | 控制通道 TLS 1.3 + 自签证书 pinning(`tls=` 指纹),无指纹时明文;控制帧 AES-256-GCM | | 传输 | 控制通道 TLS 1.3 + 自签证书 pinning(`tls=` 指纹),无指纹时明文;控制帧 AES-256-GCM |
| 会话 | ECDH P-256 → AES-256-GCM | | 会话 | ECDH P-256 → AES-256-GCM |
| 媒体 | 派生子密钥,每包 4 字节 MAC 防篡改 | | 媒体 | 派生子密钥,每包 4 字节 MAC 防篡改 |
| 权限 | 配对时选"仅查看 / 查看+控制 / 全权限(含文件)" | | 权限 | 被控端设上限,主控端请求,有效等级取较小值(`msgType=9` 请求 / `msgType=10` 应答) |
| 信令 | 客户端 pin 信令服务器公钥,防中间人 | | 信令 | 客户端 pin 信令服务器公钥,防中间人 |
| 中继 | 信封 `relay/1`,`hs/hsAck` 只交换 ECDH 公钥,帧内容仍是 AEAD 密文,服务器无法解密 | | 中继 | 信封 `relay/1`,`hs/hsAck` 只交换 ECDH 公钥,帧内容仍是 AEAD 密文,服务器无法解密 |
@@ -470,6 +471,19 @@ POST /mirror/request?token= 触发一次投屏确认(便
`tls` 为空表示对端只支持明文控制通道,主控端会跳过 TLS 直接发帧(兼容旧版被控端)。 `tls` 为空表示对端只支持明文控制通道,主控端会跳过 TLS 直接发帧(兼容旧版被控端)。
**权限分级**:等级定义在被控端 `protocol/AccessLevel.kt`(0=仅查看 1=查看+控制 2=全权限),
主控端在 `msgType=9` 会话配置里用 `access` 请求,被控端与本机上限取较小值后用 `msgType=10` 回送
`{"level":1,"name":"control","max":2,"requested":2}`。被控端强制校验,不只是界面灰按钮:
| 操作 | 最低等级 |
| --- | --- |
| 投屏看画面 | view |
| 触摸/鼠标/键盘/滚轮、剪贴板 | control |
| `msgType=7` 文件子协议(浏览/上传/下载) | full |
超出等级的控制帧被直接丢弃(日志去抖),文件请求会被拒但一定回 `{"op":"error",...}`,
避免主控端只能等到超时。被控端主界面可随时下调等级,当前连接立刻生效并推送新等级。
**不用**自写 AES、不用自写 TLS——`rustls` + `ring` 够了。 **不用**自写 AES、不用自写 TLS——`rustls` + `ring` 够了。
--- ---
@@ -13,12 +13,15 @@ import android.view.View
import android.widget.Button import android.widget.Button
import android.widget.ImageView import android.widget.ImageView
import android.widget.LinearLayout import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.RadioGroup
import android.widget.ScrollView import android.widget.ScrollView
import android.widget.Switch import android.widget.Switch
import android.widget.TextView import android.widget.TextView
import android.widget.Toast import android.widget.Toast
import com.ttstd.lancast.receiver.discovery.HostBeacon import com.ttstd.lancast.receiver.discovery.HostBeacon
import com.ttstd.lancast.receiver.file.StorageAccess import com.ttstd.lancast.receiver.file.StorageAccess
import com.ttstd.lancast.receiver.protocol.AccessLevel
import com.ttstd.lancast.receiver.session.PairingCode import com.ttstd.lancast.receiver.session.PairingCode
import com.ttstd.lancast.receiver.util.DeviceIdentity import com.ttstd.lancast.receiver.util.DeviceIdentity
import com.ttstd.lancast.receiver.util.Fingerprint import com.ttstd.lancast.receiver.util.Fingerprint
@@ -98,6 +101,40 @@ class MainActivity : Activity() {
} }
} }
val accessLabel = TextView(this).apply {
text = "允许主控端:"
textSize = 14f
}
val accessButtons = listOf(
AccessLevel.VIEW to "仅查看",
AccessLevel.CONTROL to "查看+控制",
AccessLevel.FULL to "全权限(含文件)",
).map { (level, label) ->
RadioButton(this).apply {
id = View.generateViewId()
text = label
textSize = 13f
tag = level
}
}
val accessGroup = RadioGroup(this).apply {
orientation = RadioGroup.HORIZONTAL
}.also { group ->
accessButtons.forEach(group::addView)
val current = Prefs.accessLevel(this)
accessButtons.firstOrNull { (it.tag as Int) == current }?.isChecked = true
group.setOnCheckedChangeListener { _, checkedId ->
val level = accessButtons.firstOrNull { it.id == checkedId }?.tag as? Int
?: return@setOnCheckedChangeListener
MediaProjectionService.setAccessLevel(this, level)
Toast.makeText(
this,
"已切换为${AccessLevel.name(level)},超出的操作会被丢弃",
Toast.LENGTH_SHORT,
).show()
}
}
val authorize = Button(this).apply { val authorize = Button(this).apply {
text = if (privileged) "系统签名:免授权投屏" else "授权屏幕录制(仅待命,不投屏)" text = if (privileged) "系统签名:免授权投屏" else "授权屏幕录制(仅待命,不投屏)"
isEnabled = !privileged isEnabled = !privileged
@@ -128,6 +165,8 @@ class MainActivity : Activity() {
addView(pairingQr) addView(pairingQr)
addView(autoSwitch) addView(autoSwitch)
addView(confirmSwitch) addView(confirmSwitch)
addView(accessLabel)
addView(accessGroup)
addView(authorize) addView(authorize)
addView(startButton) addView(startButton)
addView(storageInfo) addView(storageInfo)
@@ -20,6 +20,7 @@ import android.view.Display
import android.widget.Toast import android.widget.Toast
import com.ttstd.lancast.receiver.discovery.HostBeacon import com.ttstd.lancast.receiver.discovery.HostBeacon
import com.ttstd.lancast.receiver.file.FileHttpServer import com.ttstd.lancast.receiver.file.FileHttpServer
import com.ttstd.lancast.receiver.protocol.AccessLevel
import com.ttstd.lancast.receiver.protocol.MirrorAction import com.ttstd.lancast.receiver.protocol.MirrorAction
import com.ttstd.lancast.receiver.util.DeviceIdentity import com.ttstd.lancast.receiver.util.DeviceIdentity
import com.ttstd.lancast.receiver.util.Fingerprint import com.ttstd.lancast.receiver.util.Fingerprint
@@ -75,6 +76,25 @@ class MediaProjectionService : Service() {
var filePort = 0 var filePort = 0
private set private set
/** 当前活跃会话,仅供本机界面调整权限使用。 */
@Volatile
private var sessionRef: ReceiverSession? = null
/**
* 调整本机允许主控端使用的最高权限。
*
* 服务未运行时只写偏好设置,下次会话沿用;运行中则立即作用于当前连接。
*/
fun setAccessLevel(context: Context, level: Int) {
val next = AccessLevel.clamp(level)
val active = sessionRef
if (active != null) {
active.setMaxAccess(next)
} else {
Prefs.setAccessLevel(context, next)
}
}
/** 是否有待确认的投屏请求。 */ /** 是否有待确认的投屏请求。 */
@Volatile @Volatile
var pendingRequest = false var pendingRequest = false
@@ -261,6 +281,7 @@ class MediaProjectionService : Service() {
} }
} }
session = created session = created
sessionRef = created
created.start() created.start()
startBeacon() startBeacon()
startFileServer() startFileServer()
@@ -483,6 +504,7 @@ class MediaProjectionService : Service() {
filePort = 0 filePort = 0
session?.stop() session?.stop()
session = null session = null
sessionRef = null
worker.shutdownNow() worker.shutdownNow()
fileServer?.stop() fileServer?.stop()
fileServer = null fileServer = null
@@ -1,6 +1,7 @@
package com.ttstd.lancast.receiver package com.ttstd.lancast.receiver
import android.content.Context import android.content.Context
import com.ttstd.lancast.receiver.protocol.AccessLevel
import java.security.SecureRandom import java.security.SecureRandom
/** /**
@@ -17,6 +18,7 @@ object Prefs {
private const val KEY_FILE_SERVICE = "file_service_enabled" private const val KEY_FILE_SERVICE = "file_service_enabled"
private const val KEY_FILE_TOKEN = "file_token" private const val KEY_FILE_TOKEN = "file_token"
private const val KEY_MIRROR_CONFIRM = "mirror_confirm" private const val KEY_MIRROR_CONFIRM = "mirror_confirm"
private const val KEY_ACCESS_LEVEL = "access_level"
private fun prefs(context: Context) = context.applicationContext private fun prefs(context: Context) = context.applicationContext
.getSharedPreferences(NAME, Context.MODE_PRIVATE) .getSharedPreferences(NAME, Context.MODE_PRIVATE)
@@ -34,6 +36,16 @@ object Prefs {
prefs(context).edit().putBoolean(KEY_MIRROR_CONFIRM, value).apply() prefs(context).edit().putBoolean(KEY_MIRROR_CONFIRM, value).apply()
} }
/** 本机允许主控端使用的最高权限(view / control / full),默认 full 保持旧行为。 */
fun accessLevel(context: Context): Int = AccessLevel.parse(
prefs(context).getString(KEY_ACCESS_LEVEL, null),
AccessLevel.FULL,
)
fun setAccessLevel(context: Context, level: Int) {
prefs(context).edit().putString(KEY_ACCESS_LEVEL, AccessLevel.name(level)).apply()
}
fun fileServiceEnabled(context: Context): Boolean = fun fileServiceEnabled(context: Context): Boolean =
prefs(context).getBoolean(KEY_FILE_SERVICE, true) prefs(context).getBoolean(KEY_FILE_SERVICE, true)
@@ -24,6 +24,7 @@ import com.ttstd.lancast.receiver.encode.VideoEncoder
import com.ttstd.lancast.receiver.file.FileBrowser import com.ttstd.lancast.receiver.file.FileBrowser
import com.ttstd.lancast.receiver.file.FileService import com.ttstd.lancast.receiver.file.FileService
import com.ttstd.lancast.receiver.input.InputInjector import com.ttstd.lancast.receiver.input.InputInjector
import com.ttstd.lancast.receiver.protocol.AccessLevel
import com.ttstd.lancast.receiver.protocol.ControlEvent import com.ttstd.lancast.receiver.protocol.ControlEvent
import com.ttstd.lancast.receiver.session.ReceiverTransport import com.ttstd.lancast.receiver.session.ReceiverTransport
import com.ttstd.lancast.receiver.util.DeviceIdentity import com.ttstd.lancast.receiver.util.DeviceIdentity
@@ -99,6 +100,10 @@ class ReceiverSession(
@Volatile @Volatile
private var clipboardSyncEnabled: Boolean = true private var clipboardSyncEnabled: Boolean = true
/** 本机允许主控端使用的最高权限;改权限立即作用于当前连接并持久化。 */
@Volatile
private var maxAccessLevel: Int = Prefs.accessLevel(context)
/** 编码长边上限:随编码格式变化(软编降一档)。 */ /** 编码长边上限:随编码格式变化(软编降一档)。 */
@Volatile @Volatile
private var maxLongSide: Int = MAX_LONG_SIDE private var maxLongSide: Int = MAX_LONG_SIDE
@@ -199,6 +204,23 @@ class ReceiverSession(
transport?.sendMirror(action, message) transport?.sendMirror(action, message)
} }
/** 当前允许的最高权限等级(`AccessLevel.VIEW/CONTROL/FULL`)。 */
fun maxAccess(): Int = maxAccessLevel
/**
* 调整允许主控端使用的最高权限。
*
* 立即作用于当前连接(超出部分的事件会被丢弃并收到 msgType=10 应答),并写入偏好设置,
* 下次启动沿用。
*/
fun setMaxAccess(level: Int) {
val next = AccessLevel.clamp(level)
maxAccessLevel = next
Prefs.setAccessLevel(context, next)
transport?.maxAccess = next
Log.i(TAG, "本机权限上限设为 ${AccessLevel.name(next)}")
}
val connected: Boolean get() = transport?.keyEstablished == true val connected: Boolean get() = transport?.keyEstablished == true
private fun startCapture() { private fun startCapture() {
@@ -325,6 +347,7 @@ class ReceiverSession(
) )
created.onMirrorEvent = { action, message -> onMirrorRequest?.invoke(action, message) } created.onMirrorEvent = { action, message -> onMirrorRequest?.invoke(action, message) }
created.onSessionConfig = { json -> applySessionConfig(json) } created.onSessionConfig = { json -> applySessionConfig(json) }
created.maxAccess = maxAccessLevel
transport = created transport = created
created.start() created.start()
return return
@@ -82,8 +82,9 @@ class InputInjector(private val context: Context) {
is ControlEvent.Ping, is ControlEvent.Pong -> Unit is ControlEvent.Ping, is ControlEvent.Pong -> Unit
// 投屏请求由 Service 处理,不参与输入注入。 // 投屏请求由 Service 处理,不参与输入注入。
is ControlEvent.Mirror -> Unit is ControlEvent.Mirror -> Unit
// 会话配置由 ReceiverSession 处理。 // 会话配置由 ReceiverSession 处理,权限应答由 ReceiverTransport 处理。
is ControlEvent.SessionConfig -> Unit is ControlEvent.SessionConfig -> Unit
is ControlEvent.Access -> Unit
} }
} }
@@ -0,0 +1,42 @@
package com.ttstd.lancast.receiver.protocol
/**
* 会话权限等级。
*
* 由被控端本机设定上限(持久化在 `Prefs`),主控端在
* msgType=9 会话配置帧里用 `access` 字段请求,被控端取两者较小值作为有效等级,
* 再用 msgType=10 把结果回给主控端。
*
* - [VIEW]:只能看画面(投屏),不能注入输入、不能同步剪贴板、不能访问文件。
* - [CONTROL]:看画面 + 注入触摸/鼠标/键盘/滚轮 + 剪贴板同步。
* - [FULL]:在上面基础上开放文件子协议(浏览/上传/下载)。
*/
object AccessLevel {
const val VIEW = 0
const val CONTROL = 1
const val FULL = 2
const val VIEW_NAME = "view"
const val CONTROL_NAME = "control"
const val FULL_NAME = "full"
/** 解析名称或数字,非法值回落到 [fallback]。 */
fun parse(value: String?, fallback: Int = CONTROL): Int {
val text = value?.trim()?.lowercase().orEmpty()
if (text.isEmpty()) return fallback
return when (text) {
VIEW_NAME, "0", "read", "readonly", "read-only" -> VIEW
CONTROL_NAME, "1" -> CONTROL
FULL_NAME, "2" -> FULL
else -> text.toIntOrNull()?.coerceIn(VIEW, FULL) ?: fallback
}
}
fun name(level: Int): String = when (level.coerceIn(VIEW, FULL)) {
VIEW -> VIEW_NAME
CONTROL -> CONTROL_NAME
else -> FULL_NAME
}
fun clamp(level: Int): Int = level.coerceIn(VIEW, FULL)
}
@@ -22,10 +22,18 @@ sealed class ControlEvent {
* 会话配置(msgType = 9)。 * 会话配置(msgType = 9)。
* *
* payload 是 UTF-8 JSON,字段全部可选: * payload 是 UTF-8 JSON,字段全部可选:
* `preferH265` / `bitrateMbps` / `audioEnabled` / `clipboardSync`。 * `preferH265` / `bitrateMbps` / `audioEnabled` / `clipboardSync` / `access`。
* 主控端在请求投屏之前下发,被控端据此决定编码格式、码率与音频/剪贴板开关。 * 主控端在请求投屏之前下发,被控端据此决定编码格式、码率与音频/剪贴板开关。
*/ */
data class SessionConfig(val json: String) : ControlEvent() data class SessionConfig(val json: String) : ControlEvent()
/**
* 权限等级应答(msgType = 10)。
*
* payload 是 UTF-8 JSON:`{"level":0|1|2,"name":"view|control|full","max":0|1|2,"requested":0|1|2}`。
* 被控端在收到 `access` 请求或本机上限变化后回送,主控端据此禁用超出权限的操作。
*/
data class Access(val json: String) : ControlEvent()
} }
/** /**
@@ -125,6 +133,7 @@ object ControlFrames {
ControlEvent.Mirror(action, message) ControlEvent.Mirror(action, message)
} }
9 -> ControlEvent.SessionConfig(String(payload, StandardCharsets.UTF_8)) 9 -> ControlEvent.SessionConfig(String(payload, StandardCharsets.UTF_8))
10 -> ControlEvent.Access(String(payload, StandardCharsets.UTF_8))
else -> return null else -> return null
} }
return ControlFrame(version, sequence, event) return ControlFrame(version, sequence, event)
@@ -153,6 +162,7 @@ object ControlFrames {
byteArrayOf(event.action.toByte()) + event.message.toByteArray(StandardCharsets.UTF_8) byteArrayOf(event.action.toByte()) + event.message.toByteArray(StandardCharsets.UTF_8)
} }
is ControlEvent.SessionConfig -> event.json.toByteArray(StandardCharsets.UTF_8) is ControlEvent.SessionConfig -> event.json.toByteArray(StandardCharsets.UTF_8)
is ControlEvent.Access -> event.json.toByteArray(StandardCharsets.UTF_8)
} }
return byteArrayOf(VERSION.toByte(), msgType(event).toByte()) + return byteArrayOf(VERSION.toByte(), msgType(event).toByte()) +
u16Bytes(sequence) + u32Bytes(payload.size) + payload u16Bytes(sequence) + u32Bytes(payload.size) + payload
@@ -168,6 +178,7 @@ object ControlFrames {
is ControlEvent.Pong -> 6 is ControlEvent.Pong -> 6
is ControlEvent.Mirror -> 8 is ControlEvent.Mirror -> 8
is ControlEvent.SessionConfig -> 9 is ControlEvent.SessionConfig -> 9
is ControlEvent.Access -> 10
} }
private fun u16(bytes: ByteArray, offset: Int) = private fun u16(bytes: ByteArray, offset: Int) =
@@ -6,6 +6,7 @@ import android.util.Log
import com.ttstd.lancast.receiver.clipboard.ClipboardBridge import com.ttstd.lancast.receiver.clipboard.ClipboardBridge
import com.ttstd.lancast.receiver.file.FileService import com.ttstd.lancast.receiver.file.FileService
import com.ttstd.lancast.receiver.input.InputInjector import com.ttstd.lancast.receiver.input.InputInjector
import com.ttstd.lancast.receiver.protocol.AccessLevel
import com.ttstd.lancast.receiver.protocol.ControlEvent import com.ttstd.lancast.receiver.protocol.ControlEvent
import com.ttstd.lancast.receiver.protocol.ControlFrames import com.ttstd.lancast.receiver.protocol.ControlFrames
import com.ttstd.lancast.receiver.protocol.MirrorAction import com.ttstd.lancast.receiver.protocol.MirrorAction
@@ -31,7 +32,11 @@ import java.util.concurrent.Executors
* 跨网段时(TCP 直连不通)可用信令服务器中继控制通道:协议与直连完全一致, * 跨网段时(TCP 直连不通)可用信令服务器中继控制通道:协议与直连完全一致,
* 只是把加密帧整帧塞进 `/relay` 消息。中继不承载视频/音频,投屏请求会被直接拒绝。 * 只是把加密帧整帧塞进 `/relay` 消息。中继不承载视频/音频,投屏请求会被直接拒绝。
* *
* 握手后控制通道的机密性由控制帧 AES-GCM 保证,demo 阶段不再叠加 TLS。 * 控制通道可叠加 TLS(被控端作为 TLS 服务端出示自签证书,主控端按 `tls` 指纹 pinning),
* 无论是否 TLS,控制帧都要再套一层 AES-GCM。
*
* 权限分级:[maxAccess] 是本机上限,主控端通过 msgType=9 的 `access` 字段请求,
* 有效等级取两者较小值,并用 msgType=10 回送。输入/剪贴板需要 control,文件需要 full。
*/ */
class ReceiverTransport( class ReceiverTransport(
private val host: String, private val host: String,
@@ -122,6 +127,33 @@ class ReceiverTransport(
@Volatile @Volatile
var clipboardSyncEnabled: Boolean = true var clipboardSyncEnabled: Boolean = true
/** 本机允许的最高权限等级,由被控端界面/偏好设置决定。 */
@Volatile
var maxAccess: Int = AccessLevel.FULL
set(value) {
val next = AccessLevel.clamp(value)
field = next
// 上限调低时立刻把有效等级压下去并通知主控端,不等下一帧。
if (access > next) {
access = next
sendAccessReply(access)
Log.i(TAG, "权限上限调整为 ${AccessLevel.name(next)},已通知主控端")
}
}
/** 当前生效的权限等级:`min(主控端请求, 本机上限)`。 */
@Volatile
var access: Int = AccessLevel.FULL
private set
/** 已回送过的最新等级,避免每帧回一次应答。 */
@Volatile
private var reportedAccess: Int = -1
/** 因权限不足丢弃的事件计数,只用于日志去抖。 */
@Volatile
private var accessDrops: Int = 0
/** 回送投屏应答(GRANTED / DENIED / STOPPED / ERROR)。 */ /** 回送投屏应答(GRANTED / DENIED / STOPPED / ERROR)。 */
fun sendMirror(action: Int, message: String = "") { fun sendMirror(action: Int, message: String = "") {
sendControl(ControlEvent.Mirror(action, message)) sendControl(ControlEvent.Mirror(action, message))
@@ -237,6 +269,8 @@ class ReceiverTransport(
running = true running = true
consecutiveFailures = 0 consecutiveFailures = 0
Log.i(TAG, "已连接主控端 $host:$controlPort") Log.i(TAG, "已连接主控端 $host:$controlPort")
// 先报一次当前等级,主控端在收到会话配置前也知道能不能操作。
sendAccessReply()
readLoop(input) readLoop(input)
return true return true
} }
@@ -397,11 +431,16 @@ class ReceiverTransport(
val plaintext = crypto.decodeControlFrame(secureFrame, controlKey) ?: return val plaintext = crypto.decodeControlFrame(secureFrame, controlKey) ?: return
if (plaintext.size < 8) return if (plaintext.size < 8) return
when (plaintext[1].toInt() and 0xff) { when (plaintext[1].toInt() and 0xff) {
7 -> handleFileFrame(plaintext.copyOfRange(8, plaintext.size)) 7 -> {
val payload = plaintext.copyOfRange(8, plaintext.size)
if (access < AccessLevel.FULL) rejectFileFrame(payload) else handleFileFrame(payload)
}
else -> { else -> {
val frame = ControlFrames.decode(plaintext) ?: return val frame = ControlFrames.decode(plaintext) ?: return
when (val event = frame.event) { when (val event = frame.event) {
is ControlEvent.Clipboard -> if (clipboardSyncEnabled) { is ControlEvent.Clipboard -> if (access < AccessLevel.CONTROL) {
dropForAccess("剪贴板")
} else if (clipboardSyncEnabled) {
clipboard.publish(event.text) clipboard.publish(event.text)
} }
is ControlEvent.Ping -> sendControl(ControlEvent.Pong(event.timestamp)) is ControlEvent.Ping -> sendControl(ControlEvent.Pong(event.timestamp))
@@ -414,13 +453,71 @@ class ReceiverTransport(
onMirrorEvent?.invoke(event.action, event.message) onMirrorEvent?.invoke(event.action, event.message)
} }
} }
is ControlEvent.SessionConfig -> onSessionConfig?.invoke(event.json) is ControlEvent.SessionConfig -> {
else -> injector.inject(frame) applyAccessRequest(event.json)
onSessionConfig?.invoke(event.json)
}
// 权限应答是被控端发出去的,收到只可能来自旧版对端,忽略即可。
is ControlEvent.Access -> Unit
else -> if (access < AccessLevel.CONTROL) {
dropForAccess("输入")
} else {
injector.inject(frame)
}
} }
} }
} }
} }
/**
* 解析主控端请求的权限等级:`{"access":"view|control|full"}`。
*
* 有效等级永远不超过 [maxAccess],结果变化时回送一次 msgType=10 应答,
* 主控端据此把超出权限的操作禁掉。
*/
private fun applyAccessRequest(json: String) {
val requested = try {
AccessLevel.parse(JSONObject(json).optString("access"), access)
} catch (_: Exception) {
return
}
val next = minOf(requested, maxAccess)
if (next != access) {
access = next
Log.i(TAG, "权限等级 ${AccessLevel.name(next)}(请求 ${AccessLevel.name(requested)},上限 ${AccessLevel.name(maxAccess)})")
}
if (next != reportedAccess) sendAccessReply(next)
}
/** 主动回送当前有效等级(首次连接、上限调整、主控端重新请求时)。 */
fun sendAccessReply(level: Int = access) {
reportedAccess = level
val payload = JSONObject()
.put("level", level)
.put("name", AccessLevel.name(level))
.put("max", maxAccess)
.put("requested", level)
sendControl(ControlEvent.Access(payload.toString()))
}
private fun dropForAccess(what: String) {
if (accessDrops++ % 50 == 0) {
Log.i(TAG, "当前权限为 ${AccessLevel.name(access)},丢弃${what}事件")
}
}
/** 文件子协议被权限拦截时也要回错误响应,否则主控端只能等到超时。 */
private fun rejectFileFrame(payload: ByteArray) {
val reason = "被控端当前权限为 ${AccessLevel.name(access)},文件访问需要 full"
sendRaw(
7,
JSONObject()
.put("op", "error")
.put("error", reason)
.toString(),
)
}
/** /**
* 空闲时轮询信令服务器,等待主控端发来的 `hs`。 * 空闲时轮询信令服务器,等待主控端发来的 `hs`。
* *
@@ -499,6 +596,7 @@ class ReceiverTransport(
running = true running = true
consecutiveFailures = 0 consecutiveFailures = 0
Log.i(TAG, "已通过中继连接 $peerId") Log.i(TAG, "已通过中继连接 $peerId")
sendAccessReply()
try { try {
relayReadLoop(client, sessionKeys.control, peerId) relayReadLoop(client, sessionKeys.control, peerId)
} catch (error: Exception) { } catch (error: Exception) {
+53 -2
View File
@@ -8,8 +8,7 @@ enum ConnectionPhase {
failed, failed,
} }
extension ConnectionPhaseX on ConnectionPhase { extension ConnectionPhaseX on ConnectionPhase { String get wireName => name;
String get wireName => name;
String get label => switch (this) { String get label => switch (this) {
ConnectionPhase.idle => '未连接', ConnectionPhase.idle => '未连接',
@@ -116,6 +115,51 @@ class DeviceInfo {
} }
} }
/// 会话权限等级,与被控端 `protocol/AccessLevel.kt` 一一对应。
///
/// 主控端只能「请求」等级,被控端按本机上限裁剪后用 msgType=10 回送有效等级;
/// 界面按 [granted] 决定哪些操作可用,超出的操作在被控端也会被丢弃。
enum AccessLevel {
view(0, 'view', '仅查看'),
control(1, 'control', '查看+控制'),
full(2, 'full', '全权限');
const AccessLevel(this.value, this.code, this.label);
final int value;
final String code;
final String label;
/// 能否注入输入与同步剪贴板。
bool get allowsControl => value >= control.value;
/// 能否使用文件子协议(浏览/上传/下载)。
bool get allowsFiles => this == AccessLevel.full;
static AccessLevel fromValue(Object? raw, {AccessLevel fallback = AccessLevel.full}) {
final value = raw is num ? raw.toInt() : int.tryParse('$raw');
for (final level in AccessLevel.values) {
if (level.value == value) return level;
}
return fromCode(raw, fallback: fallback);
}
static AccessLevel fromCode(Object? raw, {AccessLevel fallback = AccessLevel.full}) {
final text = (raw ?? '').toString().trim().toLowerCase();
if (text.isEmpty) return fallback;
for (final level in AccessLevel.values) {
if (level.code == text || '${level.value}' == text) return level;
}
return switch (text) {
'read' || 'readonly' || 'read-only' => AccessLevel.view,
_ => fallback,
};
}
/// 取两者中更严格的等级。
AccessLevel cap(AccessLevel max) => value <= max.value ? this : max;
}
class AppSettings { class AppSettings {
final String signalingUrl; final String signalingUrl;
final bool useLocalSignaling; final bool useLocalSignaling;
@@ -132,6 +176,8 @@ class AppSettings {
final String fileToken; final String fileToken;
/// 连接时是否走信令中继(跨网段)。中继只承载控制通道,不能投屏。 /// 连接时是否走信令中继(跨网段)。中继只承载控制通道,不能投屏。
final bool relayEnabled; final bool relayEnabled;
/// 向被控端请求的权限等级(被控端可能按其本机上限下调)。
final AccessLevel access;
const AppSettings({ const AppSettings({
this.signalingUrl = '', this.signalingUrl = '',
@@ -146,6 +192,7 @@ class AppSettings {
this.filePort = 53317, this.filePort = 53317,
this.fileToken = '', this.fileToken = '',
this.relayEnabled = false, this.relayEnabled = false,
this.access = AccessLevel.full,
}); });
static const defaults = AppSettings(); static const defaults = AppSettings();
@@ -165,6 +212,7 @@ class AppSettings {
int? filePort, int? filePort,
String? fileToken, String? fileToken,
bool? relayEnabled, bool? relayEnabled,
AccessLevel? access,
}) { }) {
return AppSettings( return AppSettings(
signalingUrl: signalingUrl ?? this.signalingUrl, signalingUrl: signalingUrl ?? this.signalingUrl,
@@ -179,6 +227,7 @@ class AppSettings {
filePort: filePort ?? this.filePort, filePort: filePort ?? this.filePort,
fileToken: fileToken ?? this.fileToken, fileToken: fileToken ?? this.fileToken,
relayEnabled: relayEnabled ?? this.relayEnabled, relayEnabled: relayEnabled ?? this.relayEnabled,
access: access ?? this.access,
); );
} }
@@ -198,6 +247,7 @@ class AppSettings {
filePort: (json['filePort'] is num ? json['filePort'] as num : 53317).toInt(), filePort: (json['filePort'] is num ? json['filePort'] as num : 53317).toInt(),
fileToken: (json['fileToken'] ?? defaults.fileToken).toString(), fileToken: (json['fileToken'] ?? defaults.fileToken).toString(),
relayEnabled: json['relayEnabled'] as bool? ?? defaults.relayEnabled, relayEnabled: json['relayEnabled'] as bool? ?? defaults.relayEnabled,
access: AccessLevel.fromCode(json['access'], fallback: defaults.access),
); );
} }
@@ -214,5 +264,6 @@ class AppSettings {
'filePort': filePort, 'filePort': filePort,
'fileToken': fileToken, 'fileToken': fileToken,
'relayEnabled': relayEnabled, 'relayEnabled': relayEnabled,
'access': access.code,
}; };
} }
@@ -31,6 +31,7 @@ class _SettingsPageState extends State<SettingsPage> {
late bool _clipboardSync; late bool _clipboardSync;
late bool _fileTransfer; late bool _fileTransfer;
late bool _relayEnabled; late bool _relayEnabled;
late AccessLevel _access;
late int _bitrateMbps; late int _bitrateMbps;
DeviceInfo? _localListener; DeviceInfo? _localListener;
ServiceCheckResult? _serviceResult; ServiceCheckResult? _serviceResult;
@@ -52,6 +53,7 @@ class _SettingsPageState extends State<SettingsPage> {
_clipboardSync = widget.settings.clipboardSync; _clipboardSync = widget.settings.clipboardSync;
_fileTransfer = widget.settings.fileTransfer; _fileTransfer = widget.settings.fileTransfer;
_relayEnabled = widget.settings.relayEnabled; _relayEnabled = widget.settings.relayEnabled;
_access = widget.settings.access;
_bitrateMbps = widget.settings.bitrateMbps; _bitrateMbps = widget.settings.bitrateMbps;
_loadLocalListener(); _loadLocalListener();
_refreshListenerState(); _refreshListenerState();
@@ -216,6 +218,7 @@ class _SettingsPageState extends State<SettingsPage> {
clipboardSync: _clipboardSync, clipboardSync: _clipboardSync,
fileTransfer: _fileTransfer, fileTransfer: _fileTransfer,
relayEnabled: _relayEnabled, relayEnabled: _relayEnabled,
access: _access,
bitrateMbps: _bitrateMbps, bitrateMbps: _bitrateMbps,
filePort: int.tryParse(_filePort.text.trim()) ?? widget.settings.filePort, filePort: int.tryParse(_filePort.text.trim()) ?? widget.settings.filePort,
fileToken: _fileToken.text.trim(), fileToken: _fileToken.text.trim(),
@@ -417,6 +420,29 @@ class _SettingsPageState extends State<SettingsPage> {
value: _fileTransfer, value: _fileTransfer,
onChanged: (value) => setState(() => _fileTransfer = value), onChanged: (value) => setState(() => _fileTransfer = value),
), ),
ListTile(
title: const Text('请求权限等级'),
subtitle: Text(
'当前:${_access.label}。被控端有自己的上限,'
'实际等级取两者更严格的一方,超出部分的操作会被禁用。',
),
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: SegmentedButton<AccessLevel>(
segments: AccessLevel.values
.map(
(level) => ButtonSegment<AccessLevel>(
value: level,
label: Text(level.label),
),
)
.toList(growable: false),
selected: <AccessLevel>{_access},
onSelectionChanged: (selection) =>
setState(() => _access = selection.first),
),
),
SwitchListTile( SwitchListTile(
title: const Text('连接走信令中继'), title: const Text('连接走信令中继'),
subtitle: const Text('跨网段时使用;中继只承载控制通道,不能投屏/传音频'), subtitle: const Text('跨网段时使用;中继只承载控制通道,不能投屏/传音频'),
+103 -6
View File
@@ -1,4 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
@@ -65,6 +66,10 @@ class _HomePageState extends State<HomePage> {
bool _refreshQueued = false; bool _refreshQueued = false;
/// 当前控制通道是否走信令中继(中继模式不支持投屏)。 /// 当前控制通道是否走信令中继(中继模式不支持投屏)。
bool _relayActive = false; bool _relayActive = false;
/// 被控端回送的有效权限等级(msgType=10);被控端未应答前按请求值乐观处理。
AccessLevel _grantedAccess = AccessLevel.full;
/// 权限不足提示的去抖时间,避免连续手势把 SnackBar 刷爆。
DateTime? _lastAccessWarnAt;
List<DeviceInfo> _devices = const <DeviceInfo>[]; List<DeviceInfo> _devices = const <DeviceInfo>[];
DeviceInfo? _selected; DeviceInfo? _selected;
@@ -180,6 +185,7 @@ class _HomePageState extends State<HomePage> {
void _refreshDemoStatus() { void _refreshDemoStatus() {
if (_nativeCore == null || !mounted) return; if (_nativeCore == null || !mounted) return;
try { try {
final wasConnected = _phase.isConnected;
final status = _bridge.demoStatus(); final status = _bridge.demoStatus();
final running = status['running'] == true; final running = status['running'] == true;
final connected = status['peerConnected'] == true; final connected = status['peerConnected'] == true;
@@ -203,6 +209,12 @@ class _HomePageState extends State<HomePage> {
} }
}); });
if (sessionEnded) _snack('中继会话已断开'); if (sessionEnded) _snack('中继会话已断开');
// 刚连上时主动下发一次会话配置,顺带把权限等级请求发过去;
// 被控端会用 msgType=10 回送裁剪后的有效等级。
if (!wasConnected && _phase.isConnected) {
_grantedAccess = _settings.access;
_applySessionConfig();
}
} on Object catch (error) { } on Object catch (error) {
_diagnosticLog.write('demoStatus refresh failed: $error'); _diagnosticLog.write('demoStatus refresh failed: $error');
} }
@@ -229,6 +241,8 @@ class _HomePageState extends State<HomePage> {
_handleMirrorEvent(action, text); _handleMirrorEvent(action, text);
case 4: case 4:
unawaited(_applyRemoteClipboard(text)); unawaited(_applyRemoteClipboard(text));
case 10:
_handleAccessEvent(text);
case 6: case 6:
_diagnosticLog.write('pong received'); _diagnosticLog.write('pong received');
default: default:
@@ -271,6 +285,35 @@ class _HomePageState extends State<HomePage> {
_snack(message); _snack(message);
} }
/// 被控端回送的权限等级(msgType=10,payload 是 JSON)。
///
/// 有效等级可能低于请求值:被控端有自己的上限,且不允许主控端自行提权。
/// 降级时明确提示,否则用户会以为「点了没反应」是自己网络卡了。
void _handleAccessEvent(String text) {
if (text.isEmpty) return;
AccessLevel level;
int max;
try {
final decoded = jsonDecode(text);
if (decoded is! Map) return;
level = AccessLevel.fromValue(decoded['level'], fallback: _grantedAccess);
max = AccessLevel.fromValue(decoded['max'], fallback: level).value;
} on Object catch (error) {
_diagnosticLog.write('access event parse failed: $error ($text)');
return;
}
final requested = _settings.access;
final capped = level.cap(_settings.access);
_diagnosticLog.write(
'access event: granted=${level.code} max=$max requested=${requested.code}',
);
if (!mounted) return;
setState(() => _grantedAccess = capped);
if (capped.value < requested.value) {
_snack('被控端将权限限制为「${capped.label}」,超出部分的操作不可用');
}
}
/// 被控端上行的剪贴板内容 → 写入本机剪贴板。 /// 被控端上行的剪贴板内容 → 写入本机剪贴板。
Future<void> _applyRemoteClipboard(String text) async { Future<void> _applyRemoteClipboard(String text) async {
if (text.isEmpty || !_settings.clipboardSync) return; if (text.isEmpty || !_settings.clipboardSync) return;
@@ -287,6 +330,7 @@ class _HomePageState extends State<HomePage> {
Future<void> _syncLocalClipboard() async { Future<void> _syncLocalClipboard() async {
if (!mounted || _nativeCore == null) return; if (!mounted || _nativeCore == null) return;
if (!_phase.isConnected || !_settings.clipboardSync) return; if (!_phase.isConnected || !_settings.clipboardSync) return;
if (!_grantedAccess.allowsControl) return;
final ClipboardData? data; final ClipboardData? data;
try { try {
data = await Clipboard.getData(Clipboard.kTextPlain); data = await Clipboard.getData(Clipboard.kTextPlain);
@@ -307,6 +351,7 @@ class _HomePageState extends State<HomePage> {
_snack('请先连接被控端'); _snack('请先连接被控端');
return; return;
} }
if (!_requireControl()) return;
final data = await Clipboard.getData(Clipboard.kTextPlain); final data = await Clipboard.getData(Clipboard.kTextPlain);
final text = data?.text; final text = data?.text;
if (text == null || text.isEmpty) { if (text == null || text.isEmpty) {
@@ -328,6 +373,8 @@ class _HomePageState extends State<HomePage> {
'bitrateMbps': _settings.bitrateMbps, 'bitrateMbps': _settings.bitrateMbps,
'audioEnabled': _settings.audioEnabled, 'audioEnabled': _settings.audioEnabled,
'clipboardSync': _settings.clipboardSync, 'clipboardSync': _settings.clipboardSync,
// 权限只能「请求」:被控端会按本机上限裁剪并用 msgType=10 回送有效等级。
'access': _settings.access.code,
}; };
_bridge.sendControl('sessionConfig', payload); _bridge.sendControl('sessionConfig', payload);
_diagnosticLog.write('sessionConfig sent: $payload'); _diagnosticLog.write('sessionConfig sent: $payload');
@@ -454,7 +501,7 @@ class _HomePageState extends State<HomePage> {
/// 坐标是画面像素(与编码分辨率一致),被控端会按「画面尺寸 → 真实屏幕尺寸」 /// 坐标是画面像素(与编码分辨率一致),被控端会按「画面尺寸 → 真实屏幕尺寸」
/// 换算后再注入,因此主控端不需要知道手机的真实分辨率。 /// 换算后再注入,因此主控端不需要知道手机的真实分辨率。
void _onVideoPointer(int action, int x, int y) { void _onVideoPointer(int action, int x, int y) {
if (!_phase.isConnected) return; if (!_phase.isConnected || !_requireControl()) return;
_sendControl('touch', { _sendControl('touch', {
'action': action, 'action': action,
'pointerId': 1, 'pointerId': 1,
@@ -469,7 +516,7 @@ class _HomePageState extends State<HomePage> {
/// ///
/// 被控端把右键映射成「返回」、中键映射成「多任务」,符合桌面操作习惯。 /// 被控端把右键映射成「返回」、中键映射成「多任务」,符合桌面操作习惯。
void _onVideoMouseButton(int button, int action, int x, int y) { void _onVideoMouseButton(int button, int action, int x, int y) {
if (!_phase.isConnected) return; if (!_phase.isConnected || !_requireControl()) return;
final buttons = switch (button) { final buttons = switch (button) {
1 => 0x02, // bit1 = 右键 1 => 0x02, // bit1 = 右键
2 => 0x04, // bit2 = 中键 2 => 0x04, // bit2 = 中键
@@ -485,7 +532,7 @@ class _HomePageState extends State<HomePage> {
/// 串流窗口里的滚轮 → 滚轮控制帧(被控端用屏幕中心作为滚动起点)。 /// 串流窗口里的滚轮 → 滚轮控制帧(被控端用屏幕中心作为滚动起点)。
void _onVideoWheel(int deltaX, int deltaY) { void _onVideoWheel(int deltaX, int deltaY) {
if (!_phase.isConnected) return; if (!_phase.isConnected || !_requireControl()) return;
if (deltaX == 0 && deltaY == 0) return; if (deltaX == 0 && deltaY == 0) return;
_sendControl('wheel', { _sendControl('wheel', {
'deltaX': deltaX, 'deltaX': deltaX,
@@ -496,7 +543,7 @@ class _HomePageState extends State<HomePage> {
/// 串流窗口里的键盘 → 按键控制帧。 /// 串流窗口里的键盘 → 按键控制帧。
void _onVideoKey(int action, int vk, int modifiers) { void _onVideoKey(int action, int vk, int modifiers) {
if (!_phase.isConnected) return; if (!_phase.isConnected || !_requireControl()) return;
final keycode = _androidKeycodeFromVk(vk); final keycode = _androidKeycodeFromVk(vk);
if (keycode == null) return; if (keycode == null) return;
_sendControl('key', { _sendControl('key', {
@@ -506,6 +553,28 @@ class _HomePageState extends State<HomePage> {
}); });
} }
/// 输入/剪贴板需要 control 权限;不足时去抖提示一次。
bool _requireControl() {
if (_grantedAccess.allowsControl) return true;
_warnAccess();
return false;
}
/// 文件子协议需要 full 权限。
bool _requireFiles() {
if (_grantedAccess.allowsFiles) return true;
_warnAccess();
return false;
}
void _warnAccess() {
final now = DateTime.now();
final last = _lastAccessWarnAt;
if (last != null && now.difference(last) < const Duration(seconds: 3)) return;
_lastAccessWarnAt = now;
_snack('被控端当前权限为「${_grantedAccess.label}」,该操作不可用');
}
void _snack(String message) { void _snack(String message) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of(context) ScaffoldMessenger.of(context)
@@ -543,9 +612,13 @@ class _HomePageState extends State<HomePage> {
), ),
const SizedBox(height: 10), const SizedBox(height: 10),
FilledButton.tonalIcon( FilledButton.tonalIcon(
onPressed: _settings.fileTransfer ? _openFileBrowser : null, onPressed: _settings.fileTransfer && _grantedAccess.allowsFiles
? _openFileBrowser
: null,
icon: const Icon(Icons.folder_open, size: 18), icon: const Icon(Icons.folder_open, size: 18),
label: const Text('浏览被控端文件'), label: Text(
_grantedAccess.allowsFiles ? '浏览被控端文件' : '浏览被控端文件(需要全权限)',
),
), ),
], ],
), ),
@@ -571,6 +644,7 @@ class _HomePageState extends State<HomePage> {
} }
Future<void> _openFileBrowser() async { Future<void> _openFileBrowser() async {
if (!_requireFiles()) return;
if (_selected == null) { if (_selected == null) {
_snack('请先选中被控端设备'); _snack('请先选中被控端设备');
return; return;
@@ -905,6 +979,8 @@ class _HomePageState extends State<HomePage> {
setState(() { setState(() {
_phase = ConnectionPhase.idle; _phase = ConnectionPhase.idle;
_relayActive = false; _relayActive = false;
// 断开后回到「未协商」状态,重连时按设置重新请求。
_grantedAccess = _settings.access;
}); });
} }
@@ -1223,6 +1299,27 @@ class _HomePageState extends State<HomePage> {
enabled: _phase.isConnected, enabled: _phase.isConnected,
onEvent: _sendControl, onEvent: _sendControl,
), ),
const SizedBox(height: 8),
Row(
children: [
Icon(
_grantedAccess.allowsFiles
? Icons.verified_user_outlined
: Icons.lock_outline,
size: 14,
color: _phase.isConnected
? Theme.of(context).colorScheme.primary
: Theme.of(context).disabledColor,
),
const SizedBox(width: 6),
Text(
_phase.isConnected
? '权限:${_grantedAccess.label}(请求 ${_settings.access.label})'
: '权限:未协商,连接后由被控端确认',
style: Theme.of(context).textTheme.labelSmall,
),
],
),
const SizedBox(height: 12), const SizedBox(height: 12),
_buildFileTransferCard(), _buildFileTransferCard(),
const SizedBox(height: 12), const SizedBox(height: 12),
+13 -3
View File
@@ -1,9 +1,9 @@
use super::codec::{CodecError, ControlFrameCodec, ControlFrameHeader}; use super::codec::{CodecError, ControlFrameCodec, ControlFrameHeader};
use super::events::{ use super::events::{
ClipboardEvent, ConfigEvent, ControlEvent, ControlEventKind, FileEvent, KeyAction, AccessEvent, ClipboardEvent, ConfigEvent, ControlEvent, ControlEventKind, FileEvent, KeyAction,
KeyboardEvent, MirrorEvent, MouseAction, MouseEvent, TouchAction, TouchEvent, WheelEvent, KeyboardEvent, MirrorEvent, MouseAction, MouseEvent, TouchAction, TouchEvent, WheelEvent,
MSG_CLIPBOARD, MSG_CONFIG, MSG_FILE, MSG_KEY, MSG_MIRROR, MSG_MOUSE, MSG_PING, MSG_PONG, MSG_ACCESS, MSG_CLIPBOARD, MSG_CONFIG, MSG_FILE, MSG_KEY, MSG_MIRROR, MSG_MOUSE, MSG_PING,
MSG_TOUCH, MSG_WHEEL, PROTOCOL_VERSION, MSG_PONG, MSG_TOUCH, MSG_WHEEL, PROTOCOL_VERSION,
}; };
#[derive(Debug, Default, Clone, Copy)] #[derive(Debug, Default, Clone, Copy)]
@@ -59,6 +59,9 @@ impl ControlFrameCodec for BinaryCodec {
ControlEventKind::Config(payload) => { ControlEventKind::Config(payload) => {
buffer.extend_from_slice(payload.json.as_bytes()); buffer.extend_from_slice(payload.json.as_bytes());
} }
ControlEventKind::Access(payload) => {
buffer.extend_from_slice(payload.json.as_bytes());
}
ControlEventKind::File(payload) => { ControlEventKind::File(payload) => {
buffer.extend_from_slice(payload.json.as_bytes()); buffer.extend_from_slice(payload.json.as_bytes());
} }
@@ -173,6 +176,10 @@ fn decode_payload(msg_type: u8, payload: &[u8]) -> Result<ControlEventKind, Code
let json = String::from_utf8(payload.to_vec()).map_err(|_| CodecError::InvalidUtf8)?; let json = String::from_utf8(payload.to_vec()).map_err(|_| CodecError::InvalidUtf8)?;
Ok(ControlEventKind::Config(ConfigEvent { json })) Ok(ControlEventKind::Config(ConfigEvent { json }))
} }
MSG_ACCESS => {
let json = String::from_utf8(payload.to_vec()).map_err(|_| CodecError::InvalidUtf8)?;
Ok(ControlEventKind::Access(AccessEvent { json }))
}
MSG_FILE => { MSG_FILE => {
let json = String::from_utf8(payload.to_vec()).map_err(|_| CodecError::InvalidUtf8)?; let json = String::from_utf8(payload.to_vec()).map_err(|_| CodecError::InvalidUtf8)?;
Ok(ControlEventKind::File(FileEvent { json })) Ok(ControlEventKind::File(FileEvent { json }))
@@ -237,6 +244,9 @@ mod tests {
assert_roundtrip(ControlEventKind::Config(ConfigEvent { assert_roundtrip(ControlEventKind::Config(ConfigEvent {
json: r#"{"preferH265":true,"bitrateMbps":12}"#.to_string(), json: r#"{"preferH265":true,"bitrateMbps":12}"#.to_string(),
})); }));
assert_roundtrip(ControlEventKind::Access(AccessEvent {
json: r#"{"level":1,"name":"control","max":2,"requested":2}"#.to_string(),
}));
assert_roundtrip(ControlEventKind::File(FileEvent { assert_roundtrip(ControlEventKind::File(FileEvent {
json: r#"{"op":"list","path":""}"#.to_string(), json: r#"{"op":"list","path":""}"#.to_string(),
})); }));
+14 -1
View File
@@ -15,9 +15,13 @@ pub const MSG_FILE: u8 = 7;
pub const MSG_MIRROR: u8 = 8; pub const MSG_MIRROR: u8 = 8;
/// 会话配置。payload = UTF-8 JSON:`preferH265` / `bitrateMbps` / /// 会话配置。payload = UTF-8 JSON:`preferH265` / `bitrateMbps` /
/// `audioEnabled` / `clipboardSync`,字段全部可选。 /// `audioEnabled` / `clipboardSync` / `access`,字段全部可选。
pub const MSG_CONFIG: u8 = 9; pub const MSG_CONFIG: u8 = 9;
/// 权限等级应答。payload = UTF-8 JSON:
/// `{"level":0|1|2,"name":"view|control|full","max":0|1|2,"requested":0|1|2}`。
pub const MSG_ACCESS: u8 = 10;
/// 投屏控制动作,两端必须保持一致。 /// 投屏控制动作,两端必须保持一致。
pub mod mirror_action { pub mod mirror_action {
pub const REQUEST: u8 = 0; pub const REQUEST: u8 = 0;
@@ -171,6 +175,13 @@ pub struct ConfigEvent {
pub json: String, pub json: String,
} }
/// 权限等级应答负载(msgType=10)。`json` 是被控端计算后的有效等级,例如
/// `{"level":1,"name":"control","max":2,"requested":2}`。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AccessEvent {
pub json: String,
}
/// 文件子协议负载(msgType=7)。`json` 是原样的 UTF-8 JSON,字段由子协议定义。 /// 文件子协议负载(msgType=7)。`json` 是原样的 UTF-8 JSON,字段由子协议定义。
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct FileEvent { pub struct FileEvent {
@@ -188,6 +199,7 @@ pub enum ControlEventKind {
Pong(u64), Pong(u64),
Mirror(MirrorEvent), Mirror(MirrorEvent),
Config(ConfigEvent), Config(ConfigEvent),
Access(AccessEvent),
File(FileEvent), File(FileEvent),
} }
@@ -217,6 +229,7 @@ impl ControlEvent {
ControlEventKind::Pong(_) => MSG_PONG, ControlEventKind::Pong(_) => MSG_PONG,
ControlEventKind::Mirror(_) => MSG_MIRROR, ControlEventKind::Mirror(_) => MSG_MIRROR,
ControlEventKind::Config(_) => MSG_CONFIG, ControlEventKind::Config(_) => MSG_CONFIG,
ControlEventKind::Access(_) => MSG_ACCESS,
ControlEventKind::File(_) => MSG_FILE, ControlEventKind::File(_) => MSG_FILE,
} }
} }
+15 -2
View File
@@ -15,8 +15,9 @@ use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use crate::control::events::{ use crate::control::events::{
ClipboardEvent, ConfigEvent, FileEvent, KeyAction, KeyboardEvent, MirrorEvent, MouseAction, AccessEvent, ClipboardEvent, ConfigEvent, FileEvent, KeyAction, KeyboardEvent, MirrorEvent,
MouseEvent, TouchAction, TouchEvent, WheelEvent, MSG_CLIPBOARD, MSG_MIRROR, MouseAction, MouseEvent, TouchAction, TouchEvent, WheelEvent, MSG_ACCESS, MSG_CLIPBOARD,
MSG_MIRROR,
}; };
use crate::control::{ControlEvent, ControlEventKind}; use crate::control::{ControlEvent, ControlEventKind};
@@ -857,6 +858,11 @@ pub fn config_event(sequence: u16, json: String) -> ControlEvent {
ControlEvent::new(sequence, ControlEventKind::Config(ConfigEvent { json })) ControlEvent::new(sequence, ControlEventKind::Config(ConfigEvent { json }))
} }
/// msgType=10 权限等级应答:payload 是被控端算出的有效等级 JSON。
pub fn access_event(sequence: u16, json: String) -> ControlEvent {
ControlEvent::new(sequence, ControlEventKind::Access(AccessEvent { json }))
}
fn run_tcp(listener: TcpListener, shared: Arc<Shared>) { fn run_tcp(listener: TcpListener, shared: Arc<Shared>) {
while shared.running.load(Ordering::Relaxed) { while shared.running.load(Ordering::Relaxed) {
match listener.accept() { match listener.accept() {
@@ -1222,6 +1228,13 @@ fn dispatch_control_event(
text: mirror.message.clone(), text: mirror.message.clone(),
}); });
} }
ControlEventKind::Access(access) => {
shared.push_inbound(InboundEvent {
msg_type: MSG_ACCESS,
action: 0,
text: access.json.clone(),
});
}
ControlEventKind::Clipboard(clipboard) => { ControlEventKind::Clipboard(clipboard) => {
shared.push_inbound(InboundEvent { shared.push_inbound(InboundEvent {
msg_type: MSG_CLIPBOARD, msg_type: MSG_CLIPBOARD,
+7 -1
View File
@@ -302,6 +302,7 @@ pub unsafe extern "C" fn ttstd_control_decode(
ControlEventKind::Clipboard(_) => "clipboard", ControlEventKind::Clipboard(_) => "clipboard",
ControlEventKind::Mirror(_) => "mirror", ControlEventKind::Mirror(_) => "mirror",
ControlEventKind::Config(_) => "config", ControlEventKind::Config(_) => "config",
ControlEventKind::Access(_) => "access",
ControlEventKind::File(_) => "file", ControlEventKind::File(_) => "file",
}; };
let json = format!( let json = format!(
@@ -315,7 +316,7 @@ pub unsafe extern "C" fn ttstd_control_decode(
/// 向当前被控端下发控制帧。payload 为各事件类型的二进制负载。 /// 向当前被控端下发控制帧。payload 为各事件类型的二进制负载。
/// msg_type: 0=touch 1=mouse 2=key 3=wheel 4=clipboard(UTF-8) 5=ping(u64 LE) /// msg_type: 0=touch 1=mouse 2=key 3=wheel 4=clipboard(UTF-8) 5=ping(u64 LE)
/// 8=mirror([action:u8]+文本) 9=sessionConfig(UTF-8 JSON) /// 8=mirror([action:u8]+文本) 9=sessionConfig(UTF-8 JSON) 10=access(UTF-8 JSON)
#[no_mangle] #[no_mangle]
pub unsafe extern "C" fn ttstd_demo_send_control( pub unsafe extern "C" fn ttstd_demo_send_control(
sequence: u16, sequence: u16,
@@ -373,6 +374,11 @@ pub unsafe extern "C" fn ttstd_demo_send_control(
sequence, sequence,
String::from_utf8_lossy(bytes).to_string(), String::from_utf8_lossy(bytes).to_string(),
)), )),
// 10 = 权限等级应答:payload 就是 UTF-8 JSON
10 => Some(crate::demo_server::access_event(
sequence,
String::from_utf8_lossy(bytes).to_string(),
)),
_ => None, _ => None,
}; };
match event { match event {