feat(devices): P1 设备注册打通 —— 登录/注册即写 devices 表
ci-pangolin / Lint — shellcheck (push) Successful in 8s
ci-pangolin / OpenAPI Sync Check (push) Successful in 16s
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (push) Successful in 7s
ci-pangolin / Flutter — analyze + test (push) Successful in 26s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (push) Successful in 5s
ci-pangolin / Codegen Drift — token 生成物未漂移 (push) Successful in 5s
ci-pangolin / Go — build + test (push) Failing after 10s
ci-pangolin / E2E Smoke — L4 进程级端到端 (push) Successful in 15s
ci-pangolin / Go — integration (mysql/redis testcontainers) (push) Failing after 4m10s
ci-pangolin / Golden — 视觉回归 (components + auth) (push) Successful in 14s
ci-pangolin / Lint — shellcheck (push) Successful in 8s
ci-pangolin / OpenAPI Sync Check (push) Successful in 16s
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (push) Successful in 7s
ci-pangolin / Flutter — analyze + test (push) Successful in 26s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (push) Successful in 5s
ci-pangolin / Codegen Drift — token 生成物未漂移 (push) Successful in 5s
ci-pangolin / Go — build + test (push) Failing after 10s
ci-pangolin / E2E Smoke — L4 进程级端到端 (push) Successful in 15s
ci-pangolin / Go — integration (mysql/redis testcontainers) (push) Failing after 4m10s
ci-pangolin / Golden — 视觉回归 (components + auth) (push) Successful in 14s
后端:auth.Service 加 DeviceMeta + DeviceRegistrar 接口(consumer-side 解耦), Login/Register 成功签发后 best-effort 注册设备(不强制设备上限,避免免费档重装 churn 锁死用户);handler 加 device 请求体;main 用 authDeviceRegistrar 适配 devices.Service 注入;normalizePlatform 加 linux。 客户端:新 device_identity.dart(SecureKV 接缝 + 稳定 UUIDv4 device_id 持久化 + 名称/平台/版本);弃用硬编码 'mac-001';auth_api login/register + connect 携带 device 元数据。加 uuid + device_info_plus 依赖。 测试:auth 设备注册(触发/best-effort/空 meta) + device_identity(生成/持久/ 读失败不重生成/UUIDv4 形态);normalizePlatform linux=true。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -61,11 +61,13 @@ class AuthApi {
|
||||
required String email,
|
||||
required String code,
|
||||
required String password,
|
||||
Map<String, dynamic>? device,
|
||||
}) async {
|
||||
final resp = await _post('/v1/auth/register', {
|
||||
'email': email,
|
||||
'code': code,
|
||||
'password': password,
|
||||
if (device != null) 'device': device,
|
||||
});
|
||||
if (resp.statusCode != 200 && resp.statusCode != 201) {
|
||||
_throwFromResponse(resp);
|
||||
@@ -78,10 +80,12 @@ class AuthApi {
|
||||
Future<AuthTokens> login({
|
||||
required String email,
|
||||
required String password,
|
||||
Map<String, dynamic>? device,
|
||||
}) async {
|
||||
final resp = await _post('/v1/auth/login', {
|
||||
'email': email,
|
||||
'password': password,
|
||||
if (device != null) 'device': device,
|
||||
});
|
||||
if (resp.statusCode != 200) _throwFromResponse(resp);
|
||||
return AuthTokens.fromJson(jsonDecode(resp.body) as Map<String, dynamic>);
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// device_identity.dart — 设备身份:稳定 device_id + 名称/平台/客户端版本上报
|
||||
//
|
||||
// device_id 首次启动随机生成(UUID v4)、写入 flutter_secure_storage 持久化,之后
|
||||
// 每次读取复用 → 同一安装跨重启恒定(替换早期硬编码 'mac-001')。名称/平台/版本
|
||||
// 取自系统。随 登录/注册/连接 上报给控制面,用于「我的设备」登记与会话绑定。
|
||||
import 'dart:io' show Platform;
|
||||
|
||||
import 'package:device_info_plus/device_info_plus.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:package_info_plus/package_info_plus.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
/// 设备元数据,随认证/连接请求上报。
|
||||
class DeviceMeta {
|
||||
const DeviceMeta({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.platform,
|
||||
required this.clientVersion,
|
||||
});
|
||||
|
||||
final String id;
|
||||
final String name;
|
||||
final String platform; // ios | android | windows | macos | linux
|
||||
final String clientVersion;
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
'id': id,
|
||||
'name': name,
|
||||
'platform': platform,
|
||||
'client_version': clientVersion,
|
||||
};
|
||||
}
|
||||
|
||||
/// 极简键值存储接缝(便于单测注入;默认走 flutter_secure_storage)。
|
||||
abstract class SecureKV {
|
||||
Future<String?> read(String key);
|
||||
Future<void> write(String key, String value);
|
||||
}
|
||||
|
||||
class _SecureStorageKV implements SecureKV {
|
||||
// 与 TokenStore 一致:macOS 文件式 keychain,避免未签名 app 报 -34018。
|
||||
static const _s = FlutterSecureStorage(
|
||||
mOptions: MacOsOptions(useDataProtectionKeyChain: false),
|
||||
);
|
||||
@override
|
||||
Future<String?> read(String key) => _s.read(key: key);
|
||||
@override
|
||||
Future<void> write(String key, String value) => _s.write(key: key, value: value);
|
||||
}
|
||||
|
||||
/// 设备身份服务。device_id 持久于安全存储;其余字段取自系统(缓存)。
|
||||
class DeviceIdentity {
|
||||
DeviceIdentity({SecureKV? store}) : _kv = store ?? _SecureStorageKV();
|
||||
|
||||
final SecureKV _kv;
|
||||
static const _kDeviceId = 'pangolin_device_id';
|
||||
static const _uuid = Uuid();
|
||||
|
||||
String? _cachedId;
|
||||
DeviceMeta? _cachedMeta;
|
||||
|
||||
/// 稳定 device_id。读到→复用;读到空→生成并持久化;
|
||||
/// 读**失败**(平台异常)≠ 不存在 → 退回进程内临时 id,**不写库**,避免冲掉真实 id。
|
||||
Future<String> deviceId() async {
|
||||
if (_cachedId != null) return _cachedId!;
|
||||
String? existing;
|
||||
try {
|
||||
existing = await _kv.read(_kDeviceId);
|
||||
} catch (_) {
|
||||
return _cachedId ??= _uuid.v4(); // 临时,不持久化
|
||||
}
|
||||
if (existing != null && existing.isNotEmpty) return _cachedId = existing;
|
||||
final id = _uuid.v4();
|
||||
try {
|
||||
await _kv.write(_kDeviceId, id);
|
||||
} catch (_) {
|
||||
// 写失败:本次用内存值,下次再尝试持久化。
|
||||
}
|
||||
return _cachedId = id;
|
||||
}
|
||||
|
||||
/// 完整设备元数据(缓存,首次解析后复用)。
|
||||
Future<DeviceMeta> meta() async {
|
||||
if (_cachedMeta != null) return _cachedMeta!;
|
||||
final m = DeviceMeta(
|
||||
id: await deviceId(),
|
||||
name: await _name(),
|
||||
platform: currentPlatform(),
|
||||
clientVersion: await _clientVersion(),
|
||||
);
|
||||
return _cachedMeta = m;
|
||||
}
|
||||
|
||||
/// 当前平台标识(与服务端 devices.platform 枚举对齐)。
|
||||
static String currentPlatform() {
|
||||
if (Platform.isIOS) return 'ios';
|
||||
if (Platform.isAndroid) return 'android';
|
||||
if (Platform.isMacOS) return 'macos';
|
||||
if (Platform.isWindows) return 'windows';
|
||||
if (Platform.isLinux) return 'linux';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
Future<String> _name() async {
|
||||
try {
|
||||
if (Platform.isIOS) {
|
||||
final i = await DeviceInfoPlugin().iosInfo;
|
||||
return i.name.isNotEmpty ? i.name : i.utsname.machine;
|
||||
}
|
||||
if (Platform.isAndroid) {
|
||||
final a = await DeviceInfoPlugin().androidInfo;
|
||||
return '${a.manufacturer} ${a.model}'.trim();
|
||||
}
|
||||
// 桌面:主机名最有意义(MacBook-Pro / DESKTOP-XXXX)。
|
||||
return Platform.localHostname;
|
||||
} catch (_) {
|
||||
return currentPlatform();
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> _clientVersion() async {
|
||||
try {
|
||||
final info = await PackageInfo.fromPlatform();
|
||||
return 'v${info.version}';
|
||||
} catch (_) {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 单例 DeviceIdentity(测试可 override)。
|
||||
final deviceIdentityProvider = Provider<DeviceIdentity>((ref) => DeviceIdentity());
|
||||
@@ -14,18 +14,13 @@ import '../bridge/vpn_bridge_provider.dart';
|
||||
import '../l10n/app_text.dart';
|
||||
import '../services/api_config.dart';
|
||||
import '../services/connect_api.dart';
|
||||
import '../services/device_identity.dart';
|
||||
import 'app_providers.dart';
|
||||
import 'auth_provider.dart';
|
||||
import 'nodes_provider.dart';
|
||||
import 'settings_provider.dart';
|
||||
|
||||
// ── 设备 ID(MVP 常量;后续由 device_info_plus 取真实 ID)──────────
|
||||
|
||||
const _kDeviceId = String.fromEnvironment(
|
||||
'PANGOLIN_DEVICE_ID',
|
||||
defaultValue: 'mac-001',
|
||||
);
|
||||
|
||||
// 设备 ID 由 deviceIdentityProvider 提供(secure storage 持久化的稳定 UUID)。
|
||||
// API base URL 统一用 api_config.dart 的 kApiBaseUrl(单一来源,勿再重复声明)。
|
||||
|
||||
// ── 连接阶段枚举 ──────────────────────────────────────────────────
|
||||
@@ -133,13 +128,14 @@ class ConnectionController extends StateNotifier<ConnectionState> {
|
||||
/// 取配置;access token 过期(401)时用 refresh token 续期后**重试一次**。
|
||||
/// 续期失败(refresh 也过期 / 被拒)由 authProvider.refresh() 触发登出 → UI 回登录页。
|
||||
Future<String> _fetchConfigWithRefresh(String nodeUuid) async {
|
||||
final deviceId = await _ref.read(deviceIdentityProvider).deviceId();
|
||||
Future<String> doFetch() {
|
||||
final token = _ref.read(authProvider).accessToken ?? '';
|
||||
_api?.dispose();
|
||||
_api = _ref.read(connectApiFactoryProvider)(token);
|
||||
return _api!.fetchConfig(
|
||||
nodeId: nodeUuid,
|
||||
deviceId: _kDeviceId,
|
||||
deviceId: deviceId,
|
||||
// smartRoute 偏好 → 国内分流(#5):国内 IP/域名直连,不走隧道。
|
||||
splitCN: _ref.read(settingsProvider).smartRoute,
|
||||
);
|
||||
|
||||
@@ -10,6 +10,7 @@ import '../l10n/app_text.dart';
|
||||
import '../pangolin_theme.dart';
|
||||
import '../services/api_config.dart';
|
||||
import '../services/auth_api.dart';
|
||||
import '../services/device_identity.dart';
|
||||
import '../state/auth_provider.dart';
|
||||
import 'pangolin_button.dart';
|
||||
import 'pangolin_icons.dart';
|
||||
@@ -100,10 +101,12 @@ class _AuthScreenState extends ConsumerState<AuthScreen>
|
||||
Future<void> _doRegister() async {
|
||||
setState(() { _loading = true; _errorZh = null; });
|
||||
try {
|
||||
final device = (await ref.read(deviceIdentityProvider).meta()).toJson();
|
||||
final tokens = await _api.register(
|
||||
email: _email.text.trim(),
|
||||
code: _code.text.trim(),
|
||||
password: _pw.text,
|
||||
device: device,
|
||||
);
|
||||
await ref.read(tokenStoreProvider).saveLastEmail(_email.text.trim());
|
||||
await ref.read(authProvider.notifier).saveTokens(tokens);
|
||||
@@ -116,9 +119,11 @@ class _AuthScreenState extends ConsumerState<AuthScreen>
|
||||
Future<void> _doLogin() async {
|
||||
setState(() { _loading = true; _errorZh = null; });
|
||||
try {
|
||||
final device = (await ref.read(deviceIdentityProvider).meta()).toJson();
|
||||
final tokens = await _api.login(
|
||||
email: _email.text.trim(),
|
||||
password: _pw.text,
|
||||
device: device,
|
||||
);
|
||||
await ref.read(tokenStoreProvider).saveLastEmail(_email.text.trim());
|
||||
await ref.read(authProvider.notifier).saveTokens(tokens);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import FlutterMacOS
|
||||
import Foundation
|
||||
|
||||
import device_info_plus
|
||||
import flutter_secure_storage_macos
|
||||
import package_info_plus
|
||||
import screen_retriever_macos
|
||||
@@ -13,6 +14,7 @@ import tray_manager
|
||||
import window_manager
|
||||
|
||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||
DeviceInfoPlusMacosPlugin.register(with: registry.registrar(forPlugin: "DeviceInfoPlusMacosPlugin"))
|
||||
FlutterSecureStoragePlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStoragePlugin"))
|
||||
FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin"))
|
||||
ScreenRetrieverMacosPlugin.register(with: registry.registrar(forPlugin: "ScreenRetrieverMacosPlugin"))
|
||||
|
||||
+3
-1
@@ -17,9 +17,11 @@ dependencies:
|
||||
flutter_riverpod: ^2.5.1 # 状态层(连接状态机 / 免费额度 / 节点选择 / 语言 / 主题)
|
||||
http: ^1.2.1 # 控制面 HTTP 客户端(connect API)
|
||||
path_provider: ^2.1.3 # 获取应用支持目录(sing-box 配置路径)
|
||||
flutter_secure_storage: ^9.2.2 # JWT token 安全存储
|
||||
flutter_secure_storage: ^9.2.2 # JWT token 安全存储 + 稳定 device_id 持久化
|
||||
shared_preferences: ^2.5.5
|
||||
package_info_plus: ^9.0.1
|
||||
device_info_plus: ^11.2.0 # 设备名/平台(「我的设备」上报)
|
||||
uuid: ^4.5.1 # 客户端生成稳定 device_id (UUID v4)
|
||||
launch_at_startup: ^0.5.1
|
||||
tray_manager: ^0.5.3
|
||||
window_manager: ^0.5.1
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// device_identity_test.dart — 稳定 device_id 的生成/持久/读失败语义
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pangolin_vpn/services/device_identity.dart';
|
||||
|
||||
/// 内存版 SecureKV:可模拟读失败,记录写入。
|
||||
class _FakeKV implements SecureKV {
|
||||
_FakeKV({this.failRead = false});
|
||||
final Map<String, String> map = {};
|
||||
bool failRead;
|
||||
int writes = 0;
|
||||
|
||||
@override
|
||||
Future<String?> read(String key) async {
|
||||
if (failRead) throw Exception('platform read failed');
|
||||
return map[key];
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> write(String key, String value) async {
|
||||
writes++;
|
||||
map[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('首次:生成并持久化;再读复用同一个', () async {
|
||||
final kv = _FakeKV();
|
||||
final d1 = DeviceIdentity(store: kv);
|
||||
final id1 = await d1.deviceId();
|
||||
expect(id1, isNotEmpty);
|
||||
expect(kv.writes, 1, reason: '首次应写一次');
|
||||
expect(kv.map['pangolin_device_id'], id1);
|
||||
|
||||
// 同实例缓存:不再写。
|
||||
expect(await d1.deviceId(), id1);
|
||||
expect(kv.writes, 1);
|
||||
|
||||
// 新实例、同存储:读出同一个,不重新生成。
|
||||
final d2 = DeviceIdentity(store: kv);
|
||||
expect(await d2.deviceId(), id1);
|
||||
expect(kv.writes, 1, reason: '已存在不应再写');
|
||||
});
|
||||
|
||||
test('读失败 ≠ 不存在:退回临时 id,不写库(不冲掉真实 id)', () async {
|
||||
final kv = _FakeKV(failRead: true)..map['pangolin_device_id'] = 'real-id';
|
||||
final d = DeviceIdentity(store: kv);
|
||||
final id = await d.deviceId();
|
||||
expect(id, isNotEmpty);
|
||||
expect(id, isNot('real-id'), reason: '读失败拿不到真实值,用临时');
|
||||
expect(kv.writes, 0, reason: '读失败绝不写,避免覆盖真实 id');
|
||||
// 真实 id 仍在存储里,未被破坏。
|
||||
expect(kv.map['pangolin_device_id'], 'real-id');
|
||||
});
|
||||
|
||||
test('生成的是 UUID v4 形态', () async {
|
||||
final id = await DeviceIdentity(store: _FakeKV()).deviceId();
|
||||
expect(RegExp(r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$').hasMatch(id), isTrue);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user