feat: LicenseGuard 中间件 + Flutter license model/repo (21D+21E)

21D — 后端:
- Claims 新增 LicenseExpiresAt (*int64 unix 秒),写入 JWT 避免每次查库
- middleware/license_guard.go: CalcLicensePhase / LicenseGuard / GetLicensePhase
  - grace(0-7d): 允许通行
  - readonly(7-15d): 拦截非 GET 写操作 → 403
  - locked(15d+): 全部拦截 → 403
- auth.go: issueTokens 在 JWT 中嵌入 license expires_at;Login 检查 locked 拒绝登录
- router: license/* 路由豁免 LicenseGuard(锁定时仍可激活/查状态)

21E — Flutter 前端:
- models/license.dart: 新 LicenseInfo,含 phase/maxDevices,去掉旧 activatedAt
- core/device/device_id.dart: 持久化 UUID-v4 作为设备 ID(SharedPreferences)
- repositories/license_repository.dart: getInfo/activate/deactivate,激活时携带设备信息
- providers/license_provider.dart: 改接 LicenseRepository
- settings_screen.dart: activatedAt 改为显示 maxDevices

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
wangjia
2026-06-10 00:52:07 +08:00
parent c402ea0070
commit ebf79d0355
9 changed files with 307 additions and 76 deletions
+53
View File
@@ -0,0 +1,53 @@
import 'dart:math';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';
const _kDeviceIdKey = 'device_id';
/// Returns a stable device identifier persisted across app launches.
/// On first call a random UUID-v4 is generated and stored in SharedPreferences.
/// Follows the rule: check kIsWeb before dart:io.
class DeviceId {
static String? _cached;
static Future<String> get() async {
if (_cached != null) return _cached!;
final prefs = await SharedPreferences.getInstance();
var id = prefs.getString(_kDeviceIdKey);
if (id == null || id.isEmpty) {
id = _generateUuid();
await prefs.setString(_kDeviceIdKey, id);
}
return _cached = id;
}
/// Best-effort platform name for display purposes.
static String get platformName {
if (kIsWeb) return 'web';
// defaultTargetPlatform is safe on all platforms (no dart:io needed)
switch (defaultTargetPlatform) {
case TargetPlatform.windows:
return 'windows';
case TargetPlatform.macOS:
return 'macos';
case TargetPlatform.android:
return 'android';
case TargetPlatform.iOS:
return 'ios';
case TargetPlatform.linux:
return 'linux';
default:
return 'unknown';
}
}
static String _generateUuid() {
final rng = Random.secure();
final bytes = List<int>.generate(16, (_) => rng.nextInt(256));
bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4
bytes[8] = (bytes[8] & 0x3f) | 0x80; // variant
final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();
return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-'
'${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}';
}
}
+56
View File
@@ -0,0 +1,56 @@
class LicenseInfo {
final int id;
final String type; // trial | monthly | annual | lifetime
final bool isActive;
final int maxDevices;
final DateTime? expiresAt;
final String phase; // normal | grace | readonly | locked
const LicenseInfo({
required this.id,
required this.type,
required this.isActive,
required this.maxDevices,
required this.phase,
this.expiresAt,
});
factory LicenseInfo.fromJson(Map<String, dynamic> json) {
return LicenseInfo(
id: (json['id'] as num?)?.toInt() ?? 0,
type: json['type'] as String? ?? 'trial',
isActive: json['is_active'] as bool? ?? false,
maxDevices: (json['max_devices'] as num?)?.toInt() ?? 3,
expiresAt: json['expires_at'] != null
? DateTime.tryParse(json['expires_at'] as String)
: null,
phase: json['phase'] as String? ?? 'normal',
);
}
String get typeLabel {
switch (type) {
case 'monthly':
return '月度授权';
case 'annual':
return '年度授权';
case 'lifetime':
return '永久授权';
default:
return '试用版';
}
}
bool get isExpired =>
expiresAt != null && DateTime.now().isAfter(expiresAt!);
int? get daysRemaining {
if (expiresAt == null) return null;
final diff = expiresAt!.difference(DateTime.now()).inDays;
return diff < 0 ? 0 : diff;
}
bool get isReadOnlyPhase => phase == 'readonly' || phase == 'locked';
bool get isLockedPhase => phase == 'locked';
bool get needsAttention => phase == 'grace' || phase == 'readonly' || phase == 'locked';
}
+7 -50
View File
@@ -1,53 +1,14 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../core/api/api_client.dart';
import '../core/auth/auth_state.dart';
import '../models/license.dart';
import '../repositories/license_repository.dart';
class LicenseInfo {
final String type; // trial / monthly / annual / lifetime
final bool isActive;
final DateTime? expiresAt;
final DateTime? activatedAt;
export '../models/license.dart';
const LicenseInfo({
required this.type,
required this.isActive,
this.expiresAt,
this.activatedAt,
});
factory LicenseInfo.fromJson(Map<String, dynamic> json) {
return LicenseInfo(
type: json['type'] as String? ?? 'trial',
isActive: json['is_active'] as bool? ?? false,
expiresAt: json['expires_at'] != null
? DateTime.tryParse(json['expires_at'] as String)
: null,
activatedAt: json['activated_at'] != null
? DateTime.tryParse(json['activated_at'] as String)
: null,
);
}
String get typeLabel {
switch (type) {
case 'monthly': return '月度授权';
case 'annual': return '年度授权';
case 'lifetime': return '永久授权';
default: return '试用版';
}
}
/// 是否已过期
bool get isExpired =>
expiresAt != null && DateTime.now().isAfter(expiresAt!);
/// 距到期剩余天数(null = 永久)
int? get daysRemaining {
if (expiresAt == null) return null;
final diff = expiresAt!.difference(DateTime.now()).inDays;
return diff < 0 ? 0 : diff;
}
}
final licenseRepositoryProvider = Provider<LicenseRepository>(
(ref) => LicenseRepository(ref.read(apiClientProvider)),
);
final licenseProvider =
AsyncNotifierProvider<LicenseNotifier, LicenseInfo?>(LicenseNotifier.new);
@@ -61,11 +22,7 @@ class LicenseNotifier extends AsyncNotifier<LicenseInfo?> {
Future<LicenseInfo?> _fetch() async {
try {
final client = ref.read(apiClientProvider);
final resp = await client.get('/license/info');
final data = resp.data['data'];
if (data == null) return null;
return LicenseInfo.fromJson(data as Map<String, dynamic>);
return await ref.read(licenseRepositoryProvider).getInfo();
} catch (_) {
return null;
}
@@ -0,0 +1,55 @@
import 'package:dio/dio.dart';
import '../core/api/api_client.dart';
import '../core/device/device_id.dart';
import '../core/exceptions.dart';
import '../models/license.dart';
class LicenseRepository {
final ApiClient _client;
const LicenseRepository(this._client);
Future<LicenseInfo?> getInfo() async {
try {
final resp = await _client.get('/license/info');
final data = resp.data['data'];
if (data == null) return null;
return LicenseInfo.fromJson(data as Map<String, dynamic>);
} on DioException catch (e) {
throw AppException(
e.response?.data?['error'] as String? ?? '获取授权信息失败',
statusCode: e.response?.statusCode,
);
}
}
/// Activate a license key for this device.
Future<void> activate(String licenseKey, {String? deviceName}) async {
final deviceId = await DeviceId.get();
try {
await _client.post('/license/activate', data: {
'license_key': licenseKey,
'device_id': deviceId,
'device_name': deviceName ?? DeviceId.platformName,
'platform': DeviceId.platformName,
});
} on DioException catch (e) {
throw AppException(
e.response?.data?['error'] as String? ?? '激活失败',
statusCode: e.response?.statusCode,
);
}
}
/// Deactivate (unbind) this device from its license.
Future<void> deactivate() async {
final deviceId = await DeviceId.get();
try {
await _client.post('/license/deactivate', data: {'device_id': deviceId});
} on DioException catch (e) {
throw AppException(
e.response?.data?['error'] as String? ?? '解绑失败',
statusCode: e.response?.statusCode,
);
}
}
}
@@ -381,10 +381,7 @@ class _SettingsScreenState extends ConsumerState<SettingsScreen> {
value: DateFormat('yyyy-MM-dd').format(lic.expiresAt!))
else
const _ParamRow(label: '到期时间', value: '永久有效'),
if (lic.activatedAt != null)
_ParamRow(
label: '激活时间',
value: DateFormat('yyyy-MM-dd').format(lic.activatedAt!)),
_ParamRow(label: '设备上限', value: '${lic.maxDevices}'),
const SizedBox(height: 12),
OutlinedButton.icon(
onPressed: _showRenewLicenseDialog,