feat(security): 完善信令认证与媒体加密
- 增加信令访问令牌、HTTPS 校验、限流及跨网段中继连接修复 - 同步三端媒体 v2 协议,实现 AES-GCM、防重放和乱序分片重组,升级 Rust ABI 6 - 修复文件鉴权、权限协商及剪贴板越权,完善上传校验和串流超时处理 - 增加跨端回归测试及部署文档,在 AGENTS.md 记录真机与真实跨网段待验收项目
This commit is contained in:
1 parent
4c9d006d11
commit
f6b7730684
58 files changed
+2167
-218
No files matched your search
@@ -9,6 +9,8 @@ import 'discovery_client.dart';
|
||||
import 'local_signaling.dart';
|
||||
import 'models.dart';
|
||||
import 'native_core.dart';
|
||||
import 'signaling_endpoint.dart';
|
||||
import 'settings_store.dart';
|
||||
|
||||
class SenderBridge {
|
||||
SenderBridge({
|
||||
@@ -335,9 +337,12 @@ class SenderBridge {
|
||||
}
|
||||
|
||||
Future<void> saveSettings(AppSettings settings) async {
|
||||
await SettingsStore().save(settings);
|
||||
await _invokeIgnoringMissing('settings', settings.toJson());
|
||||
}
|
||||
|
||||
AppSettings loadSettings() => SettingsStore().load();
|
||||
|
||||
Future<bool> startLocalSignaling(int port) => _localSignaling.start(port: port);
|
||||
|
||||
Future<void> stopLocalSignaling() => _localSignaling.stop();
|
||||
@@ -348,7 +353,7 @@ class SenderBridge {
|
||||
if (settings.useLocalSignaling) {
|
||||
return _localSignaling.url(port: settings.localSignalingPort);
|
||||
}
|
||||
return settings.signalingUrl;
|
||||
return SignalingEndpoint.withToken(settings.signalingUrl, settings.signalingToken);
|
||||
}
|
||||
|
||||
/// 启动 Rust Core 的本机 demo 服务。
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math' as math;
|
||||
import 'package:crypto/crypto.dart';
|
||||
|
||||
/// 控制通道文件子协议(`msg_type=7`)的客户端。
|
||||
///
|
||||
@@ -37,6 +38,8 @@ class ControlFileClient {
|
||||
throw const ControlFileException('本地文件不存在');
|
||||
}
|
||||
final length = await file.length();
|
||||
if (length > 64 * 1024 * 1024) throw const ControlFileException('单文件不能超过 64 MiB');
|
||||
final digest = await sha256.bind(file.openRead()).first;
|
||||
final name = localPath.split(RegExp(r'[\\/]')).last;
|
||||
final fileId = 'f-${DateTime.now().microsecondsSinceEpoch}';
|
||||
|
||||
@@ -50,8 +53,7 @@ class ControlFileClient {
|
||||
'name': name,
|
||||
'size': length,
|
||||
'mime': 'application/octet-stream',
|
||||
// 没有 crypto 依赖,算不了摘要;被控端只在续传判断时用它。
|
||||
'sha256': '',
|
||||
'sha256': digest.toString(),
|
||||
},
|
||||
],
|
||||
}),
|
||||
@@ -69,7 +71,7 @@ class ControlFileClient {
|
||||
while (offset < length) {
|
||||
await handle.setPosition(offset);
|
||||
final bytes = await handle.read(math.min(chunkSize, length - offset));
|
||||
if (bytes.isEmpty) break;
|
||||
if (bytes.isEmpty) throw const ControlFileException('读取文件提前结束,上传已取消');
|
||||
final ack = await send({
|
||||
'op': 'chunk',
|
||||
'sessionId': sessionId,
|
||||
|
||||
@@ -32,6 +32,7 @@ class DiagnosticLog {
|
||||
}
|
||||
|
||||
void write(String message) {
|
||||
message = message.replaceAll(RegExp(r'#token=[^\s;)]*'), '#token=[redacted]');
|
||||
final file = _file;
|
||||
if (file == null) return;
|
||||
try {
|
||||
|
||||
@@ -3,28 +3,33 @@ import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'models.dart';
|
||||
import 'signaling_endpoint.dart';
|
||||
|
||||
class DiscoveryClient {
|
||||
static Future<List<DeviceInfo>> listDevices(
|
||||
String signalingUrl, {
|
||||
Duration timeout = const Duration(seconds: 2),
|
||||
bool throwOnError = false,
|
||||
}) async {
|
||||
final trimmed = signalingUrl.trim();
|
||||
if (trimmed.isEmpty) return const <DeviceInfo>[];
|
||||
final client = HttpClient()..connectionTimeout = timeout;
|
||||
try {
|
||||
final base = Uri.parse(trimmed);
|
||||
final base = Uri.parse(SignalingEndpoint.publicUrl(trimmed));
|
||||
final path = base.path.endsWith('/')
|
||||
? '${base.path}list'
|
||||
: '${base.path}/list';
|
||||
final request = await client.getUrl(base.replace(path: path)).timeout(timeout);
|
||||
request.followRedirects = false;
|
||||
SignalingEndpoint.headers(trimmed).forEach(request.headers.set);
|
||||
final response = await request.close().timeout(timeout);
|
||||
final body = await utf8.decoder.bind(response).join().timeout(timeout);
|
||||
if (response.statusCode != HttpStatus.ok) return const <DeviceInfo>[];
|
||||
if (response.statusCode != HttpStatus.ok) throw HttpException('信令 HTTP ${response.statusCode}(请检查地址和访问令牌)');
|
||||
final value = jsonDecode(body);
|
||||
if (value is! Map) return const <DeviceInfo>[];
|
||||
return DeviceInfo.listFromJson(value['devices']);
|
||||
} on Object {
|
||||
if (throwOnError) rethrow;
|
||||
return const <DeviceInfo>[];
|
||||
} finally {
|
||||
client.close(force: true);
|
||||
|
||||
@@ -22,7 +22,10 @@ class LocalSignalingProcess {
|
||||
binary.path,
|
||||
const <String>[],
|
||||
workingDirectory: binary.parent.path,
|
||||
environment: <String, String>{'LISTEN_ADDR': ':$port'},
|
||||
environment: <String, String>{
|
||||
'LISTEN_ADDR': ':$port', 'ALLOW_INSECURE_SIGNALING': '1',
|
||||
'SIGNALING_TOKEN': '', 'TLS_CERT_FILE': '', 'TLS_KEY_FILE': '',
|
||||
},
|
||||
);
|
||||
process.stdout.listen((_) {});
|
||||
process.stderr.listen((_) {});
|
||||
|
||||
@@ -162,6 +162,7 @@ enum AccessLevel {
|
||||
|
||||
class AppSettings {
|
||||
final String signalingUrl;
|
||||
final String signalingToken;
|
||||
final bool useLocalSignaling;
|
||||
final bool localSignalingEnabled;
|
||||
final int localSignalingPort;
|
||||
@@ -181,6 +182,7 @@ class AppSettings {
|
||||
|
||||
const AppSettings({
|
||||
this.signalingUrl = '',
|
||||
this.signalingToken = '',
|
||||
this.useLocalSignaling = true,
|
||||
this.localSignalingEnabled = true,
|
||||
this.localSignalingPort = 8080,
|
||||
@@ -201,6 +203,7 @@ class AppSettings {
|
||||
|
||||
AppSettings copyWith({
|
||||
String? signalingUrl,
|
||||
String? signalingToken,
|
||||
bool? useLocalSignaling,
|
||||
bool? localSignalingEnabled,
|
||||
int? localSignalingPort,
|
||||
@@ -216,6 +219,7 @@ class AppSettings {
|
||||
}) {
|
||||
return AppSettings(
|
||||
signalingUrl: signalingUrl ?? this.signalingUrl,
|
||||
signalingToken: signalingToken ?? this.signalingToken,
|
||||
useLocalSignaling: useLocalSignaling ?? this.useLocalSignaling,
|
||||
localSignalingEnabled: localSignalingEnabled ?? this.localSignalingEnabled,
|
||||
localSignalingPort: localSignalingPort ?? this.localSignalingPort,
|
||||
@@ -234,6 +238,7 @@ class AppSettings {
|
||||
factory AppSettings.fromJson(Map<String, dynamic> json) {
|
||||
return AppSettings(
|
||||
signalingUrl: (json['signalingUrl'] ?? defaults.signalingUrl).toString(),
|
||||
signalingToken: (json['signalingToken'] ?? '').toString(),
|
||||
useLocalSignaling: json['useLocalSignaling'] as bool? ?? defaults.useLocalSignaling,
|
||||
localSignalingEnabled:
|
||||
json['localSignalingEnabled'] as bool? ?? defaults.localSignalingEnabled,
|
||||
@@ -253,6 +258,7 @@ class AppSettings {
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'signalingUrl': signalingUrl,
|
||||
'signalingToken': signalingToken,
|
||||
'useLocalSignaling': useLocalSignaling,
|
||||
'localSignalingEnabled': localSignalingEnabled,
|
||||
'localSignalingPort': localSignalingPort,
|
||||
|
||||
@@ -7,7 +7,12 @@ import 'package:ffi/ffi.dart';
|
||||
|
||||
/// Rust Core 的 ffi 通道。桌面端通过 cdylib 直接调用,测试环境可注入桩实现。
|
||||
class NativeCore {
|
||||
NativeCore({DynamicLibrary? library}) : _library = library ?? _openLibrary();
|
||||
NativeCore({DynamicLibrary? library}) : _library = library ?? _openLibrary() {
|
||||
if (abiRevision() != 6) throw UnsupportedError('Rust Core 版本不匹配,需要支持媒体 aes-gcm/2 的 ABI 6 动态库');
|
||||
}
|
||||
|
||||
static const mediaProtocol = 'aes-gcm/2';
|
||||
static const mediaPacketOverhead = 37 + 12 + 16;
|
||||
|
||||
static const int ok = 0;
|
||||
static const int errBufferTooSmall = -1;
|
||||
@@ -163,7 +168,7 @@ class NativeCore {
|
||||
Uint8List mediaEncode(int pts, int flags, List<int> key, List<int> payload) {
|
||||
return _withBytes(key, (keyPtr) {
|
||||
return _withBytes(payload, (payloadPtr) {
|
||||
final capacity = 13 + payload.length + 4;
|
||||
final capacity = mediaPacketOverhead + payload.length;
|
||||
final out = calloc<Uint8>(capacity);
|
||||
try {
|
||||
final written = _mediaEncode(
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'signaling_endpoint.dart';
|
||||
|
||||
class ServiceCheckResult {
|
||||
const ServiceCheckResult({
|
||||
@@ -32,11 +33,13 @@ class ServiceChecker {
|
||||
if (trimmed.isEmpty) return false;
|
||||
final client = HttpClient()..connectionTimeout = timeout;
|
||||
try {
|
||||
final base = Uri.parse(trimmed);
|
||||
final base = Uri.parse(SignalingEndpoint.publicUrl(trimmed));
|
||||
final path = base.path.endsWith('/')
|
||||
? '${base.path}healthz'
|
||||
: '${base.path}/healthz';
|
||||
? '${base.path}list'
|
||||
: '${base.path}/list';
|
||||
final request = await client.getUrl(base.replace(path: path)).timeout(timeout);
|
||||
request.followRedirects = false;
|
||||
SignalingEndpoint.headers(trimmed).forEach(request.headers.set);
|
||||
final response = await request.close().timeout(timeout);
|
||||
await response.drain<void>().timeout(timeout);
|
||||
return response.statusCode == HttpStatus.ok;
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'models.dart';
|
||||
|
||||
class SettingsStore {
|
||||
SettingsStore({File? file}) : file = file ?? File(_defaultPath());
|
||||
final File file;
|
||||
|
||||
static String _defaultPath() {
|
||||
final env = Platform.environment;
|
||||
final home = env['HOME'] ?? env['USERPROFILE'] ?? Directory.current.path;
|
||||
final base = Platform.isWindows
|
||||
? env['APPDATA'] ?? home
|
||||
: Platform.isMacOS
|
||||
? '$home/Library/Application Support'
|
||||
: env['XDG_CONFIG_HOME'] ?? '$home/.config';
|
||||
return '$base/TTSTDConnect/settings.json';
|
||||
}
|
||||
|
||||
AppSettings load() {
|
||||
try {
|
||||
return AppSettings.fromJson(
|
||||
jsonDecode(file.readAsStringSync()) as Map<String, dynamic>);
|
||||
} on Object {
|
||||
return AppSettings.defaults;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> save(AppSettings settings) async {
|
||||
await file.parent.create(recursive: true);
|
||||
final temp =
|
||||
File('${file.path}.${DateTime.now().microsecondsSinceEpoch}.tmp');
|
||||
try {
|
||||
await temp.create();
|
||||
if (!Platform.isWindows) {
|
||||
final result = await Process.run('chmod', ['600', temp.path]);
|
||||
if (result.exitCode != 0)
|
||||
throw FileSystemException('无法保护设置文件', temp.path);
|
||||
}
|
||||
await temp.writeAsString(jsonEncode(settings.toJson()), flush: true);
|
||||
await temp.rename(file.path);
|
||||
} finally {
|
||||
if (await temp.exists()) await temp.delete();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/// Credentials are carried internally in a URL fragment, never in HTTP paths.
|
||||
/// This preserves the Rust FFI ABI while allowing every transport to use Bearer.
|
||||
class SignalingEndpoint {
|
||||
static String withToken(String base, String token) {
|
||||
final uri = Uri.parse(base.trim());
|
||||
return token.trim().isEmpty
|
||||
? uri.removeFragment().toString()
|
||||
: uri
|
||||
.replace(fragment: 'token=${Uri.encodeComponent(token.trim())}')
|
||||
.toString();
|
||||
}
|
||||
|
||||
static String token(String url) {
|
||||
final fragment = Uri.parse(url).fragment;
|
||||
return fragment.startsWith('token=')
|
||||
? Uri.decodeComponent(fragment.substring(6))
|
||||
: '';
|
||||
}
|
||||
|
||||
static String publicUrl(String url) =>
|
||||
Uri.parse(url).removeFragment().toString();
|
||||
|
||||
static Map<String, String> headers(String url) {
|
||||
final value = token(url);
|
||||
return value.isEmpty ? const {} : {'Authorization': 'Bearer $value'};
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'signaling_endpoint.dart';
|
||||
|
||||
/// 信令服务器 `WS /watch` 的客户端。
|
||||
///
|
||||
@@ -42,7 +43,7 @@ class SignalingWatch {
|
||||
static Uri? watchUri(String base) {
|
||||
final trimmed = base.trim();
|
||||
if (trimmed.isEmpty) return null;
|
||||
final uri = Uri.tryParse(trimmed);
|
||||
final uri = Uri.tryParse(SignalingEndpoint.publicUrl(trimmed));
|
||||
if (uri == null || uri.host.isEmpty) return null;
|
||||
final scheme = switch (uri.scheme) {
|
||||
'https' || 'wss' => 'wss',
|
||||
@@ -68,7 +69,7 @@ class SignalingWatch {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final socket = await WebSocket.connect(uri.toString()).timeout(_connectTimeout);
|
||||
final socket = await WebSocket.connect(uri.toString(), headers: SignalingEndpoint.headers(signalingUrl)).timeout(_connectTimeout);
|
||||
if (_stopped) {
|
||||
await socket.close();
|
||||
return;
|
||||
|
||||
Reference in new issue
Block a user