feat(profiles): WAN-mode / conditional-override profiles [T2] — the real §7 feature
build / aarch64_cortex-a53 (push) Successful in 3m11s
build / x86_64 (push) Has been cancelled

The Profiles page was a stub for the actual catalog §7 feature (WAN-mode / failover
conditional overrides); this implements it. A `config profile` defines conditions
(active default-route interface, a connectivity probe up/down, a time window — all
AND'd) and overrides (force-enable/disable named rules, override the default
catch-all target/egress). The highest-priority profile whose conditions all hold is
active; its overrides are applied at gen/reconcile time and the cron re-applies when
the active profile flips.

- model.go/uci.go: Profile struct + `config profile` parse.
- profile_wanmode.go: defaultIface() (ip route), profileProbeUp() (HTTP), condition
  eval, activeWanProfile() (priority + AND conditions; no-condition profile never
  auto-activates), ProfileStatusJSON. strSet helper.
- generate.go: builder.activeProfile set in buildConfigInternal; buildRoutingRules
  applies enable/disable-by-name + injects a default-target catch-all when active.
- schedule.go: scheduleSignature includes the active profile name, so shater-cron
  reconciles on a profile transition (iface/probe/time boundary).
- main.go: `xrayctl wanmode`. shater.uc `wanmode` ubus + acl.
- profiles.js: rewritten to host WAN-mode Profiles (config profile GridSection) +
  active-profile banner + Config snapshots + Backup/Restore + xray compatibility.
- tests: profile_wanmode_test.go (iface/schedule/AND conditions, priority selection,
  no-condition never active, override enable/disable, default-target injection,
  inactive-no-override).

Verified live on the 512M VM: `wanmode` reports active sim-mode (iface eth1);
force-enabled a disabled rule (profileonly.example appears); flipping the iface
condition deactivates it; schedule condition active at 22:30 / inactive at 12:00;
xray -test OK. Playwright: Profiles page renders the WAN-mode form + active banner +
snapshots + backup + compat with 0 console errors. r16.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
omarandClaude Opus 4.8 committed 2026-07-09 17:11:19 +03:00
1 parent 21ee972df1
commit 6c01d8db41
14 files changed
+595 -138

No files matched your search

