Skip to content

LxBox v1.4.1

Choose a tag to compare

@github-actions github-actions released this 22 Apr 18:53
· 3799 commits to main since this release

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 from wizard_template.json on every build. Template updates automatically propagate to every user without data migrations. Example: Russian domains direct is parametric — pick Outbound + DNS Transport (DoH/DoT/UDP) + UDP server IP (Safe/Base/Family).
  • CustomRule sealed split (spec 030 §v1.4.1, task 011) — the single class is split into CustomRuleInline / 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 local RuleSetDownloader cache 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 использует shorthand rule.action: "reject" (Block Ads) или hardcoded rule.outbound: "<tag>" (Russia-only services). Override пишется в varsValues['outbound'] и применяется в preset_expand независимо от формы template'а. Shorthand action: "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/rules serializer переписан на sealed-dispatch: inline/srs/preset правила отдают только релевантные поля. Preset-правила теперь экспозят preset_id, vars_values, nested preset.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_set ru-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. Красный экран заменён на компактный ErrorBoundary fallback-widget.
  • Auto-updater coverage — §027 spam-gate покрыт тестами (consecutiveFails, minRetryInterval, maxFailsPerSession, inProgress crash-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 consecutiveFails counter'а, размораживает подписку из 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 + SNI safe.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 / withOutbound mutators on the base class — UI can write rule.withEnabled(v) without manual pattern-matching.
  • Convenience read-only getters (domains / srsUrl / presetId / …) for code that doesn't care about the concrete subclass.
  • CustomRule.fromJson dispatches on kind; legacy target field is accepted as fallback for outbound.

🗄️ 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:

  • RuleSetDownloader gets a preset__<presetId>__<tag> namespace for preset-owned cache.
  • expandPreset checks srsPaths[tag] for remote rule_sets — hit → replace with {type: "local", path: "..."}; miss → skip rule_set + warning.
  • buildConfig pre-resolves cache paths before applyPresetBundles.

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 — expandPreset now drops a routing_rule whose rule_set references 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 old GestureDetector with HitTestBehavior.opaque was swallowing taps before IconButton.onPressed. Replaced with InkWell(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 (_refreshSrsCache now runs after _template is 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; full varsValues body schema TBD).