mirror of
https://github.com/shadowsocks/ShadowsocksX-NG.git
synced 2026-11-17 19:44:42 +00:00
feat(rules): fix custom rule actions to their scheme
This commit is contained in:
+7
-6
@@ -134,18 +134,19 @@ _避免用词_:可移除节点(Removable node)。
|
||||
规则模式下,没有规则匹配目标时采用的代理或直连动作。
|
||||
_避免用词_:回退(Fallback,含义不明确)。
|
||||
|
||||
**规则预设(Rule preset)**:
|
||||
规则模式内,对内置规则来源、命中行动与规则默认动作的预先组合,也是自定义规则、规则停用、浏览、搜索、过滤与离线规则测试的顶层归属范围。它属于规则模式,不是与规则、全局、直连并列的代理模式。`RulePreset` 定义中国大陆目标直连、仅GFW列表内目标代理和中国大陆目标代理三项预设;运行选择与 `RulesWorkspaces` 管理范围相互独立。
|
||||
**规则方案(Rule preset)**:
|
||||
规则模式内,具有固定匹配后行动和未匹配行动的规则组合,也是自定义规则、规则停用、浏览与离线规则测试的归属范围,包括仅GFW列表内目标代理、中国大陆目标直连和中国大陆目标代理三项方案。内置规则与自定义规则的匹配后行动由所属方案统一决定,固定本地目标始终直连。
|
||||
_避免用词_:规则预设(产品名称统一使用规则方案)。
|
||||
|
||||
**内置规则快照(Built-in rule snapshot)**:
|
||||
随应用发布的固定规则集,包含来源、归属与转换报告等资料。它只保留转换后可决定路由的规则,不保留被吸收或遮蔽而省略的上游条目。
|
||||
|
||||
**自定义规则(Custom rule)**:
|
||||
用户拥有的代理或直连规则,以精确域名、域名后缀或 IPv4/IPv6 地址范围作为匹配条件,并具有持久身份。列表顺序不代表路由优先级。
|
||||
用户拥有的、具有持久身份的规则,以精确域名、域名后缀或 IPv4/IPv6 地址范围作为匹配条件,匹配后行动由所属规则方案决定。列表顺序不代表路由优先级。
|
||||
_避免用词_:用户规则(User rule)。
|
||||
|
||||
**自定义规则集合(Custom rule collection)**:
|
||||
一项规则预设独立拥有的自定义规则集合,仅在该预设下参与规则模式路由。切换预设保留各集合,修改一个集合不影响其他预设。
|
||||
一项规则方案独立拥有的自定义规则集合,仅在该方案下参与规则模式路由。切换方案保留各集合,修改一个集合不影响其他方案。
|
||||
|
||||
**规则身份(Rule identity)**:
|
||||
规范化匹配条件与路由动作的组合,用于识别不同来源中的等价规则。它与可编辑自定义条目的持久身份不同,单个 IP 地址与其完整前缀长度的 CIDR 等价。
|
||||
@@ -154,7 +155,7 @@ _避免用词_:用户规则(User rule)。
|
||||
一个规则身份所属的全部来源;等价条目合并展示时仍保留各来源归属。
|
||||
|
||||
**规则停用(Rule disablement)**:
|
||||
用户为一项规则预设保存的、跨该预设全部来源排除某个规则身份的选择,不影响其他预设;来源条目仍保留,覆盖同一目标的更宽规则也不因此被停用。固定本地绕过策略不能停用。
|
||||
用户为一项规则方案保存的、跨该方案全部来源排除某个规则身份的选择,不影响其他方案;来源条目仍保留,覆盖同一目标的更宽规则也不因此被停用。固定本地绕过策略不能停用。
|
||||
|
||||
**规则吸收(Rule absorption)**:
|
||||
同动作规则之间的覆盖关系,其中较宽规则使较窄规则在路由判定中冗余。它与反动作遮蔽不同,也不删除已保存的自定义规则。
|
||||
@@ -166,7 +167,7 @@ _避免用词_:用户规则(User rule)。
|
||||
生成内置规则快照时记录的转换、吸收、跳过与拒绝数量。它描述快照生成时的结果,而非当前规则集合的覆盖关系或运行状态。
|
||||
|
||||
**离线规则测试(Offline rule test)**:
|
||||
针对域名、IP 地址或 URL 主机,依据指定规则预设的规则和默认动作,解释代理或直连结论及其原因的操作。各预设的测试状态相互独立,结果不受浏览筛选、实际代理模式或运行状态影响;测试不解析 DNS,也不测试连通性。
|
||||
针对域名、IP 地址或 URL 主机,依据指定规则方案的规则和默认动作,解释代理或直连结论及其原因的操作。各方案的测试状态相互独立,结果不受浏览筛选、实际代理模式或运行状态影响;测试不解析 DNS,也不测试连通性。
|
||||
|
||||
### 代理控制与网络
|
||||
|
||||
|
||||
@@ -317,9 +317,10 @@ extension RulesWorkflow {
|
||||
return CustomRuleDraft(
|
||||
id: id, editingID: id, version: ticket.version,
|
||||
kind: rule.identity.match.editingKind, content: rule.identity.match.editingContent,
|
||||
action: rule.action)
|
||||
action: preset.matchedAction)
|
||||
}
|
||||
return CustomRuleDraft(id: UUID(), editingID: nil, version: ticket.version)
|
||||
return CustomRuleDraft(
|
||||
id: UUID(), editingID: nil, version: ticket.version, action: preset.matchedAction)
|
||||
}
|
||||
|
||||
func previewCustomRule(_ draft: CustomRuleDraft) async -> CustomRulePreview {
|
||||
|
||||
@@ -1269,19 +1269,19 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"未命中规则,采用预设默认动作。": {
|
||||
"未命中规则,采用方案默认动作。": {
|
||||
"extractionState": "manual",
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "No rule matched. Using the preset’s default action."
|
||||
"value": "No rule matched. Using the rule scheme’s default action."
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "未命中规则,采用预设默认动作。"
|
||||
"value": "未命中规则,采用方案默认动作。"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,11 +28,9 @@ struct CustomRuleEditorSheet: View {
|
||||
.pickerStyle(.segmented)
|
||||
TextField(RulesCopy.text("匹配内容"), text: $draft.content)
|
||||
.autocorrectionDisabled()
|
||||
Picker(RulesCopy.text("行动"), selection: $draft.action) {
|
||||
Text(RulesCopy.text("代理")).tag(RuleAction.proxy)
|
||||
Text(RulesCopy.text("直连")).tag(RuleAction.direct)
|
||||
LabeledContent(RulesCopy.text("行动")) {
|
||||
Text(RulesCopy.text(draft.action == .proxy ? "代理" : "直连"))
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
}
|
||||
}.disabled(isSaving || workflow.snapshot.isCommitting)
|
||||
ScrollView {
|
||||
|
||||
@@ -99,7 +99,7 @@ extension OfflineRuleMatcher.Explanation {
|
||||
case .fixedLocal: "固定本地策略优先。"
|
||||
case .domainProxy: "域名同时命中两种行动时,代理优先。"
|
||||
case .ipDirect: "IP 同时命中两种行动时,直连优先。"
|
||||
case .defaultAction: "未命中规则,采用预设默认动作。"
|
||||
case .defaultAction: "未命中规则,采用方案默认动作。"
|
||||
case .singleAction: nil
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,6 +129,8 @@ enum RulePreset: String, Codable, CaseIterable, Hashable, Sendable {
|
||||
self == .chinaDirect ? .proxyWhenUnmatched : .directWhenUnmatched
|
||||
}
|
||||
|
||||
var matchedAction: RuleAction { self == .chinaDirect ? .direct : .proxy }
|
||||
|
||||
var sources: [RulesSource] {
|
||||
self == .gfwlist ? [.gfwlist] : [.geolocationCN, .chinaIPv4]
|
||||
}
|
||||
@@ -142,9 +144,9 @@ enum RulePreset: String, Codable, CaseIterable, Hashable, Sendable {
|
||||
}
|
||||
|
||||
func rules(from snapshot: RuleSnapshot) -> [ProxyRule] {
|
||||
if self == .gfwlist { return snapshot.rules }
|
||||
if self == .gfwlist { return snapshot.rules.filter { $0.action == matchedAction } }
|
||||
return BuiltinRuleCatalog.chinaDirectRules(from: snapshot).map {
|
||||
ProxyRule(action: self == .chinaProxy ? .proxy : .direct, match: $0.match)
|
||||
ProxyRule(action: matchedAction, match: $0.match)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ struct CustomRuleDraft: Equatable, Sendable, Identifiable {
|
||||
let version: String
|
||||
var kind: Kind = .domainSuffix
|
||||
var content = ""
|
||||
var action: RuleAction = .proxy
|
||||
let action: RuleAction
|
||||
|
||||
func normalizedMatch() throws -> RuleMatch {
|
||||
let value = content.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
@@ -76,7 +76,7 @@ extension RulesCollection {
|
||||
return CustomRulePreview(failure: .staleDraft)
|
||||
}
|
||||
let rule = CustomRule(
|
||||
id: draft.id, action: draft.action, match: match)
|
||||
id: draft.id, action: preset.matchedAction, match: match)
|
||||
let others = document.rules.filter { $0.id != draft.editingID }
|
||||
guard !others.contains(where: { $0.identity == rule.identity }) else {
|
||||
return CustomRulePreview(failure: .duplicate, rule: rule)
|
||||
|
||||
@@ -10,18 +10,21 @@ enum CustomRuleStoreError: Error, Equatable, Sendable {
|
||||
/// 自定义规则持久化:独立 JSON 文档,原子写盘。
|
||||
/// Saving intent is independent of subsequent ACL application and runtime recovery.
|
||||
struct CustomRuleStore {
|
||||
static let currentSchemaVersion = 3
|
||||
static let currentSchemaVersion = 4
|
||||
|
||||
let fileURL: URL
|
||||
let baseURL: URL
|
||||
let preset: RulePreset?
|
||||
|
||||
init(fileURL: URL = CustomRuleStore.defaultFileURL()) {
|
||||
self.fileURL = fileURL
|
||||
self.baseURL = fileURL
|
||||
self.preset = nil
|
||||
}
|
||||
|
||||
init(preset: RulePreset, baseURL: URL = CustomRuleStore.defaultFileURL()) {
|
||||
self.baseURL = baseURL
|
||||
self.preset = preset
|
||||
self.fileURL = baseURL.deletingLastPathComponent()
|
||||
.appendingPathComponent("rule-presets", isDirectory: true)
|
||||
.appendingPathComponent(preset.rawValue, isDirectory: true)
|
||||
@@ -46,7 +49,16 @@ struct CustomRuleStore {
|
||||
}
|
||||
let document: CustomRuleDocument
|
||||
do {
|
||||
document = try Self.decode(data)
|
||||
let stored = try JSONDecoder().decode(StoredCustomRuleDocument.self, from: data)
|
||||
let decoded = try stored.domain()
|
||||
if let preset, stored.schemaVersion < Self.currentSchemaVersion {
|
||||
document = CustomRuleDocument(
|
||||
rules: decoded.rules.filter { $0.action == preset.matchedAction },
|
||||
disabledIdentities: decoded.disabledIdentities)
|
||||
} else {
|
||||
try validateActions(decoded)
|
||||
document = decoded
|
||||
}
|
||||
} catch let error as CustomRuleStoreError {
|
||||
throw error
|
||||
} catch {
|
||||
@@ -62,6 +74,7 @@ struct CustomRuleStore {
|
||||
}
|
||||
|
||||
func saveDocument(_ document: CustomRuleDocument) throws {
|
||||
try validateActions(document)
|
||||
let data = try Self.encode(document)
|
||||
_ = try Self.decode(data)
|
||||
do {
|
||||
@@ -71,6 +84,13 @@ struct CustomRuleStore {
|
||||
}
|
||||
}
|
||||
|
||||
private func validateActions(_ document: CustomRuleDocument) throws {
|
||||
guard let preset else { return }
|
||||
guard document.rules.allSatisfy({ $0.action == preset.matchedAction }) else {
|
||||
throw CustomRuleStoreError.corrupt(detail: "Custom rule action must match its rule scheme")
|
||||
}
|
||||
}
|
||||
|
||||
/// 安全摘要:数量 + 内容版本。
|
||||
func summary() throws -> CustomRuleSummary {
|
||||
CustomRuleSummary.summarizing(try loadDocument())
|
||||
@@ -135,7 +155,7 @@ private struct StoredCustomRuleDocument: Codable {
|
||||
init(from decoder: Decoder) throws {
|
||||
let values = try decoder.container(keyedBy: CodingKeys.self)
|
||||
schemaVersion = try values.decode(Int.self, forKey: .schemaVersion)
|
||||
guard [1, 2, CustomRuleStore.currentSchemaVersion].contains(schemaVersion) else {
|
||||
guard (1...CustomRuleStore.currentSchemaVersion).contains(schemaVersion) else {
|
||||
throw CustomRuleStoreError.schemaVersionMismatch(
|
||||
found: schemaVersion, expected: CustomRuleStore.currentSchemaVersion)
|
||||
}
|
||||
|
||||
@@ -356,7 +356,10 @@ enum RuleRuntimeCompiler {
|
||||
case .global: return source.replacingACL(.global(at: aclURL))
|
||||
case .rule:
|
||||
let document = document ?? CustomRuleDocument(rules: [])
|
||||
let custom = document.rules.filter { !document.disabledIdentities.contains($0.identity) }
|
||||
let custom = document.rules.filter {
|
||||
$0.action != defaultAction.fallbackAction
|
||||
&& !document.disabledIdentities.contains($0.identity)
|
||||
}
|
||||
let enabled = builtIn.filter { !document.disabledIdentities.contains($0) }
|
||||
let validated = CustomRuleValidator.hardValidation(custom: custom)
|
||||
let candidates = RuleAnalysis.runtimeCandidates(
|
||||
|
||||
@@ -53,6 +53,13 @@ final class RuleDocumentSession {
|
||||
guard rejected.isEmpty else {
|
||||
return RuleDocumentCommit(outcome: .rejected(rejected), document: current)
|
||||
}
|
||||
if let preset = store.preset,
|
||||
document.rules.contains(where: { $0.action != preset.matchedAction })
|
||||
{
|
||||
return RuleDocumentCommit(
|
||||
outcome: .invalidDocument(detail: "Custom rule action must match its rule scheme"),
|
||||
document: current)
|
||||
}
|
||||
guard
|
||||
document.disabledIdentities.isDisjoint(
|
||||
with: Set(RuleCoverage.fixedLocalMatches.map { ProxyRule(action: .direct, match: $0) }))
|
||||
|
||||
@@ -69,14 +69,16 @@ private struct RulesCollectionInput: Sendable {
|
||||
|
||||
mutating func readCustom(_ loadCustom: () throws -> CustomRuleDocument) {
|
||||
do {
|
||||
let document = try loadCustom()
|
||||
let custom = document.rules
|
||||
disabled = document.disabledIdentities
|
||||
userDocument = document
|
||||
let validation = CustomRuleValidator.hardValidation(custom: custom)
|
||||
let loaded = try loadCustom()
|
||||
let validation = CustomRuleValidator.hardValidation(custom: loaded.rules)
|
||||
guard validation.rejected.isEmpty else {
|
||||
throw CustomRuleStoreError.corrupt(detail: "Invalid custom rule collection")
|
||||
}
|
||||
let custom = loaded.rules.filter { $0.action == preset.matchedAction }
|
||||
let document = CustomRuleDocument(
|
||||
rules: custom, disabledIdentities: loaded.disabledIdentities)
|
||||
disabled = document.disabledIdentities
|
||||
userDocument = document
|
||||
entries += custom.map { RulesCandidate(rule: $0.proxyRule, source: .custom, customID: $0.id) }
|
||||
sources.insert(
|
||||
RulesSourceSnapshot(id: .custom, count: custom.count, metadata: nil, conversionReport: nil),
|
||||
|
||||
@@ -88,7 +88,7 @@ final class CustomRuleControllerTests: ProxyRuntimeControllerTests {
|
||||
"自定义直连规则应进入规则模式 ACL")
|
||||
}
|
||||
|
||||
func testOppositeActionsPersistAndReorderingDoesNotRedeploy() async throws {
|
||||
func testSchemeActionRulesPersistAndReorderingDoesNotRedeploy() async throws {
|
||||
let seeded = try makeSeededCatalog()
|
||||
let (store, _) = try makeCustomRuleStore(preset: .gfwlist)
|
||||
let settings = ProxyRuntimeSettings(
|
||||
@@ -98,9 +98,9 @@ final class CustomRuleControllerTests: ProxyRuntimeControllerTests {
|
||||
store: store, settings: settings, proxyMode: .rule)
|
||||
try await controller.activate(seeded.server)
|
||||
let rules = [
|
||||
CustomRule(action: .direct, match: try RuleMatch(domainSuffix: "order.example")),
|
||||
CustomRule(action: .proxy, match: try RuleMatch(domainSuffix: "order.example")),
|
||||
CustomRule(action: .proxy, match: try RuleMatch(domainExact: "a.order.example")),
|
||||
CustomRule(action: .direct, match: try RuleMatch(domainExact: "a.order.example")),
|
||||
CustomRule(action: .proxy, match: try RuleMatch(domainExact: "b.order.example")),
|
||||
]
|
||||
let first = await controller.commitRuleDocument(CustomRuleDocument(rules: rules)).outcome
|
||||
XCTAssertEqual(first, .saved)
|
||||
@@ -227,7 +227,7 @@ final class CustomRuleControllerTests: ProxyRuntimeControllerTests {
|
||||
func testCustomRuleSummaryExposesCountAndVersionOnly() async throws {
|
||||
let (store, _) = try makeCustomRuleStore()
|
||||
try store.save([
|
||||
CustomRule(action: .proxy, match: try RuleMatch(domainSuffix: "secret.example"))
|
||||
CustomRule(action: .direct, match: try RuleMatch(domainSuffix: "secret.example"))
|
||||
])
|
||||
let controller = makeControllerWithCustomRules(store: store)
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ final class CustomRuleDeletionWorkflowTests: XCTestCase {
|
||||
{
|
||||
let custom = CustomRule(
|
||||
action: .proxy, match: try RuleMatch(domainSuffix: "merged.example"))
|
||||
let other = CustomRule(action: .direct, match: try RuleMatch(domainExact: "other.example"))
|
||||
let other = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "other.example"))
|
||||
let orphan = ProxyRule(action: .proxy, match: try RuleMatch(domainExact: "orphan.example"))
|
||||
let builtin = ProxyRule(action: custom.action, match: custom.match)
|
||||
var saved = CustomRuleDocument(
|
||||
@@ -53,7 +53,7 @@ final class CustomRuleDeletionWorkflowTests: XCTestCase {
|
||||
extension CustomRuleDeletionWorkflowTests {
|
||||
func testFilteredSelectionCannotEnterConfirmationAndStaleConfirmationCannotExpand() async throws {
|
||||
let first = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "first.example"))
|
||||
let hidden = CustomRule(action: .direct, match: try RuleMatch(domainExact: "hidden.example"))
|
||||
let hidden = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "hidden.example"))
|
||||
var commits = 0
|
||||
var saved = CustomRuleDocument(rules: [first, hidden])
|
||||
let workflow = RulesWorkflow(
|
||||
|
||||
@@ -20,7 +20,6 @@ final class CustomRuleEditingControllerTests: ProxyRuntimeControllerTests {
|
||||
var draft = try XCTUnwrap(workflow.makeCustomRuleDraft())
|
||||
draft.kind = .ipAddress
|
||||
draft.content = "8.8.8.8"
|
||||
draft.action = .direct
|
||||
let result = await workflow.saveCustomRule(draft)
|
||||
XCTAssertEqual(result, .committed(.saved))
|
||||
XCTAssertEqual(try store.load().first?.id, draft.id)
|
||||
@@ -43,7 +42,6 @@ final class CustomRuleEditingControllerTests: ProxyRuntimeControllerTests {
|
||||
let registrations = agent.registerCount
|
||||
var draft = try XCTUnwrap(workflow.makeCustomRuleDraft())
|
||||
draft.content = "new-rule.example"
|
||||
draft.action = .direct
|
||||
let added = await workflow.saveCustomRule(draft)
|
||||
XCTAssertEqual(added, .committed(.saved))
|
||||
await controller.ruleApplicationTask?.value
|
||||
|
||||
@@ -14,7 +14,6 @@ final class CustomRuleEditingWorkflowTests: XCTestCase {
|
||||
var draft = try XCTUnwrap(workflow.makeCustomRuleDraft())
|
||||
draft.kind = .ipAddress
|
||||
draft.content = " 2001:DB8::1 "
|
||||
draft.action = .direct
|
||||
let preview = await workflow.previewCustomRule(draft)
|
||||
XCTAssertNil(preview.failure)
|
||||
XCTAssertEqual(preview.rule?.match, try RuleMatch(ipv6CIDR: "2001:db8::1/128"))
|
||||
@@ -48,7 +47,6 @@ final class CustomRuleEditingWorkflowTests: XCTestCase {
|
||||
let unchanged = await workflow.previewCustomRule(draft)
|
||||
XCTAssertNil(unchanged.failure, "Editing excludes its own UUID")
|
||||
draft.content = "new.example"
|
||||
draft.action = .direct
|
||||
let preview = await workflow.previewCustomRule(draft)
|
||||
XCTAssertTrue(preview.inheritsDisablement)
|
||||
XCTAssertEqual(preview.row?.isEnabled, false)
|
||||
@@ -60,7 +58,7 @@ final class CustomRuleEditingWorkflowTests: XCTestCase {
|
||||
saved.disabledIdentities,
|
||||
[
|
||||
original.identity,
|
||||
ProxyRule(action: .direct, match: try RuleMatch(domainSuffix: "new.example")),
|
||||
ProxyRule(action: .proxy, match: try RuleMatch(domainSuffix: "new.example")),
|
||||
])
|
||||
workflow.query(RulesQuery(source: .gfwlist))
|
||||
let oldRow = try XCTUnwrap(workflow.snapshot.rows.first { $0.identity == original.identity })
|
||||
@@ -81,7 +79,6 @@ final class CustomRuleEditingWorkflowTests: XCTestCase {
|
||||
await workflow.refresh()
|
||||
var draft = try XCTUnwrap(workflow.makeCustomRuleDraft())
|
||||
draft.kind = .cidr
|
||||
draft.action = .direct
|
||||
for invalid in ["/8.8.8.8", "8.8.8.8/", "8.8.8.8", "8.8.8.8/33", "2001:db8::1/129"] {
|
||||
draft.content = invalid
|
||||
let preview = await workflow.previewCustomRule(draft)
|
||||
@@ -98,7 +95,7 @@ final class CustomRuleEditingWorkflowTests: XCTestCase {
|
||||
}
|
||||
|
||||
func testDuplicateAndFixedLocalConflictAreRejectedWithoutCommit() async throws {
|
||||
let existing = CustomRule(action: .direct, match: try RuleMatch(ipv4CIDR: "8.8.8.8/32"))
|
||||
let existing = CustomRule(action: .proxy, match: try RuleMatch(ipv4CIDR: "8.8.8.8/32"))
|
||||
var commits = 0
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist, loadDocument: { CustomRuleDocument(rules: [existing]) },
|
||||
@@ -111,7 +108,6 @@ final class CustomRuleEditingWorkflowTests: XCTestCase {
|
||||
var draft = try XCTUnwrap(workflow.makeCustomRuleDraft())
|
||||
draft.kind = .ipAddress
|
||||
draft.content = "8.8.8.8"
|
||||
draft.action = .direct
|
||||
let duplicate = await workflow.previewCustomRule(draft)
|
||||
XCTAssertEqual(duplicate.failure, .duplicate)
|
||||
let duplicateSave = await workflow.saveCustomRule(draft)
|
||||
@@ -120,7 +116,6 @@ final class CustomRuleEditingWorkflowTests: XCTestCase {
|
||||
draft.content = "8.8.8.8/32"
|
||||
let cidr = await workflow.previewCustomRule(draft)
|
||||
XCTAssertEqual(cidr.failure, .duplicate, "IP and full CIDR have one identity")
|
||||
draft.action = .proxy
|
||||
draft.kind = .ipAddress
|
||||
for input in ["192.168.1.1", "::ffff:192.168.1.1", "::1"] {
|
||||
draft.content = input
|
||||
@@ -171,12 +166,11 @@ final class CustomRuleEditingWorkflowTests: XCTestCase {
|
||||
|
||||
func testDomainBoundaryAndNationalSuffixUseExistingNormalization() async throws {
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist, loadDocument: { CustomRuleDocument(rules: []) },
|
||||
preset: .chinaDirect, loadDocument: { CustomRuleDocument(rules: []) },
|
||||
commitDocument: { RuleDocumentCommit(outcome: .saved, document: $0) },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: { rulesFixture($0) }))
|
||||
await workflow.refresh()
|
||||
var draft = try XCTUnwrap(workflow.makeCustomRuleDraft())
|
||||
draft.action = .direct
|
||||
for kind in [CustomRuleDraft.Kind.domainExact, .domainSuffix] {
|
||||
draft.kind = kind
|
||||
for input in [
|
||||
@@ -204,41 +198,29 @@ final class CustomRuleEditingWorkflowTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
func testPreviewExplainsAbsorptionShadowingAndPartialOverlapButAllowsSave() async throws {
|
||||
func testPreviewExplainsSameActionAbsorptionAndAllowsSave() async throws {
|
||||
let broad = CustomRule(
|
||||
action: .direct, match: try RuleMatch(domainSuffix: "coverage.example"))
|
||||
let proxy = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "a.coverage.example"))
|
||||
action: .proxy, match: try RuleMatch(domainSuffix: "coverage.example"))
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist, loadDocument: { CustomRuleDocument(rules: [broad, proxy]) },
|
||||
preset: .gfwlist, loadDocument: { CustomRuleDocument(rules: [broad]) },
|
||||
commitDocument: { RuleDocumentCommit(outcome: .saved, document: $0) },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: { rulesFixture($0) }))
|
||||
await workflow.refresh()
|
||||
var draft = try XCTUnwrap(workflow.makeCustomRuleDraft())
|
||||
draft.kind = .domainExact
|
||||
draft.content = "a.coverage.example"
|
||||
draft.action = .direct
|
||||
let preview = await workflow.previewCustomRule(draft)
|
||||
XCTAssertNil(preview.failure)
|
||||
XCTAssertTrue(
|
||||
preview.row?.relationships.contains {
|
||||
$0.kind == .absorption && $0.extent == .full && $0.covering == [broad.identity]
|
||||
} == true)
|
||||
XCTAssertTrue(
|
||||
preview.row?.relationships.contains {
|
||||
$0.kind == .shadowing && $0.extent == .full && $0.covering == [proxy.identity]
|
||||
} == true)
|
||||
let saved = await workflow.saveCustomRule(draft)
|
||||
XCTAssertEqual(saved, .committed(.saved))
|
||||
await workflow.analysisTask?.value
|
||||
XCTAssertEqual(
|
||||
workflow.snapshot.rows.first { $0.customIDs.contains(draft.id) }?.relationships,
|
||||
preview.row?.relationships)
|
||||
var edited = try XCTUnwrap(workflow.makeCustomRuleDraft(editing: broad.id))
|
||||
edited.content = "coverage.example"
|
||||
let partial = await workflow.previewCustomRule(edited)
|
||||
XCTAssertTrue(
|
||||
partial.row?.relationships.contains { $0.kind == .shadowing && $0.extent == .partial } == true
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -284,7 +266,7 @@ extension CustomRuleEditingWorkflowTests {
|
||||
|
||||
func testSavedEditRejectsStaleDraftAndIncompleteCollection() async throws {
|
||||
let rule = CustomRule(
|
||||
action: .direct, match: try RuleMatch(domainSuffix: "old.example"))
|
||||
action: .proxy, match: try RuleMatch(domainSuffix: "old.example"))
|
||||
let original = CustomRuleDocument(rules: [rule])
|
||||
let outcome = CustomRuleUpdateOutcome.saved
|
||||
let workflow = RulesWorkflow(
|
||||
@@ -320,7 +302,7 @@ extension CustomRuleEditingWorkflowTests {
|
||||
action: .direct, match: try RuleMatch(domainExact: "disabled.example"))
|
||||
var commits = 0
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist,
|
||||
preset: .chinaDirect,
|
||||
loadDocument: {
|
||||
CustomRuleDocument(rules: [original], disabledIdentities: [original.identity])
|
||||
},
|
||||
@@ -345,7 +327,7 @@ extension CustomRuleEditingWorkflowTests {
|
||||
|
||||
extension CustomRuleEditingWorkflowTests {
|
||||
func testStaleDraftCannotOverwriteAnotherSavedChangeAndDiscardingDraftDoesNothing() async throws {
|
||||
let rule = CustomRule(action: .direct, match: try RuleMatch(domainExact: "kept.example"))
|
||||
let rule = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "kept.example"))
|
||||
var commits = 0
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist, loadDocument: { CustomRuleDocument(rules: [rule]) },
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import XCTest
|
||||
|
||||
@testable import ShadowsocksX_NG2
|
||||
@@ -139,3 +140,29 @@ final class CustomRuleMergeTests: XCTestCase {
|
||||
XCTAssertEqual(directDefault.accepted.count, 1)
|
||||
}
|
||||
}
|
||||
|
||||
struct RuleSchemeRuntimeTests {
|
||||
@Test func reverseIPExceptionCannotOverrideSchemeAction() throws {
|
||||
let proxy = ProxyRule(action: .proxy, match: try RuleMatch(ipv4CIDR: "203.0.113.0/24"))
|
||||
let reverse = CustomRule(action: .direct, match: try RuleMatch(ipv4CIDR: "203.0.113.8/32"))
|
||||
let document = CustomRuleDocument(rules: [reverse])
|
||||
let source = SslocalRuntimeDocument(servers: [], listen: ActivationFixture.listen)
|
||||
let compiled = RuleRuntimeCompiler.compile(
|
||||
.init(
|
||||
source: source, mode: .rule, defaultAction: .directWhenUnmatched,
|
||||
document: document, builtIn: [proxy], aclURL: URL(fileURLWithPath: "/tmp/scheme.acl")))
|
||||
let content = try #require(compiled.aclRuntime?.content)
|
||||
#expect(content.contains("203.0.113.0/24\n"))
|
||||
#expect(!content.contains("203.0.113.8/32\n"))
|
||||
#expect(content.contains("127.0.0.0/8\n"))
|
||||
let collection = RulesCollection.load(
|
||||
preset: .chinaProxy, custom: { [reverse] },
|
||||
builtin: {
|
||||
rulesFixture(
|
||||
$0, rules: $0 == .chinaIPv4 ? [ProxyRule(action: .direct, match: proxy.match)] : [])
|
||||
})
|
||||
let result = try OfflineRuleMatcher.test(collection: collection, address: "203.0.113.8")
|
||||
#expect(result.outcome == .proxy)
|
||||
#expect(result.deciding.map(\.identity) == [proxy])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -148,6 +148,39 @@ final class CustomRuleStoreTests: XCTestCase {
|
||||
}
|
||||
|
||||
struct CustomRuleStorageMigrationTests {
|
||||
@Test(arguments: RulePreset.allCases)
|
||||
func migrationRemovesDefaultActionRulesAndPreservesRemainingIntent(_ preset: RulePreset) throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let store = CustomRuleStore(
|
||||
preset: preset, baseURL: directory.appendingPathComponent("rules.json"))
|
||||
try FileManager.default.createDirectory(
|
||||
at: store.fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
let action: RuleAction = preset == .chinaDirect ? .direct : .proxy
|
||||
let first = CustomRule(action: action, match: try RuleMatch(domainExact: "first.example"))
|
||||
let removed = CustomRule(
|
||||
action: preset == .chinaDirect ? .proxy : .direct,
|
||||
match: try RuleMatch(ipv4CIDR: "203.0.113.8/32"))
|
||||
let last = CustomRule(action: action, match: try RuleMatch(domainSuffix: "last.example"))
|
||||
let disabled: Set<ProxyRule> = [first.identity, removed.identity]
|
||||
let document = CustomRuleDocument(rules: [first, removed, last], disabledIdentities: disabled)
|
||||
var json = try #require(
|
||||
JSONSerialization.jsonObject(with: CustomRuleStore.encode(document)) as? [String: Any])
|
||||
json["schemaVersion"] = 3
|
||||
let legacy = try JSONSerialization.data(withJSONObject: json)
|
||||
try legacy.write(to: store.fileURL)
|
||||
let loaded = try store.loadDocument()
|
||||
#expect(loaded.rules == [first, last])
|
||||
#expect(loaded.disabledIdentities == disabled)
|
||||
#expect(try store.loadDocument() == loaded)
|
||||
#expect(try Data(contentsOf: store.fileURL) == legacy)
|
||||
try store.saveDocument(loaded)
|
||||
#expect(try store.loadDocument() == loaded)
|
||||
let saved = try #require(
|
||||
JSONSerialization.jsonObject(with: Data(contentsOf: store.fileURL)) as? [String: Any])
|
||||
#expect(saved["schemaVersion"] as? Int == 4)
|
||||
}
|
||||
|
||||
@Test func legacySourceIsDiscardedOnNextSaveWithoutLosingSavedIntent() throws {
|
||||
let data = Data(
|
||||
"""
|
||||
@@ -164,7 +197,7 @@ struct CustomRuleStorageMigrationTests {
|
||||
#expect(document.disabledIdentities.count == 1)
|
||||
let encoded = try CustomRuleStore.encode(document)
|
||||
let json = try #require(JSONSerialization.jsonObject(with: encoded) as? [String: Any])
|
||||
#expect(json["schemaVersion"] as? Int == 3)
|
||||
#expect(json["schemaVersion"] as? Int == 4)
|
||||
let rule = try #require((json["rules"] as? [[String: Any]])?.first)
|
||||
#expect(rule["source"] == nil)
|
||||
#expect((rule["match"] as? [String: String])?["value"] == "203.0.113.0/24")
|
||||
@@ -173,6 +206,27 @@ struct CustomRuleStorageMigrationTests {
|
||||
}
|
||||
|
||||
extension CustomRuleStorageMigrationTests {
|
||||
@Test(arguments: [3, 4])
|
||||
func scopedLoadRejectsCorruptionWithoutRewriting(schema: Int) throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let store = CustomRuleStore(
|
||||
preset: .chinaProxy, baseURL: directory.appendingPathComponent("rules.json"))
|
||||
try FileManager.default.createDirectory(
|
||||
at: store.fileURL.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
let reverse = CustomRule(action: .direct, match: try RuleMatch(domainExact: "reverse.example"))
|
||||
// A duplicate must remain corrupt even when migration would remove both entries.
|
||||
let rules = schema == 3 ? [reverse, reverse] : [reverse]
|
||||
var json = try #require(
|
||||
JSONSerialization.jsonObject(with: CustomRuleStore.encode(CustomRuleDocument(rules: rules)))
|
||||
as? [String: Any])
|
||||
json["schemaVersion"] = schema
|
||||
let bytes = try JSONSerialization.data(withJSONObject: json)
|
||||
try bytes.write(to: store.fileURL)
|
||||
#expect(throws: CustomRuleStoreError.self) { try store.loadDocument() }
|
||||
#expect(try Data(contentsOf: store.fileURL) == bytes)
|
||||
}
|
||||
|
||||
@Test func loadDoesNotRewriteLegacyFileAndSaveRetainsOrphanDisablement() throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
|
||||
@@ -5,6 +5,35 @@ import Testing
|
||||
|
||||
@MainActor
|
||||
struct RuleDocumentSessionTests {
|
||||
@Test(arguments: RulePreset.allCases)
|
||||
func reverseActionCommitIsRejectedWithoutChangingSavedFacts(_ preset: RulePreset) throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let store = CustomRuleStore(
|
||||
preset: preset, baseURL: directory.appendingPathComponent("rules.json"))
|
||||
let session = RuleDocumentSession(store: store)
|
||||
let original = CustomRuleDocument(rules: [
|
||||
CustomRule(
|
||||
action: preset == .chinaDirect ? .direct : .proxy,
|
||||
match: try RuleMatch(domainExact: "kept.example"))
|
||||
])
|
||||
#expect(session.commit(original).outcome == .saved)
|
||||
let bytes = try Data(contentsOf: store.fileURL)
|
||||
let invalid = CustomRuleDocument(rules: [
|
||||
CustomRule(
|
||||
action: preset == .chinaDirect ? .proxy : .direct,
|
||||
match: try RuleMatch(domainExact: "reverse.example"))
|
||||
])
|
||||
let result = session.commit(invalid)
|
||||
#expect(
|
||||
result.outcome == .invalidDocument(detail: "Custom rule action must match its rule scheme"))
|
||||
#expect(result.document == original)
|
||||
#expect(session.revision == 1)
|
||||
#expect(try Data(contentsOf: store.fileURL) == bytes)
|
||||
#expect(throws: CustomRuleStoreError.self) { try store.saveDocument(invalid) }
|
||||
#expect(try Data(contentsOf: store.fileURL) == bytes)
|
||||
}
|
||||
|
||||
@Test func successfulCommitPublishesSavedFactsAndOnlyChangedContentAdvancesRevision() throws {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
|
||||
@@ -39,10 +39,10 @@ final class OfflineRuleMatcherTests: XCTestCase {
|
||||
preset: .gfwlist, custom: { entries }, builtin: { rulesFixture($0) })
|
||||
let result = try OfflineRuleMatcher.test(collection: collection, address: "a.example.com")
|
||||
XCTAssertEqual(result.outcome, .proxy)
|
||||
XCTAssertEqual(result.explanation, .domainProxy)
|
||||
XCTAssertEqual(result.explanation, .singleAction)
|
||||
XCTAssertEqual(
|
||||
Set(result.deciding.compactMap(\.identity)), [exact.identity, secondProxy.identity])
|
||||
XCTAssertEqual(result.otherMatches.map(\.identity), [suffix.identity])
|
||||
XCTAssertEqual(result.otherMatches.isEmpty, true)
|
||||
XCTAssertEqual(
|
||||
try OfflineRuleMatcher.test(collection: collection, address: "notexample.com").outcome,
|
||||
.direct)
|
||||
@@ -62,7 +62,7 @@ final class OfflineRuleMatcherTests: XCTestCase {
|
||||
.direct)
|
||||
}
|
||||
|
||||
func testIPOverlapAndMappedAddressesPreferDirectWithoutLosingOtherRanges() throws {
|
||||
func testIPOverlapAndMappedAddressesUseOnlySchemeAction() throws {
|
||||
for reverseActions in [false, true] {
|
||||
let broad = CustomRule(
|
||||
action: reverseActions ? .direct : .proxy,
|
||||
@@ -75,12 +75,12 @@ final class OfflineRuleMatcherTests: XCTestCase {
|
||||
custom: { [broad, narrow] }, builtin: { rulesFixture($0) })
|
||||
for address in ["203.0.113.8", "::ffff:203.0.113.8"] {
|
||||
let result = try OfflineRuleMatcher.test(collection: collection, address: address)
|
||||
XCTAssertEqual(result.outcome, .direct)
|
||||
XCTAssertEqual(result.explanation, .ipDirect)
|
||||
XCTAssertEqual(result.outcome, .proxy)
|
||||
XCTAssertEqual(result.explanation, .singleAction)
|
||||
XCTAssertEqual(
|
||||
result.deciding.map(\.identity), [reverseActions ? broad.identity : narrow.identity])
|
||||
result.deciding.map(\.identity), [reverseActions ? narrow.identity : broad.identity])
|
||||
XCTAssertEqual(
|
||||
result.otherMatches.map(\.identity), [reverseActions ? narrow.identity : broad.identity])
|
||||
result.otherMatches.map(\.identity), [])
|
||||
}
|
||||
XCTAssertEqual(
|
||||
try OfflineRuleMatcher.test(collection: collection, address: "203.0.113.9").outcome,
|
||||
|
||||
@@ -13,7 +13,7 @@ final class RuleEnablementWorkflowTests: XCTestCase {
|
||||
let gate = RulesAnalysisGate(started: started)
|
||||
var documents: [CustomRuleDocument] = []
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist, loadDocument: { CustomRuleDocument(rules: [broad, narrow]) },
|
||||
preset: .chinaDirect, loadDocument: { CustomRuleDocument(rules: [broad, narrow]) },
|
||||
commitDocument: {
|
||||
documents.append($0)
|
||||
return RuleDocumentCommit(outcome: .saved, document: $0)
|
||||
@@ -37,7 +37,7 @@ final class RuleEnablementWorkflowTests: XCTestCase {
|
||||
oldRelationships)
|
||||
workflow.setTestTarget("other.pending.example")
|
||||
await workflow.testAddress()
|
||||
XCTAssertEqual(workflow.snapshot.addressTest.result?.outcome, .direct)
|
||||
XCTAssertEqual(workflow.snapshot.addressTest.result?.outcome, .proxy)
|
||||
await workflow.setEnabled(true, identities: [broad.identity])
|
||||
await workflow.setEnabled(false, identities: [broad.identity])
|
||||
XCTAssertEqual(documents.count, 3)
|
||||
@@ -98,7 +98,7 @@ final class RuleEnablementWorkflowTests: XCTestCase {
|
||||
|
||||
func testSuccessfulCommitDoesNotReadSourcesOrUserDocumentAgain() async throws {
|
||||
let reads = RulesReadCounts()
|
||||
let rule = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "saved.example"))
|
||||
let rule = CustomRule(action: .direct, match: try RuleMatch(domainExact: "saved.example"))
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .chinaDirect,
|
||||
loadDocument: {
|
||||
@@ -169,7 +169,7 @@ final class RuleEnablementWorkflowTests: XCTestCase {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let store = CustomRuleStore(fileURL: directory.appendingPathComponent("rules.json"))
|
||||
let rule = CustomRule(action: .direct, match: try RuleMatch(domainExact: "kept.example"))
|
||||
let rule = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "kept.example"))
|
||||
try store.save([rule])
|
||||
var commits = 0
|
||||
let workflow = RulesWorkflow(
|
||||
|
||||
@@ -5,6 +5,60 @@ import Testing
|
||||
|
||||
@MainActor
|
||||
struct RulePresetWorkflowTests {
|
||||
@Test func gfwSchemeDropsDefaultActionBuiltinExceptions() async throws {
|
||||
let proxy = ProxyRule(action: .proxy, match: try RuleMatch(domainSuffix: "proxy.example"))
|
||||
let exception = ProxyRule(action: .direct, match: try RuleMatch(domainExact: "direct.example"))
|
||||
let snapshot = rulesFixture(.gfwlist, rules: [proxy, exception])
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist, loadCustom: { [] },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: { _ in snapshot }))
|
||||
await workflow.refresh()
|
||||
workflow.query(RulesQuery(source: .gfwlist))
|
||||
#expect(workflow.snapshot.rows.map(\.identity) == [proxy])
|
||||
workflow.setTestTarget("direct.example")
|
||||
await workflow.testAddress()
|
||||
#expect(workflow.snapshot.addressTest.result?.outcome == .direct)
|
||||
#expect(workflow.snapshot.addressTest.result?.explanation == .defaultAction)
|
||||
let source = SslocalRuntimeDocument(servers: [], listen: ActivationFixture.listen)
|
||||
let compiled = RuleRuntimeCompiler.compile(
|
||||
.init(
|
||||
source: source, mode: .rule, defaultAction: .directWhenUnmatched,
|
||||
document: nil, builtIn: RulePreset.gfwlist.rules(from: snapshot),
|
||||
aclURL: URL(fileURLWithPath: "/tmp/gfw-scheme.acl")))
|
||||
let content = try #require(compiled.aclRuntime?.content)
|
||||
#expect(content.contains("||proxy.example\n"))
|
||||
#expect(!content.contains("|direct.example\n"))
|
||||
}
|
||||
|
||||
@Test(arguments: RulePreset.allCases)
|
||||
func customRuleCreationAndEditingUseOwningSchemeAction(_ preset: RulePreset) async throws {
|
||||
var document = CustomRuleDocument(rules: [])
|
||||
let workflow = RulesWorkflow(
|
||||
preset: preset, loadDocument: { document },
|
||||
commitDocument: {
|
||||
document = $0
|
||||
return RuleDocumentCommit(outcome: .saved, document: $0)
|
||||
}, builtinSnapshots: BuiltinRuleSnapshots(loader: { rulesFixture($0) }))
|
||||
await workflow.refresh()
|
||||
var draft = try #require(workflow.makeCustomRuleDraft())
|
||||
let action: RuleAction = preset == .chinaDirect ? .direct : .proxy
|
||||
#expect(draft.action == action)
|
||||
draft.content = "created.example"
|
||||
let preview = await workflow.previewCustomRule(draft)
|
||||
#expect(preview.rule?.action == action)
|
||||
#expect(await workflow.saveCustomRule(draft) == .committed(.saved))
|
||||
var edited = try #require(workflow.makeCustomRuleDraft(editing: draft.id))
|
||||
#expect(edited.action == action)
|
||||
edited.content = "edited.example"
|
||||
#expect(await workflow.saveCustomRule(edited) == .committed(.saved))
|
||||
#expect(document.rules.first?.id == draft.id)
|
||||
#expect(document.rules.first?.action == action)
|
||||
workflow.setTestTarget("www.edited.example")
|
||||
await workflow.testAddress()
|
||||
#expect(
|
||||
workflow.snapshot.addressTest.result?.outcome == (preset == .chinaDirect ? .direct : .proxy))
|
||||
}
|
||||
|
||||
@Test(arguments: RulePreset.allCases)
|
||||
func chinaTargetsUsePresetActionAndUnmatchedUsesDefault(_ preset: RulePreset) async throws {
|
||||
let workflow = RulesWorkflow(
|
||||
@@ -61,10 +115,12 @@ extension RulePresetWorkflowTests {
|
||||
var draft = try #require(workflow.makeCustomRuleDraft())
|
||||
draft.kind = .domainSuffix
|
||||
draft.content = "shared.example"
|
||||
draft.action = .proxy
|
||||
let saved = await workflow.saveCustomRule(draft)
|
||||
#expect(saved == .committed(.saved))
|
||||
#expect(workflow.snapshot.rows.first?.identity == shared)
|
||||
#expect(
|
||||
workflow.snapshot.rows.first?.identity
|
||||
== ProxyRule(
|
||||
action: preset == .chinaDirect ? .direct : .proxy, match: shared.match))
|
||||
if preset == .gfwlist { await workflow.setEnabled(false, identities: [shared]) }
|
||||
workflow.query(query)
|
||||
workflow.setTestTarget("\(preset.rawValue).shared.example")
|
||||
@@ -77,13 +133,10 @@ extension RulePresetWorkflowTests {
|
||||
#expect(page.query == query)
|
||||
#expect(page.addressTest.target == target)
|
||||
#expect(page.addressTest.result?.target == target)
|
||||
#expect(page.addressTest.result?.outcome == (preset == .gfwlist ? .direct : .proxy))
|
||||
#expect(page.addressTest.result?.outcome == (preset == .chinaProxy ? .proxy : .direct))
|
||||
workspaces.current.query(RulesQuery(source: .custom))
|
||||
#expect(workspaces.current.snapshot.rows.first?.isEnabled == (preset != .gfwlist))
|
||||
let loaded = try CustomRuleStore(preset: preset, baseURL: baseURL).loadDocument()
|
||||
#expect(loaded.rules.count == 1)
|
||||
#expect(loaded.rules.first?.identity == shared)
|
||||
#expect(loaded.disabledIdentities == (preset == .gfwlist ? [shared] : []))
|
||||
try assertSavedSharedRule(preset: preset, baseURL: baseURL, shared: shared)
|
||||
}
|
||||
#expect(
|
||||
try legacy.loadDocument()
|
||||
@@ -109,7 +162,6 @@ extension RulePresetWorkflowTests {
|
||||
await original.refresh()
|
||||
var draft = try #require(original.makeCustomRuleDraft())
|
||||
draft.content = "delayed.example"
|
||||
draft.action = .direct
|
||||
let captured = draft
|
||||
let save = Task { await original.saveCustomRule(captured) }
|
||||
defer { release.release() }
|
||||
@@ -126,12 +178,22 @@ extension RulePresetWorkflowTests {
|
||||
#expect(other.snapshot == untouched)
|
||||
workspaces.selectedPreset = originalPreset
|
||||
#expect(workspaces.current.snapshot.rows.first?.content == "delayed.example")
|
||||
#expect(workspaces.current.snapshot.rows.first?.action == .direct)
|
||||
#expect(workspaces.current.snapshot.rows.first?.action == .proxy)
|
||||
#expect(workspaces.current.snapshot.commitOutcome == .saved)
|
||||
}
|
||||
}
|
||||
|
||||
extension RulePresetWorkflowTests {
|
||||
private func assertSavedSharedRule(preset: RulePreset, baseURL: URL, shared: ProxyRule) throws {
|
||||
let loaded = try CustomRuleStore(preset: preset, baseURL: baseURL).loadDocument()
|
||||
#expect(loaded.rules.count == 1)
|
||||
#expect(
|
||||
loaded.rules.first?.identity
|
||||
== ProxyRule(
|
||||
action: preset == .chinaDirect ? .direct : .proxy, match: shared.match))
|
||||
#expect(loaded.disabledIdentities == (preset == .gfwlist ? [shared] : []))
|
||||
}
|
||||
|
||||
private func makeWorkspaces(baseURL: URL) -> RulesWorkspaces {
|
||||
return RulesWorkspaces { preset in
|
||||
let session = RuleDocumentSession(store: CustomRuleStore(preset: preset, baseURL: baseURL))
|
||||
@@ -164,6 +226,6 @@ extension RulePresetWorkflowTests {
|
||||
#expect(workflow.snapshot.addressTest.result?.explanation == .defaultAction)
|
||||
workflow.setTestTarget("www.example.cn")
|
||||
workflow.query(RulesQuery(source: .custom))
|
||||
#expect(workflow.snapshot.rows.first?.action == .proxy)
|
||||
#expect(workflow.snapshot.rows.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,8 +25,8 @@ final class RulesPresentationTests: XCTestCase {
|
||||
}
|
||||
func testRelationshipExplanationRequiresExactlyOneRelatedSelection() async throws {
|
||||
let broad = CustomRule(action: .proxy, match: try RuleMatch(domainSuffix: "example.com"))
|
||||
let narrow = CustomRule(action: .direct, match: try RuleMatch(domainExact: "a.example.com"))
|
||||
let independent = CustomRule(action: .direct, match: try RuleMatch(domainExact: "other.net"))
|
||||
let narrow = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "a.example.com"))
|
||||
let independent = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "other.net"))
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist, loadCustom: { [broad, narrow, independent] },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: { rulesFixture($0) }))
|
||||
@@ -35,7 +35,7 @@ final class RulesPresentationTests: XCTestCase {
|
||||
workflow.select([.rule(narrow.identity)])
|
||||
let row = try XCTUnwrap(workflow.selectedRelationshipRow)
|
||||
XCTAssertEqual(row.identity, narrow.identity)
|
||||
XCTAssertEqual(row.relationships.first?.kind, .shadowing)
|
||||
XCTAssertEqual(row.relationships.first?.kind, .absorption)
|
||||
XCTAssertEqual(row.relationships.first?.covering, [broad.identity])
|
||||
workflow.select([.rule(narrow.identity), .rule(independent.identity)])
|
||||
XCTAssertNil(workflow.selectedRelationshipRow)
|
||||
@@ -48,7 +48,7 @@ final class RulesPresentationTests: XCTestCase {
|
||||
let narrow = CustomRule(action: .direct, match: try RuleMatch(domainExact: "a.example.net"))
|
||||
let local = CustomRule(action: .direct, match: try RuleMatch(domainExact: "device.local"))
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist, loadCustom: { [broad, narrow, local] },
|
||||
preset: .chinaDirect, loadCustom: { [broad, narrow, local] },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: { rulesFixture($0) }))
|
||||
await workflow.refresh()
|
||||
workflow.select([.rule(narrow.identity)])
|
||||
|
||||
@@ -5,62 +5,64 @@ import XCTest
|
||||
@MainActor
|
||||
final class RulesWorkflowCoverageTests: XCTestCase {
|
||||
func testCoverageUsesAllSourcesAndDistinguishesPartialFromFull() async throws {
|
||||
let broad = CustomRule(action: .direct, match: try RuleMatch(domainSuffix: "example.com"))
|
||||
let narrow = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "www.example.com"))
|
||||
let duplicate = CustomRule(
|
||||
action: .direct, match: try RuleMatch(domainExact: "www.example.com"))
|
||||
let broad = ProxyRule(action: .direct, match: try RuleMatch(domainSuffix: "example.com"))
|
||||
let narrow = CustomRule(action: .direct, match: try RuleMatch(domainExact: "www.example.com"))
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist, loadCustom: { [broad, narrow, duplicate] },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: { rulesFixture($0) }))
|
||||
preset: .chinaDirect, loadCustom: { [narrow] },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: {
|
||||
rulesFixture($0, rules: $0 == .geolocationCN ? [broad] : [])
|
||||
}))
|
||||
await workflow.refresh()
|
||||
workflow.query(RulesQuery(action: .direct, source: .custom))
|
||||
let broadRow = try XCTUnwrap(workflow.snapshot.rows.first { $0.identity == broad.identity })
|
||||
workflow.query(RulesQuery(source: .geolocationCN))
|
||||
let broadRow = try XCTUnwrap(workflow.snapshot.rows.first { $0.identity == broad })
|
||||
XCTAssertTrue(
|
||||
broadRow.relationships.contains {
|
||||
$0.kind == .shadowing && $0.extent == .partial && $0.covering == [narrow.identity]
|
||||
$0.kind == .absorption && $0.extent == .partial && $0.covering == [narrow.identity]
|
||||
})
|
||||
let narrowRow = try XCTUnwrap(
|
||||
workflow.snapshot.rows.first { $0.identity == duplicate.identity })
|
||||
XCTAssertTrue(narrowRow.relationships.contains { $0.kind == .shadowing && $0.extent == .full })
|
||||
XCTAssertTrue(narrowRow.relationships.contains { $0.kind == .absorption && $0.extent == .full })
|
||||
XCTAssertTrue(workflow.snapshot.rows.filter(\.isFixed).allSatisfy { $0.relationships.isEmpty })
|
||||
workflow.query(RulesQuery(source: .custom))
|
||||
let narrowRow = try XCTUnwrap(workflow.snapshot.rows.first)
|
||||
XCTAssertTrue(
|
||||
narrowRow.relationships.contains {
|
||||
$0.kind == .absorption && $0.extent == .full && $0.covering == [broad]
|
||||
})
|
||||
XCTAssertTrue(narrowRow.relationships.allSatisfy { $0.kind != .shadowing })
|
||||
}
|
||||
|
||||
func testMappedIPAndCombinedNarrowRangesExplainCoverageThroughWorkflow() async throws {
|
||||
let proxy = CustomRule(action: .proxy, match: try RuleMatch(ipv6CIDR: "::ffff:8.8.8.0/120"))
|
||||
let broad = CustomRule(action: .direct, match: try RuleMatch(ipv6CIDR: "::ffff:8.8.8.0/120"))
|
||||
let lower = CustomRule(action: .direct, match: try RuleMatch(ipv4CIDR: "8.8.8.0/25"))
|
||||
let upper = CustomRule(action: .direct, match: try RuleMatch(ipv4CIDR: "8.8.8.128/25"))
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist, loadCustom: { [proxy, lower, upper] },
|
||||
preset: .chinaDirect, loadCustom: { [broad, lower, upper] },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: { rulesFixture($0) }))
|
||||
await workflow.refresh()
|
||||
workflow.query(RulesQuery(action: .proxy, source: .custom))
|
||||
workflow.query(RulesQuery(action: .direct, source: .custom))
|
||||
let row = try XCTUnwrap(workflow.snapshot.rows.first)
|
||||
XCTAssertEqual(row.identity, proxy.identity)
|
||||
XCTAssertEqual(row.identity, broad.identity)
|
||||
XCTAssertEqual(row.relationships.count, 1)
|
||||
XCTAssertEqual(row.relationships.first?.kind, .shadowing)
|
||||
XCTAssertEqual(row.relationships.first?.kind, .absorption)
|
||||
XCTAssertEqual(row.relationships.first?.extent, .full)
|
||||
XCTAssertEqual(Set(row.relationships.first?.covering ?? []), [lower.identity, upper.identity])
|
||||
}
|
||||
|
||||
func testFixedProtectionExplainsSimpleHostsAndPreventsFalseLocalShadowing() async throws {
|
||||
let simple = ProxyRule(
|
||||
action: .proxy, match: try RuleMatch(domainExact: "printer"))
|
||||
let simpleSuffix = ProxyRule(action: .proxy, match: try RuleMatch(nationalDomainSuffix: "cn"))
|
||||
action: .direct, match: try RuleMatch(domainExact: "printer"))
|
||||
let simpleSuffix = ProxyRule(action: .direct, match: try RuleMatch(nationalDomainSuffix: "cn"))
|
||||
let localProxy = ProxyRule(
|
||||
action: .proxy, match: try RuleMatch(domainExact: "device.local"))
|
||||
action: .direct, match: try RuleMatch(domainExact: "device.local"))
|
||||
let localDirect = CustomRule(action: .direct, match: try RuleMatch(domainExact: "device.local"))
|
||||
let nationalDirect = CustomRule(
|
||||
action: .direct, match: try RuleMatch(nationalDomainSuffix: "cn"))
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist,
|
||||
preset: .chinaDirect,
|
||||
loadCustom: { [localDirect, nationalDirect] },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: { requested in
|
||||
rulesFixture(
|
||||
requested, rules: requested == .gfwlist ? [simple, simpleSuffix, localProxy] : [])
|
||||
requested, rules: requested == .geolocationCN ? [simple, simpleSuffix, localProxy] : [])
|
||||
}))
|
||||
await workflow.refresh()
|
||||
workflow.query(RulesQuery(source: .gfwlist))
|
||||
workflow.query(RulesQuery(source: .geolocationCN))
|
||||
let simpleRow = try XCTUnwrap(workflow.snapshot.rows.first { $0.identity == simple })
|
||||
XCTAssertEqual(simpleRow.fixedCoverage?.extent, .full)
|
||||
let suffixRow = try XCTUnwrap(
|
||||
@@ -74,15 +76,14 @@ final class RulesWorkflowCoverageTests: XCTestCase {
|
||||
let nationalRow = try XCTUnwrap(
|
||||
workflow.snapshot.rows.first { $0.identity == nationalDirect.identity })
|
||||
XCTAssertEqual(nationalRow.fixedCoverage?.extent, .partial)
|
||||
XCTAssertTrue(
|
||||
nationalRow.relationships.contains { $0.kind == .shadowing && $0.extent == .partial })
|
||||
XCTAssertFalse(nationalRow.relationships.contains { $0.kind == .shadowing })
|
||||
}
|
||||
|
||||
func testFullyFixedProtectedProxyDoesNotShadowAnUnprotectedDirectSuffix() async throws {
|
||||
func testFixedLocalCoverageDoesNotShadowPublicPartOfDirectSuffix() async throws {
|
||||
let direct = CustomRule(action: .direct, match: try RuleMatch(nationalDomainSuffix: "cn"))
|
||||
let proxy = ProxyRule(action: .proxy, match: try RuleMatch(domainExact: "cn"))
|
||||
let workflow = RulesWorkflow(
|
||||
preset: .gfwlist,
|
||||
preset: .chinaDirect,
|
||||
loadCustom: { [direct] },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: { requested in
|
||||
rulesFixture(requested, rules: requested == .gfwlist ? [proxy] : [])
|
||||
|
||||
@@ -10,7 +10,7 @@ final class RulesWorkflowTests: XCTestCase {
|
||||
let store = CustomRuleStore(fileURL: directory.appendingPathComponent("rules.json"))
|
||||
let broad = CustomRule(
|
||||
action: .proxy, match: try RuleMatch(domainSuffix: "example.com"))
|
||||
let narrow = CustomRule(action: .direct, match: try RuleMatch(domainExact: "safe.example.com"))
|
||||
let narrow = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "safe.example.com"))
|
||||
let orphan = ProxyRule(action: .proxy, match: try RuleMatch(domainExact: "gone.example"))
|
||||
try store.saveDocument(
|
||||
CustomRuleDocument(rules: [broad, narrow], disabledIdentities: [orphan]))
|
||||
@@ -40,7 +40,7 @@ final class RulesWorkflowTests: XCTestCase {
|
||||
await workflow.refresh()
|
||||
let version = workflow.snapshot.version
|
||||
let covered = try XCTUnwrap(workflow.snapshot.rows.first { $0.identity == narrow.identity })
|
||||
XCTAssertTrue(covered.relationships.contains { $0.kind == .shadowing && $0.extent == .full })
|
||||
XCTAssertTrue(covered.relationships.contains { $0.kind == .absorption && $0.extent == .full })
|
||||
workflow.select([.rule(broad.identity), .noDotHostname])
|
||||
XCTAssertEqual(workflow.actionableSelection, [broad.identity])
|
||||
await workflow.setEnabled(false, identities: workflow.actionableSelection)
|
||||
@@ -62,7 +62,7 @@ final class RulesWorkflowTests: XCTestCase {
|
||||
workflow.snapshot.rows.first { $0.identity == narrow.identity }!.relationships.isEmpty)
|
||||
workflow.setTestTarget("safe.example.com")
|
||||
await workflow.testAddress()
|
||||
XCTAssertEqual(workflow.snapshot.addressTest.result?.outcome, .direct)
|
||||
XCTAssertEqual(workflow.snapshot.addressTest.result?.outcome, .proxy)
|
||||
workflow.query(RulesQuery(enabled: false))
|
||||
XCTAssertTrue(workflow.snapshot.rows.contains { $0.identity == orphan && !$0.hasCurrentSource })
|
||||
await workflow.setEnabled(true, identities: [orphan])
|
||||
@@ -109,12 +109,12 @@ final class RulesWorkflowTests: XCTestCase {
|
||||
|
||||
func testSearchActionAndSourceIntersectAndHiddenSelectionIsCleared() async throws {
|
||||
let direct = CustomRule(action: .direct, match: try RuleMatch(domainSuffix: "example.com"))
|
||||
let proxy = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "outside.net"))
|
||||
let other = CustomRule(action: .direct, match: try RuleMatch(domainExact: "outside.net"))
|
||||
let workflow = RulesWorkflow(
|
||||
loadCustom: { [direct, proxy] },
|
||||
preset: .chinaDirect, loadCustom: { [direct, other] },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: { rulesFixture($0) }))
|
||||
await workflow.refresh()
|
||||
workflow.select([.rule(direct.identity), .rule(proxy.identity), .noDotHostname])
|
||||
workflow.select([.rule(direct.identity), .rule(other.identity), .noDotHostname])
|
||||
workflow.query(RulesQuery(search: "EXAMPLE", action: .direct, source: .custom))
|
||||
XCTAssertEqual(workflow.snapshot.rows.map(\.identity), [direct.identity])
|
||||
XCTAssertEqual(workflow.snapshot.selection, [.rule(direct.identity)])
|
||||
@@ -127,7 +127,7 @@ final class RulesWorkflowTests: XCTestCase {
|
||||
func testStableInputOrderAndNavigationPreserveVersionAndSessionQuery() async throws {
|
||||
let entries = [
|
||||
CustomRule(action: .proxy, match: try RuleMatch(domainExact: "z.net")),
|
||||
CustomRule(action: .direct, match: try RuleMatch(domainExact: "a.net")),
|
||||
CustomRule(action: .proxy, match: try RuleMatch(domainExact: "a.net")),
|
||||
]
|
||||
let workflow = RulesWorkflow(
|
||||
loadCustom: { entries }, builtinSnapshots: BuiltinRuleSnapshots(loader: { rulesFixture($0) }))
|
||||
@@ -194,7 +194,7 @@ final class RulesWorkflowTests: XCTestCase {
|
||||
let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
let store = CustomRuleStore(fileURL: directory.appendingPathComponent("rules.json"))
|
||||
let old = CustomRule(action: .direct, match: try RuleMatch(domainExact: "old.net"))
|
||||
let old = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "old.net"))
|
||||
let new = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "new.net"))
|
||||
try store.save([old])
|
||||
let workflow = RulesWorkflow(
|
||||
@@ -250,7 +250,7 @@ final class RulesWorkflowTests: XCTestCase {
|
||||
|
||||
extension RulesWorkflowTests {
|
||||
func testCandidatePermutationKeepsVersionAndCoverageWhilePreservingInputOrder() async throws {
|
||||
let broad = CustomRule(action: .direct, match: try RuleMatch(domainSuffix: "example.com"))
|
||||
let broad = CustomRule(action: .proxy, match: try RuleMatch(domainSuffix: "example.com"))
|
||||
let narrow = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "www.example.com"))
|
||||
let forward = RulesWorkflow(
|
||||
loadCustom: { [broad, narrow] },
|
||||
@@ -271,8 +271,8 @@ extension RulesWorkflowTests {
|
||||
}
|
||||
|
||||
func testSameNamedExactAndSuffixHaveStableVersionsAcrossRefreshes() async throws {
|
||||
let exact = CustomRule(action: .direct, match: try RuleMatch(domainExact: "example.com"))
|
||||
let suffix = CustomRule(action: .direct, match: try RuleMatch(domainSuffix: "example.com"))
|
||||
let exact = CustomRule(action: .proxy, match: try RuleMatch(domainExact: "example.com"))
|
||||
let suffix = CustomRule(action: .proxy, match: try RuleMatch(domainSuffix: "example.com"))
|
||||
let workflow = RulesWorkflow(
|
||||
loadCustom: { [suffix, exact] },
|
||||
builtinSnapshots: BuiltinRuleSnapshots(loader: { rulesFixture($0) }))
|
||||
@@ -289,7 +289,7 @@ extension RulesWorkflowTests {
|
||||
}
|
||||
|
||||
extension RulesWorkflowTests {
|
||||
func testCollectionPreservesInputOrderForEqualContentWithDistinctActionsAndMatches() throws {
|
||||
func testCollectionRemovesReverseActionsAndPreservesRemainingInputOrder() throws {
|
||||
let exact = try RuleMatch(domainExact: "same.example")
|
||||
let suffix = try RuleMatch(domainSuffix: "same.example")
|
||||
let rules = [
|
||||
@@ -304,7 +304,7 @@ extension RulesWorkflowTests {
|
||||
XCTAssertTrue(collection.issues.isEmpty)
|
||||
XCTAssertEqual(
|
||||
collection.rows.filter { $0.content == "same.example" }.compactMap(\.identity),
|
||||
input.map(\.identity))
|
||||
input.filter { $0.action == .proxy }.map(\.identity))
|
||||
XCTAssertTrue(collection.rows.contains { $0.id == .noDotHostname && $0.isFixed })
|
||||
}
|
||||
}
|
||||
@@ -342,7 +342,7 @@ private final class RulesReadBarrier: @unchecked Sendable {
|
||||
guard release.wait(timeout: .now() + 5) == .success else { throw RuleSnapshotError.missing }
|
||||
}
|
||||
return [
|
||||
CustomRule(action: .direct, match: try RuleMatch(domainExact: first ? "old.net" : "new.net"))
|
||||
CustomRule(action: .proxy, match: try RuleMatch(domainExact: first ? "old.net" : "new.net"))
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
|
||||
**状态**:已接受,已实现(2026-10-24;默认项与展示顺序于 2026-10-25 调整)。
|
||||
|
||||
[ADR-0055](0055-preset-owned-custom-rule-actions.md) 已接受、已实现:将产品术语统一为“规则方案”,取代下文“自定义规则保留自身行动”的约定,并规定现有方案自定义规则的迁移方式。
|
||||
|
||||
## 决定
|
||||
|
||||
规则、全局、直连仍是代理模式。规则模式内使用三种规则预设,展示顺序为“仅GFW列表内目标代理”“中国大陆目标直连”“中国大陆目标代理”。预设一起确定内置来源、命中行动和默认动作,替代原来的默认动作选择入口,不另设独立默认动作开关。新预设复用中国域名、`.cn` 和中国 IPv4 数据,将其用于代理,其余目标默认直连;固定本地目标仍直连,不维护视频专用集合,也不承诺平台内容可播放。
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# 规则方案统一决定自定义规则行动
|
||||
|
||||
**状态**:已接受,已实现(2026-10-30)。
|
||||
|
||||
## 决定与原因
|
||||
|
||||
产品术语统一为“规则方案”,替代“规则预设”。每项方案固定定义匹配后行动与未匹配行动;内置规则和自定义规则的匹配后行动由所属方案统一决定。固定本地目标仍始终直连,不受方案行动影响。
|
||||
|
||||
| 规则方案 | 匹配后行动 | 未匹配行动 |
|
||||
| --- | --- | --- |
|
||||
| 仅GFW列表内目标代理 | 代理 | 直连 |
|
||||
| 中国大陆目标直连 | 直连 | 代理 |
|
||||
| 中国大陆目标代理 | 代理 | 直连 |
|
||||
|
||||
新增和编辑自定义规则只允许编辑匹配类型与匹配内容,行动以只读说明呈现。预览、保存、加载、离线测试和运行配置生成均遵守所属方案的行动约束,不能仅通过隐藏表单控件实现。各方案仍独立拥有自定义规则集合,查看或编辑方案不切换实际路由。
|
||||
|
||||
这一约束有意收紧上游 ACL 能力,降低用户理解成本。项目固定使用的 [sslocal v1.26.0](https://github.com/qiuyuzhou/shadowsocks-rust/blob/v1.26.0/crates/shadowsocks-service/src/acl/mod.rs) 对 IP 字面地址先检查直连列表,再检查代理列表,最后采用模式默认行动;未命中域名规则而检查 DNS 解析结果时,则按模式选择一个方向的 IP 列表。允许每条自定义规则独立选择行动,会把这些差异带入用户模型。产品选择统一的方案语义,不要求用户理解这些差异。
|
||||
|
||||
## 迁移与兼容边界
|
||||
|
||||
迁移现有各方案的自定义规则集合:移除行动与该方案未匹配行动相同的自定义规则,保留行动与匹配后行动一致的条目及其 UUID、匹配条件和相对顺序。被移除条目不翻转行动,也不迁往其他方案。schema 1–3 文档在读取时迁移,不重写原文件,下次正常原子保存写入 schema 4;schema 4 文档中的反向行动视为无效并拒载。旧客户端拒绝 schema 4,避免降级后重新写入反向行动。
|
||||
|
||||
该迁移不承诺保持所有旧流量行为。例如“中国大陆目标代理”方案中,自定义直连 IP 规则可以优先于覆盖该 IP 的内置代理规则;移除后,直接访问该 IP 可能从直连变为代理。接受旧反向例外失效,以换取规则方案对 IP 与域名一致的用户语义。发布说明应说明移除规则及可能的路由变化。
|
||||
|
||||
规则身份仍按匹配条件与行动共同确定。规则停用仍作用于方案内跨来源的规则身份;沿用现有孤立停用记录保留原则,删除自定义条目不隐式清除其停用记录,也不改变其他身份的启用状态。固定本地保护及损坏文件不覆盖原则保持有效。
|
||||
|
||||
本决定取代 [ADR-0051](0051-explicit-rule-preset-modeling.md) 中“自定义规则保留自身行动”的约定,以及旧自定义文档直接保留反向行动的加载行为;其他方案归属、规则身份和停用语义保持有效。
|
||||
@@ -10,7 +10,7 @@ Bundled snapshots used by rule mode are explicitly maintained artifacts:
|
||||
|
||||
Snapshots use compact JSON with schema 2 / converter 2.0.0: each rule has only `action` and `match`; the source appears only in `metadata.source`; the conversion report retains counts only. Absorbed `.cn` entries and shadowed GFWList exceptions are not distributed in the snapshot and are not restored after a broad rule is disabled. See [ADR-0024](adr/0024-snapshot-drops-absorbed-and-forensics.md). Older snapshot versions are rejected.
|
||||
|
||||
Domain values and file DTOs for rules evolve independently. `ProxyRule` represents both a normalized rule value and rule identity across sources; custom entries also retain a UUID. Custom-rule files are written as schema 3 and no longer store `source` per rule. Schemas 1 and 2 remain readable; reading does not rewrite the file, and the next normal save updates its format. The bundled snapshot format is unchanged. See [ADR-0039](adr/0039-rule-values-and-independent-storage-models.md).
|
||||
Domain values and file DTOs for rules evolve independently. `ProxyRule` represents both a normalized rule value and rule identity across sources; custom entries also retain a UUID. Custom-rule files use schema 4 and do not store `source` per rule. Each rule scheme fixes the matched and unmatched actions; custom-rule creation and editing show the matched action as read-only. Schema 1–3 documents remain readable: loading a scheme removes custom rules whose action equals its unmatched action, retaining the remaining UUIDs, order, and all disablement records. Reading leaves the original file intact; the next normal save writes schema 4. Schema 4 documents with reverse-action custom rules are rejected. Older clients cannot read schema 4. **Migration can change routing:** an old custom direct IP exception in the China-proxy scheme may previously have overridden a built-in proxy range; after removal, that IP follows the scheme's proxy rule. Fixed local targets still bypass the proxy. The bundled snapshot format is unchanged. See [ADR-0039](adr/0039-rule-values-and-independent-storage-models.md) and [ADR-0055](adr/0055-preset-owned-custom-rule-actions.md).
|
||||
|
||||
Python is the only upstream conversion implementation. Swift loads, validates, and consumes snapshots; it does not parse upstream input independently. Run the offline regression checks for conversion scripts with `PYTHONDONTWRITEBYTECODE=1 python3 Scripts/test-rule-snapshot-converters.py`. The default `task test` also runs both Python checks; run `task test:rules` for just these checks. Also run `PYTHONDONTWRITEBYTECODE=1 python3 Scripts/test-rule-conversion-behavior.py` to verify conversion behavior and the fixed snapshot fixtures used by the unit-test bundle. After reviewing a conversion change, add `--write-fixtures` to the same command to rebuild the fixtures. Fixture timestamps are fixed, and normal tests compare generated output byte for byte. Check snapshot integrity with `Scripts/verify-rule-snapshots.sh`.
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
|
||||
快照使用 schema 2 / converter 2.0.0 的紧凑 JSON:每条规则只有 `action` 和 `match`,来源只在 `metadata.source`,转换报告只保留计数。被吸收的 `.cn` 条目与被遮蔽的 GFWList 例外不随快照分发,禁用宽规则后不再恢复;详见 [ADR-0024](adr/0024-snapshot-drops-absorbed-and-forensics.md)。旧版本快照拒载。
|
||||
|
||||
规则领域值与文件 DTO 独立演化。`ProxyRule` 同时表达规范化规则值与跨来源规则身份,自定义条目另外保留 UUID。自定义规则文件写入 schema 3,不再逐条保存 `source`;兼容读取 schema 1/2,读取不重写,下一次正常保存才更新格式。内置快照格式不变。见 [ADR-0039](adr/0039-rule-values-and-independent-storage-models.md)。
|
||||
规则领域值与文件 DTO 独立演化。`ProxyRule` 同时表达规范化规则值与跨来源规则身份,自定义条目另外保留 UUID。自定义规则文件写入 schema 4,不逐条保存 `source`。每项规则方案固定匹配后行动与未匹配行动,新增和编辑自定义规则时只读展示所属方案的匹配后行动。兼容读取 schema 1–3:加载方案时移除行动等于未匹配行动的自定义规则,保留剩余条目的 UUID、顺序和全部停用记录;读取不重写原文件,下一次正常保存才写入 schema 4。schema 4 文档包含反向行动时拒载,旧客户端不能读取 schema 4。**迁移可能改变路由**:“中国大陆目标代理”方案中,旧自定义直连 IP 例外可能曾覆盖内置代理网段,移除后该 IP 按方案规则代理。固定本地目标仍始终直连。内置快照格式不变。见 [ADR-0039](adr/0039-rule-values-and-independent-storage-models.md) 和 [ADR-0055](adr/0055-preset-owned-custom-rule-actions.md)。
|
||||
|
||||
Python 是唯一的上游转换实现;Swift 只加载、校验并消费快照,不另行解析上游输入。转换脚本的离线回归检查:`PYTHONDONTWRITEBYTECODE=1 python3 Scripts/test-rule-snapshot-converters.py`。默认 `task test` 也会运行两组 Python 检查;可单独运行 `task test:rules`。另运行 `PYTHONDONTWRITEBYTECODE=1 python3 Scripts/test-rule-conversion-behavior.py`,验证转换行为和单测 bundle 使用的固定快照夹具。审查转换变化后,可通过同一命令加 `--write-fixtures` 重建夹具。夹具时间固定,正常测试逐字节检查生成结果。快照完整性检查:`Scripts/verify-rule-snapshots.sh`。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user