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

后端: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:
wangjia
2026-06-29 00:28:13 +08:00
parent 889cff4556
commit c0c4b94e29
18 changed files with 498 additions and 96 deletions
+4
View File
@@ -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>);
+134
View File
@@ -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());
+4 -8
View File
@@ -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';
// ── 设备 IDMVP 常量;后续由 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,
);
+5
View File
@@ -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);