Repository navigation
LxBox v1.4.1
L×Box v1.4.1
Iterative release on top of 1.4.0. Two major internal changes + reworked templated routing rules.
✨ Highlights
- Preset bundles (spec 033) —
CustomRule(kind: preset)is now a thin reference to a template preset; content is expanded fromwizard_template.jsonon every build. Template updates automatically propagate to every user without data migrations. Example:Russian domains directis parametric — pick Outbound + DNS Transport (DoH/DoT/UDP) + UDP server IP (Safe/Base/Family). CustomRulesealed split (spec 030 §v1.4.1, task 011) — the single class is split intoCustomRuleInline/CustomRuleSrs/CustomRulePreset. Exhaustive pattern-match in builder/UI, compile-time checks instead of runtime ifs. Legacy JSON reads without migrations.- SRS cache for preset bundles — bundles with a remote
rule_set(Block Ads, Russia-only services) now go through the localRuleSetDownloadercache instead of sing-box auto-download. Spec 011 invariant restored. (UI ☁ buttons are in 1.4.2.) - Rename
target → outbound,out → outbound— everywhere, matching the sing-box JSON schema and the UI label. - Universal outbound override for presets —
OutboundPickerв tile работает для любого bundle'а, даже если его template использует shorthandrule.action: "reject"(Block Ads) или hardcodedrule.outbound: "<tag>"(Russia-only services). Override пишется вvarsValues['outbound']и применяется вpreset_expandнезависимо от формы template'а. Shorthandaction: "reject"теперь означает "default", не "lock": юзер может сменить Block Ads с reject на vpn-1 и обратно. См. spec 033 §Expansion §5. - Initial insertion sort для Custom Rules — при добавлении reject-правила оно ложится в самый верх списка, direct — сразу за начальным блоком reject'ов. Proxy-правила (vpn-1, auto, прочие) — в хвост. First-match-wins sing-box-семантика соблюдается из коробки. Drag-handle остаётся свободным: юзер может переставить как хочет, автосортировка — только на вставке. См. spec 030 §Initial insertion sort.
- Debug API refresh —
/state/rulesserializer переписан на sealed-dispatch: inline/srs/preset правила отдают только релевантные поля. Preset-правила теперь экспозятpreset_id,vars_values, nestedpreset.remote_rule_sets[]с per-rule_set SRS-cache статусом (cached,path,mtime), флагready. Debug API честно отражает sealed-иерархию task 011. - SRS cache prune —
RuleSetDownloader.pruneOrphans()при каждом_refreshSrsCacheсметает.srs-файлы без живого референса. Orphan'ы после миграций схемы (pre-bundle → bundle) больше не копятся. .онлайн(xn--80asehdb) в Russian domains direct — добавлен в inline rule_setru-domainsи в DNS-правило черезyandex_doh.
🛡 Reliability & Safety
- Retry + exponential backoff для subscription fetch и rule_set download — 3 попытки (1s → 3s).
4xx— permanent (без ретраев),5xx/ timeout /SocketException— retry. Снимает львиную долю жалоб "подписка не обновляется" у юзеров с нестабильной сетью. - Top-level error boundary (
FlutterError.onError) — uncaught Flutter-ошибки попадают вAppLogи видны на Debug → Logs. Красный экран заменён на компактныйErrorBoundaryfallback-widget. - Auto-updater coverage — §027 spam-gate покрыт тестами (
consecutiveFails,minRetryInterval,maxFailsPerSession,inProgresscrash-safe reset на старте). Никаких скрытых background-refresh не добавлено.
🔐 Security
- URL masking audit — subscription URL больше не течёт в
AppLogцеликом. Везде используетсяmaskSubscriptionUrl(scheme://host/***). Полный URL доступен только в Debug API сreveal=trueпараметром. Закрыты 4 leak-сайта (hydrate-fail, inProgress-skip, shortUrl truncation,addFromInput).
🎨 UX
- Human-readable errors (
humanizeError) — все user-visible сообщения приведены к человеческому виду. Было:Exception: HTTP 503 for https://…. Стало:Server error (503) — provider is down, try later. Timeout сообщает длительность. Покрыто топ-5 сценариев: subscription fetch, rule-set download, parse, config build, VPN start. - Parse hints — когда подписка загружена, но распарсилась в 0 нод, показываем причину: HTML-страница провайдера, Clash YAML, full sing-box config, plain-text error. Юзер понимает "что именно не так", а не "unknown parse error".
- Pull-to-refresh на Subscriptions screen — стандартный Android-gesture запускает
updateAll. - Getting Started card — при пустом списке подписок показывается пояснительная карточка: как добавить URL / paste clipboard / file pick.
- Unsaved-input guard — на Add Subscription, введённый в поле текст без сохранения → back → диалог "Discard input?".
- Relative time —
2h ago / yesterday / 3d ago / 2w ago / 2mo ago / 2y agoвместо абсолютных timestamp'ов в узких местах. - Debug log search —
/logsподдерживаетq=substring search иlevel=multi-filter (level=error,warn). - Reset fail-count & retry (long-press на подписке) — ручной reset
consecutiveFailscounter'а, размораживает подписку из session-cap и сразу пытается обновить. - Share URL (masked / full) — long-press → "Share URL…" → диалог с выбором: замаскированный или полный URL (для приватной передачи).
🧪 Testing
- +97 tests (262 → 359). Новые модули покрыты полностью:
error_humanize,url_mask,parse_hints,relative_time,input_helpers,http_cache,rule_set_downloader,auto_updater,body_decoder, validator edge cases, preset-expand.
🧹 Cleanup
flutter analyze: 20 info/warning → 0.@overrideаннотации на subclass fields, удалены избыточные!.- Dispose / dead-code audit — чисто, без правок.
🔖 Preset bundles (spec 033)
Before 1.4.1, a preset was copied into CustomRule at "Add to Rules" time; template updates never reached existing rules.
Now CustomRule(kind: preset) stores only {presetId, varsValues}:
{
"id": "...", "name": "Russian domains direct",
"kind": "preset", "presetId": "ru-direct",
"varsValues": {"outbound": "direct-out", "dns_server": "yandex_doh", "dns_ip": "77.88.8.88"}
}On every build buildConfig expands via expandPreset(rule, preset):
- substitute
@var→ user values or template defaults. - rule_set / dns_rule / routing_rule / dns_servers get injected into the sing-box config.
Preset-local var types: outbound (outbound-group picker), dns_servers (picker of preset.dns_servers[].tag). WizardOption {title, value} syntax — dropdowns show human-readable titles (e.g. "77.88.8.88 · Safe").
Russian domains direct exposes 3 vars:
- Outbound (default
direct-out). - Transport (DoH/DoT/UDP, default
yandex_doh). - UDP server IP — 10 Safe/Base/Family × IPv4/IPv6 primary/alt options, used only when Transport = UDP. DoH/DoT are hardcoded to
77.88.8.88+ SNIsafe.dot.dns.yandex.net.
Existing user rules (created via + Add rule with match fields) stay as CustomRuleInline / CustomRuleSrs — spec 033 does not touch them.
🧬 Sealed CustomRule (task 011)
Previously a single class with enum discriminator, unused fields per kind, runtime ifs.
Now:
sealed class CustomRule { id, name, enabled, kind, toJson, fromJson-dispatch }
├── CustomRuleInline { domains/suffixes/keywords/cidrs/ports/packages/protocols/ipIsPrivate + outbound }
├── CustomRuleSrs { srsUrl + routing-level extra filters + outbound }
└── CustomRulePreset { presetId, varsValues } // outbound lives in varsValues['outbound']
switch (cr)in builder / UI is exhaustive-checked by the compiler.- Type-preserving
withEnabled/withName/withOutboundmutators on the base class — UI can writerule.withEnabled(v)without manual pattern-matching. - Convenience read-only getters (
domains/srsUrl/presetId/ …) for code that doesn't care about the concrete subclass. CustomRule.fromJsondispatches onkind; legacytargetfield is accepted as fallback foroutbound.
🗄️ SRS cache for preset
Spec 011 requires "sing-box never downloads — always type: local, path: <cache>". In 1.4.0-beta preset bundles with type: remote broke this — sing-box fetched rule_set files on its own at startup.
1.4.1 restores the invariant:
RuleSetDownloadergets apreset__<presetId>__<tag>namespace for preset-owned cache.expandPresetcheckssrsPaths[tag]for remote rule_sets — hit → replace with{type: "local", path: "..."}; miss → skip rule_set + warning.buildConfigpre-resolves cache paths beforeapplyPresetBundles.
UI side is in 1.4.1: preset-rules with remote rule_set'ы show the same ☁ button as srs rules in the Rules list. Tap downloads every remote rule_set of the preset into the cache. Long-press → Refresh / Clear menu. The Switch auto-downloads on toggle-on if the cache is missing and enables the rule on success. "Cached" means every remote rule_set of the preset has a local .srs file.
🛠️ Fixes (task 011 polish)
Failed to start service: rule-set not found—expandPresetnow drops arouting_rulewhoserule_setreferences a tag that was skipped (missing cache), instead of leaving a dangling reference that crashed sing-box at startup.- Preset
☁icon now reacts to tap — the oldGestureDetectorwithHitTestBehavior.opaquewas swallowing taps beforeIconButton.onPressed. Replaced withInkWell(onTap+onLongPress). - Adding a preset with remote rule_set'ами via "Add to Rules" creates it disabled (same policy as
CustomRuleSrs). Users tap ☁ to download, then flip the switch — or toggle-on triggers auto-download + enable. - On load, any rule whose SRS cache is missing is auto-disabled (
_refreshSrsCachenow runs after_templateis assigned, so preset lookup actually resolves).
🏷 Rename target → outbound, out → outbound
CustomRule.target is renamed to CustomRule.outbound; the sentinel kRejectTarget to kOutboundReject. In template presets the var out / @out is renamed to outbound / @outbound. This matches the sing-box JSON schema ("outbound": "<tag>") and the UI label.
Backward-compat: CustomRule.fromJson reads target as fallback for outbound — old 1.4.0 storage loads without losses.
📦 Install
Release APK: ./scripts/build-local-apk.sh (arm64-only, minimal). Signed with the keystore from key.properties.
🧪 Tests
flutter test: 359 passed, zero warnings in flutter analyze.
📝 Known limitations
- Debug API POST/PUT schema for preset-kind rules is partial (accepts
preset_id; fullvarsValuesbody schema TBD).