+25
View File
@@ -168,6 +168,31 @@ config preset 'block_ads'
Без geodata гео-only паки (block-ads/ru-bypass) выкидываются (fail-open); private
работает всегда (литеральные RFC1918/ULA).
### profile (0..N — WAN-mode / условные оверрайды, T2)
```
config profile 'sim_mode'
option name 'sim-mode'
option enabled '1'
option priority '10' # выше = приоритетнее среди активных
# условия (все указанные И-объединяются; профиль без условий НЕ активируется):
list match_iface 'wwan0' # активен когда default-route dev ∈ списке
option probe_url '' # опц. connectivity-probe (HTTP)
option probe_mode 'up' # up|down (down = failover: активен когда probe лежит)
list sched_day 'mon' # окно по дням/времени (как в rule)
option sched_start '09:00'
option sched_end '18:00'
option sched_tz ''
# оверрайды при активности:
list enable_rule 'sim-vless-wrap' # форс-включить правила по имени
list disable_rule 'direct-ru' # выключить правила
option default_target 'group:ru-reality' # переопределить catch-all target
option default_egress ''
```
Активный профиль (наивысший priority с выполненными условиями) вычисляется при
gen/reconcile; `xrayctl wanmode` показывает активный. shater-cron переприменяет при
смене активного профиля (входит в scheduleSignature). Кейсы: SIM-аплинк→VLESS-egress,
whitelist-часы→RU-reality.
### resolver (0..N) + dns_rule (0..N) — DNS
```
config resolver
+15
View File
@@ -180,6 +180,21 @@ egress-binding и DNS-рендер; далее T1 (цепочки в UI, per-cli
Пруф: `ip netns exec shater_lan uclient-fetch https://1.1.1.1/cdn-cgi/trace` → exit ≠ WAN; nft-счётчик `c_rule_lan_proxy`=26 пакетов; оба `192.168.1.60/.61` в set `clients`; 184/254 ноды alive (observatory). Конфиг восстановлен (sub0-кеш→group g0 leastPing→tproxy inbound lan→rule src 192.168.1.0/24→group). Т.е. весь control-plane (mux/wg/inbounds/presets/schedule/ops/sub-форматы) не сломал data-plane.
## Дозакрытие (2026-07-09) — WAN-mode / условные профили (каталог §7, T2) — БЫЛА заглушка, теперь реализовано
Настоящая фича «Профили» (не путать с config-снапшотами): `config profile` — условные
оверрайды, авто-переключающие роутинг по активному аплинку / connectivity-probe / окну времени.
| Что | Пруф (живой, 512M VM) |
|---|---|
| `xrayctl wanmode` | `{active:"sim-mode", default_iface:"eth1", profiles:[{active:true}]}` |
| условие по iface | профиль с `match_iface=eth1` активен (eth1 — текущий default); force-enable правила → `profileonly.example` появился в gen |
| смена условия | `match_iface=wwan-nope` → active:"", правило исчезло (gen: 0 совпадений) |
| условие по расписанию | `SHATER_FAKE_NOW=22:30` → active sim-mode; `12:00` → active "" |
| оверрайды | enable_rule/disable_rule по имени + default_target (инжектит catch-all); `xray -test OK` |
| приоритет / AND-условия | unit: priority-выбор, iface∧schedule, «нет условий ⇒ никогда не активен» |
| cron re-apply | активный профиль входит в `scheduleSignature` → shater-cron переприменяет при смене |
| UI | страница Backup/Profiles: секция **WAN-mode profiles** (config profile) + баннер активного + Config snapshots + Backup + Compat; Playwright: рендерит, **0 console-ошибок** |
---
## (продолжение) geodata-опциональность — детали пруфа
@@ -1,20 +1,25 @@
'use strict';
'require view';
'require form';
'require dom';
'require rpc';
'require ui';
'require uci';
// Backup / restore, named config profiles, and xray version compatibility.
// Backend: xrayctl backup|restore|profile|compat via the `xray` ubus object.
// This page hosts three things:
// 1. WAN-mode Profiles (config profile) — conditional overrides that auto-switch
// routing by active uplink / connectivity probe / time window (catalog §7).
// 2. Config snapshots — save/restore/switch named backups of the whole config.
// 3. Backup/Restore + xray compatibility.
var callBackup = rpc.declare({ object: 'xray', method: 'backup', expect: { '': {} } });
var callRestore = rpc.declare({ object: 'xray', method: 'restore', params: ['b64', 'confirm'], expect: { '': {} } });
var callProfiles = rpc.declare({ object: 'xray', method: 'profile_list', expect: { '': {} } });
var callProfileSave = rpc.declare({ object: 'xray', method: 'profile_save', params: ['name'], expect: { '': {} } });
var callProfileSwitch = rpc.declare({ object: 'xray', method: 'profile_switch', params: ['name', 'confirm'], expect: { '': {} } });
var callProfileDelete = rpc.declare({ object: 'xray', method: 'profile_delete', params: ['name'], expect: { '': {} } });
var callSnapshots = rpc.declare({ object: 'xray', method: 'profile_list', expect: { '': {} } });
var callSnapSave = rpc.declare({ object: 'xray', method: 'profile_save', params: ['name'], expect: { '': {} } });
var callSnapSwitch = rpc.declare({ object: 'xray', method: 'profile_switch', params: ['name', 'confirm'], expect: { '': {} } });
var callSnapDelete = rpc.declare({ object: 'xray', method: 'profile_delete', params: ['name'], expect: { '': {} } });
var callCompat = rpc.declare({ object: 'xray', method: 'compat', expect: { '': {} } });
var callWanmode = rpc.declare({ object: 'xray', method: 'wanmode', expect: { '': {} } });
function fmtBytes(v) {
v = v || 0;
@@ -22,36 +27,153 @@ function fmtBytes(v) {
if (v >= 1024) return (v / 1024).toFixed(1) + ' KB';
return v + ' B';
}
function confirmTimeout() {
var v = uci.get('shater', 'globals', 'confirm_timeout');
return v || '0';
}
function reloadSoon() {
window.setTimeout(function () { window.location.reload(); }, 800);
}
function confirmTimeout() { return uci.get('shater', 'globals', 'confirm_timeout') || '0'; }
function reloadSoon() { window.setTimeout(function () { window.location.reload(); }, 800); }
var HHMM = /^([01]?\d|2[0-3]):[0-5]\d$/;
return view.extend({
handleSaveApply: null,
handleSave: null,
handleReset: null,
load: function () {
return Promise.all([
uci.load('shater'),
L.resolveDefault(callProfiles(), { profiles: [] }),
L.resolveDefault(callCompat(), {})
L.resolveDefault(callSnapshots(), { profiles: [] }),
L.resolveDefault(callCompat(), {}),
L.resolveDefault(callWanmode(), {})
]);
},
render: function (data) {
var profiles = (data[1] && data[1].profiles) || [];
var snapshots = (data[1] && data[1].profiles) || [];
var compat = data[2] || {};
var wan = data[3] || {};
// --- Backup / Restore card ---
var downloadBtn = E('button', {
'class': 'btn cbi-button cbi-button-action',
// ---------- 1. WAN-mode Profiles (editable config) ----------
var m = new form.Map('shater', null,
_('Conditional overrides that auto-switch routing by the active uplink, a ' +
'connectivity probe, or a time window. The highest-priority profile whose ' +
'conditions all hold becomes active and applies its overrides.'));
var s = m.section(form.GridSection, 'profile', _('WAN-mode profiles'));
s.addremove = true;
s.anonymous = true;
s.nodescriptions = true;
s.addbtntitle = _('Add profile');
var o = s.option(form.Value, 'name', _('Name'));
o.rmempty = false;
o.placeholder = 'sim-mode';
o = s.option(form.Flag, 'enabled', _('Enabled'));
o.default = '0';
o.editable = true;
o = s.option(form.Value, 'priority', _('Priority'));
o.datatype = 'uinteger';
o.default = '0';
// conditions
o = s.option(form.DynamicList, 'match_iface', _('Active uplink is'),
_('Profile active when the default route egresses via one of these interfaces (e.g. wwan0, usb0).'));
o.modalonly = true;
o.placeholder = 'wwan0';
o = s.option(form.Value, 'probe_url', _('Connectivity probe URL'),
_('Optional. Profile gated on whether this URL is reachable.'));
o.modalonly = true;
o.placeholder = 'http://www.gstatic.com/generate_204';
o = s.option(form.ListValue, 'probe_mode', _('Probe condition'));
o.value('up', _('active when probe is UP'));
o.value('down', _('active when probe is DOWN (failover)'));
o.default = 'up';
o.modalonly = true;
o = s.option(form.MultiValue, 'sched_day', _('Days'));
[['mon', 'Mon'], ['tue', 'Tue'], ['wed', 'Wed'], ['thu', 'Thu'],
['fri', 'Fri'], ['sat', 'Sat'], ['sun', 'Sun']].forEach(function (d) { o.value(d[0], _(d[1])); });
o.widget = 'checkbox';
o.modalonly = true;
o = s.option(form.Value, 'sched_start', _('Window start (HH:MM)'));
o.modalonly = true;
o.placeholder = '09:00';
o.validate = function (sid, v) { return (!v || HHMM.test(v)) ? true : _('Use HH:MM'); };
o = s.option(form.Value, 'sched_end', _('Window end (HH:MM)'));
o.modalonly = true;
o.placeholder = '18:00';
o.validate = function (sid, v) { return (!v || HHMM.test(v)) ? true : _('Use HH:MM'); };
o = s.option(form.Value, 'sched_tz', _('Timezone'));
o.modalonly = true;
o.optional = true;
// overrides
o = s.option(form.DynamicList, 'enable_rule', _('Force-enable rules'),
_('Rule names to enable while this profile is active.'));
o.modalonly = true;
o = s.option(form.DynamicList, 'disable_rule', _('Disable rules'));
o.modalonly = true;
o = s.option(form.Value, 'default_target', _('Override default target'),
_('group:/node:/chain:/direct/block — becomes the catch-all while active.'));
o.modalonly = true;
o.placeholder = 'group:ru-reality';
o = s.option(form.Value, 'default_egress', _('Override default egress'));
o.modalonly = true;
// active-profile banner
var activeTxt = wan.active
? E('span', {}, [_('Active WAN-mode profile: '), E('strong', { 'style': 'color:#5cb85c' }, wan.active)])
: E('span', { 'style': 'opacity:.7' }, _('No WAN-mode profile is currently active.'));
var banner = E('div', { 'class': 'cbi-section', 'style': 'padding:.4em .6em' }, [
activeTxt,
wan.default_iface ? E('span', { 'style': 'opacity:.7;margin-left:1em' }, [_('default uplink: '), E('code', {}, wan.default_iface)]) : ''
]);
// ---------- 2. Config snapshots ----------
var nameInput = E('input', { 'type': 'text', 'class': 'cbi-input-text', 'placeholder': _('snapshot name') });
var saveBtn = E('button', {
'class': 'btn cbi-button cbi-button-add',
'click': ui.createHandlerFn(this, function () {
var n = (nameInput.value || '').trim();
if (!n) { ui.addNotification(null, E('p', {}, _('Enter a name.')), 'warning'); return; }
return callSnapSave(n).then(function () { ui.addNotification(null, E('p', {}, _('Snapshot saved.')), 'info'); reloadSoon(); });
})
}, _('Save current as…'));
var rows = snapshots.map(function (p) {
return E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td' }, [p.name, p.active ? E('span', { 'class': 'label', 'style': 'margin-left:.5em;background:#5cb85c;color:#fff' }, _('active')) : '']),
E('td', { 'class': 'td' }, fmtBytes(p.size)),
E('td', { 'class': 'td' }, 'v' + (p.schema_version || 0)),
E('td', { 'class': 'td' }, [
E('button', { 'class': 'btn cbi-button cbi-button-action', 'style': 'margin-right:.4em',
'click': ui.createHandlerFn(this, function () {
if (!confirm(_('Switch to snapshot "%s"?').format(p.name))) return;
ui.showModal(_('Switching…'), [E('p', { 'class': 'spinning' }, _('Applying snapshot.'))]);
return callSnapSwitch(p.name, confirmTimeout()).then(function () { ui.hideModal(); reloadSoon(); })
.catch(function (e) { ui.hideModal(); ui.addNotification(null, E('p', {}, '' + e), 'danger'); });
}) }, _('Switch')),
E('button', { 'class': 'btn cbi-button cbi-button-remove',
'click': ui.createHandlerFn(this, function () {
if (!confirm(_('Delete snapshot "%s"?').format(p.name))) return;
return callSnapDelete(p.name).then(function () { reloadSoon(); });
}) }, _('Delete'))
])
]);
});
var snapTable = E('table', { 'class': 'table cbi-section-table' }, [
E('tr', { 'class': 'tr table-titles' }, [
E('th', { 'class': 'th' }, _('Snapshot')), E('th', { 'class': 'th' }, _('Size')),
E('th', { 'class': 'th' }, _('Schema')), E('th', { 'class': 'th' }, _('Actions'))
])
].concat(rows.length ? rows : [E('tr', { 'class': 'tr' }, [E('td', { 'class': 'td', 'colspan': 4 }, E('em', {}, _('No snapshots.')))])]));
var snapCard = E('div', { 'class': 'cbi-section' }, [
E('h3', {}, _('Config snapshots')),
E('p', {}, _('Named snapshots of the whole config you can switch between atomically (commit-confirm protected).')),
snapTable,
E('div', { 'style': 'margin-top:.6em;display:flex;gap:.5em;align-items:center' }, [nameInput, saveBtn])
]);
// ---------- 3. Backup / Restore ----------
var downloadBtn = E('button', { 'class': 'btn cbi-button cbi-button-action',
'click': ui.createHandlerFn(this, function () {
return callBackup().then(function (r) {
if (!r || !r.data) throw _('Backup failed');
@@ -59,18 +181,12 @@ return view.extend({
for (var i = 0; i < bin.length; i++) buf[i] = bin.charCodeAt(i);
var url = URL.createObjectURL(new Blob([buf], { type: 'application/gzip' }));
var a = E('a', { 'href': url, 'download': r.filename || 'shater-backup.tar.gz' });
document.body.appendChild(a); a.click(); a.remove();
URL.revokeObjectURL(url);
document.body.appendChild(a); a.click(); a.remove(); URL.revokeObjectURL(url);
ui.addNotification(null, E('p', {}, _('Backup downloaded.')), 'info');
}).catch(function (e) {
ui.addNotification(null, E('p', {}, _('Backup error: ') + e), 'danger');
});
})
}, _('Download backup'));
}).catch(function (e) { ui.addNotification(null, E('p', {}, _('Backup error: ') + e), 'danger'); });
}) }, _('Download backup'));
var fileInput = E('input', { 'type': 'file', 'accept': '.tar.gz,application/gzip' });
var restoreBtn = E('button', {
'class': 'btn cbi-button cbi-button-negative',
var restoreBtn = E('button', { 'class': 'btn cbi-button cbi-button-negative',
'click': ui.createHandlerFn(this, function () {
var f = fileInput.files && fileInput.files[0];
if (!f) { ui.addNotification(null, E('p', {}, _('Choose a backup file first.')), 'warning'); return; }
@@ -79,123 +195,49 @@ return view.extend({
var reader = new FileReader();
reader.onload = function () {
var b64 = String(reader.result).replace(/^data:[^,]*,/, '');
ui.showModal(_('Restoring…'), [E('p', { 'class': 'spinning' }, _('Validating and applying the restored config.'))]);
ui.showModal(_('Restoring…'), [E('p', { 'class': 'spinning' }, _('Validating and applying.'))]);
callRestore(b64, confirmTimeout()).then(function (r) {
ui.hideModal();
if (r && r.ok === false)
ui.addNotification(null, E('p', {}, _('Restore failed (config kept).')), 'danger');
else {
ui.addNotification(null, E('p', {}, _('Restored. Reloading…')), 'info');
reloadSoon();
}
if (r && r.ok === false) ui.addNotification(null, E('p', {}, _('Restore failed (config kept).')), 'danger');
else { ui.addNotification(null, E('p', {}, _('Restored. Reloading…')), 'info'); reloadSoon(); }
resolve();
}).catch(function (e) { ui.hideModal(); ui.addNotification(null, E('p', {}, _('Restore error: ') + e), 'danger'); resolve(); });
};
reader.readAsDataURL(f);
});
})
}, _('Restore'));
}) }, _('Restore'));
var backupCard = E('div', { 'class': 'cbi-section' }, [
E('h3', {}, _('Backup / Restore')),
E('p', {}, _('A backup bundles /etc/config/shater and the subscription caches. ' +
'It contains credentials — keep it private. Restore validates the config ' +
'with xray -test and applies it with commit-confirm.')),
E('div', { 'style': 'display:flex;gap:.75em;align-items:center;flex-wrap:wrap' }, [
downloadBtn, E('span', { 'style': 'width:1em' }), fileInput, restoreBtn
])
E('p', {}, _('A backup bundles /etc/config/shater and the subscription caches. It contains credentials — keep it private.')),
E('div', { 'style': 'display:flex;gap:.75em;align-items:center;flex-wrap:wrap' }, [downloadBtn, E('span', { 'style': 'width:1em' }), fileInput, restoreBtn])
]);
// --- Profiles card ---
var nameInput = E('input', { 'type': 'text', 'class': 'cbi-input-text', 'placeholder': _('profile name') });
var saveBtn = E('button', {
'class': 'btn cbi-button cbi-button-add',
'click': ui.createHandlerFn(this, function () {
var n = (nameInput.value || '').trim();
if (!n) { ui.addNotification(null, E('p', {}, _('Enter a name.')), 'warning'); return; }
return callProfileSave(n).then(function () {
ui.addNotification(null, E('p', {}, _('Profile saved.')), 'info'); reloadSoon();
});
})
}, _('Save current as…'));
var rows = profiles.map(function (p) {
return E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td' }, [
p.name, p.active ? E('span', { 'class': 'label', 'style': 'margin-left:.5em;background:#5cb85c;color:#fff' }, _('active')) : ''
]),
E('td', { 'class': 'td' }, fmtBytes(p.size)),
E('td', { 'class': 'td' }, 'v' + (p.schema_version || 0)),
E('td', { 'class': 'td' }, [
E('button', {
'class': 'btn cbi-button cbi-button-action', 'style': 'margin-right:.4em',
'click': ui.createHandlerFn(this, function () {
if (!confirm(_('Switch to profile "%s"?').format(p.name))) return;
ui.showModal(_('Switching…'), [E('p', { 'class': 'spinning' }, _('Applying profile.'))]);
return callProfileSwitch(p.name, confirmTimeout()).then(function () { ui.hideModal(); reloadSoon(); })
.catch(function (e) { ui.hideModal(); ui.addNotification(null, E('p', {}, '' + e), 'danger'); });
})
}, _('Switch')),
E('button', {
'class': 'btn cbi-button cbi-button-remove',
'click': ui.createHandlerFn(this, function () {
if (!confirm(_('Delete profile "%s"?').format(p.name))) return;
return callProfileDelete(p.name).then(function () { reloadSoon(); });
})
}, _('Delete'))
])
]);
});
var profileTable = E('table', { 'class': 'table cbi-section-table' }, [
E('tr', { 'class': 'tr table-titles' }, [
E('th', { 'class': 'th' }, _('Profile')),
E('th', { 'class': 'th' }, _('Size')),
E('th', { 'class': 'th' }, _('Schema')),
E('th', { 'class': 'th' }, _('Actions'))
])
].concat(rows.length ? rows : [E('tr', { 'class': 'tr' }, [E('td', { 'class': 'td', 'colspan': 4 }, E('em', {}, _('No saved profiles.')))])]));
var profilesCard = E('div', { 'class': 'cbi-section' }, [
E('h3', {}, _('Config profiles')),
E('p', {}, _('Named config snapshots you can switch between atomically (commit-confirm protected).')),
profileTable,
E('div', { 'style': 'margin-top:.6em;display:flex;gap:.5em;align-items:center' }, [nameInput, saveBtn])
]);
// --- Compat card ---
// ---------- 4. Compatibility ----------
var feats = (compat.features || []).map(function (f) {
return E('tr', { 'class': 'tr' }, [
E('td', { 'class': 'td' }, f.name),
E('td', { 'class': 'td' }, f.required || '—'),
E('td', { 'class': 'td' }, f.name), E('td', { 'class': 'td' }, f.required || '—'),
E('td', { 'class': 'td' }, f.detected || '?'),
E('td', { 'class': 'td' }, f.ok
? E('span', { 'style': 'color:#5cb85c' }, '✓')
: E('span', { 'style': 'color:#c00' }, '✗'))
E('td', { 'class': 'td' }, f.ok ? E('span', { 'style': 'color:#5cb85c' }, '✓') : E('span', { 'style': 'color:#c00' }, '✗'))
]);
});
var compatCard = E('div', { 'class': 'cbi-section' }, [
E('h3', {}, _('xray compatibility')),
E('p', {}, [
_('Detected xray: '), E('strong', {}, compat.xray_version || _('unknown')),
' — ', compat.ok
? E('span', { 'style': 'color:#5cb85c' }, _('all used features supported'))
: E('span', { 'style': 'color:#c00' }, _('some features need a newer xray'))
]),
E('p', {}, [_('Detected xray: '), E('strong', {}, compat.xray_version || _('unknown')), ' — ',
compat.ok ? E('span', { 'style': 'color:#5cb85c' }, _('all used features supported')) : E('span', { 'style': 'color:#c00' }, _('some features need a newer xray'))]),
feats.length ? E('table', { 'class': 'table cbi-section-table' }, [
E('tr', { 'class': 'tr table-titles' }, [
E('th', { 'class': 'th' }, _('Feature')),
E('th', { 'class': 'th' }, _('Requires')),
E('th', { 'class': 'th' }, _('Detected')),
E('th', { 'class': 'th' }, _('OK'))
])
E('tr', { 'class': 'tr table-titles' }, [E('th', { 'class': 'th' }, _('Feature')), E('th', { 'class': 'th' }, _('Requires')), E('th', { 'class': 'th' }, _('Detected')), E('th', { 'class': 'th' }, _('OK'))])
].concat(feats)) : E('p', {}, E('em', {}, _('No version-sensitive features in use.')))
]);
return E('div', {}, [
E('h2', {}, _('Shater — Backup / Profiles')),
backupCard,
profilesCard,
compatCard
]);
return m.render().then(function (wanForm) {
return E('div', {}, [
E('h2', {}, _('Shater — Backup / Profiles')),
banner,
wanForm,
snapCard,
backupCard,
compatCard
]);
});
}
});
@@ -4,7 +4,7 @@
"read": {
"uci": [ "shater" ],
"ubus": {
"xray": [ "status", "nodes", "stats", "explain", "geodata_status", "compat", "profile_list", "backup", "sub_info", "conns", "node_qr" ]
"xray": [ "status", "nodes", "stats", "explain", "geodata_status", "compat", "profile_list", "backup", "sub_info", "conns", "node_qr", "wanmode" ]
}
},
"write": {
@@ -232,6 +232,13 @@ return {
}
},
// Active WAN-mode profile + evaluation { default_iface, active, profiles:[...] }.
wanmode: {
call: function() {
return run_json(XRAYCTL + ' wanmode');
}
},
// List saved config profiles -> { profiles: [...] }.
profile_list: {
call: function() {
+1 -1
View File
@@ -14,7 +14,7 @@ include $(TOPDIR)/rules.mk
PKG_NAME:=shater-core
PKG_VERSION:=0.1.0
PKG_RELEASE:=15
PKG_RELEASE:=16
PKG_MAINTAINER:=Shater <maqrota@icloud.com>
PKG_LICENSE:=GPL-2.0-or-later
+1 -1
View File
@@ -10,7 +10,7 @@ include $(TOPDIR)/rules.mk
PKG_NAME:=xrayctl
PKG_VERSION:=0.1.0
PKG_RELEASE:=15
PKG_RELEASE:=16
PKG_MAINTAINER:=shater
PKG_LICENSE:=MIT
+30 -2
View File
@@ -42,8 +42,9 @@ type builder struct {
groupFallback map[string]string // group name -> balancer fallbackTag (block|direct), kill-switch driven
probeURL string
probeItv string
geoOK bool // geoip.dat/geosite.dat present -> geo matchers are usable
geoStripped int // count of geosite:/geoip: matchers dropped when absent
geoOK bool // geoip.dat/geosite.dat present -> geo matchers are usable
geoStripped int // count of geosite:/geoip: matchers dropped when absent
activeProfile *Profile // active WAN-mode override, or nil
}
// apiInboundPort is the loopback dokodemo port exposing the xray gRPC API
@@ -99,6 +100,10 @@ func newProbeBuilder(m *Model) *builder { return newBuilder(m) }
func buildConfigInternal(m *Model, withAPI bool) (map[string]any, error) {
b := newBuilder(m)
// WAN-mode: pick the active conditional-override profile (nil if none). Its
// rule enable/disable + default-target override are applied in buildRoutingRules.
b.activeProfile = activeWanProfile(m, timeNow())
// Kill-switch: decide each group balancer's fallbackTag before emitting them.
b.computeGroupFallback()
@@ -634,6 +639,29 @@ func (b *builder) buildRoutingRules() {
// Preset packs sort ahead of user rules by their low Order (first-match).
rules := append([]Rule(nil), b.presetRules()...)
rules = append(rules, b.m.Rules...)
// WAN-mode active profile: force-enable / disable rules by name, and append a
// default-target catch-all when the profile overrides the default egress/target.
if p := b.activeProfile; p != nil {
en := strSet(p.EnableRules)
dis := strSet(p.DisableRules)
for i := range rules {
if en[rules[i].Name] {
rules[i].Enabled = true
}
if dis[rules[i].Name] {
rules[i].Enabled = false
}
}
if p.DefaultTarget != "" || p.DefaultEgress != "" {
rules = append(rules, Rule{
Name: "_profile-" + p.Name + "-default",
Enabled: true,
Order: 1 << 20, // sorts last: catches everything unmatched
Target: orDefault(p.DefaultTarget, "direct"),
Egress: p.DefaultEgress,
})
}
}
sort.SliceStable(rules, func(i, j int) bool { return rules[i].Order < rules[j].Order })
now := timeNow()
for _, r := range rules {
+2
View File
@@ -63,6 +63,8 @@ func run(args []string) int {
return errWrap(Migrate())
case "compat":
return emit(CompatJSON())
case "wanmode":
return emit(ProfileStatusJSON())
case "ruleset":
return cmdRuleset(rest)
case "status":
+28
View File
@@ -21,6 +21,7 @@ type Model struct {
Rulesets []Ruleset
Rules []Rule
Presets []Preset
Profiles []Profile
Resolvers []Resolver
DNSRules []DNSRule
}
@@ -182,6 +183,33 @@ type Egress struct {
Target string
}
// Profile is a `config profile` — a WAN-mode / failover conditional override
// (catalog §7, T2). When its conditions hold (active default-route interface,
// connectivity probe up/down, and/or a time window — all AND'd), the highest-
// priority active profile applies its overrides: force-enable / disable named
// rules and optionally override the default catch-all target/egress. Evaluated
// at gen/reconcile time; the cron re-applies when the active profile changes.
type Profile struct {
Name string
Enabled bool
Priority int
// conditions (only the specified ones are checked; all must hold)
MatchIface []string // active default-route dev in this set (e.g. wwan0, usb0)
ProbeURL string // connectivity probe (HTTP); empty = no probe condition
ProbeMode string // up|down — active when the probe succeeds/fails (default up)
SchedDays []string
SchedStart string
SchedEnd string
SchedTZ string
// overrides applied while active
EnableRules []string // rule names to force-enable
DisableRules []string // rule names to disable
DefaultTarget string // override the default catch-all target (group:/node:/chain:/direct/block)
DefaultEgress string // override the default egress binding
}
// Ruleset is a `config ruleset` (reusable domain/ip list).
type Ruleset struct {
Name string
+163
View File
@@ -0,0 +1,163 @@
package main
// WAN-mode / failover profiles (catalog §7, T2). A `config profile` defines
// conditions (active default-route interface, a connectivity probe up/down, a
// time window — all AND'd) and overrides (force-enable/disable named rules,
// override the default catch-all target/egress). The highest-priority profile
// whose conditions all hold is "active"; its overrides are applied at gen time.
// Evaluated on every reconcile; the cron re-applies when the active profile
// changes (its name feeds scheduleSignature).
import (
"net/http"
"os/exec"
"sort"
"strings"
"time"
)
// strSet builds a lookup set from a string slice.
func strSet(ss []string) map[string]bool {
m := map[string]bool{}
for _, s := range ss {
m[s] = true
}
return m
}
// defaultIface returns the interface of the current default route (lowest metric
// first), or "" if none / unavailable.
func defaultIface() string {
out, err := exec.Command("ip", "route", "show", "default").Output()
if err != nil {
return ""
}
best, bestMetric := "", 1<<30
for _, line := range strings.Split(string(out), "\n") {
f := strings.Fields(line)
dev, metric := "", 0
for i := 0; i < len(f); i++ {
if f[i] == "dev" && i+1 < len(f) {
dev = f[i+1]
}
if f[i] == "metric" && i+1 < len(f) {
metric = atoiOr(f[i+1], 0)
}
}
if dev != "" && metric < bestMetric {
best, bestMetric = dev, metric
}
}
return best
}
// profileProbeUp reports whether an HTTP(S) probe to url succeeds (2xx/3xx).
func profileProbeUp(url string) bool {
if !strings.Contains(url, "://") {
url = "http://" + url
}
c := &http.Client{Timeout: 6 * time.Second}
resp, err := c.Get(url)
if err != nil {
return false
}
defer resp.Body.Close()
return resp.StatusCode < 400
}
// profileConditionsHold checks a profile's specified conditions (all must hold).
// iface and now are passed in so a full evaluation dials the probe at most once.
func profileConditionsHold(p Profile, iface string, now time.Time) bool {
if len(p.MatchIface) > 0 {
hit := false
for _, want := range p.MatchIface {
if strings.EqualFold(strings.TrimSpace(want), iface) {
hit = true
break
}
}
if !hit {
return false
}
}
if p.ProbeURL != "" {
up := profileProbeUp(p.ProbeURL)
if strings.EqualFold(p.ProbeMode, "down") {
if up {
return false // want probe down, but it's up
}
} else if !up {
return false // want probe up, but it's down
}
}
if p.SchedStart != "" || p.SchedEnd != "" || len(p.SchedDays) > 0 {
r := Rule{SchedEnabled: true, SchedDays: p.SchedDays, SchedStart: p.SchedStart, SchedEnd: p.SchedEnd, SchedTZ: p.SchedTZ}
if !ruleActiveNow(r, now) {
return false
}
}
return true
}
// activeWanProfile returns the highest-priority enabled profile whose conditions
// all hold, or nil. A profile with NO conditions never activates (avoids a
// permanent override with an empty match set).
func activeWanProfile(m *Model, now time.Time) *Profile {
var candidates []Profile
for _, p := range m.Profiles {
if !p.Enabled {
continue
}
if len(p.MatchIface) == 0 && p.ProbeURL == "" && p.SchedStart == "" && p.SchedEnd == "" && len(p.SchedDays) == 0 {
continue // no conditions -> never auto-activates
}
candidates = append(candidates, p)
}
sort.SliceStable(candidates, func(i, j int) bool { return candidates[i].Priority > candidates[j].Priority })
iface := ""
needIface := false
for _, p := range candidates {
if len(p.MatchIface) > 0 {
needIface = true
}
}
if needIface {
iface = defaultIface()
}
for i := range candidates {
if profileConditionsHold(candidates[i], iface, now) {
p := candidates[i]
return &p
}
}
return nil
}
// ProfileStatusJSON reports the currently-active WAN-mode profile + evaluation.
func ProfileStatusJSON() ([]byte, error) {
m, err := ReadUCI()
if err != nil {
return nil, err
}
now := timeNow()
iface := defaultIface()
active := activeWanProfile(m, now)
type row struct {
Name string `json:"name"`
Enabled bool `json:"enabled"`
Active bool `json:"active"`
}
var rows []row
for _, p := range m.Profiles {
rows = append(rows, row{p.Name, p.Enabled, active != nil && active.Name == p.Name})
}
res := map[string]any{
"default_iface": iface,
"active": "",
"profiles": rows,
}
if active != nil {
res["active"] = active.Name
}
return jsonMarshalIndent(res)
}
+126
View File
@@ -0,0 +1,126 @@
package main
import (
"testing"
"time"
)
func TestProfileConditionsIface(t *testing.T) {
p := Profile{Name: "sim", Enabled: true, MatchIface: []string{"wwan0", "usb0"}}
now := at(t, "2026-07-09T12:00:00Z")
if !profileConditionsHold(p, "wwan0", now) {
t.Fatal("should hold on wwan0")
}
if profileConditionsHold(p, "eth0", now) {
t.Fatal("should not hold on eth0")
}
}
func TestProfileConditionsSchedule(t *testing.T) {
p := Profile{Name: "night", Enabled: true, SchedTZ: "UTC", SchedStart: "22:00", SchedEnd: "23:00"}
if !profileConditionsHold(p, "", at(t, "2026-07-09T22:30:00Z")) {
t.Fatal("should hold at 22:30")
}
if profileConditionsHold(p, "", at(t, "2026-07-09T12:00:00Z")) {
t.Fatal("should not hold at 12:00")
}
}
func TestProfileConditionsAND(t *testing.T) {
// iface AND schedule: both must hold
p := Profile{Name: "x", Enabled: true, MatchIface: []string{"wwan0"}, SchedTZ: "UTC", SchedStart: "22:00", SchedEnd: "23:00"}
if profileConditionsHold(p, "wwan0", at(t, "2026-07-09T12:00:00Z")) {
t.Fatal("iface ok but out of window -> must not hold")
}
if profileConditionsHold(p, "eth0", at(t, "2026-07-09T22:30:00Z")) {
t.Fatal("in window but wrong iface -> must not hold")
}
if !profileConditionsHold(p, "wwan0", at(t, "2026-07-09T22:30:00Z")) {
t.Fatal("both hold -> must hold")
}
}
func TestActiveWanProfilePriority(t *testing.T) {
m := &Model{Globals: defaultGlobals()}
m.Profiles = []Profile{
{Name: "lo", Enabled: true, Priority: 1, SchedTZ: "UTC", SchedStart: "00:00", SchedEnd: "23:59"},
{Name: "hi", Enabled: true, Priority: 9, SchedTZ: "UTC", SchedStart: "00:00", SchedEnd: "23:59"},
}
p := activeWanProfile(m, at(t, "2026-07-09T12:00:00Z"))
if p == nil || p.Name != "hi" {
t.Fatalf("expected 'hi' by priority, got %v", p)
}
}
func TestActiveWanProfileNoConditionsNeverActive(t *testing.T) {
m := &Model{Globals: defaultGlobals()}
m.Profiles = []Profile{{Name: "empty", Enabled: true}}
if activeWanProfile(m, at(t, "2026-07-09T12:00:00Z")) != nil {
t.Fatal("a profile with no conditions must never auto-activate")
}
}
func TestProfileOverrideEnableDisable(t *testing.T) {
saved := timeNow
defer func() { timeNow = saved }()
timeNow = func() time.Time { return at(t, "2026-07-09T22:30:00Z") }
m := &Model{Globals: defaultGlobals()}
m.Nodes = []Node{{Name: "n1", Enabled: true, URI: vlessReality}}
m.Rules = []Rule{
{Name: "off-by-default", Enabled: false, Order: 10, DstDomain: []string{"ru.example"}, Target: "node:n1"},
{Name: "on-by-default", Enabled: true, Order: 11, DstDomain: []string{"keep.example"}, Target: "node:n1"},
}
m.Profiles = []Profile{{
Name: "night", Enabled: true, SchedTZ: "UTC", SchedStart: "22:00", SchedEnd: "23:00",
EnableRules: []string{"off-by-default"}, DisableRules: []string{"on-by-default"},
}}
cfg, err := BuildConfig(m)
if err != nil {
t.Fatalf("BuildConfig: %v", err)
}
if ruleWithDomain(cfg, "ru.example") == nil {
t.Fatal("profile should have enabled 'off-by-default'")
}
if ruleWithDomain(cfg, "keep.example") != nil {
t.Fatal("profile should have disabled 'on-by-default'")
}
}
func TestProfileDefaultTargetInjected(t *testing.T) {
saved := timeNow
defer func() { timeNow = saved }()
timeNow = func() time.Time { return at(t, "2026-07-09T22:30:00Z") }
m := &Model{Globals: defaultGlobals()}
m.Nodes = []Node{{Name: "ru", Enabled: true, URI: vlessReality}}
m.Profiles = []Profile{{
Name: "whitelist", Enabled: true, SchedTZ: "UTC", SchedStart: "22:00", SchedEnd: "23:00",
DefaultTarget: "node:ru",
}}
cfg, err := BuildConfig(m)
if err != nil {
t.Fatalf("BuildConfig: %v", err)
}
if routingHasTarget(cfg, "node_ru") == nil {
t.Fatal("profile default target should inject a catch-all to node_ru")
}
}
func TestProfileInactiveNoOverride(t *testing.T) {
saved := timeNow
defer func() { timeNow = saved }()
timeNow = func() time.Time { return at(t, "2026-07-09T12:00:00Z") } // outside window
m := &Model{Globals: defaultGlobals()}
m.Nodes = []Node{{Name: "n1", Enabled: true, URI: vlessReality}}
m.Rules = []Rule{{Name: "off-by-default", Enabled: false, Order: 10, DstDomain: []string{"ru.example"}, Target: "node:n1"}}
m.Profiles = []Profile{{
Name: "night", Enabled: true, SchedTZ: "UTC", SchedStart: "22:00", SchedEnd: "23:00",
EnableRules: []string{"off-by-default"},
}}
cfg, _ := BuildConfig(m)
if ruleWithDomain(cfg, "ru.example") != nil {
t.Fatal("inactive profile must not enable the rule")
}
}
+6 -2
View File
@@ -113,8 +113,9 @@ func ruleActiveNow(r Rule, now time.Time) bool {
return false
}
// scheduleSignature hashes the set of currently-active scheduled rules; it changes
// exactly when a schedule boundary is crossed.
// scheduleSignature hashes the set of currently-active scheduled rules AND the
// active WAN-mode profile; it changes exactly when a schedule boundary is crossed
// or the active profile flips, so the cron reconciles at those transitions.
func scheduleSignature(m *Model, now time.Time) string {
var active []string
for _, r := range m.Rules {
@@ -128,6 +129,9 @@ func scheduleSignature(m *Model, now time.Time) string {
h.Write([]byte(n))
h.Write([]byte{0})
}
if p := activeWanProfile(m, now); p != nil {
h.Write([]byte("profile:" + p.Name))
}
return strconv.FormatUint(h.Sum64(), 16)
}
+17
View File
@@ -161,6 +161,23 @@ func ParseUCIExport(text string) (*Model, error) {
Order: parseInt(s.opt("order"), 0),
Target: s.opt("target"),
})
case "profile":
m.Profiles = append(m.Profiles, Profile{
Name: s.optOr("name", s.Name),
Enabled: s.optBool("enabled", false),
Priority: parseInt(s.opt("priority"), 0),
MatchIface: nonEmpty(s.list("match_iface")),
ProbeURL: s.opt("probe_url"),
ProbeMode: s.optOr("probe_mode", "up"),
SchedDays: s.list("sched_day"),
SchedStart: s.opt("sched_start"),
SchedEnd: s.opt("sched_end"),
SchedTZ: s.opt("sched_tz"),
EnableRules: nonEmpty(s.list("enable_rule")),
DisableRules: nonEmpty(s.list("disable_rule")),
DefaultTarget: s.opt("default_target"),
DefaultEgress: s.opt("default_egress"),
})
case "resolver":
m.Resolvers = append(m.Resolvers, Resolver{
Name: firstNonEmpty(s.opt("name"), s.Name),