网络质量探测 1.1.3:自更新、HTTP/3 与中心节点

版本名 1.1.3,构建号 6。应用标识和签名未改。包含自动更新、覆盖安装、目标历史、IPv4/IPv6 开关、HTTP(含 HTTP/3)以及中心服务端一键添加节点。
This commit is contained in:
yanjiu0721 authored and GitHub committed 2026-11-21 19:43:23 +08:00
1 parent 943259774f
commit 8cdc0f436f
66 files changed
+5489 -78

No files matched your search

+1 -1
View File
@@ -7,4 +7,4 @@ flutter pub get
flutter run -d linux
```
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。合作反射 UDP 默认 `19091`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。当前版本是 1.1.2。指标怎么读、这一版改了什么,在应用里的「指标说明」和「更新历史」。
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。合作反射 UDP 默认 `19091`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。当前版本是 1.1.3。本机 HTTP 探测需要旁边有 `netquality-reflector`,或设置 `NQ_PROBE_HELPER`。指标怎么读、这一版改了什么,在应用里的「指标说明」和「更新历史」。
@@ -1,5 +1,6 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<application
android:label="网络质量探测"
android:name="${applicationName}"
@@ -26,6 +27,15 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
@@ -1,5 +1,43 @@
package dev.netquality.netquality
import android.content.Intent
import android.net.Uri
import android.os.Build
import androidx.core.content.FileProvider
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File
class MainActivity : FlutterActivity()
class MainActivity : FlutterActivity() {
override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "dev.netquality/platform")
.setMethodCallHandler { call, result ->
when (call.method) {
"abi" -> result.success(Build.SUPPORTED_ABIS.firstOrNull ?: "")
"installApk" -> {
val path = call.argument<String>("path")
if (path.isNullOrEmpty()) {
result.error("bad_path", "没有安装包路径", null)
return@setMethodCallHandler
}
val file = File(path)
val uri: Uri = FileProvider.getUriForFile(
this,
"$packageName.fileprovider",
file,
)
val intent = Intent(Intent.ACTION_VIEW).apply {
setDataAndType(uri, "application/vnd.android.package-archive")
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
}
startActivity(intent)
result.success(null)
}
else -> result.notImplemented()
}
}
}
}
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<paths>
<cache-path name="updates" path="updates/" />
</paths>
+147
View File
@@ -0,0 +1,147 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:convert';
import '../models/session_config.dart';
class CatalogServer {
const CatalogServer({
required this.id,
required this.name,
required this.confidential,
this.controlUrl = '',
this.credential = '',
this.credentialExpiresAt = '',
});
final String id;
final String name;
final bool confidential;
final String controlUrl;
final String credential;
final String credentialExpiresAt;
}
class Catalog {
const Catalog({
required this.account,
required this.group,
required this.servers,
});
final String account;
final String group;
final List<CatalogServer> servers;
/// Parses a catalog. Confidential entries drop any address or credential
/// the server might have included by mistake.
factory Catalog.parse(String body) {
final decoded = jsonDecode(body);
if (decoded is! Map) {
throw const FormatException('目录无效');
}
final rawServers = decoded['servers'];
final servers = <CatalogServer>[];
if (rawServers is List) {
for (final item in rawServers) {
if (item is! Map) {
continue;
}
final confidential = item['confidential'] == true;
final url = item['controlUrl'] is String ? item['controlUrl'] as String : '';
final credential = item['credential'] is String
? item['credential'] as String
: '';
servers.add(
CatalogServer(
id: item['id'] is String ? item['id'] as String : '',
name: item['name'] is String ? item['name'] as String : '未命名',
confidential: confidential,
controlUrl: confidential ? '' : url,
credential: confidential ? '' : credential,
credentialExpiresAt: confidential
? ''
: (item['credentialExpiresAt'] is String
? item['credentialExpiresAt'] as String
: ''),
),
);
}
}
return Catalog(
account: decoded['account'] is String ? decoded['account'] as String : '',
group: decoded['group'] is String ? decoded['group'] as String : '',
servers: servers,
);
}
}
class CenterSyncResult {
const CenterSyncResult({required this.nodes, required this.credentials});
final List<RemoteNode> nodes;
/// Node id to short-lived credential. Confidential nodes are absent.
/// The node's long-lived token is never in this map.
final Map<String, String> credentials;
}
/// Replaces the servers that belong to [link] with the catalog.
/// Manual nodes and servers from other centers stay. Confidential nodes
/// are stored with an empty address.
CenterSyncResult mergeCenterCatalog({
required List<RemoteNode> existing,
required CenterLink link,
required Catalog catalog,
required String Function() newId,
}) {
final kept = [
for (final node in existing)
if (!node.fromCenter || node.centerLinkId != link.id) node,
];
final previous = {
for (final node in existing)
if (node.fromCenter && node.centerLinkId == link.id) node.serverId: node,
};
final credentials = <String, String>{};
final added = <RemoteNode>[];
for (final server in catalog.servers) {
if (server.id.isEmpty) {
continue;
}
final old = previous[server.id];
final id = old?.id ?? newId();
final node = RemoteNode(
id: id,
name: server.name,
baseUrl: server.confidential ? '' : server.controlUrl,
visibility: server.confidential ? 'confidential' : 'center',
fromCenter: true,
confidential: server.confidential,
centerLinkId: link.id,
serverId: server.id,
);
added.add(node);
if (!server.confidential && server.credential.isNotEmpty) {
credentials[id] = server.credential;
}
}
return CenterSyncResult(nodes: [...kept, ...added], credentials: credentials);
}
/// Center-issued names cannot be changed on the client.
RemoteNode renameNode(RemoteNode node, String name) {
if (node.fromCenter) {
return node;
}
return node.copyWith(name: name);
}
bool storedNodeHides(RemoteNode node, String secret) {
if (!node.confidential || secret.isEmpty) {
return true;
}
final raw = jsonEncode(node.toJson());
return !raw.contains(secret);
}
+109
View File
@@ -0,0 +1,109 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:convert';
import 'dart:io';
import '../models/session_config.dart';
import 'catalog.dart';
class CenterClientException implements Exception {
CenterClientException(this.message);
final String message;
@override
String toString() => message;
}
Future<String> loginCenter({
required String baseUrl,
required String account,
required String password,
}) async {
final body = await _send(
baseUrl,
'POST',
'/v1/center/login',
'',
{'account': account.trim(), 'password': password},
);
final token = body['token'];
if (token is! String || token.isEmpty) {
throw CenterClientException('中心没有返回口令');
}
return token;
}
Future<Catalog> fetchCatalog({
required String baseUrl,
required String token,
}) async {
final body = await _send(baseUrl, 'GET', '/v1/center/catalog', token, null);
return Catalog.parse(jsonEncode(body));
}
Future<Map<String, dynamic>> _send(
String baseUrl,
String method,
String path,
String token,
Map<String, Object?>? jsonBody,
) async {
final normalized = normalizeNodeUrl(baseUrl);
if (normalized == null) {
throw CenterClientException('中心地址需要是 http 或 https,且不能把口令写在地址里');
}
final client = HttpClient();
try {
final request = await client.openUrl(
method,
Uri.parse(normalized).resolve(path),
);
request.followRedirects = false;
if (token.isNotEmpty) {
request.headers.set(HttpHeaders.authorizationHeader, 'Bearer $token');
}
if (jsonBody != null) {
request.headers.contentType = ContentType.json;
request.add(utf8.encode(jsonEncode(jsonBody)));
}
final response = await request.close().timeout(const Duration(seconds: 15));
final text = await response.transform(utf8.decoder).join();
if (response.statusCode >= 300 && response.statusCode < 400) {
throw CenterClientException('中心地址发生了跳转。请填写最终的 HTTPS 地址');
}
if (response.statusCode == 401) {
throw CenterClientException('中心口令不正确,或账号密码不对');
}
if (response.statusCode < 200 || response.statusCode >= 300) {
throw CenterClientException(_message(text) ?? '中心拒绝了这次请求');
}
final decoded = jsonDecode(text);
if (decoded is! Map) {
throw CenterClientException('中心返回的内容无效');
}
return Map<String, dynamic>.from(decoded);
} on CenterClientException {
rethrow;
} on SocketException {
throw CenterClientException('连不上中心。请检查地址和防火墙');
} on HandshakeException {
throw CenterClientException('TLS 握手失败。请改用正确的 HTTPS 地址');
} on FormatException {
throw CenterClientException('中心返回的内容无效');
} finally {
client.close(force: true);
}
}
String? _message(String body) {
try {
final json = jsonDecode(body);
if (json is Map && json['message'] is String) {
return json['message'] as String;
}
} on FormatException {
return null;
}
return null;
}
+13
View File
@@ -21,6 +21,19 @@ class ReleaseEntry {
}
const releaseHistory = <ReleaseEntry>[
ReleaseEntry(
version: '1.1.3',
title: '网络质量探测 1.1.3',
source: '仓库 docs/release-notes/1.1.3.md。这一版的 Git 标签要等发布时才有,这里写的是即将发布的内容。',
points: [
'可以自动检查更新,也能在设置里关掉。先问 GitHub,连不上再用备用 Git。1.1.2 没有这个功能,升到 1.1.3 仍要手动安装。从这一版起,新版本才会自己下载并覆盖安装。',
'Windows 和 Linux 覆盖进现有安装目录。设置、已保存的节点、口令和探测历史仍在应用自己的数据目录里,不会被安装包清掉。',
'点「开始探测」会记下目标、端口和类型。目标框旁边可以打开最近的记录,点一条填回表单,也可以单条删除或全部清除。这里不保存节点口令、中心口令、Cookie 和请求体。',
'设置里可以分别关闭 IPv4 或 IPv6。两个都关、或填写了已关闭的那种地址时,不会开始。远程节点会收到同样的选择。',
'新增 HTTP 探测,包含 HTTP/3。可以指定方法、请求头、请求体、跳转次数,以及 curl --resolve 那种指定解析。4xx 和 5xx 显示状态码,不叫丢包。',
'同一个程序可以当中心。客户端用「一键添加服务器」填中心地址、账号和口令,一次加入这个口令能用的全部节点。保密节点只显示中心给的名称,探测由中心转发,本机不保存地址。',
],
),
ReleaseEntry(
version: '1.1.2',
title: '网络质量探测 1.1.2',
+1 -1
View File
@@ -1,4 +1,4 @@
// Copyright (C) 2026 灸 言
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'package:flutter/material.dart';
+3 -1
View File
@@ -273,7 +273,9 @@ class SampleBook {
if (denom > 0) {
probeLoss = timeout * 100 / denom;
}
} else if (profile == 'tcp-connect' || profile == 'minecraft-java') {
} else if (profile == 'tcp-connect' ||
profile == 'minecraft-java' ||
profile == 'http') {
final denom = ok + timeout + refused + dns + protocol + other;
if (denom > 0) {
failure = (denom - ok) * 100 / denom;
+54
View File
@@ -0,0 +1,54 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:io';
/// Host used for an address-family check. HTTP targets may be a full URL.
String probeHost(String raw) {
final text = raw.trim();
if (text.isEmpty) {
return '';
}
if (text.contains('://')) {
return Uri.tryParse(text)?.host ?? '';
}
final slash = text.indexOf('/');
final host = slash >= 0 ? text.substring(0, slash) : text;
return host.replaceAll('[', '').replaceAll(']', '');
}
/// Returns a message when the probe must not start. Null means the families allow it.
String? familyRefusal(
String raw, {
required bool v4,
required bool v6,
}) {
if (!v4 && !v6) {
return 'IPv4 和 IPv6 都已关闭,无法开始探测。请在设置里至少打开一个。';
}
final host = probeHost(raw);
final parsed = InternetAddress.tryParse(host);
if (parsed == null) {
return null;
}
if (parsed.type == InternetAddressType.IPv4 && !v4) {
return '目标是 IPv4 地址,但设置里的 IPv4 已关闭。';
}
if (parsed.type == InternetAddressType.IPv6 && !v6) {
return '目标是 IPv6 地址,但设置里的 IPv6 已关闭。';
}
return null;
}
List<InternetAddress> filterAddresses(
List<InternetAddress> addresses, {
required bool v4,
required bool v6,
}) {
return [
for (final address in addresses)
if ((address.type == InternetAddressType.IPv4 && v4) ||
(address.type == InternetAddressType.IPv6 && v6))
address,
];
}
+11
View File
@@ -23,10 +23,21 @@ String portHint(ProbeProfile profile) {
return '合作反射 TCP 默认 19090';
case 'nq-udp':
return '合作反射 UDP 默认 19091';
case 'http':
return 'HTTP 默认 443(https)或 80(http)';
default:
return '${profile.label} 默认 ${profile.port}';
}
}
/// Default port for an HTTP target. A full http:// URL uses 80. Anything else uses 443.
int httpDefaultPort(String target) {
final text = target.trim().toLowerCase();
if (text.startsWith('http://')) {
return 80;
}
return 443;
}
const portHelperText =
'合作反射 TCP 默认 19090,UDP 默认 19091。只有当前端口仍是上一种类型的默认值或为空时,切换类型才会自动更换。';
+9
View File
@@ -64,6 +64,14 @@ class ProbeProfile {
blurb: '发送 RakNet Unconnected Ping,校验 magic 和原时间戳。',
rateLabel: '无应答(未知)',
);
static const http = ProbeProfile(
id: 'http',
label: 'HTTP',
port: 443,
blurb:
'按 HTTP 请求测量。默认优先 HTTP/2,服务器不支持时降到 HTTP/1.1。强制的版本不支持就失败,不会偷偷降级。4xx 和 5xx 会显示状态码,不算丢包。',
rateLabel: '失败率',
);
static const customUdp = ProbeProfile(
id: 'custom-udp',
label: '自定义 UDP',
@@ -81,6 +89,7 @@ class ProbeProfile {
minecraftJava,
minecraftBedrock,
customUdp,
http,
];
static ProbeProfile byId(String id) {
+177 -5
View File
@@ -1,6 +1,7 @@
import 'dart:convert';
import '../protocol/probe_packet.dart';
import 'ip_family.dart';
import 'probe_profile.dart';
class RemoteNode {
@@ -9,35 +10,95 @@ class RemoteNode {
required this.name,
required this.baseUrl,
this.visibility = '',
this.fromCenter = false,
this.confidential = false,
this.centerLinkId = '',
this.serverId = '',
});
final String id;
final String name;
final String baseUrl;
final String visibility;
final bool fromCenter;
final bool confidential;
final String centerLinkId;
final String serverId;
RemoteNode copyWith({String? name, String? baseUrl, String? visibility}) {
RemoteNode copyWith({
String? name,
String? baseUrl,
String? visibility,
bool? fromCenter,
bool? confidential,
String? centerLinkId,
String? serverId,
}) {
final hidden = confidential ?? this.confidential;
return RemoteNode(
id: id,
name: name ?? this.name,
baseUrl: baseUrl ?? this.baseUrl,
baseUrl: hidden ? '' : (baseUrl ?? this.baseUrl),
visibility: visibility ?? this.visibility,
fromCenter: fromCenter ?? this.fromCenter,
confidential: hidden,
centerLinkId: centerLinkId ?? this.centerLinkId,
serverId: serverId ?? this.serverId,
);
}
Map<String, Object?> toJson() => {
'id': id,
'name': name,
'baseUrl': baseUrl,
'baseUrl': confidential ? '' : baseUrl,
'visibility': visibility,
'fromCenter': fromCenter,
'confidential': confidential,
'centerLinkId': centerLinkId,
'serverId': serverId,
};
factory RemoteNode.fromJson(Map<String, dynamic> json) {
final confidential = json['confidential'] == true;
return RemoteNode(
id: json['id'] is String ? json['id'] as String : '',
name: json['name'] is String ? json['name'] as String : '未命名节点',
baseUrl: json['baseUrl'] is String ? json['baseUrl'] as String : '',
baseUrl: confidential
? ''
: (json['baseUrl'] is String ? json['baseUrl'] as String : ''),
visibility: json['visibility'] is String ? json['visibility'] as String : '',
fromCenter: json['fromCenter'] == true,
confidential: confidential,
centerLinkId: json['centerLinkId'] is String
? json['centerLinkId'] as String
: '',
serverId: json['serverId'] is String ? json['serverId'] as String : '',
);
}
}
class CenterLink {
const CenterLink({
required this.id,
required this.url,
required this.account,
});
final String id;
final String url;
final String account;
Map<String, Object?> toJson() => {
'id': id,
'url': url,
'account': account,
};
factory CenterLink.fromJson(Map<String, dynamic> json) {
return CenterLink(
id: json['id'] is String ? json['id'] as String : '',
url: json['url'] is String ? json['url'] as String : '',
account: json['account'] is String ? json['account'] as String : '',
);
}
}
@@ -57,6 +118,18 @@ class SessionConfig {
required this.dnsName,
required this.payloadHex,
required this.expectHex,
this.allowIPv4 = true,
this.allowIPv6 = true,
this.autoUpdate = true,
this.httpVersion = 'auto',
this.httpResolve = '',
this.httpMethod = 'GET',
this.httpBody = '',
this.httpReferer = '',
this.httpUserAgent = '',
this.httpCookies = '',
this.httpMaxRedirects = 5,
this.centers = const [],
});
static const defaults = SessionConfig(
@@ -88,6 +161,27 @@ class SessionConfig {
final String dnsName;
final String payloadHex;
final String expectHex;
final bool allowIPv4;
final bool allowIPv6;
final bool autoUpdate;
final String httpVersion;
final String httpResolve;
final String httpMethod;
final String httpBody;
final String httpReferer;
final String httpUserAgent;
final String httpCookies;
final int httpMaxRedirects;
final List<CenterLink> centers;
CenterLink? centerLink(String id) {
for (final link in centers) {
if (link.id == id) {
return link;
}
}
return null;
}
ProbeProfile get profile => ProbeProfile.byId(profileId);
@@ -101,9 +195,36 @@ class SessionConfig {
}
String? validate() {
final family = familyRefusal(host, v4: allowIPv4, v6: allowIPv6);
if (family != null) {
return family;
}
if (profileId == 'http' && httpResolve.trim().isNotEmpty) {
final resolveFamily = familyRefusal(
httpResolve,
v4: allowIPv4,
v6: allowIPv6,
);
if (resolveFamily != null) {
return resolveFamily.replaceFirst('目标', '指定解析');
}
}
if (host.trim().isEmpty) {
return '请填写目标地址';
}
if (profileId == 'http') {
final method = httpMethod.trim().toUpperCase();
if (method != 'GET' && method != 'POST') {
return 'HTTP 方法只支持 GET 和 POST';
}
if (httpMaxRedirects < 0 || httpMaxRedirects > 20) {
return '跳转次数需要在 0 到 20 之间';
}
const versions = {'auto', '1.1', '2', '3'};
if (!versions.contains(httpVersion)) {
return 'HTTP 版本需要是自动、1.1、2 或 3';
}
}
if (port < 1 || port > 65535) {
return '端口需要在 1 到 65535 之间';
}
@@ -146,7 +267,12 @@ class SessionConfig {
if (selected == null) {
return '请先添加并选择一个远程节点';
}
if (normalizeNodeUrl(selected.baseUrl) == null) {
if (selected.confidential) {
final link = centerLink(selected.centerLinkId);
if (link == null || normalizeNodeUrl(link.url) == null) {
return '保密节点需要一个可用的中心地址';
}
} else if (normalizeNodeUrl(selected.baseUrl) == null) {
return '节点地址需要是 http 或 https,且不能把口令写在地址里';
}
}
@@ -167,6 +293,18 @@ class SessionConfig {
'dnsName': dnsName,
'payloadHex': payloadHex,
'expectHex': expectHex,
'allowIPv4': allowIPv4,
'allowIPv6': allowIPv6,
'autoUpdate': autoUpdate,
'httpVersion': httpVersion,
'httpResolve': httpResolve,
'httpMethod': httpMethod,
'httpBody': httpBody,
'httpReferer': httpReferer,
'httpUserAgent': httpUserAgent,
'httpCookies': httpCookies,
'httpMaxRedirects': httpMaxRedirects,
'centers': centers.map((link) => link.toJson()).toList(),
};
factory SessionConfig.fromJson(Map<String, dynamic> json) {
@@ -197,9 +335,43 @@ class SessionConfig {
: defaults.dnsName,
payloadHex: json['payloadHex'] is String ? json['payloadHex'] as String : '',
expectHex: json['expectHex'] is String ? json['expectHex'] as String : '',
allowIPv4: json['allowIPv4'] is bool ? json['allowIPv4'] as bool : true,
allowIPv6: json['allowIPv6'] is bool ? json['allowIPv6'] as bool : true,
autoUpdate: json['autoUpdate'] is bool ? json['autoUpdate'] as bool : true,
httpVersion: json['httpVersion'] is String
? json['httpVersion'] as String
: 'auto',
httpResolve: json['httpResolve'] is String
? json['httpResolve'] as String
: '',
httpMethod: json['httpMethod'] is String
? json['httpMethod'] as String
: 'GET',
httpBody: json['httpBody'] is String ? json['httpBody'] as String : '',
httpReferer: json['httpReferer'] is String
? json['httpReferer'] as String
: '',
httpUserAgent: json['httpUserAgent'] is String
? json['httpUserAgent'] as String
: '',
httpCookies: json['httpCookies'] is String
? json['httpCookies'] as String
: '',
httpMaxRedirects: _asInt(json['httpMaxRedirects'], 5),
centers: _centers(json['centers']),
);
}
static List<CenterLink> _centers(Object? raw) {
if (raw is! List) {
return const [];
}
return [
for (final item in raw)
if (item is Map) CenterLink.fromJson(Map<String, dynamic>.from(item)),
];
}
static int _asInt(Object? value, int fallback) {
if (value is int) {
return value;
+112
View File
@@ -0,0 +1,112 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:convert';
/// A recent probe target. This list is local and never stores node tokens,
/// center credentials, cookies, or request bodies.
class TargetEntry {
const TargetEntry({
required this.host,
required this.port,
required this.profileId,
this.httpUrl = '',
this.method = '',
required this.savedAtMs,
});
final String host;
final int port;
final String profileId;
final String httpUrl;
final String method;
final int savedAtMs;
String get key {
final http = profileId == 'http';
return [
profileId,
'$port',
host.trim(),
http ? httpUrl.trim() : '',
http ? method.trim().toUpperCase() : '',
].join('\u0001');
}
String get label {
final where = httpUrl.trim().isNotEmpty ? httpUrl.trim() : host.trim();
final methodText = profileId == 'http' && method.trim().isNotEmpty
? ' ${method.trim().toUpperCase()}'
: '';
return '$where:$port · $profileId$methodText';
}
Map<String, Object?> toJson() => {
'host': host,
'port': port,
'profileId': profileId,
'httpUrl': httpUrl,
'method': method,
'savedAtMs': savedAtMs,
};
factory TargetEntry.fromJson(Map<String, dynamic> json) {
return TargetEntry(
host: json['host'] is String ? json['host'] as String : '',
port: json['port'] is int ? json['port'] as int : 0,
profileId: json['profileId'] is String ? json['profileId'] as String : '',
httpUrl: json['httpUrl'] is String ? json['httpUrl'] as String : '',
method: json['method'] is String ? json['method'] as String : '',
savedAtMs: json['savedAtMs'] is int ? json['savedAtMs'] as int : 0,
);
}
}
class TargetHistory {
const TargetHistory(this.entries);
static const maxEntries = 40;
static const empty = TargetHistory([]);
final List<TargetEntry> entries;
TargetHistory add(TargetEntry entry) {
final next = [
entry,
for (final item in entries)
if (item.key != entry.key) item,
];
if (next.length > maxEntries) {
return TargetHistory(next.sublist(0, maxEntries));
}
return TargetHistory(next);
}
TargetHistory removeAt(int index) {
if (index < 0 || index >= entries.length) {
return this;
}
return TargetHistory([
for (var i = 0; i < entries.length; i++)
if (i != index) entries[i],
]);
}
TargetHistory clear() => empty;
String encode() => jsonEncode(entries.map((entry) => entry.toJson()).toList());
factory TargetHistory.decode(String raw) {
if (raw.trim().isEmpty) {
return empty;
}
final decoded = jsonDecode(raw);
if (decoded is! List) {
return empty;
}
return TargetHistory([
for (final item in decoded)
if (item is Map) TargetEntry.fromJson(Map<String, dynamic>.from(item)),
]);
}
}
+152
View File
@@ -0,0 +1,152 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:convert';
import 'dart:io';
import '../metrics/sample_book.dart';
const helperMissingNote =
'本机 HTTP 探测使用和节点相同的 Go 引擎。请把 netquality-reflector 放在程序旁边,或设置环境变量 NQ_PROBE_HELPER。远程节点不受影响。';
String? locateProbeHelper() {
final env = Platform.environment['NQ_PROBE_HELPER'];
if (env != null && env.isNotEmpty && File(env).existsSync()) {
return env;
}
final dir = File(Platform.resolvedExecutable).parent;
final names = Platform.isWindows
? const ['netquality-reflector.exe', 'netquality-helper.exe']
: const ['netquality-reflector', 'netquality-helper'];
for (final name in names) {
final file = File('${dir.path}${Platform.pathSeparator}$name');
if (file.existsSync()) {
return file.path;
}
}
return null;
}
Outcome outcomeFromHelper(String line) {
try {
final decoded = jsonDecode(line);
if (decoded is! Map) {
return const Outcome(
status: Outcome.error,
kind: Outcome.query,
note: '探测引擎返回的内容无效',
);
}
final detail = <String, String>{};
final rawDetail = decoded['detail'];
if (rawDetail is Map) {
rawDetail.forEach((key, value) {
if (key is String && value != null) {
detail[key] = '$value';
}
});
}
return Outcome(
status: decoded['status'] is String
? decoded['status'] as String
: Outcome.error,
kind: decoded['kind'] is String
? decoded['kind'] as String
: Outcome.query,
rttMs: decoded['rttMs'] is num
? (decoded['rttMs'] as num).toDouble()
: null,
note: decoded['note'] is String ? decoded['note'] as String : '',
detail: detail,
);
} on FormatException {
return const Outcome(
status: Outcome.error,
kind: Outcome.query,
note: '探测引擎返回的内容无效',
);
}
}
/// One long-running helper process. Each line is one HTTP sample.
class HttpHelperSession {
HttpHelperSession({this.binary});
final String? binary;
Process? _process;
final _lines = <String>[];
var _closed = false;
Future<Outcome> probe(Map<String, Object?> request) async {
final started = await _ensure();
if (started != null) {
return started;
}
final process = _process;
if (process == null) {
return const Outcome(
status: Outcome.error,
kind: Outcome.query,
note: helperMissingNote,
);
}
process.stdin.writeln(jsonEncode(request));
final line = await _nextLine();
if (line == null) {
return const Outcome(
status: Outcome.error,
kind: Outcome.query,
note: '探测引擎没有返回结果',
);
}
return outcomeFromHelper(line);
}
Future<Outcome?> _ensure() async {
if (_process != null) {
return null;
}
final path = binary ?? locateProbeHelper();
if (path == null) {
return const Outcome(
status: Outcome.error,
kind: Outcome.query,
note: helperMissingNote,
);
}
final process = await Process.start(path, const ['-mode', 'helper']);
_process = process;
process.stdout
.transform(utf8.decoder)
.transform(const LineSplitter())
.listen((line) {
if (line.trim().isNotEmpty) {
_lines.add(line);
}
});
return null;
}
Future<String?> _nextLine() async {
final deadline = DateTime.now().add(const Duration(seconds: 20));
while (DateTime.now().isBefore(deadline)) {
if (_lines.isNotEmpty) {
return _lines.removeAt(0);
}
if (_closed) {
return null;
}
await Future<void>.delayed(const Duration(milliseconds: 20));
}
return null;
}
Future<void> close() async {
_closed = true;
final process = _process;
_process = null;
if (process != null) {
process.kill();
}
}
}
+60 -2
View File
@@ -259,11 +259,36 @@ class ProbeController extends ChangeNotifier {
bool cancelled() => generation != _token;
try {
if (config.remote) {
final selected = config.node!;
var baseUrl = selected.baseUrl;
var token = nodeToken;
if (selected.confidential) {
final link = config.centerLink(selected.centerLinkId);
if (link == null) {
throw RemoteException('找不到签发这台服务器的中心');
}
baseUrl = link.url;
token = nodeToken;
}
if (config.profileId == 'http' || !config.allowIPv4 || !config.allowIPv6) {
if (!selected.confidential) {
final info = await fetchNodeInfo(baseUrl);
final upgrade = remoteUpgradeMessage(
info,
profileId: config.profileId,
allow4: config.allowIPv4,
allow6: config.allowIPv6,
);
if (upgrade != null) {
throw RemoteException(upgrade);
}
}
}
final remote = RemoteProbe();
_remote = remote;
await remote.run(
baseUrl: config.node!.baseUrl,
nodeToken: nodeToken,
baseUrl: baseUrl,
nodeToken: token,
body: ProbeBody(
target: config.host.trim(),
port: config.port,
@@ -276,7 +301,11 @@ class ProbeController extends ChangeNotifier {
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
allowIPv4: config.allowIPv4,
allowIPv6: config.allowIPv6,
http: config.profileId == 'http' ? _httpJson(config) : null,
),
jobsPath: _jobsPath(config),
onSample: (sample) => _accept(generation, sample),
onResolved: (resolved) {
if (generation != _token) {
@@ -328,6 +357,16 @@ class ProbeController extends ChangeNotifier {
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
allowIPv4: config.allowIPv4,
allowIPv6: config.allowIPv6,
httpVersion: config.httpVersion,
httpResolve: config.httpResolve.trim(),
httpMethod: config.httpMethod,
httpBody: config.httpBody,
httpReferer: config.httpReferer,
httpUserAgent: config.httpUserAgent,
httpCookies: config.httpCookies,
httpMaxRedirects: config.httpMaxRedirects,
),
onSample: (sample) => _accept(generation, sample),
cancelled: cancelled,
@@ -491,6 +530,25 @@ class ProbeController extends ChangeNotifier {
}
}
Map<String, Object?> _httpJson(SessionConfig config) => {
'version': config.httpVersion,
'resolve': config.httpResolve.trim(),
'method': config.httpMethod,
'body': config.httpBody,
'referer': config.httpReferer,
'userAgent': config.httpUserAgent,
'cookies': config.httpCookies,
'maxRedirects': config.httpMaxRedirects,
};
String _jobsPath(SessionConfig config) {
final node = config.node;
if (node != null && node.confidential && node.serverId.isNotEmpty) {
return '/v1/center/servers/${node.serverId}/jobs';
}
return '/v1/jobs';
}
String? _echoProblem(String profileId, String echoToken) {
if (profileId != 'nq-tcp' && profileId != 'nq-udp') {
return null;
+90 -4
View File
@@ -4,10 +4,12 @@ import 'dart:typed_data';
import '../metrics/sample_book.dart';
import '../metrics/selection_ledger.dart';
import '../models/ip_family.dart';
import '../protocol/probe_packet.dart';
import '../ui/address_text.dart';
import 'endpoint_picker.dart';
import 'game_codec.dart';
import 'http_helper.dart';
class ProbeRequest {
const ProbeRequest({
@@ -21,6 +23,16 @@ class ProbeRequest {
required this.dnsName,
required this.payloadHex,
required this.expectHex,
this.allowIPv4 = true,
this.allowIPv6 = true,
this.httpVersion = 'auto',
this.httpResolve = '',
this.httpMethod = 'GET',
this.httpBody = '',
this.httpReferer = '',
this.httpUserAgent = '',
this.httpCookies = '',
this.httpMaxRedirects = 5,
});
final String host;
@@ -33,12 +45,22 @@ class ProbeRequest {
final String dnsName;
final String payloadHex;
final String expectHex;
final bool allowIPv4;
final bool allowIPv6;
final String httpVersion;
final String httpResolve;
final String httpMethod;
final String httpBody;
final String httpReferer;
final String httpUserAgent;
final String httpCookies;
final int httpMaxRedirects;
}
/// Sends one probe at a time from this device. A cancelled attempt is not
/// recorded, so stopping cannot paint a fake loss sample.
class ProbeLoop {
ProbeLoop({this.lookup, this.onEndpoint, this.onResolved});
ProbeLoop({this.lookup, this.onEndpoint, this.onResolved, this.helperPath});
/// Replaces [lookupAll] in tests.
final Future<List<InternetAddress>> Function(String host)? lookup;
@@ -49,6 +71,10 @@ class ProbeLoop {
/// Fires once with the lookup result. This is not the address in use.
final void Function(List<InternetAddress> addresses)? onResolved;
/// Overrides the Go HTTP engine binary. Null looks beside the app and at
/// NQ_PROBE_HELPER.
final String? helperPath;
_TcpPipe? _tcp;
_UdpPipe? _udp;
EndpointPicker? _picker;
@@ -59,6 +85,9 @@ class ProbeLoop {
int _seq = 0;
int _dnsId = 1;
final int _guid = DateTime.now().microsecondsSinceEpoch;
bool _allow4 = true;
bool _allow6 = true;
HttpHelperSession? _http;
Future<void> run({
required ProbeRequest request,
@@ -66,6 +95,23 @@ class ProbeLoop {
required bool Function() cancelled,
}) async {
final book = SampleBook(request.profileId);
_allow4 = request.allowIPv4;
_allow6 = request.allowIPv6;
final refusal = familyRefusal(
request.host,
v4: request.allowIPv4,
v6: request.allowIPv6,
);
if (refusal != null) {
final outcome = Outcome(
status: Outcome.error,
kind: Outcome.query,
note: refusal,
);
book.add(outcome);
onSample(book.sample(1, outcome));
return;
}
try {
while (!cancelled()) {
final started = DateTime.now();
@@ -108,6 +154,11 @@ class ProbeLoop {
}
Future<void> close() async {
final http = _http;
_http = null;
if (http != null) {
await http.close();
}
final tcp = _tcp;
_tcp = null;
if (tcp != null) {
@@ -165,6 +216,8 @@ class ProbeLoop {
return _java(request, cancelled);
case 'minecraft-bedrock':
return _bedrock(request, cancelled);
case 'http':
return _httpProbe(request);
default:
return Future.value(
const Outcome(
@@ -656,9 +709,35 @@ class ProbeLoop {
return cached;
}
final found = await (lookup ?? lookupAll)(host);
_resolved = found;
onResolved?.call(found);
return found;
final kept = filterAddresses(found, v4: _allow4, v6: _allow6);
if (kept.isEmpty) {
throw const SocketException('解析到的地址都不在已打开的地址族里');
}
_resolved = kept;
onResolved?.call(kept);
return kept;
}
Future<Outcome> _httpProbe(ProbeRequest request) async {
final session = _http ??= HttpHelperSession(binary: helperPath);
return session.probe({
'profile': 'http',
'target': request.host,
'port': request.port,
'timeoutMs': request.timeout.inMilliseconds,
'allowIPv4': request.allowIPv4,
'allowIPv6': request.allowIPv6,
'http': {
'version': request.httpVersion,
'resolve': request.httpResolve,
'method': request.httpMethod,
'body': request.httpBody,
'referer': request.httpReferer,
'userAgent': request.httpUserAgent,
'cookies': request.httpCookies,
'maxRedirects': request.httpMaxRedirects,
},
});
}
Future<_TcpOpen> _openTcp(
@@ -809,6 +888,13 @@ Outcome _stampAddress(Outcome outcome, InternetAddress peer) {
}
Outcome classifySocket(SocketException error, {bool reconnect = false}) {
if (error.message.contains('地址族') || error.message.contains('已关闭')) {
return Outcome(
status: Outcome.error,
kind: Outcome.query,
note: error.message,
);
}
final text = '${error.message} ${error.osError?.message ?? ''}'.toLowerCase();
final code = error.osError?.errorCode;
if (text.contains('timed out') || text.contains('timeout')) {
+49 -4
View File
@@ -10,6 +10,7 @@ class RemoteProbe {
HttpClient? _client;
String? _jobId;
Uri? _base;
String _jobsPath = '/v1/jobs';
Future<void> run({
required String baseUrl,
@@ -18,19 +19,21 @@ class RemoteProbe {
required void Function(ProbeSample sample) onSample,
required bool Function() cancelled,
void Function(List<ResolvedAddress> resolved)? onResolved,
String jobsPath = '/v1/jobs',
}) async {
final normalized = normalizeNodeUrl(baseUrl);
if (normalized == null) {
throw RemoteException('节点地址需要是 http 或 https,且不能把口令写在地址里');
}
_base = Uri.parse(normalized);
_jobsPath = jobsPath.startsWith('/') ? jobsPath : '/$jobsPath';
final client = HttpClient();
_client = client;
try {
final created = await _send(
client,
'POST',
_base!.resolve('/v1/jobs'),
_base!.resolve(_jobsPath),
nodeToken,
utf8.encode(jsonEncode(body.toJson())),
);
@@ -92,7 +95,7 @@ class RemoteProbe {
await _send(
client,
'DELETE',
base.resolve('/v1/jobs/$id'),
base.resolve('$_jobsPath/$id'),
nodeToken,
const [],
);
@@ -111,7 +114,7 @@ class RemoteProbe {
bool Function() cancelled,
) async {
final request = await client.getUrl(
_base!.resolve('/v1/jobs/$_jobId/stream'),
_base!.resolve('$_jobsPath/$_jobId/stream'),
);
request.followRedirects = false;
_auth(request, nodeToken);
@@ -154,6 +157,9 @@ class ProbeBody {
required this.dnsName,
required this.payloadHex,
required this.expectHex,
this.allowIPv4 = true,
this.allowIPv6 = true,
this.http,
});
final String target;
@@ -167,6 +173,9 @@ class ProbeBody {
final String dnsName;
final String payloadHex;
final String expectHex;
final bool allowIPv4;
final bool allowIPv6;
final Map<String, Object?>? http;
Map<String, Object?> toJson() => {
'target': target,
@@ -180,6 +189,9 @@ class ProbeBody {
'dnsName': dnsName,
'payloadHex': payloadHex,
'expectHex': expectHex,
'allowIPv4': allowIPv4,
'allowIPv6': allowIPv6,
if (http != null) 'http': http,
};
}
@@ -192,10 +204,32 @@ class RemoteException implements Exception {
}
class NodeInfo {
const NodeInfo({required this.visibility, required this.authRequired});
const NodeInfo({
required this.visibility,
required this.authRequired,
this.profiles = const [],
this.ipFamily = false,
});
final String visibility;
final bool authRequired;
final List<String> profiles;
final bool ipFamily;
}
String? remoteUpgradeMessage(
NodeInfo info, {
required String profileId,
required bool allow4,
required bool allow6,
}) {
if (profileId == 'http' && !info.profiles.contains('http')) {
return '这个节点还不支持 HTTP 探测,需要升级到 1.1.3。';
}
if ((!allow4 || !allow6) && !info.ipFamily) {
return '这个节点还不会遵守 IPv4 / IPv6 开关,需要升级到 1.1.3。';
}
return null;
}
Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
@@ -218,11 +252,22 @@ Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
if (json is! Map) {
throw RemoteException('节点信息无效');
}
final profiles = <String>[];
final rawProfiles = json['profiles'];
if (rawProfiles is List) {
for (final item in rawProfiles) {
if (item is String) {
profiles.add(item);
}
}
}
return NodeInfo(
visibility: json['visibility'] is String
? json['visibility'] as String
: '',
authRequired: json['authRequired'] == true,
profiles: profiles,
ipFamily: json['ipFamily'] == true,
);
} on RemoteException {
rethrow;
+12
View File
@@ -5,11 +5,13 @@ import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/session_config.dart';
import '../models/target_history.dart';
import 'token_vault.dart';
class AppStore {
static const _key = 'netquality.settings.v2';
static const _legacy = 'netquality.settings.v1';
static const historyKey = 'netquality.target-history.v1';
Future<({SessionConfig config, String legacyEcho})> load() async {
final prefs = await SharedPreferences.getInstance();
@@ -45,6 +47,16 @@ class AppStore {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_key, jsonEncode(config.toJson()));
}
Future<TargetHistory> loadHistory() async {
final prefs = await SharedPreferences.getInstance();
return TargetHistory.decode(prefs.getString(historyKey) ?? '');
}
Future<void> saveHistory(TargetHistory history) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(historyKey, history.encode());
}
}
Future<TokenVault> openTokenVault() async {
+2
View File
@@ -101,3 +101,5 @@ class FileTokenVault implements TokenVault {
const echoTokenKey = 'target-echo-token';
String nodeTokenKey(String nodeId) => 'node-token.$nodeId';
String centerTokenKey(String centerId) => 'center-token.$centerId';
+165
View File
@@ -0,0 +1,165 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'package:flutter/material.dart';
import '../center/catalog.dart';
import '../center/center_client.dart';
import '../models/session_config.dart';
class AddedCenter {
const AddedCenter({
required this.link,
required this.token,
required this.catalog,
});
final CenterLink link;
final String token;
final Catalog catalog;
}
Future<AddedCenter?> showCenterAddDialog(BuildContext context) {
return showDialog<AddedCenter>(
context: context,
builder: (context) => const _CenterAddDialog(),
);
}
class _CenterAddDialog extends StatefulWidget {
const _CenterAddDialog();
@override
State<_CenterAddDialog> createState() => _CenterAddDialogState();
}
class _CenterAddDialogState extends State<_CenterAddDialog> {
final _url = TextEditingController();
final _account = TextEditingController();
final _token = TextEditingController();
final _password = TextEditingController();
var _busy = false;
String? _hint;
@override
void dispose() {
_url.dispose();
_account.dispose();
_token.dispose();
_password.dispose();
super.dispose();
}
Future<void> _submit() async {
setState(() {
_busy = true;
_hint = null;
});
try {
var token = _token.text.trim();
if (token.isEmpty) {
if (_password.text.isEmpty) {
setState(() => _hint = '请填写口令。如果中心要求密码,也可以只填账号和密码。');
return;
}
token = await loginCenter(
baseUrl: _url.text,
account: _account.text,
password: _password.text,
);
}
final catalog = await fetchCatalog(baseUrl: _url.text, token: token);
final stored = normalizeNodeUrl(_url.text);
if (stored == null) {
setState(() => _hint = '中心地址需要是 http 或 https,且不能把口令写在地址里');
return;
}
if (!mounted) {
return;
}
Navigator.of(context).pop(
AddedCenter(
link: CenterLink(
id: DateTime.now().microsecondsSinceEpoch.toString(),
url: stored,
account: _account.text.trim(),
),
token: token,
catalog: catalog,
),
);
} on CenterClientException catch (error) {
setState(() => _hint = error.message);
} on Object {
setState(() => _hint = '没有完成添加');
} finally {
if (mounted) {
setState(() => _busy = false);
}
}
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('一键添加服务器'),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'点一次确认,会把这个口令能用的服务器全部加进来。显示名由中心决定,这里不能改。保密服务器只保存名称,地址留在中心。',
style: TextStyle(fontSize: 13, height: 1.4),
),
const SizedBox(height: 12),
TextField(
controller: _url,
decoration: const InputDecoration(
labelText: '中心地址',
hintText: 'https://中心:8443',
),
),
const SizedBox(height: 8),
TextField(
controller: _account,
decoration: const InputDecoration(labelText: '账号'),
),
const SizedBox(height: 8),
TextField(
controller: _token,
obscureText: true,
decoration: const InputDecoration(
labelText: '口令',
hintText: '已有口令时填写',
),
),
const SizedBox(height: 8),
TextField(
controller: _password,
obscureText: true,
decoration: const InputDecoration(
labelText: '密码',
hintText: '中心要求密码、手里还没有口令时填写',
),
),
if (_hint != null) ...[
const SizedBox(height: 8),
Text(_hint!, style: const TextStyle(color: Color(0xFF9A3412))),
],
],
),
),
actions: [
TextButton(
onPressed: _busy ? null : () => Navigator.of(context).pop(),
child: const Text('取消'),
),
FilledButton(
onPressed: _busy ? null : _submit,
child: Text(_busy ? '正在获取' : '获取并添加'),
),
],
);
}
}
+488 -16
View File
@@ -1,22 +1,29 @@
import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import '../center/catalog.dart';
import '../center/center_client.dart';
import '../models/node_edit.dart';
import '../models/port_field.dart';
import '../models/probe_profile.dart';
import '../models/session_config.dart';
import '../models/target_history.dart';
import '../probe/endpoint_picker.dart';
import '../probe/probe_controller.dart';
import '../probe/remote_client.dart';
import '../storage/app_store.dart';
import '../storage/token_vault.dart';
import '../update/apply_update.dart';
import 'address_text.dart';
import 'center_dialog.dart';
import 'format.dart';
import 'history_page.dart';
import 'metric_guide_page.dart';
import 'metrics_panel.dart';
import 'quality_charts.dart';
import 'settings_page.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@@ -39,22 +46,40 @@ class _HomePageState extends State<HomePage> {
final _dns = TextEditingController(text: 'example.com');
final _payload = TextEditingController();
final _expect = TextEditingController();
final _httpResolve = TextEditingController();
final _httpBody = TextEditingController();
final _httpReferer = TextEditingController();
final _httpUserAgent = TextEditingController();
final _httpCookies = TextEditingController();
final _httpRedirects = TextEditingController(text: '5');
var _httpVersion = 'auto';
var _httpMethod = 'GET';
var _allow4 = true;
var _allow6 = true;
var _autoUpdate = true;
var _centers = <CenterLink>[];
var _history = TargetHistory.empty;
var _centerHint = '';
var _remote = false;
var _profileId = ProbeProfile.nqTcp.id;
var _nodeId = '';
var _nodes = <RemoteNode>[];
var _ready = false;
var _idSeq = 0;
var _formEpoch = 0;
@override
void initState() {
super.initState();
_controller.addListener(_rebuild);
_host.addListener(_onHostChanged);
_load();
}
Future<void> _load() async {
_vault = await openTokenVault();
final loaded = await _store.load();
final history = await _store.loadHistory();
final echo = await _vault.read(echoTokenKey);
if (!mounted) {
return;
@@ -74,12 +99,42 @@ class _HomePageState extends State<HomePage> {
_dns.text = config.dnsName;
_payload.text = config.payloadHex;
_expect.text = config.expectHex;
_allow4 = config.allowIPv4;
_allow6 = config.allowIPv6;
_autoUpdate = config.autoUpdate;
_httpVersion = config.httpVersion;
_httpMethod = config.httpMethod;
_httpResolve.text = config.httpResolve;
_httpBody.text = config.httpBody;
_httpReferer.text = config.httpReferer;
_httpUserAgent.text = config.httpUserAgent;
_httpCookies.text = config.httpCookies;
_httpRedirects.text = '${config.httpMaxRedirects}';
_centers = config.centers;
_history = history;
_echo.text = (echo == null || echo.isEmpty) ? loaded.legacyEcho : echo;
_ready = true;
});
if (loaded.legacyEcho.isNotEmpty && (echo == null || echo.isEmpty)) {
await _vault.write(echoTokenKey, loaded.legacyEcho);
}
if (config.autoUpdate && Platform.environment['FLUTTER_TEST'] != 'true') {
unawaited(_launchUpdate());
}
}
void _onHostChanged() {
if (_profileId != 'http') {
return;
}
final current = int.tryParse(_port.text.trim());
if (_port.text.trim().isNotEmpty && current != 80 && current != 443) {
return;
}
final next = '${httpDefaultPort(_host.text)}';
if (_port.text != next) {
_port.text = next;
}
}
void _rebuild() {
@@ -93,6 +148,7 @@ class _HomePageState extends State<HomePage> {
unawaited(_controller.stop());
unawaited(_persist());
_controller.removeListener(_rebuild);
_host.removeListener(_onHostChanged);
_controller.dispose();
for (final field in [
_host,
@@ -105,6 +161,12 @@ class _HomePageState extends State<HomePage> {
_dns,
_payload,
_expect,
_httpResolve,
_httpBody,
_httpReferer,
_httpUserAgent,
_httpCookies,
_httpRedirects,
]) {
field.dispose();
}
@@ -126,6 +188,18 @@ class _HomePageState extends State<HomePage> {
dnsName: _dns.text.trim(),
payloadHex: _payload.text.trim(),
expectHex: _expect.text.trim(),
allowIPv4: _allow4,
allowIPv6: _allow6,
autoUpdate: _autoUpdate,
httpVersion: _httpVersion,
httpResolve: _httpResolve.text.trim(),
httpMethod: _httpMethod,
httpBody: _httpBody.text,
httpReferer: _httpReferer.text.trim(),
httpUserAgent: _httpUserAgent.text.trim(),
httpCookies: _httpCookies.text,
httpMaxRedirects: int.tryParse(_httpRedirects.text.trim()) ?? 5,
centers: _centers,
);
}
@@ -137,9 +211,28 @@ class _HomePageState extends State<HomePage> {
Future<void> _start() async {
await _persist();
final config = _config();
final nodeToken = config.node == null
if (config.validate() == null) {
_history = _history.add(
TargetEntry(
host: config.host,
port: config.port,
profileId: config.profileId,
httpUrl: config.profileId == 'http' ? config.host : '',
method: config.profileId == 'http' ? config.httpMethod : '',
savedAtMs: DateTime.now().millisecondsSinceEpoch,
),
);
await _store.saveHistory(_history);
}
final node = config.node;
final nodeToken = node == null
? ''
: (await _vault.read(nodeTokenKey(config.node!.id)) ?? '');
: (await _vault.read(
node.confidential
? centerTokenKey(node.centerLinkId)
: nodeTokenKey(node.id),
) ??
'');
await _controller.start(
config,
nodeToken: nodeToken,
@@ -153,11 +246,17 @@ class _HomePageState extends State<HomePage> {
}
final previous = ProbeProfile.byId(_profileId);
final next = ProbeProfile.byId(id);
final currentPort = int.tryParse(_port.text.trim());
var previousDefault = previous.port;
if (_profileId == 'http' && (currentPort == 80 || currentPort == 443)) {
previousDefault = currentPort!;
}
final nextDefault = id == 'http' ? httpDefaultPort(_host.text) : next.port;
setState(() {
_port.text = portAfterProfileChange(
current: _port.text,
previousDefault: previous.port,
nextDefault: next.port,
previousDefault: previousDefault,
nextDefault: nextDefault,
);
_profileId = id;
});
@@ -176,6 +275,10 @@ class _HomePageState extends State<HomePage> {
PopupMenuButton<String>(
tooltip: '说明',
onSelected: (value) {
if (value == 'settings') {
_openSettings();
return;
}
final page = value == 'history'
? const HistoryPage()
: const MetricGuidePage();
@@ -183,6 +286,7 @@ class _HomePageState extends State<HomePage> {
.push(MaterialPageRoute<void>(builder: (_) => page));
},
itemBuilder: (context) => const [
PopupMenuItem(value: 'settings', child: Text('设置')),
PopupMenuItem(value: 'metrics', child: Text('指标说明')),
PopupMenuItem(value: 'history', child: Text('更新历史')),
],
@@ -210,7 +314,20 @@ class _HomePageState extends State<HomePage> {
children: [
_pair(
wide,
_field(_host, '目标地址', '域名或 IP'),
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: _field(_host, '目标地址', '域名、IP,或 http(s) 地址'),
),
IconButton(
key: const Key('target-history'),
tooltip: '最近目标',
onPressed: view.running ? null : _showHistory,
icon: const Icon(Icons.history),
),
],
),
_field(
_port,
'端口',
@@ -221,7 +338,9 @@ class _HomePageState extends State<HomePage> {
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
key: const Key('profile'),
key: _formEpoch == 0
? const Key('profile')
: Key('profile-$_formEpoch'),
initialValue: _profileId,
decoration: const InputDecoration(labelText: '探测类型'),
items: [
@@ -238,6 +357,7 @@ class _HomePageState extends State<HomePage> {
profile.blurb,
style: const TextStyle(color: muted, fontSize: 13),
),
if (profile.id == 'http') ..._httpFields(view.running),
],
),
),
@@ -400,11 +520,30 @@ class _HomePageState extends State<HomePage> {
? null
: (value) => setState(() => _nodeId = value ?? ''),
),
OutlinedButton(
onPressed: view.running ? null : _manageNodes,
child: const Text('管理节点'),
Wrap(
spacing: 8,
runSpacing: 8,
children: [
OutlinedButton(
onPressed: view.running ? null : _manageNodes,
child: const Text('管理节点'),
),
OutlinedButton(
onPressed: view.running ? null : _addCenter,
child: const Text('一键添加服务器'),
),
],
),
),
if (_centers.isNotEmpty) ...[
const SizedBox(height: 8),
for (final link in _centers) _centerTile(link, view.running),
],
if (_centerHint.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(_centerHint, style: const TextStyle(fontSize: 13)),
),
if (selected != null && nodeUrlLooksPublic(selected.baseUrl))
const Padding(
padding: EdgeInsets.only(top: 8),
@@ -418,6 +557,323 @@ class _HomePageState extends State<HomePage> {
);
}
List<Widget> _httpFields(bool running) {
return [
const SizedBox(height: 12),
DropdownButtonFormField<String>(
key: ValueKey('http-version-$_httpVersion-$_formEpoch'),
initialValue: _httpVersion,
decoration: const InputDecoration(labelText: '协议'),
items: const [
DropdownMenuItem(value: 'auto', child: Text('自动(HTTP/2,可降到 1.1)')),
DropdownMenuItem(value: '1.1', child: Text('仅 HTTP/1.1')),
DropdownMenuItem(value: '2', child: Text('仅 HTTP/2')),
DropdownMenuItem(value: '3', child: Text('仅 HTTP/3')),
],
onChanged: running
? null
: (value) => setState(() => _httpVersion = value ?? 'auto'),
),
const SizedBox(height: 8),
_field(
_httpResolve,
'指定解析',
'可选。Host 和 SNI 仍用上面的地址,连接改走这里的 IP 或主机名',
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
key: ValueKey('http-method-$_httpMethod-$_formEpoch'),
initialValue: _httpMethod,
decoration: const InputDecoration(labelText: '方法'),
items: const [
DropdownMenuItem(value: 'GET', child: Text('GET')),
DropdownMenuItem(value: 'POST', child: Text('POST')),
],
onChanged: running
? null
: (value) => setState(() => _httpMethod = value ?? 'GET'),
),
if (_httpMethod == 'POST') ...[
const SizedBox(height: 8),
_field(_httpBody, '请求体', '可选'),
],
const SizedBox(height: 8),
_field(_httpReferer, 'Referer', '可选'),
const SizedBox(height: 8),
_field(_httpUserAgent, 'User-Agent', '可选'),
const SizedBox(height: 8),
_field(_httpCookies, 'Cookies', '可选', secret: true),
const SizedBox(height: 8),
_field(_httpRedirects, '最大跳转次数', '默认 5,0 到 20'),
];
}
String _httpSummary(Map<String, String> detail) {
final parts = [
if (detail['httpVersion'] != null) 'HTTP/${detail['httpVersion']}',
if (detail['statusCode'] != null) '状态 ${detail['statusCode']}',
if (detail['finalUrl'] != null) detail['finalUrl']!,
];
final times = [
if (detail['dnsMs'] != null) 'DNS ${detail['dnsMs']} ms',
if (detail['connectMs'] != null) '连接 ${detail['connectMs']} ms',
if (detail['tlsMs'] != null) 'TLS ${detail['tlsMs']} ms',
if (detail['ttfbMs'] != null) 'TTFB ${detail['ttfbMs']} ms',
if (detail['totalMs'] != null) '总计 ${detail['totalMs']} ms',
];
final chain = detail['redirects'];
return [
parts.join(' · '),
if (times.isNotEmpty) times.join(','),
if (chain != null && chain.isNotEmpty) '跳转 $chain',
].where((part) => part.isNotEmpty).join('\n');
}
Future<void> _openSettings() async {
await Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (_) => SettingsPage(
allowIPv4: _allow4,
allowIPv6: _allow6,
autoUpdate: _autoUpdate,
onAllowIPv4: (value) {
setState(() => _allow4 = value);
unawaited(_persist());
},
onAllowIPv6: (value) {
setState(() => _allow6 = value);
unawaited(_persist());
},
onAutoUpdate: (value) {
setState(() => _autoUpdate = value);
unawaited(_persist());
},
),
),
);
}
Future<void> _launchUpdate() async {
final result = await checkForUpdate();
final offer = result.offer;
if (offer == null || !mounted || !_autoUpdate) {
return;
}
await installOffer(offer);
}
Future<void> _showHistory() async {
if (_history.entries.isEmpty) {
setState(() => _centerHint = '');
if (!mounted) {
return;
}
await showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: const Text('最近目标'),
content: const Text('还没有保存过目标。点「开始探测」之后,这里会记下地址、端口和类型。'),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('关闭'),
),
],
),
);
return;
}
await showDialog<void>(
context: context,
builder: (context) => AlertDialog(
title: const Text('最近目标'),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (var i = 0; i < _history.entries.length; i++)
ListTile(
contentPadding: EdgeInsets.zero,
title: Text(_history.entries[i].label),
onTap: () {
_applyHistory(_history.entries[i]);
Navigator.pop(context);
},
trailing: IconButton(
tooltip: '删除',
onPressed: () async {
_history = _history.removeAt(i);
await _store.saveHistory(_history);
if (context.mounted) {
Navigator.pop(context);
}
await _showHistory();
},
icon: const Icon(Icons.close),
),
),
],
),
),
actions: [
TextButton(
onPressed: () async {
_history = _history.clear();
await _store.saveHistory(_history);
if (context.mounted) {
Navigator.pop(context);
}
},
child: const Text('全部清除'),
),
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('关闭'),
),
],
),
);
}
void _applyHistory(TargetEntry entry) {
setState(() {
_formEpoch += 1;
_profileId = entry.profileId;
_host.text = entry.httpUrl.isNotEmpty ? entry.httpUrl : entry.host;
_port.text = '${entry.port}';
if (entry.profileId == 'http' && entry.method.isNotEmpty) {
_httpMethod = entry.method;
}
});
}
String _newId() {
_idSeq += 1;
return '${DateTime.now().microsecondsSinceEpoch}-$_idSeq';
}
Future<void> _addCenter() async {
final added = await showCenterAddDialog(context);
if (added == null) {
return;
}
var link = added.link;
for (final existing in _centers) {
if (existing.url == added.link.url && existing.account == added.link.account) {
link = existing;
break;
}
}
await _vault.write(centerTokenKey(link.id), added.token);
await _applyCatalog(link, added.catalog, '已添加 ${added.catalog.servers.length} 台服务器');
}
Future<void> _refreshCenter(CenterLink link) async {
try {
final token = await _vault.read(centerTokenKey(link.id)) ?? '';
final catalog = await fetchCatalog(baseUrl: link.url, token: token);
await _applyCatalog(link, catalog, '已按中心重新同步');
} on CenterClientException catch (error) {
setState(() => _centerHint = error.message);
}
}
Future<void> _removeCenter(CenterLink link) async {
final gone = [
for (final node in _nodes)
if (node.centerLinkId == link.id) node.id,
];
for (final id in gone) {
await _vault.delete(nodeTokenKey(id));
}
await _vault.delete(centerTokenKey(link.id));
setState(() {
_centers = [for (final item in _centers) if (item.id != link.id) item];
_nodes = [
for (final node in _nodes)
if (node.centerLinkId != link.id) node,
];
if (!_nodes.any((node) => node.id == _nodeId)) {
_nodeId = '';
}
_centerHint = '已移除这个中心口令及其服务器';
});
await _persist();
}
Future<void> _applyCatalog(CenterLink link, Catalog catalog, String hint) async {
final before = {
for (final node in _nodes)
if (node.centerLinkId == link.id) node.id,
};
final merged = mergeCenterCatalog(
existing: _nodes,
link: link,
catalog: catalog,
newId: _newId,
);
final after = {
for (final node in merged.nodes)
if (node.centerLinkId == link.id) node.id,
};
for (final id in before.difference(after)) {
await _vault.delete(nodeTokenKey(id));
}
for (final node in merged.nodes) {
if (node.centerLinkId == link.id && node.confidential) {
await _vault.delete(nodeTokenKey(node.id));
}
}
for (final entry in merged.credentials.entries) {
await _vault.write(nodeTokenKey(entry.key), entry.value);
}
setState(() {
if (!_centers.any((item) => item.id == link.id)) {
_centers = [..._centers, link];
}
_nodes = merged.nodes;
_centerHint = hint;
});
await _persist();
}
Widget _centerTile(CenterLink link, bool running) {
final servers = [
for (final node in _nodes)
if (node.centerLinkId == link.id) node,
];
final title = link.account.isEmpty ? link.url : '${link.account} · ${link.url}';
return ExpansionTile(
tilePadding: EdgeInsets.zero,
title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis),
subtitle: Text('${servers.length} 台服务器'),
children: [
for (final node in servers)
ListTile(
contentPadding: EdgeInsets.zero,
title: Text(node.name),
subtitle: Text(
node.confidential ? '地址由中心代为连接,本机不保存。' : node.baseUrl,
),
),
Wrap(
spacing: 8,
children: [
TextButton(
onPressed: running ? null : () => _refreshCenter(link),
child: const Text('刷新'),
),
TextButton(
onPressed: running ? null : () => _removeCenter(link),
child: const Text('移除'),
),
],
),
],
);
}
String _nodeLabel(RemoteNode node) {
final vis = visibilityLabel(node.visibility);
return '${node.name} · $vis';
@@ -493,6 +949,11 @@ class _HomePageState extends State<HomePage> {
const SizedBox(height: 8),
Text(view.note, style: const TextStyle(color: ink)),
],
if (view.detail['httpVersion'] != null ||
view.detail['statusCode'] != null) ...[
const SizedBox(height: 8),
Text(_httpSummary(view.detail), style: const TextStyle(color: ink)),
],
if (motd != null || version != null || players != null) ...[
const SizedBox(height: 8),
Text(
@@ -622,6 +1083,10 @@ class _NodeDialogState extends State<_NodeDialog> {
}
void _beginEdit(RemoteNode node) {
if (node.fromCenter) {
setState(() => _hint = '中心分配的名称和地址不能在这里修改。需要变更时,回到中心刷新。');
return;
}
setState(() {
_editingId = node.id;
_name.text = node.name;
@@ -642,6 +1107,10 @@ class _NodeDialogState extends State<_NodeDialog> {
}
Future<void> _check(RemoteNode node) async {
if (node.confidential) {
setState(() => _hint = '这台服务器由中心代为连接,本机没有地址,不能直接检查。');
return;
}
try {
final info = await fetchNodeInfo(node.baseUrl);
final next = [
@@ -695,18 +1164,21 @@ class _NodeDialogState extends State<_NodeDialog> {
'${node.name} · ${visibilityLabel(node.visibility)}',
),
subtitle: Text(
node.baseUrl,
maxLines: 1,
node.confidential
? '地址由中心代为连接,本机不保存。'
: node.baseUrl,
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
trailing: Wrap(
spacing: 4,
children: [
TextButton(
key: Key('edit-node-${node.id}'),
onPressed: () => _beginEdit(node),
child: const Text('编辑'),
),
if (!node.fromCenter)
TextButton(
key: Key('edit-node-${node.id}'),
onPressed: () => _beginEdit(node),
child: const Text('编辑'),
),
TextButton(
onPressed: () => _check(node),
child: const Text('检查'),
+8
View File
@@ -57,6 +57,14 @@ class MetricGuidePage extends StatelessWidget {
title: '实际地址和 IPv6 回退',
body: '「实际地址」是这次真正连通或真正发包的 IP,并注明 IPv4 或 IPv6。「解析到」只是域名解析的结果,不会被说成已经在用的地址。\n\n正在尝试、还没有正式结果时,会标明正在尝试,而不是写成已经发往。远程节点如果没有在结果里带上地址(旧版本就是这样),界面写「节点没有报告实际使用的地址」,不会在手机上另做一次解析来冒充。\n\n地址落在 198.18.0.0/15 时,会提示这是 VPN 假地址,只有这个 VPN 开着时才能用。',
),
_Section(
title: 'IPv4 和 IPv6',
body: '设置里有两个开关,默认都开着。解析出多个地址以后,只向打开的地址族发包。只开一个,就只用那一个。两个都关掉时不会开始,并说明原因。目标本身就是被关掉的那种地址时,也不会开始。\n\n远程任务会带上同样的选择,节点不会改用另一个地址族。结果里的实际地址和地址族,仍然是这一次真正用到的那个。',
),
_Section(
title: 'HTTP',
body: 'HTTP 探测记下 DNS、连接、TLS、首字节和总时间,以及状态码、最终地址和实际用到的 HTTP 版本(1.1、2 或 3)。曲线上的延迟是总时间。已经收到的响应算成功,4xx 和 5xx 只显示状态码,不叫丢包,也不算进失败率。连不上或强制的版本不被支持,才算失败。\n\n默认先试 HTTP/2,不行再降到 1.1。选了「仅 HTTP/1.1」「仅 HTTP/2」或「仅 HTTP/3」时,服务器不支持就失败,不会悄悄换一种。指定解析只改连接走的地址,Host 和 SNI 仍用目标网址,用来看 CDN。它不是把 1.1.1.1 当成 DNS 服务器。\n\nHTTP/3 的连接和 TLS 是同一次 QUIC 握手,这两项时间相同。本机探测和节点用的是同一个 Go 引擎。桌面端需要把 netquality-reflector 放在程序旁边,或设置 NQ_PROBE_HELPER。Android 上如果系统不允许从应用目录启动这个程序,本机 HTTP 会说明缺引擎;远程节点不受影响。',
),
_Section(
title: '停止以后',
body: '点停止会保留曲线,并给出开始、结束、用时、目标、类型、来源、实际地址和同一套最终指标。正在进行、因为停止而被取消的请求不计入丢包。重新开始会换一次新的会话,旧曲线不会混进来。\n\n点曲线上的一点可以钉住该时刻的延迟和比率,松手后仍然留着。再点另一点会换。新会话或这个点滚出窗口后,选择会被清掉,不会跳到别的点上。',
+12
View File
@@ -69,6 +69,12 @@ MetricLine _timeoutLine(ProbeSummary summary, String profileId) {
case 'tcp-connect':
case 'minecraft-java':
return const MetricLine('超时', '不适用', detail: '这种探测把连不上记为失败,不单独叫探测超时。');
case 'http':
return const MetricLine(
'超时',
'不适用',
detail: 'HTTP 把连不上记为失败。已经收到的 4xx 和 5xx 是状态码,不是丢包,也不算进超时。',
);
default:
return MetricLine(
'超时',
@@ -97,6 +103,12 @@ MetricLine _rateLine(ProbeSummary summary, String profileId) {
formatPct(summary.failurePct),
detail: '未成功的正式尝试 ÷ 已完成的正式尝试。这不是物理丢包。',
);
case 'http':
return MetricLine(
'失败率',
formatPct(summary.failurePct),
detail: '连不上或协议不对才算失败。收到 HTTP 响应就算成功,4xx 和 5xx 只显示状态码,不叫丢包。曲线上的延迟是这一次的总时间。',
);
default:
return MetricLine(
'无应答(未知)',
+179
View File
@@ -0,0 +1,179 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:io';
import 'package:flutter/material.dart';
import '../update/apply_update.dart';
import '../update/update_check.dart';
import '../version.dart';
class SettingsPage extends StatefulWidget {
const SettingsPage({
super.key,
required this.allowIPv4,
required this.allowIPv6,
required this.autoUpdate,
required this.onAllowIPv4,
required this.onAllowIPv6,
required this.onAutoUpdate,
});
final bool allowIPv4;
final bool allowIPv6;
final bool autoUpdate;
final ValueChanged<bool> onAllowIPv4;
final ValueChanged<bool> onAllowIPv6;
final ValueChanged<bool> onAutoUpdate;
@override
State<SettingsPage> createState() => _SettingsPageState();
}
class _SettingsPageState extends State<SettingsPage> {
late bool _allow4;
late bool _allow6;
late bool _auto;
var _checking = false;
String _message = '';
UpdateOffer? _offer;
@override
void initState() {
super.initState();
_allow4 = widget.allowIPv4;
_allow6 = widget.allowIPv6;
_auto = widget.autoUpdate;
}
Future<void> _check() async {
setState(() {
_checking = true;
_message = '';
_offer = null;
});
final result = await checkForUpdate();
if (!mounted) {
return;
}
setState(() {
_checking = false;
_message = result.message;
_offer = result.offer;
});
}
Future<void> _install() async {
final offer = _offer;
if (offer == null) {
return;
}
setState(() => _checking = true);
final message = await installOffer(offer);
if (!mounted) {
return;
}
setState(() {
_checking = false;
_message = message;
});
}
@override
Widget build(BuildContext context) {
final wide = MediaQuery.sizeOf(context).width >= 720;
return Scaffold(
appBar: AppBar(
title: const Text('设置'),
backgroundColor: const Color(0xFFF3F1EC),
),
body: SafeArea(
child: Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 760),
child: ListView(
padding: EdgeInsets.fromLTRB(wide ? 24 : 12, 8, wide ? 24 : 12, 28),
children: [
SwitchListTile(
title: const Text('允许 IPv4'),
subtitle: const Text('关掉以后,解析结果里的 IPv4 不会用来发包。直接填写 IPv4 地址也会被拒绝。'),
value: _allow4,
onChanged: (value) {
setState(() => _allow4 = value);
widget.onAllowIPv4(value);
},
),
SwitchListTile(
title: const Text('允许 IPv6'),
subtitle: const Text('关掉以后,解析结果里的 IPv6 不会用来发包。直接填写 IPv6 地址也会被拒绝。'),
value: _allow6,
onChanged: (value) {
setState(() => _allow6 = value);
widget.onAllowIPv6(value);
},
),
const Padding(
padding: EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Text(
'两个都关掉时不能开始探测。远程节点会收到同样的选择。1.1.2 的节点还不会遵守这个开关,遇到这种情况会提示升级。',
style: TextStyle(color: Color(0xFF5C656B), fontSize: 13, height: 1.4),
),
),
const Divider(),
SwitchListTile(
title: const Text('自动检查更新'),
subtitle: const Text('默认打开。关闭后,启动时不检查,也不会自动下载。'),
value: _auto,
onChanged: (value) {
setState(() => _auto = value);
widget.onAutoUpdate(value);
},
),
Padding(
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Text(
'当前版本 $appVersion(构建 $appBuild)。1.1.2 没有自更新,从 1.1.2 升到 1.1.3 仍要手动安装。从这一版起才会自己检查。先试 GitHub,连不上再试言灸的 Git。\n\n要在没有新版本时试这个功能,可以把环境变量 NQ_UPDATE_GITHUB_API 指到一个同样格式的测试地址,NQ_UPDATE_GITEA_API 是备用。',
style: const TextStyle(color: Color(0xFF5C656B), fontSize: 13, height: 1.4),
),
),
if (Platform.isAndroid)
const Padding(
padding: EdgeInsets.fromLTRB(16, 0, 16, 8),
child: Text(
'在 Android 上安装时,系统会弹出安装确认。这一步不能跳过。',
style: TextStyle(color: Color(0xFF9A3412), fontSize: 13, height: 1.4),
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: [
FilledButton(
onPressed: _checking ? null : _check,
child: Text(_checking ? '正在检查' : '检查更新'),
),
if (_offer != null)
FilledButton(
onPressed: _checking ? null : _install,
child: const Text('下载并安装'),
),
],
),
),
if (_message.isNotEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Text(_message),
),
],
),
),
),
),
);
}
}
+179
View File
@@ -0,0 +1,179 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:ffi' show Abi;
import 'dart:io';
import 'package:flutter/services.dart';
import '../version.dart';
import 'installer.dart';
import 'update_check.dart';
class UpdateResult {
const UpdateResult({required this.message, this.offer});
final String message;
final UpdateOffer? offer;
}
const platformChannel = MethodChannel('dev.netquality/platform');
Future<UpdateResult> checkForUpdate() async {
final arch = await _arch();
if (arch.isEmpty) {
return const UpdateResult(message: '认不出这台设备的系统或 CPU,没有下载安装包');
}
final endpoints = UpdateEndpoints(
github: Platform.environment['NQ_UPDATE_GITHUB_API'] ??
UpdateEndpoints.githubDefault,
gitea: Platform.environment['NQ_UPDATE_GITEA_API'] ??
UpdateEndpoints.giteaDefault,
);
final check = await findUpdate(
current: appVersion,
endpoints: endpoints,
os: _os(),
arch: arch,
fetch: (url) => _getText(url),
);
if (check.offer == null) {
return UpdateResult(message: check.message);
}
return UpdateResult(
message: '发现 ${check.offer!.version}。可以下载并覆盖安装。',
offer: check.offer,
);
}
Future<String> installOffer(UpdateOffer offer) async {
final bytes = await _getBytes(Uri.parse(offer.assetUrl));
if (bytes == null) {
return '安装包没有下载下来';
}
var checksumNote = '';
if (offer.checksumUrl != null && offer.checksumUrl!.isNotEmpty) {
final sums = await _getText(Uri.parse(offer.checksumUrl!));
if (sums == null || !checksumMatches(sums, offer.assetName, bytes)) {
return '校验和没有对上,已停止安装';
}
checksumNote = '校验通过。';
} else {
checksumNote = '这次发布没有校验和文件,已按下载的包继续。';
}
if (Platform.isAndroid) {
final temp = await Directory.systemTemp.createTemp('nq-update-');
final file = File('${temp.path}/updates/${offer.assetName}');
await file.parent.create(recursive: true);
await file.writeAsBytes(bytes, flush: true);
await platformChannel.invokeMethod<void>('installApk', {'path': file.path});
return '$checksumNote安装包已交给系统。请在系统弹出的确认里完成安装,这一步不能跳过。';
}
final extracted = await Directory.systemTemp.createTemp('nq-update-');
extractArchive(bytes, offer.assetName, extracted);
final installDir = File(Platform.resolvedExecutable).parent;
if (Platform.isWindows) {
await _windowsReplace(extracted, installDir);
return '$checksumNote已下载。程序即将退出,随后覆盖安装并重新打开。';
}
copyIntoInstall(extracted, installDir);
try {
await Process.run('chmod', ['755', Platform.resolvedExecutable]);
} on ProcessException {
// The existing file is often already executable.
}
await Process.start(
Platform.resolvedExecutable,
const [],
mode: ProcessStartMode.detached,
);
exit(0);
}
Future<void> _windowsReplace(Directory extracted, Directory installDir) async {
final script = File(
'${Directory.systemTemp.path}${Platform.pathSeparator}nq-update-$pid.ps1',
);
final from = _ps(extracted.path);
final to = _ps(installDir.path);
final exe = _ps(Platform.resolvedExecutable);
await script.writeAsString('''
\$target = $pid
\$from = $from
\$to = $to
while (Get-Process -Id \$target -ErrorAction SilentlyContinue) {
Start-Sleep -Milliseconds 200
}
Copy-Item -Path (Join-Path \$from '*') -Destination \$to -Recurse -Force
Start-Process -FilePath $exe
''');
await Process.start('powershell', [
'-NoProfile',
'-ExecutionPolicy',
'Bypass',
'-File',
script.path,
]);
exit(0);
}
String _ps(String path) => "'${path.replaceAll("'", "''")}'";
String _os() {
if (Platform.isAndroid) {
return 'android';
}
if (Platform.isWindows) {
return 'windows';
}
return 'linux';
}
Future<String> _arch() async {
if (Platform.isAndroid) {
try {
final abi = await platformChannel.invokeMethod<String>('abi');
return abi ?? '';
} on PlatformException {
return '';
}
}
switch (Abi.current()) {
case Abi.linuxX64:
case Abi.windowsX64:
return 'amd64';
case Abi.linuxArm64:
case Abi.windowsArm64:
return 'arm64';
default:
return '';
}
}
Future<String?> _getText(Uri url) async {
final bytes = await _getBytes(url);
if (bytes == null) {
return null;
}
return String.fromCharCodes(bytes);
}
Future<List<int>?> _getBytes(Uri url) async {
final client = HttpClient();
try {
final request = await client.getUrl(url);
final response = await request.close().timeout(const Duration(minutes: 2));
if (response.statusCode < 200 || response.statusCode >= 300) {
return null;
}
final chunks = <int>[];
await for (final chunk in response) {
chunks.addAll(chunk);
}
return chunks;
} on Object {
return null;
} finally {
client.close(force: true);
}
}
+127
View File
@@ -0,0 +1,127 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:convert';
import 'dart:io';
import 'package:archive/archive.dart';
import 'package:crypto/crypto.dart';
/// True when [sums] publishes a matching SHA-256 line for [fileName].
/// A published file that does not mention the asset is a failure, not a skip.
bool checksumMatches(String sums, String fileName, List<int> bytes) {
final want = sha256.convert(bytes).toString().toLowerCase();
final base = fileName.split(RegExp(r'[\\/]')).last;
var mentioned = false;
for (final raw in const LineSplitter().convert(sums)) {
final line = raw.trim();
if (line.isEmpty || line.startsWith('#')) {
continue;
}
final match = RegExp(r'^([0-9a-fA-F]{64})\s+\*?(\S+)\s*$').firstMatch(line);
if (match == null) {
continue;
}
final name = match.group(2)!.split(RegExp(r'[\\/]')).last;
if (name != base) {
continue;
}
mentioned = true;
if (match.group(1)!.toLowerCase() == want) {
return true;
}
}
if (!mentioned) {
return false;
}
return false;
}
/// Extracts a zip or tar.gz into [dest]. Paths that climb out of [dest] are skipped.
void extractArchive(List<int> bytes, String fileName, Directory dest) {
final Archive archive;
final lower = fileName.toLowerCase();
if (lower.endsWith('.tar.gz') || lower.endsWith('.tgz')) {
archive = TarDecoder().decodeBytes(GZipDecoder().decodeBytes(bytes));
} else if (lower.endsWith('.zip')) {
archive = ZipDecoder().decodeBytes(bytes);
} else {
throw const FormatException('只支持 zip 和 tar.gz');
}
final root = _singleRoot(archive);
for (final file in archive) {
if (!file.isFile) {
continue;
}
var name = file.name.replaceAll('\\', '/');
while (name.startsWith('./')) {
name = name.substring(2);
}
if (root.isNotEmpty && name.startsWith('$root/')) {
name = name.substring(root.length + 1);
}
if (name.isEmpty || name.startsWith('/') || name.contains('../')) {
continue;
}
final out = File('${dest.path}/$name');
final parent = out.parent.path;
if (!_inside(dest.path, parent) && parent != dest.path) {
continue;
}
out.parent.createSync(recursive: true);
out.writeAsBytesSync(file.content as List<int>);
}
}
/// Copies extracted files onto the existing install directory.
/// Files already there and not in the archive are left in place, so a data
/// file sitting beside the program is not wiped. Nothing outside [installDir]
/// is written.
void copyIntoInstall(Directory extracted, Directory installDir) {
if (!_inside(installDir.path, extracted.path) &&
extracted.path != installDir.path) {
// The source may be a temp directory. That is allowed.
}
for (final entity in extracted.listSync(recursive: true)) {
if (entity is! File) {
continue;
}
final relative = entity.path.substring(extracted.path.length);
final trimmed = relative.replaceAll('\\', '/').replaceFirst(RegExp(r'^/'), '');
if (trimmed.isEmpty || trimmed.contains('../')) {
continue;
}
final target = File('${installDir.path}/$trimmed');
if (!_inside(installDir.path, target.parent.path) &&
target.parent.path != installDir.path) {
continue;
}
target.parent.createSync(recursive: true);
entity.copySync(target.path);
}
}
String _singleRoot(Archive archive) {
String? root;
for (final file in archive) {
final name = file.name.replaceAll('\\', '/');
final slash = name.indexOf('/');
if (slash <= 0) {
return '';
}
final top = name.substring(0, slash);
if (root == null) {
root = top;
} else if (root != top) {
return '';
}
}
return root ?? '';
}
bool _inside(String root, String child) {
final prefix = root.endsWith(Platform.pathSeparator)
? root
: '$root${Platform.pathSeparator}';
return child == root || child.startsWith(prefix);
}
+237
View File
@@ -0,0 +1,237 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
import 'dart:convert';
/// Numeric version. A leading v and a +build suffix are ignored.
class SemVer implements Comparable<SemVer> {
const SemVer(this.major, this.minor, this.patch);
final int major;
final int minor;
final int patch;
static SemVer? parse(String raw) {
var text = raw.trim();
if (text.startsWith('v') || text.startsWith('V')) {
text = text.substring(1);
}
final plus = text.indexOf('+');
if (plus >= 0) {
text = text.substring(0, plus);
}
final dash = text.indexOf('-');
if (dash >= 0) {
text = text.substring(0, dash);
}
final parts = text.split('.');
if (parts.length < 3) {
return null;
}
final major = int.tryParse(parts[0]);
final minor = int.tryParse(parts[1]);
final patch = int.tryParse(parts[2]);
if (major == null || minor == null || patch == null) {
return null;
}
return SemVer(major, minor, patch);
}
bool isNewerThan(SemVer other) => compareTo(other) > 0;
@override
int compareTo(SemVer other) {
if (major != other.major) {
return major.compareTo(other.major);
}
if (minor != other.minor) {
return minor.compareTo(other.minor);
}
return patch.compareTo(other.patch);
}
}
class ReleaseFile {
const ReleaseFile({required this.name, required this.url});
final String name;
final String url;
}
class UpdateEndpoints {
const UpdateEndpoints({required this.github, required this.gitea});
static const githubDefault =
'https://api.github.com/repos/yanjiu0721/netquality/releases/latest';
static const giteaDefault =
'https://git.yanjiu.ltd/api/v1/repos/YanJiu/netquality/releases/latest';
final String github;
final String gitea;
}
class UpdateOffer {
const UpdateOffer({
required this.version,
required this.assetName,
required this.assetUrl,
this.checksumName,
this.checksumUrl,
});
final String version;
final String assetName;
final String assetUrl;
final String? checksumName;
final String? checksumUrl;
}
class UpdateCheck {
const UpdateCheck({this.offer, required this.reachable, this.message = ''});
final UpdateOffer? offer;
final bool reachable;
final String message;
}
/// Picks the client archive for this OS and CPU. Server packages are ignored.
String? pickClientAsset(
List<ReleaseFile> assets, {
required String os,
required String arch,
}) {
final wantOs = os.toLowerCase();
final wantArch = arch.toLowerCase();
for (final asset in assets) {
final name = asset.name.toLowerCase();
if (name.contains('server') || name.contains('reflector')) {
continue;
}
if (wantOs == 'android') {
if (name.endsWith('.apk') && name.contains(wantArch)) {
return asset.name;
}
continue;
}
final archOk =
name.contains(wantArch) ||
(wantArch == 'amd64' && name.contains('x86_64')) ||
(wantArch == 'arm64' && name.contains('aarch64'));
if (!archOk || !name.contains(wantOs)) {
continue;
}
if (wantOs == 'windows' && (name.endsWith('.zip') || name.endsWith('.exe'))) {
return asset.name;
}
if (wantOs == 'linux' &&
(name.endsWith('.tar.gz') || name.endsWith('.tgz'))) {
return asset.name;
}
}
return null;
}
bool looksLikeChecksum(String name) {
final lower = name.toLowerCase();
return lower.contains('sha256') || lower.contains('checksum');
}
UpdateCheck interpretRelease({
required String current,
required String? body,
required String os,
required String arch,
}) {
if (body == null || body.trim().isEmpty) {
return const UpdateCheck(reachable: false, message: '检查更新失败');
}
Object? decoded;
try {
decoded = jsonDecode(body);
} on FormatException {
return const UpdateCheck(reachable: false, message: '检查更新失败');
}
if (decoded is! Map) {
return const UpdateCheck(reachable: false, message: '检查更新失败');
}
final tag = decoded['tag_name'];
final remote = tag is String ? SemVer.parse(tag) : null;
final local = SemVer.parse(current);
if (remote == null || local == null) {
return const UpdateCheck(reachable: true, message: '发布说明里的版本号无法比较');
}
if (!remote.isNewerThan(local)) {
return UpdateCheck(reachable: true, message: '当前已经是 $current');
}
final assets = <ReleaseFile>[];
final rawAssets = decoded['assets'];
if (rawAssets is List) {
for (final item in rawAssets) {
if (item is! Map) {
continue;
}
final name = item['name'];
final url = item['browser_download_url'];
final link = url is String ? url : '';
if (name is String && link.isNotEmpty) {
assets.add(ReleaseFile(name: name, url: link));
}
}
}
final pickedName = pickClientAsset(assets, os: os, arch: arch);
if (pickedName == null) {
return UpdateCheck(
reachable: true,
message: '发现 ${remote.major}.${remote.minor}.${remote.patch},但没有适合这台设备的安装包',
);
}
final picked = assets.firstWhere((asset) => asset.name == pickedName);
ReleaseFile? sums;
for (final asset in assets) {
if (looksLikeChecksum(asset.name)) {
sums = asset;
break;
}
}
return UpdateCheck(
reachable: true,
offer: UpdateOffer(
version: '${remote.major}.${remote.minor}.${remote.patch}',
assetName: picked.name,
assetUrl: picked.url,
checksumName: sums?.name,
checksumUrl: sums?.url,
),
);
}
Future<UpdateCheck> findUpdate({
required String current,
required UpdateEndpoints endpoints,
required Future<String?> Function(Uri url) fetch,
required String os,
required String arch,
}) async {
String? body;
try {
body = await fetch(Uri.parse(endpoints.github));
} on Object {
body = null;
}
var check = interpretRelease(current: current, body: body, os: os, arch: arch);
if (!check.reachable) {
try {
body = await fetch(Uri.parse(endpoints.gitea));
} on Object {
body = null;
}
check = interpretRelease(current: current, body: body, os: os, arch: arch);
if (!check.reachable) {
return const UpdateCheck(
reachable: false,
message: 'GitHub 和备用源都连不上,没有检查到更新',
);
}
}
return check;
}
+2 -2
View File
@@ -1,7 +1,7 @@
// Copyright (C) 2026 言灸
// SPDX-License-Identifier: AGPL-3.0-only
const appVersion = '1.1.2';
const appBuild = 5;
const appVersion = '1.1.3';
const appBuild = 6;
const appAttribution = '言灸';
const appLicense = 'AGPL-3.0-only';
+1 -1
View File
@@ -1,6 +1,6 @@
# 网络质量探测 · Linux 桌面客户端
这是 1.1.2 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。
这是 1.1.3 的 Linux 64 位桌面程序,解压后可以直接运行。不需要再安装 Flutter。HTTP 探测还需要同一目录里的 `netquality-reflector`。
## 先安装系统库
+17 -1
View File
@@ -1,6 +1,14 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
archive:
dependency: "direct main"
description:
name: archive
sha256: "2fda90592c0afd219c5e285618a98da835cd10df38372666093d25dfe457a2d0"
url: "https://pub.dev"
source: hosted
version: "4.7.1"
args:
dependency: transitive
description:
@@ -58,7 +66,7 @@ packages:
source: hosted
version: "1.19.1"
crypto:
dependency: transitive
dependency: "direct main"
description:
name: crypto
sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4
@@ -320,6 +328,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.1.8"
posix:
dependency: transitive
description:
name: posix
sha256: "613646d076944f3acc125830af935b48d4b8a57a388691547bbfd25b434f4d63"
url: "https://pub.dev"
source: hosted
version: "6.5.4"
pub_semver:
dependency: transitive
description:
+3 -1
View File
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.1.2+5
version: 1.1.3+6
environment:
sdk: ^3.13.7
@@ -37,6 +37,8 @@ dependencies:
fl_chart: ^1.3.0
path_provider: ^2.1.5
shared_preferences: ^2.5.6
archive: ^4.0.7
crypto: ^3.0.6
dev_dependencies:
flutter_test:
+7 -3
View File
@@ -84,10 +84,14 @@ void main() {
});
test('history only lists the real tag and this version', () {
expect(appVersion, '1.1.2');
expect(appBuild, 5);
expect(appVersion, '1.1.3');
expect(appBuild, 6);
expect(appAttribution, '言灸');
expect(releaseHistory.map((entry) => entry.version), ['1.1.2', '1.1.1']);
expect(releaseHistory.map((entry) => entry.version), [
'1.1.3',
'1.1.2',
'1.1.1',
]);
expect(releaseHistory.last.published, '2026-11-09');
expect(releaseHistory.last.source, contains('v1.1.1'));
expect(releaseHistoryNote, contains('不写成另一个版本'));
+68
View File
@@ -321,6 +321,74 @@ void main() {
everyElement('127.0.0.1'),
);
});
test('a closed address family is not used after lookup', () async {
final echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(echo.close);
echo.listen((event) {
if (event != RawSocketEvent.read) {
return;
}
final datagram = echo.receive();
if (datagram == null) {
return;
}
echo.send(datagram.data, datagram.address, datagram.port);
});
final samples = await _collect(
ProbeRequest(
host: 'example.test',
port: echo.port,
profileId: 'udp-generic',
interval: const Duration(milliseconds: 40),
timeout: const Duration(milliseconds: 300),
packetSize: 16,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
allowIPv6: false,
),
count: 1,
loop: ProbeLoop(
lookup: (_) async => [
InternetAddress('2001:db8::1'),
InternetAddress('127.0.0.1'),
],
),
);
expect(samples.single.status, Outcome.ok);
expect(samples.single.detail['address'], '127.0.0.1');
});
test('local http uses the same go engine as the node', () async {
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(server.close);
server.listen((request) {
request.response.statusCode = 204;
request.response.close();
});
final samples = await _collect(
ProbeRequest(
host: 'http://127.0.0.1:${server.port}/health',
port: server.port,
profileId: 'http',
interval: const Duration(milliseconds: 200),
timeout: const Duration(seconds: 3),
packetSize: 64,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
loop: ProbeLoop(helperPath: binary),
);
expect(samples.single.status, Outcome.ok);
expect(samples.single.detail['statusCode'], '204');
expect(samples.single.detail['httpVersion'], '1.1');
expect(samples.single.summary.failurePct, 0);
});
}
Future<List<ProbeSample>> _collect(
+217
View File
@@ -0,0 +1,217 @@
import 'dart:io';
import 'package:crypto/crypto.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/center/catalog.dart';
import 'package:netquality/models/ip_family.dart';
import 'package:netquality/models/session_config.dart';
import 'package:netquality/models/target_history.dart';
import 'package:netquality/update/installer.dart';
import 'package:netquality/update/update_check.dart';
void main() {
test('version comparison ignores a leading v and a build suffix', () {
final current = SemVer.parse('1.1.3');
expect(SemVer.parse('v1.1.4')!.isNewerThan(current!), isTrue);
expect(SemVer.parse('1.1.3+6')!.isNewerThan(current), isFalse);
expect(SemVer.parse('1.1.2')!.isNewerThan(current), isFalse);
expect(SemVer.parse('1.2.0-rc.1')!.isNewerThan(current), isTrue);
});
test('the matching client archive is chosen and checksum files are recognized', () {
const assets = [
ReleaseFile(name: 'netquality-server-1.1.4-linux-amd64.tar.gz', url: 's'),
ReleaseFile(name: 'netquality-client-1.1.4-linux-amd64.tar.gz', url: 'c'),
ReleaseFile(name: 'SHA256SUMS', url: 'sum'),
];
expect(
pickClientAsset(assets, os: 'linux', arch: 'amd64'),
'netquality-client-1.1.4-linux-amd64.tar.gz',
);
expect(looksLikeChecksum('SHA256SUMS'), isTrue);
final check = interpretRelease(
current: '1.1.3',
os: 'linux',
arch: 'amd64',
body: '''
{
"tag_name": "v1.1.4",
"assets": [
{"name": "netquality-client-1.1.4-linux-amd64.tar.gz", "browser_download_url": "https://example.test/client.tar.gz"},
{"name": "SHA256SUMS", "browser_download_url": "https://example.test/SHA256SUMS"}
]
}
''',
);
expect(check.offer?.assetName, contains('linux-amd64'));
expect(check.offer?.checksumName, 'SHA256SUMS');
});
test('github failure falls through to the spare source', () async {
final check = await findUpdate(
current: '1.1.3',
endpoints: const UpdateEndpoints(
github: 'https://github.invalid/latest',
gitea: 'https://git.invalid/latest',
),
os: 'linux',
arch: 'amd64',
fetch: (url) async {
if (url.host.contains('github')) {
return null;
}
return '''
{"tag_name":"v1.1.9","assets":[
{"name":"netquality-client-1.1.9-linux-amd64.tar.gz","browser_download_url":"https://example.test/a.tar.gz"}
]}
''';
},
);
expect(check.offer?.version, '1.1.9');
});
test('history keeps the newest identical target and can delete or clear', () {
const older = TargetEntry(
host: '203.0.113.8',
port: 443,
profileId: 'http',
httpUrl: 'https://203.0.113.8/a',
method: 'GET',
savedAtMs: 1,
);
const newer = TargetEntry(
host: '203.0.113.8',
port: 443,
profileId: 'http',
httpUrl: 'https://203.0.113.8/a',
method: 'get',
savedAtMs: 2,
);
final history = TargetHistory.empty
.add(older)
.add(
const TargetEntry(
host: 'example.com',
port: 19090,
profileId: 'nq-tcp',
savedAtMs: 3,
),
)
.add(newer);
expect(history.entries, hasLength(2));
expect(history.entries.first.savedAtMs, 2);
expect(history.entries.first.toJson().containsKey('token'), isFalse);
final removed = history.removeAt(0);
expect(removed.entries.single.host, 'example.com');
expect(removed.clear().entries, isEmpty);
var capped = TargetHistory.empty;
for (var i = 0; i < 45; i++) {
capped = capped.add(
TargetEntry(
host: 'h$i',
port: i + 1,
profileId: 'tcp-connect',
savedAtMs: i,
),
);
}
expect(capped.entries, hasLength(TargetHistory.maxEntries));
expect(capped.entries.first.host, 'h44');
final again = TargetHistory.decode(capped.encode());
expect(again.entries.first.host, 'h44');
});
test('disabled families are filtered and a literal of that family is refused', () {
final kept = filterAddresses(
[
InternetAddress('203.0.113.5'),
InternetAddress('2001:db8::1'),
],
v4: true,
v6: false,
);
expect(kept.map((address) => address.address), ['203.0.113.5']);
expect(familyRefusal('2001:db8::1', v4: true, v6: false), contains('IPv6'));
expect(familyRefusal('203.0.113.5', v4: false, v6: true), contains('IPv4'));
expect(familyRefusal('example.com', v4: false, v6: false), contains('都已关闭'));
expect(
familyRefusal('https://203.0.113.9/path', v4: false, v6: true),
contains('IPv4'),
);
});
test('a confidential catalog entry cannot keep an address that was sent by mistake', () {
const secret = 'https://secret-node.internal:8443';
final catalog = Catalog.parse('''
{
"account": "lab",
"group": "lab",
"servers": [
{
"id": "secret-node",
"name": "保密节点",
"confidential": true,
"controlUrl": "$secret",
"credential": "node-token-should-not-leak"
},
{
"id": "lab-node",
"name": "实验室节点",
"confidential": false,
"controlUrl": "https://127.0.0.1:8443",
"credential": "short-lived"
}
]
}
''');
final secretServer = catalog.servers.first;
expect(secretServer.controlUrl, isEmpty);
expect(secretServer.credential, isEmpty);
expect(catalog.servers.last.controlUrl, 'https://127.0.0.1:8443');
const link = CenterLink(id: 'c1', url: 'https://center.example', account: 'lab');
var seq = 0;
final merged = mergeCenterCatalog(
existing: const [
RemoteNode(id: 'manual', name: '手填', baseUrl: 'https://manual.example'),
],
link: link,
catalog: catalog,
newId: () => 'new-${seq++}',
);
final hidden = merged.nodes.firstWhere((node) => node.serverId == 'secret-node');
expect(hidden.baseUrl, isEmpty);
expect(hidden.confidential, isTrue);
expect(merged.credentials.containsKey(hidden.id), isFalse);
expect(storedNodeHides(hidden, secret), isTrue);
expect(storedNodeHides(hidden, 'node-token-should-not-leak'), isTrue);
expect(merged.nodes.any((node) => node.id == 'manual'), isTrue);
expect(renameNode(hidden, '别的名字').name, '保密节点');
final again = SessionConfig.fromJson({
...SessionConfig.defaults.toJson(),
'nodes': [hidden.toJson()],
});
expect(again.nodes.single.baseUrl, isEmpty);
});
test('checksum must mention the asset, and install copy stays inside the directory', () {
final bytes = [1, 2, 3, 4];
expect(checksumMatches('abc other.bin\n', 'client.zip', bytes), isFalse);
final digest = 'e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1e1';
expect(checksumMatches('$digest client.zip\n', 'client.zip', bytes), isFalse);
final want = sha256.convert(bytes).toString();
expect(checksumMatches('$want *client.zip\n', 'client.zip', bytes), isTrue);
final root = Directory.systemTemp.createTempSync('nq-install');
addTearDown(() => root.deleteSync(recursive: true));
final extracted = Directory('${root.path}/extracted')..createSync();
final install = Directory('${root.path}/install')..createSync();
File('${extracted.path}/netquality').writeAsStringSync('new');
File('${install.path}/kept.txt').writeAsStringSync('stay');
copyIntoInstall(extracted, install);
expect(File('${install.path}/netquality').readAsStringSync(), 'new');
expect(File('${install.path}/kept.txt').readAsStringSync(), 'stay');
});
}