Compare commits
3 Commits
52912268d0
...
a307c6ca2c
| Author | SHA1 | Date | |
|---|---|---|---|
| a307c6ca2c | |||
| 2930d76cf3 | |||
| 3159dd75c1 |
@@ -665,5 +665,8 @@ abstract class AppText {
|
||||
String get routingAddRule; // 添加规则 / Add rule
|
||||
String get routingImport; // 从文本导入 / Import from text
|
||||
String get routingReset; // 重置默认 / Reset defaults
|
||||
String get routingResetConfirmTitle; // 重置为默认规则? / Reset to defaults?
|
||||
String get routingResetConfirmBody; // 重置确认弹层正文 / Reset confirm dialog body
|
||||
String get routingResetConfirmAction; // 重置(确认按钮) / Reset (confirm action)
|
||||
String get routingBack; // 返回设置 / Back to settings
|
||||
}
|
||||
|
||||
@@ -575,6 +575,12 @@ class StringsEn extends AppText {
|
||||
@override
|
||||
String get routingReset => 'Reset defaults';
|
||||
@override
|
||||
String get routingResetConfirmTitle => 'Reset to defaults?';
|
||||
@override
|
||||
String get routingResetConfirmBody => 'This clears all your custom rules and restores the factory routing table.';
|
||||
@override
|
||||
String get routingResetConfirmAction => 'Reset';
|
||||
@override
|
||||
String get routingBack => 'Back to settings';
|
||||
@override
|
||||
List<String> get days7 => const ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
|
||||
|
||||
@@ -575,6 +575,12 @@ class StringsEs extends AppText {
|
||||
@override
|
||||
String get routingReset => 'Restablecer';
|
||||
@override
|
||||
String get routingResetConfirmTitle => '¿Restablecer las reglas predeterminadas?';
|
||||
@override
|
||||
String get routingResetConfirmBody => 'Esto borra todas tus reglas personalizadas y restaura la tabla de enrutamiento de fábrica.';
|
||||
@override
|
||||
String get routingResetConfirmAction => 'Restablecer';
|
||||
@override
|
||||
String get routingBack => 'Volver a ajustes';
|
||||
@override
|
||||
List<String> get days7 => const ['L', 'M', 'X', 'J', 'V', 'S', 'D'];
|
||||
|
||||
@@ -575,6 +575,12 @@ class StringsJa extends AppText {
|
||||
@override
|
||||
String get routingReset => 'デフォルトに戻す';
|
||||
@override
|
||||
String get routingResetConfirmTitle => 'デフォルトのルールに戻しますか?';
|
||||
@override
|
||||
String get routingResetConfirmBody => 'カスタムルールをすべて削除し、出荷時の分流テーブルに戻します。';
|
||||
@override
|
||||
String get routingResetConfirmAction => 'リセット';
|
||||
@override
|
||||
String get routingBack => '設定に戻る';
|
||||
@override
|
||||
List<String> get days7 => const ['月', '火', '水', '木', '金', '土', '日'];
|
||||
|
||||
@@ -575,6 +575,12 @@ class StringsKo extends AppText {
|
||||
@override
|
||||
String get routingReset => '기본값 재설정';
|
||||
@override
|
||||
String get routingResetConfirmTitle => '기본 규칙으로 재설정할까요?';
|
||||
@override
|
||||
String get routingResetConfirmBody => '사용자 지정 규칙을 모두 삭제하고 초기 분산 규칙으로 복원합니다.';
|
||||
@override
|
||||
String get routingResetConfirmAction => '재설정';
|
||||
@override
|
||||
String get routingBack => '설정으로 돌아가기';
|
||||
@override
|
||||
List<String> get days7 => const ['월', '화', '수', '목', '금', '토', '일'];
|
||||
|
||||
@@ -575,6 +575,12 @@ class StringsRu extends AppText {
|
||||
@override
|
||||
String get routingReset => 'Сбросить настройки';
|
||||
@override
|
||||
String get routingResetConfirmTitle => 'Сбросить к правилам по умолчанию?';
|
||||
@override
|
||||
String get routingResetConfirmBody => 'Это удалит все ваши пользовательские правила и восстановит заводскую таблицу маршрутизации.';
|
||||
@override
|
||||
String get routingResetConfirmAction => 'Сбросить';
|
||||
@override
|
||||
String get routingBack => 'Назад к настройкам';
|
||||
@override
|
||||
List<String> get days7 => const ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'];
|
||||
|
||||
@@ -575,6 +575,12 @@ class StringsZh extends AppText {
|
||||
@override
|
||||
String get routingReset => '重置默认';
|
||||
@override
|
||||
String get routingResetConfirmTitle => '重置为默认规则?';
|
||||
@override
|
||||
String get routingResetConfirmBody => '将清除你自定义的所有规则,恢复到出厂分流表。';
|
||||
@override
|
||||
String get routingResetConfirmAction => '重置';
|
||||
@override
|
||||
String get routingBack => '返回设置';
|
||||
@override
|
||||
List<String> get days7 => const ['一', '二', '三', '四', '五', '六', '日'];
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
// routing_profile.dart — 可配置分流档案(GET/POST /v1/me/routing)。
|
||||
//
|
||||
// 对齐后端契约(server/internal/httpapi 分流端点):
|
||||
// {mode, builtin:{china_direct,lan_direct,private_via_tunnel}, rules:[...], final}。
|
||||
// {mode, builtin:{china_direct,lan_direct,private_via_tunnel}, rules:[...], final,
|
||||
// system_locked_domains:[...]}(FT-A 起响应含只读私有服务域名清单)。
|
||||
// 手写 fromJson/toJson(项目无 json_serializable,仿 lib/models/me.dart)。
|
||||
import 'package:flutter/foundation.dart' show listEquals;
|
||||
|
||||
/// 分流模式。
|
||||
/// 'rule' = 按规则(内置 + 自定义) | 'global' = 全局代理 | 'direct' = 全局直连。
|
||||
@@ -55,8 +57,24 @@ class Builtin {
|
||||
lanDirect: lanDirect ?? this.lanDirect,
|
||||
privateViaTunnel: privateViaTunnel ?? this.privateViaTunnel,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is Builtin &&
|
||||
runtimeType == other.runtimeType &&
|
||||
chinaDirect == other.chinaDirect &&
|
||||
lanDirect == other.lanDirect &&
|
||||
privateViaTunnel == other.privateViaTunnel;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(chinaDirect, lanDirect, privateViaTunnel);
|
||||
}
|
||||
|
||||
/// copyWith 的哨兵值:用于区分「未传参(保留原值)」与「显式传 null(清空该字段)」,
|
||||
/// 仅 [RoutingRule.note] 需要(其它字段无「清空」语义,`??` 已够用)。
|
||||
const _noteSentinel = Object();
|
||||
|
||||
/// 单条自定义分流规则。
|
||||
///
|
||||
/// **enabled 语义**(计划裁决):构造默认 `true`;[toJson] 恒输出 `enabled` 字段
|
||||
@@ -95,20 +113,35 @@ class RoutingRule {
|
||||
'enabled': enabled,
|
||||
};
|
||||
|
||||
/// [note] 用哨兵:不传 → 保留原值;显式传 `null` → 清空为 null。
|
||||
RoutingRule copyWith({
|
||||
String? type,
|
||||
String? value,
|
||||
String? action,
|
||||
String? note,
|
||||
Object? note = _noteSentinel,
|
||||
bool? enabled,
|
||||
}) =>
|
||||
RoutingRule(
|
||||
type: type ?? this.type,
|
||||
value: value ?? this.value,
|
||||
action: action ?? this.action,
|
||||
note: note ?? this.note,
|
||||
note: identical(note, _noteSentinel) ? this.note : note as String?,
|
||||
enabled: enabled ?? this.enabled,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is RoutingRule &&
|
||||
runtimeType == other.runtimeType &&
|
||||
type == other.type &&
|
||||
value == other.value &&
|
||||
action == other.action &&
|
||||
note == other.note &&
|
||||
enabled == other.enabled;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(type, value, action, note, enabled);
|
||||
}
|
||||
|
||||
/// 分流档案(账户级,单份)。
|
||||
@@ -118,6 +151,7 @@ class RoutingProfile {
|
||||
this.builtin = const Builtin(),
|
||||
this.rules = const [],
|
||||
this.finalAction = 'proxy',
|
||||
this.systemLockedDomains = const [],
|
||||
});
|
||||
|
||||
final RoutingMode mode;
|
||||
@@ -127,6 +161,11 @@ class RoutingProfile {
|
||||
/// 兜底动作(JSON key 为保留字 `final`,Dart 侧改名)。'proxy' | 'direct'。
|
||||
final String finalAction;
|
||||
|
||||
/// **只读**:系统强制走隧道的私有服务域名清单(服务端 `PANGOLIN_PRIVATE_SPLIT_DOMAINS`,
|
||||
/// FT-A 起随 GET /v1/me/routing 下发)。`toJson()` 不输出——服务端忽略,且此字段
|
||||
/// 客户端不可写。
|
||||
final List<String> systemLockedDomains;
|
||||
|
||||
factory RoutingProfile.fromJson(Map<String, dynamic> m) => RoutingProfile(
|
||||
mode: m['mode'] as String? ?? 'rule',
|
||||
builtin: m['builtin'] != null
|
||||
@@ -136,6 +175,8 @@ class RoutingProfile {
|
||||
.map((e) => RoutingRule.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
finalAction: m['final'] as String? ?? 'proxy',
|
||||
systemLockedDomains:
|
||||
(m['system_locked_domains'] as List?)?.cast<String>() ?? const [],
|
||||
);
|
||||
|
||||
Map<String, dynamic> toJson() => {
|
||||
@@ -145,16 +186,48 @@ class RoutingProfile {
|
||||
'final': finalAction,
|
||||
};
|
||||
|
||||
/// 出厂默认档案(对齐服务端 `routing.Default()`):智能分流 + 内置全开 + 无自定义规则。
|
||||
/// 不含 systemLockedDomains(那是账户相关的只读回显,由调用方按需保留;见
|
||||
/// RoutingProfileNotifier.resetToDefault())。
|
||||
factory RoutingProfile.defaults() => const RoutingProfile(
|
||||
mode: 'rule',
|
||||
builtin: Builtin(),
|
||||
rules: [],
|
||||
finalAction: 'proxy',
|
||||
);
|
||||
|
||||
RoutingProfile copyWith({
|
||||
RoutingMode? mode,
|
||||
Builtin? builtin,
|
||||
List<RoutingRule>? rules,
|
||||
String? finalAction,
|
||||
List<String>? systemLockedDomains,
|
||||
}) =>
|
||||
RoutingProfile(
|
||||
mode: mode ?? this.mode,
|
||||
builtin: builtin ?? this.builtin,
|
||||
rules: rules ?? this.rules,
|
||||
finalAction: finalAction ?? this.finalAction,
|
||||
systemLockedDomains: systemLockedDomains ?? this.systemLockedDomains,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
identical(this, other) ||
|
||||
other is RoutingProfile &&
|
||||
runtimeType == other.runtimeType &&
|
||||
mode == other.mode &&
|
||||
builtin == other.builtin &&
|
||||
listEquals(rules, other.rules) &&
|
||||
finalAction == other.finalAction &&
|
||||
listEquals(systemLockedDomains, other.systemLockedDomains);
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
mode,
|
||||
builtin,
|
||||
Object.hashAll(rules),
|
||||
finalAction,
|
||||
Object.hashAll(systemLockedDomains),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -69,6 +69,14 @@ class RoutingProfileNotifier extends AsyncNotifier<RoutingProfile> {
|
||||
return p.copyWith(rules: rules);
|
||||
});
|
||||
|
||||
/// 重置为出厂默认档案(模式/内置开关/自定义规则/final 全部还原),但保留当前只读的
|
||||
/// [RoutingProfile.systemLockedDomains] 回显不丢——它不是用户可改的档案内容,只是
|
||||
/// 服务端下发的账户相关信息,与「重置」无关。复用 [_mutateAndSave]/[_persist]:
|
||||
/// 乐观更新 + 失败回滚 rethrow + 存成功后连接态 on 则自动重连,同 addRule。
|
||||
Future<void> resetToDefault() => _mutateAndSave(
|
||||
(p) => RoutingProfile.defaults().copyWith(systemLockedDomains: p.systemLockedDomains),
|
||||
);
|
||||
|
||||
Future<void> _mutateAndSave(RoutingProfile Function(RoutingProfile) transform) async {
|
||||
final prev = state.valueOrNull ?? const RoutingProfile();
|
||||
final next = transform(prev);
|
||||
|
||||
@@ -7,13 +7,12 @@
|
||||
// 冲突提示两类(prototype 里只是静态示例,这里落成真computed 逻辑):
|
||||
// ①「已被上面规则覆盖」——同 type+value 的自定义规则被更靠前的规则遮蔽(纯本地计算,
|
||||
// 首命中生效语义决定)。
|
||||
// ②「系统强制走隧道,此规则不生效」——命中系统锁定目标。当前 RoutingProfile 契约
|
||||
// 只下发 builtin 三个布尔开关,并未下发具体锁定域名清单(PANGOLIN_PRIVATE_SPLIT_DOMAINS
|
||||
// 只在服务端 env,未经 API 暴露给客户端),故本屏对②采用保守启发式:仅当自定义规则
|
||||
// 类型为 ip_cidr 且落在私网/回环地址段(RFC1918 + 127.0.0.0/8)时标记——这部分恒被
|
||||
// 内置「局域网 / 私网直连」(builtin.lanDirect,强制不可关)接管,与用户规则动作冲突。
|
||||
// 域名级私有服务分流(如 git.yanmeiai.com)不在此启发式覆盖范围,需服务端把锁定域名
|
||||
// 清单下发给客户端后再补全(见 task-7-report.md 里的疑虑)。
|
||||
// ②「系统强制走隧道,此规则不生效」——命中系统锁定目标,两类启发式并存:
|
||||
// - ip_cidr 落在私网/回环地址段(RFC1918 + 127.0.0.0/8)——恒被内置「局域网 / 私网
|
||||
// 直连」(builtin.lanDirect,强制不可关)接管。
|
||||
// - 域名类规则(domain/domain_suffix/domain_keyword)命中 RoutingProfile.
|
||||
// systemLockedDomains(FT-A 起 GET /v1/me/routing 下发的私有服务域名清单,
|
||||
// PANGOLIN_PRIVATE_SPLIT_DOMAINS)——服务端渲染时恒强制走隧道,与用户规则动作冲突。
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
@@ -139,8 +138,10 @@ class _RoutingBody extends ConsumerWidget {
|
||||
onReorder: (oldIndex, newIndex) => notifier.reorder(oldIndex, newIndex),
|
||||
children: [
|
||||
for (var i = 0; i < profile.rules.length; i++)
|
||||
_ruleRow(context, c, t, i, profile.rules[i],
|
||||
_conflictFor(profile.rules, i), i < profile.rules.length - 1,
|
||||
_ruleRow(
|
||||
context, c, t, i, profile.rules[i],
|
||||
_conflictFor(profile.rules, i, profile.systemLockedDomains),
|
||||
i < profile.rules.length - 1,
|
||||
onDelete: () => notifier.removeRule(i)),
|
||||
],
|
||||
),
|
||||
@@ -172,10 +173,56 @@ class _RoutingBody extends ConsumerWidget {
|
||||
]),
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 20),
|
||||
|
||||
// ── 重置默认(桌面/移动共用同一按钮;二次确认防误触) ──
|
||||
PangolinButton(
|
||||
label: t.routingReset,
|
||||
icon: PangolinIcons.refreshCw,
|
||||
variant: PangolinButtonVariant.ghost,
|
||||
expand: true,
|
||||
onPressed: () => _confirmReset(context, ref, c, t),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _confirmReset(BuildContext context, WidgetRef ref, PangolinScheme c, AppText t) async {
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (ctx) => AlertDialog(
|
||||
backgroundColor: c.surface,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(PangolinRadius.xl)),
|
||||
title: Row(children: [
|
||||
Container(
|
||||
width: 34, height: 34,
|
||||
decoration: BoxDecoration(color: c.dangerSubtle, shape: BoxShape.circle),
|
||||
child: Icon(PangolinIcons.refreshCw, size: 18, color: c.danger),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(t.routingResetConfirmTitle,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: PangolinText.body.copyWith(color: c.fg1, fontWeight: FontWeight.w700)),
|
||||
),
|
||||
]),
|
||||
content: Text(t.routingResetConfirmBody, style: PangolinText.sm.copyWith(color: c.fg2, height: 1.5)),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, false),
|
||||
child: Text(t.devCancel, style: PangolinText.sm.copyWith(color: c.fg2, fontWeight: FontWeight.w600)),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(ctx, true),
|
||||
child: Text(t.routingResetConfirmAction, style: PangolinText.sm.copyWith(color: c.danger, fontWeight: FontWeight.w700)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (ok != true) return;
|
||||
await ref.read(routingProfileProvider.notifier).resetToDefault();
|
||||
}
|
||||
|
||||
Future<void> _openAddDialog(BuildContext context, WidgetRef ref, AppText t) async {
|
||||
final rule = await showDialog<RoutingRule>(context: context, builder: (_) => _AddRuleDialog(t: t));
|
||||
if (rule == null) return;
|
||||
@@ -291,9 +338,9 @@ class _RoutingBody extends ConsumerWidget {
|
||||
/// 规则行冲突类型:先判系统锁定(与规则顺序无关),再判是否被更靠前的同规则遮蔽。
|
||||
enum _RuleConflict { none, shadowed, systemLocked }
|
||||
|
||||
_RuleConflict _conflictFor(List<RoutingRule> rules, int i) {
|
||||
_RuleConflict _conflictFor(List<RoutingRule> rules, int i, List<String> systemLockedDomains) {
|
||||
final r = rules[i];
|
||||
if (_looksSystemLocked(r)) return _RuleConflict.systemLocked;
|
||||
if (_looksSystemLocked(r, systemLockedDomains)) return _RuleConflict.systemLocked;
|
||||
for (var j = 0; j < i; j++) {
|
||||
final o = rules[j];
|
||||
if (o.type == r.type && o.value.trim().toLowerCase() == r.value.trim().toLowerCase()) {
|
||||
@@ -303,10 +350,29 @@ _RuleConflict _conflictFor(List<RoutingRule> rules, int i) {
|
||||
return _RuleConflict.none;
|
||||
}
|
||||
|
||||
/// 私网/回环地址段启发式(RFC1918 + 127.0.0.0/8),见文件头注释——真正的系统锁定域名清单
|
||||
/// 未经 API 下发,这里只覆盖 ip_cidr 类型且落在该地址段的情形。
|
||||
/// 私网/回环地址段启发式(RFC1918 + 127.0.0.0/8),见文件头注释。
|
||||
final _privateIpPrefix = RegExp(r'^(10\.|192\.168\.|127\.|172\.(1[6-9]|2\d|3[01])\.)');
|
||||
bool _looksSystemLocked(RoutingRule r) => r.type == 'ip_cidr' && _privateIpPrefix.hasMatch(r.value);
|
||||
|
||||
/// 系统锁定判定:ip_cidr 私网/回环启发式,或域名类规则命中 [systemLockedDomains]。
|
||||
bool _looksSystemLocked(RoutingRule r, List<String> systemLockedDomains) {
|
||||
if (r.type == 'ip_cidr') return _privateIpPrefix.hasMatch(r.value);
|
||||
if (systemLockedDomains.isEmpty) return false;
|
||||
final value = r.value.trim().toLowerCase();
|
||||
if (value.isEmpty) return false;
|
||||
switch (r.type) {
|
||||
case 'domain':
|
||||
return systemLockedDomains.any((d) => d.toLowerCase() == value);
|
||||
case 'domain_suffix':
|
||||
return systemLockedDomains.any((d) {
|
||||
final dl = d.toLowerCase();
|
||||
return dl == value || dl.endsWith('.$value');
|
||||
});
|
||||
case 'domain_keyword':
|
||||
return systemLockedDomains.any((d) => d.toLowerCase().contains(value));
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
String _routingTypeLabel(AppText t, String type) => switch (type) {
|
||||
'domain' => t.routingTypeDomain,
|
||||
|
||||
@@ -36,4 +36,67 @@ void main() {
|
||||
expect(p.builtin.lanDirect, isTrue);
|
||||
expect(p.builtin.privateViaTunnel, isTrue);
|
||||
});
|
||||
|
||||
test('systemLockedDomains:fromJson 读取,默认空,toJson 不输出(只读字段)', () {
|
||||
final withLocks = RoutingProfile.fromJson({
|
||||
'mode': 'rule',
|
||||
'rules': [],
|
||||
'final': 'proxy',
|
||||
'system_locked_domains': ['git.yanmeiai.com', 'admin.yanmeiai.com'],
|
||||
});
|
||||
expect(withLocks.systemLockedDomains, ['git.yanmeiai.com', 'admin.yanmeiai.com']);
|
||||
expect(withLocks.toJson().containsKey('system_locked_domains'), isFalse);
|
||||
|
||||
final withoutLocks = RoutingProfile.fromJson({'mode': 'rule', 'rules': [], 'final': 'proxy'});
|
||||
expect(withoutLocks.systemLockedDomains, isEmpty);
|
||||
});
|
||||
|
||||
test('RoutingProfile.defaults() 对齐服务端 routing.Default()', () {
|
||||
final d = RoutingProfile.defaults();
|
||||
expect(d.mode, 'rule');
|
||||
expect(d.builtin.chinaDirect, isTrue);
|
||||
expect(d.builtin.lanDirect, isTrue);
|
||||
expect(d.builtin.privateViaTunnel, isTrue);
|
||||
expect(d.rules, isEmpty);
|
||||
expect(d.finalAction, 'proxy');
|
||||
});
|
||||
|
||||
test('RoutingRule.copyWith 用哨兵让 note 可清空为 null', () {
|
||||
const r = RoutingRule(type: 'domain', value: 'a.com', action: 'proxy', note: 'ci');
|
||||
final cleared = r.copyWith(note: null);
|
||||
expect(cleared.note, isNull, reason: '显式传 null 应清空 note,而不是被 ?? 吞掉');
|
||||
|
||||
final unchanged = r.copyWith(value: 'b.com');
|
||||
expect(unchanged.note, 'ci', reason: '不传 note 时应保留原值');
|
||||
});
|
||||
|
||||
test('RoutingRule / Builtin / RoutingProfile 值相等(operator==)', () {
|
||||
const r1 = RoutingRule(type: 'domain', value: 'a.com', action: 'proxy', note: 'x');
|
||||
const r2 = RoutingRule(type: 'domain', value: 'a.com', action: 'proxy', note: 'x');
|
||||
const r3 = RoutingRule(type: 'domain', value: 'a.com', action: 'direct', note: 'x');
|
||||
expect(r1, r2);
|
||||
expect(r1.hashCode, r2.hashCode);
|
||||
expect(r1 == r3, isFalse);
|
||||
|
||||
const b1 = Builtin(chinaDirect: true, lanDirect: false, privateViaTunnel: true);
|
||||
const b2 = Builtin(chinaDirect: true, lanDirect: false, privateViaTunnel: true);
|
||||
const b3 = Builtin();
|
||||
expect(b1, b2);
|
||||
expect(b1.hashCode, b2.hashCode);
|
||||
expect(b1 == b3, isFalse);
|
||||
|
||||
const p1 = RoutingProfile(mode: 'rule', rules: [r1], finalAction: 'proxy');
|
||||
const p2 = RoutingProfile(mode: 'rule', rules: [r2], finalAction: 'proxy');
|
||||
final p3 = RoutingProfile.fromJson({
|
||||
'mode': 'rule',
|
||||
'rules': [
|
||||
{'type': 'domain', 'value': 'a.com', 'action': 'proxy', 'note': 'x', 'enabled': true}
|
||||
],
|
||||
'final': 'proxy',
|
||||
'system_locked_domains': ['git.yanmeiai.com'],
|
||||
});
|
||||
expect(p1, p2);
|
||||
expect(p1.hashCode, p2.hashCode);
|
||||
expect(p1 == p3, isFalse, reason: 'systemLockedDomains 不同应视为不相等');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -115,6 +115,36 @@ void main() {
|
||||
expect(api.saved, hasLength(3));
|
||||
});
|
||||
|
||||
test('resetToDefault() 还原出厂档案,保留 systemLockedDomains,并落盘', () async {
|
||||
final api = _FakeAccountApi()
|
||||
..initial = RoutingProfile.fromJson({
|
||||
'mode': 'global',
|
||||
'builtin': {'china_direct': false, 'lan_direct': true, 'private_via_tunnel': true},
|
||||
'rules': [
|
||||
{'type': 'domain', 'value': 'a.com', 'action': 'reject'},
|
||||
],
|
||||
'final': 'direct',
|
||||
'system_locked_domains': ['git.yanmeiai.com'],
|
||||
});
|
||||
final c = _makeContainer(api);
|
||||
addTearDown(c.dispose);
|
||||
await _waitLoggedIn(c);
|
||||
await c.read(routingProfileProvider.future);
|
||||
|
||||
await c.read(routingProfileProvider.notifier).resetToDefault();
|
||||
|
||||
final state = c.read(routingProfileProvider).value!;
|
||||
expect(state.mode, 'rule');
|
||||
expect(state.builtin.chinaDirect, isTrue);
|
||||
expect(state.rules, isEmpty);
|
||||
expect(state.finalAction, 'proxy');
|
||||
expect(state.systemLockedDomains, ['git.yanmeiai.com'],
|
||||
reason: '只读字段随重置保留,不因重置默认档案而丢失');
|
||||
|
||||
expect(api.saved, hasLength(1));
|
||||
expect(api.saved.single.mode, 'rule');
|
||||
});
|
||||
|
||||
test('保存失败:回退到变更前 state 且 rethrow,不静默吞', () async {
|
||||
final api = _FakeAccountApi();
|
||||
final c = _makeContainer(api);
|
||||
|
||||
@@ -103,11 +103,101 @@ void main() {
|
||||
|
||||
expect(find.text(StringsZh().routingRuleShadowed), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('a domain rule matching a system-locked domain is flagged forced', (tester) async {
|
||||
final profile = RoutingProfile.fromJson({
|
||||
'mode': 'rule',
|
||||
'builtin': {'china_direct': true, 'lan_direct': true, 'private_via_tunnel': true},
|
||||
'rules': [
|
||||
{'type': 'domain_suffix', 'value': 'git.yanmeiai.com', 'action': 'direct'},
|
||||
],
|
||||
'final': 'proxy',
|
||||
'system_locked_domains': ['git.yanmeiai.com'],
|
||||
});
|
||||
|
||||
await tester.pumpWidget(ProviderScope(
|
||||
overrides: [
|
||||
appTextProvider.overrideWithValue(StringsZh()),
|
||||
routingProfileProvider.overrideWith(() => _FakeRoutingNotifier(profile)),
|
||||
],
|
||||
child: MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: PangolinTheme.light,
|
||||
home: const RoutingScreen(),
|
||||
),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text(StringsZh().routingForcedRow), findsOneWidget);
|
||||
});
|
||||
|
||||
testWidgets('reset button opens confirm dialog and resets on confirm', (tester) async {
|
||||
final profile = RoutingProfile.fromJson({
|
||||
'mode': 'rule',
|
||||
'builtin': {'china_direct': true, 'lan_direct': true, 'private_via_tunnel': true},
|
||||
'rules': [
|
||||
{'type': 'domain_suffix', 'value': 'x.com', 'action': 'direct'},
|
||||
],
|
||||
'final': 'proxy',
|
||||
});
|
||||
|
||||
final notifier = _FakeRoutingNotifier(profile);
|
||||
await tester.pumpWidget(ProviderScope(
|
||||
overrides: [
|
||||
appTextProvider.overrideWithValue(StringsZh()),
|
||||
routingProfileProvider.overrideWith(() => notifier),
|
||||
],
|
||||
child: MaterialApp(
|
||||
debugShowCheckedModeBanner: false,
|
||||
theme: PangolinTheme.light,
|
||||
home: const RoutingScreen(),
|
||||
),
|
||||
));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(find.text('x.com'), findsOneWidget);
|
||||
|
||||
// 重置按钮在 FINAL 区之后,滚到可见再点(屏内不止一个 Scrollable,取外层 ListView)。
|
||||
await tester.scrollUntilVisible(
|
||||
find.text(StringsZh().routingReset),
|
||||
200,
|
||||
scrollable: find.byType(Scrollable).first,
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text(StringsZh().routingReset));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
// 确认弹层出现,取消不触发重置。
|
||||
expect(find.text(StringsZh().routingResetConfirmBody), findsOneWidget);
|
||||
await tester.tap(find.text(StringsZh().devCancel));
|
||||
await tester.pumpAndSettle();
|
||||
expect(notifier.resetCalled, isFalse);
|
||||
expect(find.text('x.com'), findsOneWidget);
|
||||
|
||||
// 再次点击并确认 → 触发重置。
|
||||
await tester.tap(find.text(StringsZh().routingReset));
|
||||
await tester.pumpAndSettle();
|
||||
await tester.tap(find.text(StringsZh().routingResetConfirmAction));
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
expect(notifier.resetCalled, isTrue);
|
||||
expect(find.text('x.com'), findsNothing);
|
||||
});
|
||||
}
|
||||
|
||||
class _FakeRoutingNotifier extends RoutingProfileNotifier {
|
||||
_FakeRoutingNotifier(this._v);
|
||||
final RoutingProfile _v;
|
||||
bool resetCalled = false;
|
||||
|
||||
@override
|
||||
Future<RoutingProfile> build() async => _v;
|
||||
|
||||
/// 绕过真实 _persist(需要 accountApiProvider/网络),只验证「确认后触发重置」的
|
||||
/// UI 交互链路;真正的 _persist 复用行为由 routing_provider_test.dart 覆盖。
|
||||
@override
|
||||
Future<void> resetToDefault() async {
|
||||
resetCalled = true;
|
||||
state = AsyncData(RoutingProfile.defaults().copyWith(systemLockedDomains: _v.systemLockedDomains));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2257,6 +2257,30 @@
|
||||
"ru": "Сбросить настройки",
|
||||
"es": "Restablecer"
|
||||
},
|
||||
"routingResetConfirmTitle": {
|
||||
"zh": "重置为默认规则?",
|
||||
"en": "Reset to defaults?",
|
||||
"ja": "デフォルトのルールに戻しますか?",
|
||||
"ko": "기본 규칙으로 재설정할까요?",
|
||||
"ru": "Сбросить к правилам по умолчанию?",
|
||||
"es": "¿Restablecer las reglas predeterminadas?"
|
||||
},
|
||||
"routingResetConfirmBody": {
|
||||
"zh": "将清除你自定义的所有规则,恢复到出厂分流表。",
|
||||
"en": "This clears all your custom rules and restores the factory routing table.",
|
||||
"ja": "カスタムルールをすべて削除し、出荷時の分流テーブルに戻します。",
|
||||
"ko": "사용자 지정 규칙을 모두 삭제하고 초기 분산 규칙으로 복원합니다.",
|
||||
"ru": "Это удалит все ваши пользовательские правила и восстановит заводскую таблицу маршрутизации.",
|
||||
"es": "Esto borra todas tus reglas personalizadas y restaura la tabla de enrutamiento de fábrica."
|
||||
},
|
||||
"routingResetConfirmAction": {
|
||||
"zh": "重置",
|
||||
"en": "Reset",
|
||||
"ja": "リセット",
|
||||
"ko": "재설정",
|
||||
"ru": "Сбросить",
|
||||
"es": "Restablecer"
|
||||
},
|
||||
"routingBack": {
|
||||
"zh": "返回设置",
|
||||
"en": "Back to settings",
|
||||
|
||||
@@ -244,10 +244,18 @@ components:
|
||||
description: 国内域名/IP 直连
|
||||
lan_direct:
|
||||
type: boolean
|
||||
description: 局域网直连
|
||||
readOnly: true
|
||||
description: >-
|
||||
reserved/always-on:局域网直连由系统层恒渲染(route_exclude_address +
|
||||
固定 LAN 直连规则),渲染器不读此开关,当前始终生效;字段保留供未来扩展
|
||||
per-user 关闭,目前无实际效果。
|
||||
private_via_tunnel:
|
||||
type: boolean
|
||||
description: 私有服务域名强制走隧道(家庭内网穿透场景)
|
||||
readOnly: true
|
||||
description: >-
|
||||
reserved/always-on:配置了 PANGOLIN_PRIVATE_SPLIT_DOMAINS 时,这些私有
|
||||
服务域名恒强制走隧道,渲染器不读此开关,当前始终生效;字段保留供未来扩展
|
||||
per-user 关闭,目前无实际效果。
|
||||
|
||||
RoutingProfile:
|
||||
type: object
|
||||
@@ -267,6 +275,24 @@ components:
|
||||
type: string
|
||||
enum: [proxy, direct]
|
||||
|
||||
RoutingProfileResponse:
|
||||
description: GET /me/routing 响应体:档案字段 + 只读的系统强制域名清单
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/RoutingProfile'
|
||||
- type: object
|
||||
required: [system_locked_domains]
|
||||
properties:
|
||||
system_locked_domains:
|
||||
type: array
|
||||
readOnly: true
|
||||
items:
|
||||
type: string
|
||||
description: >-
|
||||
系统强制走隧道的私有服务域名(PANGOLIN_PRIVATE_SPLIT_DOMAINS)。
|
||||
用户对这些域名的自定义规则会静默失效;仅供客户端提示用户,不可写入
|
||||
(POST 请求体中出现该字段会被忽略,不会持久化)。
|
||||
example: [nas.example.com]
|
||||
|
||||
RoutingValidationError:
|
||||
type: object
|
||||
required: [code, message_zh, message_en, errors]
|
||||
@@ -500,11 +526,11 @@ paths:
|
||||
summary: 获取当前用户的分流配置(可配置分流;未自定义时返回默认档案)
|
||||
responses:
|
||||
'200':
|
||||
description: 分流档案
|
||||
description: 分流档案(含只读 system_locked_domains)
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RoutingProfile'
|
||||
$ref: '#/components/schemas/RoutingProfileResponse'
|
||||
'401':
|
||||
description: 未认证
|
||||
content:
|
||||
|
||||
+30
-4
@@ -259,11 +259,11 @@ paths:
|
||||
tags: [Account]
|
||||
responses:
|
||||
"200":
|
||||
description: 分流档案
|
||||
description: 分流档案(含只读 system_locked_domains)
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: "#/components/schemas/RoutingProfile"
|
||||
$ref: "#/components/schemas/RoutingProfileResponse"
|
||||
"401":
|
||||
$ref: "#/components/responses/Unauthorized"
|
||||
"500":
|
||||
@@ -1209,10 +1209,18 @@ components:
|
||||
description: 国内域名/IP 直连
|
||||
lan_direct:
|
||||
type: boolean
|
||||
description: 局域网直连
|
||||
readOnly: true
|
||||
description: >-
|
||||
reserved/always-on:局域网直连由系统层恒渲染(route_exclude_address +
|
||||
固定 LAN 直连规则),渲染器不读此开关,当前始终生效;字段保留供未来扩展
|
||||
per-user 关闭,目前无实际效果。
|
||||
private_via_tunnel:
|
||||
type: boolean
|
||||
description: 私有服务域名强制走隧道(家庭内网穿透场景)
|
||||
readOnly: true
|
||||
description: >-
|
||||
reserved/always-on:配置了 PANGOLIN_PRIVATE_SPLIT_DOMAINS 时,这些私有
|
||||
服务域名恒强制走隧道,渲染器不读此开关,当前始终生效;字段保留供未来扩展
|
||||
per-user 关闭,目前无实际效果。
|
||||
|
||||
RoutingProfile:
|
||||
type: object
|
||||
@@ -1232,6 +1240,24 @@ components:
|
||||
type: string
|
||||
enum: [proxy, direct]
|
||||
|
||||
RoutingProfileResponse:
|
||||
description: GET /me/routing 响应体:档案字段 + 只读的系统强制域名清单
|
||||
allOf:
|
||||
- $ref: "#/components/schemas/RoutingProfile"
|
||||
- type: object
|
||||
required: [system_locked_domains]
|
||||
properties:
|
||||
system_locked_domains:
|
||||
type: array
|
||||
readOnly: true
|
||||
items:
|
||||
type: string
|
||||
description: >-
|
||||
系统强制走隧道的私有服务域名(PANGOLIN_PRIVATE_SPLIT_DOMAINS)。
|
||||
用户对这些域名的自定义规则会静默失效;仅供客户端提示用户,不可写入
|
||||
(POST 请求体中出现该字段会被忽略,不会持久化)。
|
||||
example: [nas.example.com]
|
||||
|
||||
RoutingValidationError:
|
||||
type: object
|
||||
required: [code, message_zh, message_en, errors]
|
||||
|
||||
+13
-10
@@ -408,7 +408,18 @@ func mountV1(r chi.Router, sqlDB *sql.DB, rdb *redis.Client, nodeSvc *nodes.Serv
|
||||
accountAPI := httpapi.NewAccountAPI(sqlDB)
|
||||
|
||||
// ── Routing profile (可配置分流) ───────────────────────────────────────────
|
||||
routingAPI := httpapi.NewRoutingAPI(routing.NewStore(sqlDB))
|
||||
// 私有服务域名分流(家庭内网穿透,如 nas/git/win.yanmeiai.com):逗号分隔;
|
||||
// 这些域名用系统 DNS 解析、在外强制走隧道(排在国内分流前)。用户对这些域名的
|
||||
// 自定义规则会静默失效——同一份 slice 注入 RoutingAPI,GET /v1/me/routing
|
||||
// 附带 system_locked_domains 供客户端提示,以及 NodeAPI(渲染 sing-box 配置)。
|
||||
var privateSplitDomains []string
|
||||
for _, d := range strings.Split(os.Getenv("PANGOLIN_PRIVATE_SPLIT_DOMAINS"), ",") {
|
||||
if d = strings.TrimSpace(d); d != "" {
|
||||
privateSplitDomains = append(privateSplitDomains, d)
|
||||
}
|
||||
}
|
||||
routingStore := routing.NewStore(sqlDB)
|
||||
routingAPI := httpapi.NewRoutingAPI(routingStore, privateSplitDomains)
|
||||
|
||||
// ── Nodes + Connect ───────────────────────────────────────────────────────
|
||||
var nodeAPI *httpapi.NodeAPI
|
||||
@@ -423,15 +434,7 @@ func mountV1(r chi.Router, sqlDB *sql.DB, rdb *redis.Client, nodeSvc *nodes.Serv
|
||||
slog.Warn("PANGOLIN_PUBLIC_URL 未设置:国内分流(split_cn)将被静默跳过,客户端全量走隧道。" +
|
||||
"如需国内直连,设为控制面对外公网基址(如 http://<公网IP>:8080)")
|
||||
}
|
||||
// 私有服务域名分流(家庭内网穿透,如 nas/git/win.yanmeiai.com):
|
||||
// 逗号分隔;这些域名用系统 DNS 解析、在外强制走隧道(排在国内分流前)。
|
||||
var privateSplitDomains []string
|
||||
for _, d := range strings.Split(os.Getenv("PANGOLIN_PRIVATE_SPLIT_DOMAINS"), ",") {
|
||||
if d = strings.TrimSpace(d); d != "" {
|
||||
privateSplitDomains = append(privateSplitDomains, d)
|
||||
}
|
||||
}
|
||||
nodeAPI = httpapi.NewNodeAPI(nodeStore, nodeSvc.Hub(), nodeSvc.Load(), os.Getenv("NODE_DERIVE_KEY"), publicURL, privateSplitDomains, routing.NewStore(sqlDB))
|
||||
nodeAPI = httpapi.NewNodeAPI(nodeStore, nodeSvc.Hub(), nodeSvc.Load(), os.Getenv("NODE_DERIVE_KEY"), publicURL, privateSplitDomains, routingStore)
|
||||
}
|
||||
|
||||
// 国内分流(#5)的 rule-set 静态服务:GET /v1/rules/{name}.srs(自托管,
|
||||
|
||||
@@ -270,9 +270,15 @@ func BuildClientConfig(node *nodes.NodeRow, dpUUID, deriveKey string, opts Clien
|
||||
if len(extraExclude) > 0 {
|
||||
// IP 直连真生效:并入 TUN 入站的 route_exclude_address(auto_route 层排除,
|
||||
// 见 tunIn 构造处注释——单靠 route.rules 的 ip_cidr→direct 在 macOS
|
||||
// strict_route 下不生效)。与既有 LAN 网段去重合并。
|
||||
exclude := []string{"192.168.0.0/16", "10.0.0.0/8"}
|
||||
seen := map[string]bool{"192.168.0.0/16": true, "10.0.0.0/8": true}
|
||||
// strict_route 下不生效)。单源读 tunIn 现有种子(不重复硬编码 LAN 网段;
|
||||
// 其为 192.168+10,与上面 route.rules 的 LAN 直连 4 段有意不同——不能改成
|
||||
// LAN 全集,否则会漏排除/多排除),与 extraExclude 去重合并、写回。
|
||||
base, _ := tunIn["route_exclude_address"].([]string)
|
||||
exclude := append([]string{}, base...)
|
||||
seen := make(map[string]bool, len(base))
|
||||
for _, e := range base {
|
||||
seen[e] = true
|
||||
}
|
||||
for _, e := range extraExclude {
|
||||
if !seen[e] {
|
||||
seen[e] = true
|
||||
|
||||
@@ -64,6 +64,19 @@ func openRoutingDB(t *testing.T) *sql.DB {
|
||||
return db
|
||||
}
|
||||
|
||||
// seedConnectUser inserts a minimal users row so routing_profiles inserts
|
||||
// (which now declare FOREIGN KEY (user_id) REFERENCES users(id)) satisfy the
|
||||
// constraint — this DB opens with _pragma=foreign_keys(1) (internal/db/db.go),
|
||||
// so SQLite does enforce it, unlike a bare default SQLite connection.
|
||||
func seedConnectUser(t *testing.T, db *sql.DB, id int64) {
|
||||
t.Helper()
|
||||
uuid := "u-connect"
|
||||
if _, err := db.Exec(`INSERT INTO users (id,uuid,email,pw_hash,dp_uuid,status,created_at)
|
||||
VALUES (?,?,?, 'x','dp-'||?, 'active', ?)`, id, uuid, uuid+"@x", uuid, time.Now().UTC()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// newOnlineHub returns a real *nodes.Hub (backed by miniredis) with nodeUUID
|
||||
// registered online, so ConnectNode's a.hub.IsOnline(...) gate passes and
|
||||
// Push(...) succeeds without a real Redis deployment.
|
||||
@@ -98,6 +111,7 @@ func TestConnectNode_ReadsRoutingProfile(t *testing.T) {
|
||||
const uid = int64(42)
|
||||
|
||||
db := openRoutingDB(t)
|
||||
seedConnectUser(t, db, uid)
|
||||
rst := routing.NewStore(db)
|
||||
p := routing.Default()
|
||||
p.Rules = []routing.Rule{
|
||||
@@ -167,6 +181,7 @@ func TestConnectNode_RoutingStoreErr_FailsSafe(t *testing.T) {
|
||||
const uid = int64(44)
|
||||
|
||||
db := openRoutingDB(t)
|
||||
seedConnectUser(t, db, uid)
|
||||
// 写入一条无法反序列化的 profile_json,模拟 Get 出错。
|
||||
if _, err := db.Exec(`INSERT INTO routing_profiles (user_id, profile_json, updated_at) VALUES (?,?,?)`,
|
||||
uid, "{not-json", time.Now().UTC()); err != nil {
|
||||
|
||||
@@ -14,10 +14,28 @@ import (
|
||||
// user hasn't customized one yet; POST validates and upserts.
|
||||
type RoutingAPI struct {
|
||||
store *routing.Store
|
||||
// lockedDomains are the system-forced-tunnel private-service domains
|
||||
// (PANGOLIN_PRIVATE_SPLIT_DOMAINS, same slice injected into NodeAPI) —
|
||||
// read-only, surfaced to GET so clients can warn users that rules against
|
||||
// these domains silently have no effect. Never written to the persisted
|
||||
// Profile.
|
||||
lockedDomains []string
|
||||
}
|
||||
|
||||
// NewRoutingAPI creates a RoutingAPI backed by the given routing.Store.
|
||||
func NewRoutingAPI(store *routing.Store) *RoutingAPI { return &RoutingAPI{store: store} }
|
||||
// lockedDomains is the system-forced private-service domain list (may be nil).
|
||||
func NewRoutingAPI(store *routing.Store, lockedDomains []string) *RoutingAPI {
|
||||
return &RoutingAPI{store: store, lockedDomains: lockedDomains}
|
||||
}
|
||||
|
||||
// profileResponse wraps routing.Profile for GET /v1/me/routing, adding the
|
||||
// read-only system_locked_domains list. It deliberately lives here — not on
|
||||
// routing.Profile itself — so the field can never leak into the writable
|
||||
// Profile contract that SaveProfile decodes POST bodies into.
|
||||
type profileResponse struct {
|
||||
*routing.Profile
|
||||
SystemLockedDomains []string `json:"system_locked_domains"`
|
||||
}
|
||||
|
||||
// GetProfile handles GET /v1/me/routing.
|
||||
func (a *RoutingAPI) GetProfile(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -34,7 +52,11 @@ func (a *RoutingAPI) GetProfile(w http.ResponseWriter, r *http.Request) {
|
||||
if p == nil {
|
||||
p = routing.Default()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, p)
|
||||
locked := a.lockedDomains
|
||||
if locked == nil {
|
||||
locked = []string{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, profileResponse{Profile: p, SystemLockedDomains: locked})
|
||||
}
|
||||
|
||||
// SaveProfile handles POST /v1/me/routing. On validation failure it returns
|
||||
|
||||
@@ -65,7 +65,7 @@ func doAuthReq(t *testing.T, method, target string, body *strings.Reader, uid in
|
||||
func TestRoutingGetDefaultThenSave(t *testing.T) {
|
||||
db := openRoutingTestDB(t)
|
||||
seedRoutingUser(t, db, 7)
|
||||
api := NewRoutingAPI(routing.NewStore(db))
|
||||
api := NewRoutingAPI(routing.NewStore(db), nil)
|
||||
|
||||
// GET 无档案 → 200 + Default
|
||||
rr := doAuthReq(t, http.MethodGet, "/v1/me/routing", nil, 7, api.GetProfile)
|
||||
@@ -120,7 +120,7 @@ func TestRoutingGetDefaultThenSave(t *testing.T) {
|
||||
|
||||
func TestRoutingGetUnauthorized(t *testing.T) {
|
||||
db := openRoutingTestDB(t)
|
||||
api := NewRoutingAPI(routing.NewStore(db))
|
||||
api := NewRoutingAPI(routing.NewStore(db), nil)
|
||||
req := httptest.NewRequest(http.MethodGet, "/v1/me/routing", nil)
|
||||
rr := httptest.NewRecorder()
|
||||
api.GetProfile(rr, req)
|
||||
@@ -128,3 +128,82 @@ func TestRoutingGetUnauthorized(t *testing.T) {
|
||||
t.Fatalf("expected 401, got %d", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRoutingGetExposesSystemLockedDomains: GET must surface the injected
|
||||
// lockedDomains list under system_locked_domains, without it ever ending up
|
||||
// as part of routing.Profile's own field set.
|
||||
func TestRoutingGetExposesSystemLockedDomains(t *testing.T) {
|
||||
db := openRoutingTestDB(t)
|
||||
seedRoutingUser(t, db, 8)
|
||||
api := NewRoutingAPI(routing.NewStore(db), []string{"nas.x.com"})
|
||||
|
||||
rr := doAuthReq(t, http.MethodGet, "/v1/me/routing", nil, 8, api.GetProfile)
|
||||
if rr.Code != 200 {
|
||||
t.Fatalf("GET code %d", rr.Code)
|
||||
}
|
||||
var resp struct {
|
||||
SystemLockedDomains []string `json:"system_locked_domains"`
|
||||
}
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &resp); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if len(resp.SystemLockedDomains) != 1 || resp.SystemLockedDomains[0] != "nas.x.com" {
|
||||
t.Fatalf("want system_locked_domains=[nas.x.com], got %v", resp.SystemLockedDomains)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRoutingGetSystemLockedDomainsNilBecomesEmptyArray: a nil lockedDomains
|
||||
// slice (no PANGOLIN_PRIVATE_SPLIT_DOMAINS configured) must serialize as
|
||||
// `[]`, not `null` — clients shouldn't need a nil-check.
|
||||
func TestRoutingGetSystemLockedDomainsNilBecomesEmptyArray(t *testing.T) {
|
||||
db := openRoutingTestDB(t)
|
||||
seedRoutingUser(t, db, 9)
|
||||
api := NewRoutingAPI(routing.NewStore(db), nil)
|
||||
|
||||
rr := doAuthReq(t, http.MethodGet, "/v1/me/routing", nil, 9, api.GetProfile)
|
||||
if rr.Code != 200 {
|
||||
t.Fatalf("GET code %d", rr.Code)
|
||||
}
|
||||
var raw map[string]json.RawMessage
|
||||
if err := json.Unmarshal(rr.Body.Bytes(), &raw); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if got := string(raw["system_locked_domains"]); got != "[]" {
|
||||
t.Fatalf("want system_locked_domains=`[]`, got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRoutingSaveIgnoresSystemLockedDomains: a client POSTing a body that
|
||||
// includes system_locked_domains must not have it persisted — SaveProfile
|
||||
// decodes straight into routing.Profile, which has no such field, so the
|
||||
// key is silently dropped. Verify against the raw stored row (not the GET
|
||||
// response, which always injects it from a.lockedDomains regardless of what
|
||||
// was ever saved).
|
||||
func TestRoutingSaveIgnoresSystemLockedDomains(t *testing.T) {
|
||||
db := openRoutingTestDB(t)
|
||||
seedRoutingUser(t, db, 10)
|
||||
store := routing.NewStore(db)
|
||||
api := NewRoutingAPI(store, []string{"nas.x.com"})
|
||||
|
||||
body := `{"mode":"rule","builtin":{"china_direct":true,"lan_direct":true,"private_via_tunnel":true},` +
|
||||
`"rules":[],"final":"proxy","system_locked_domains":["evil.attacker.com"]}`
|
||||
rr := doAuthReq(t, http.MethodPost, "/v1/me/routing", strings.NewReader(body), 10, api.SaveProfile)
|
||||
if rr.Code != 200 {
|
||||
t.Fatalf("POST code %d body %s", rr.Code, rr.Body)
|
||||
}
|
||||
|
||||
stored, err := store.Get(context.Background(), 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored == nil {
|
||||
t.Fatal("expected a persisted profile")
|
||||
}
|
||||
raw, err := json.Marshal(stored)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(raw), "system_locked_domains") || strings.Contains(string(raw), "evil.attacker.com") {
|
||||
t.Fatalf("system_locked_domains must never be persisted, got stored profile JSON: %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,8 +21,17 @@ type Rule struct {
|
||||
// Builtin toggles the built-in routing behaviors that previously were
|
||||
// hardcoded into the server's sing-box config rendering.
|
||||
type Builtin struct {
|
||||
ChinaDirect bool `json:"china_direct"`
|
||||
LanDirect bool `json:"lan_direct"`
|
||||
ChinaDirect bool `json:"china_direct"`
|
||||
// LanDirect is reserved/always-on: the system layer (route_exclude_address
|
||||
// + the hardcoded LAN direct rule in clientconfig.go) renders unconditionally
|
||||
// regardless of this flag's value — the renderer does not read it. Kept in
|
||||
// the wire contract for a possible future per-user opt-out; today it has no
|
||||
// effect on rendering.
|
||||
LanDirect bool `json:"lan_direct"`
|
||||
// PrivateViaTunnel is reserved/always-on: when PANGOLIN_PRIVATE_SPLIT_DOMAINS
|
||||
// is configured, those domains are always force-routed through the tunnel —
|
||||
// the renderer does not read this flag. Kept in the wire contract for a
|
||||
// possible future per-user opt-out; today it has no effect on rendering.
|
||||
PrivateViaTunnel bool `json:"private_via_tunnel"`
|
||||
}
|
||||
|
||||
@@ -64,11 +73,11 @@ var geoWhitelist = map[string]bool{"cn": true} // geoip/geosite 仅自托管 cn
|
||||
|
||||
// Validate checks the profile against the type/action whitelist, CIDR
|
||||
// syntax, the geo set whitelist, and the rule count cap. It returns an empty
|
||||
// (nil) slice when the profile is valid; every violation is reported
|
||||
// independently (no short-circuiting) so callers can surface all errors at
|
||||
// once.
|
||||
// (non-nil) slice when the profile is valid — so JSON encoding produces `[]`
|
||||
// rather than `null` — and every violation is reported independently (no
|
||||
// short-circuiting) so callers can surface all errors at once.
|
||||
func (p *Profile) Validate() []FieldError {
|
||||
var errs []FieldError
|
||||
errs := []FieldError{}
|
||||
if p.Mode != "rule" && p.Mode != "global" && p.Mode != "direct" {
|
||||
errs = append(errs, FieldError{-1, "mode", "must be rule|global|direct"})
|
||||
}
|
||||
@@ -102,14 +111,20 @@ func (p *Profile) Validate() []FieldError {
|
||||
return errs
|
||||
}
|
||||
|
||||
// dedupKey identifies a rule for Normalize's de-duplication. Using a struct
|
||||
// (rather than string-concatenating Type+Value+Action with a separator)
|
||||
// avoids false-collision when a value itself contains the separator
|
||||
// character.
|
||||
type dedupKey struct{ Type, Value, Action string }
|
||||
|
||||
// Normalize trims rule values and de-duplicates rules by (type, value,
|
||||
// action), keeping the first occurrence's position (and its Note/Enabled).
|
||||
func (p *Profile) Normalize() {
|
||||
seen := map[string]bool{}
|
||||
seen := map[dedupKey]bool{}
|
||||
out := p.Rules[:0]
|
||||
for _, r := range p.Rules {
|
||||
r.Value = strings.TrimSpace(r.Value)
|
||||
k := r.Type + "|" + r.Value + "|" + r.Action
|
||||
k := dedupKey{r.Type, r.Value, r.Action}
|
||||
if seen[k] {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -1,13 +1,32 @@
|
||||
package routing
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestValidateEmptyErrorsSerializeAsArray guards the JSON shape API clients
|
||||
// depend on: a valid profile's Validate() must marshal to `[]`, not `null`.
|
||||
func TestValidateEmptyErrorsSerializeAsArray(t *testing.T) {
|
||||
raw, err := json.Marshal(Default().Validate())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(raw) != "[]" {
|
||||
t.Fatalf("want `[]`, got %s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
ok := Default()
|
||||
ok.Rules = []Rule{{Type: "domain_suffix", Value: "example.com", Action: "direct", Enabled: true}}
|
||||
if e := ok.Validate(); len(e) != 0 {
|
||||
e := ok.Validate()
|
||||
if len(e) != 0 {
|
||||
t.Fatalf("valid profile got errors %v", e)
|
||||
}
|
||||
if e == nil {
|
||||
t.Fatal("Validate must return a non-nil empty slice (serializes to [] not null)")
|
||||
}
|
||||
|
||||
bad := Default()
|
||||
bad.Mode = "weird" // 非法 mode
|
||||
@@ -48,3 +67,19 @@ func TestNormalizeDedupAndTrim(t *testing.T) {
|
||||
t.Fatalf("want first-occurrence order preserved, got %v", p.Rules)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeDedupNoSeparatorCollision guards against the historical
|
||||
// string-concatenation dedup key ("type|value|action"): two distinct rules
|
||||
// whose Value contains "|" could concatenate to the same string even though
|
||||
// (type, value, action) differ. The struct-keyed dedup must tell them apart.
|
||||
func TestNormalizeDedupNoSeparatorCollision(t *testing.T) {
|
||||
p := Default()
|
||||
p.Rules = []Rule{
|
||||
{Type: "domain", Value: "a|b", Action: "proxy", Enabled: true},
|
||||
{Type: "domain", Value: "a", Action: "b|proxy", Enabled: true},
|
||||
}
|
||||
p.Normalize()
|
||||
if len(p.Rules) != 2 {
|
||||
t.Fatalf("want 2 distinct rules preserved (no false collision), got %d: %v", len(p.Rules), p.Rules)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,27 @@ func seedU(t *testing.T, db *sql.DB, id int64, uuid string) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestSQLiteRoutingStoreGetNoProfileRow isolates the "queried the DB, found
|
||||
// no row" path from TestSQLiteRoutingStoreUpsertGet's combined
|
||||
// empty→upsert→overwrite flow: a store backed by a real (non-nil) *sql.DB,
|
||||
// with the user seeded but no routing_profiles row for them, must return
|
||||
// (nil, nil) — not an error — via the sql.ErrNoRows branch in Store.Get.
|
||||
func TestSQLiteRoutingStoreGetNoProfileRow(t *testing.T) {
|
||||
db := openDB(t)
|
||||
seedU(t, db, 2, "u2")
|
||||
st := NewStore(db)
|
||||
if st == nil {
|
||||
t.Fatal("NewStore returned nil")
|
||||
}
|
||||
got, err := st.Get(context.Background(), 2)
|
||||
if err != nil {
|
||||
t.Fatalf("want nil error for no-rows, got %v", err)
|
||||
}
|
||||
if got != nil {
|
||||
t.Fatalf("want nil profile for seeded user with no profile row, got %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSQLiteRoutingStoreUpsertGet(t *testing.T) {
|
||||
db := openDB(t) // 内存库 + MigrateUp(sqlite)
|
||||
seedU(t, db, 1, "u1")
|
||||
|
||||
@@ -104,29 +104,12 @@ func TestCodesLibMigrateRoundTrip(t *testing.T) {
|
||||
// the reviewer's repro hit: the lib's `codes` table collides with the
|
||||
// name 000022's down script renames legacy_codes back to.
|
||||
m := newSQLiteStepper(t, db)
|
||||
// 000027 (pay_promo_paid_unique), 000026 (notices), 000025
|
||||
// (user_device_limit_override), 000024 (invite_rewards) and 000023
|
||||
// (pay_purchases/source-enum) now sit on top of 000022
|
||||
// (codes_lib_legacy_rename) and are unrelated to this collision — step
|
||||
// them back down first so we land exactly on the 000022 boundary the
|
||||
// test targets.
|
||||
if err := m.Steps(-1); err != nil {
|
||||
t.Fatalf("step 000027 down: %v", err)
|
||||
}
|
||||
if err := m.Steps(-1); err != nil {
|
||||
t.Fatalf("step 000026 down: %v", err)
|
||||
}
|
||||
if err := m.Steps(-1); err != nil {
|
||||
t.Fatalf("step 000025 down: %v", err)
|
||||
}
|
||||
if err := m.Steps(-1); err != nil {
|
||||
t.Fatalf("step 000024 down: %v", err)
|
||||
}
|
||||
if err := m.Steps(-1); err != nil {
|
||||
t.Fatalf("step 000023 down: %v", err)
|
||||
}
|
||||
if err := m.Steps(-1); err != nil {
|
||||
t.Fatalf("step 000022 down: %v (this is the reviewer-reported collision — "+
|
||||
// 所有排在 000022 之上的迁移(000023..最新,如 pay_purchases / invite_rewards /
|
||||
// notices / routing_profiles …)都与本冲突无关 —— 一次性降到版本 21,恰好落在
|
||||
// 000022(codes_lib_legacy_rename)down 之后的边界。用版本号显式定位而非硬编码
|
||||
// Steps(-1) 计数,避免栈顶新增迁移(如 000028)后步数漂移、跳过 000022 down。
|
||||
if err := m.Migrate(21); err != nil {
|
||||
t.Fatalf("migrate down to v21 (past 000022 down): %v (this is the reviewer-reported collision — "+
|
||||
"000022 down must DROP the codes-lib tables before renaming legacy_* back)", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
CREATE TABLE routing_profiles (
|
||||
user_id INTEGER NOT NULL PRIMARY KEY,
|
||||
profile_json TEXT NOT NULL,
|
||||
updated_at DATETIME NOT NULL
|
||||
updated_at DATETIME NOT NULL,
|
||||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user