From 6433f2dda90ecadd1d572a57e24f2815f10645ca Mon Sep 17 00:00:00 2001 From: Cd1s <135119404+Cd1s@users.noreply.github.com> Date: Sun, 18 Oct 2026 00:44:33 +0800 Subject: [PATCH 1/4] fix: keep LAN renumbering reachable --- docs/api.md | 7 +++ mr/api.go | 94 ++++++++++++++++++++++++++++++++++---- mr/api_test.go | 32 +++++++++++++ mr/apply.go | 24 ++++++---- mr/history.go | 3 ++ mr/mod_net_render.go | 19 +++++++- mr/mod_net_test.go | 17 +++++++ mr/mod_sys.go | 7 ++- mr/mod_sys_test.go | 2 +- rootfs/www/ui/core.js | 36 ++++++++++++++- rootfs/www/ui/lang/en.json | 39 +++++++++++----- rootfs/www/ui/net.js | 53 ++++++++++++++++++++- tools/ci.d/net.sh | 9 ++++ tools/ci.d/sys.sh | 2 +- 14 files changed, 307 insertions(+), 37 deletions(-) diff --git a/docs/api.md b/docs/api.md index b0c4322..c1e52bd 100644 --- a/docs/api.md +++ b/docs/api.md @@ -103,6 +103,13 @@ expired token, 403 not allowed, 404 unknown, 405 POST required, 409 conflict, 42 | `POST apply` | `{patch \| yaml \| config, base_rev, confirm (s, default 120), comment, secrets?}` (`yaml`: the whole router.yaml text, written as typed — the web UI's 系统 → router.yaml 原文) → `{ok, confirm}`: the apply job starts; 409 when `base_rev` is stale or another change waits for confirmation | | `GET job` | → `{job: {state: running \| ok \| failed, output}, confirm_pending, pending}` | | `POST confirm` / `POST revert` | keep / undo the pending change (a token: only its own) | + +When a Web UI apply changes `lan.ipv4`, the response additionally contains `confirm_token` and +`confirm_ip`. The browser uses `http://confirm_ip/#confirm=confirm_token` after the old origin goes +away. The token is 256 bits of random data, valid only for this pending apply and its 120-second +window, accepted only by `POST confirm` from a LAN source, and consumed by the first successful +confirmation. The pending marker stores only a SHA-256 digest; the raw token is held briefly in a +0600 tmpfs file while the apply worker starts and is never written to the job log or history. | `GET history`, `POST history.diff {rev}`, `POST rollback {rev}` | revisions; the config from before #rev applied as a new change | `secrets` sets secret values by name (`{"proxy_jp2": "…"}`; empty = keep) — for new credentials; values diff --git a/mr/api.go b/mr/api.go index cfd8a6e..dd797bb 100644 --- a/mr/api.go +++ b/mr/api.go @@ -40,12 +40,13 @@ const ( // the apply job's input and state (variables so tests can point them elsewhere) var ( - CandidateYAML = RunDir + "/candidate.yaml" - CandidateSec = RunDir + "/candidate-secrets.yaml" - JobFile = RunDir + "/job.json" - JobLog = RunDir + "/job.log" - loadLANConfig = func() (*Config, error) { return loadConfig(ConfigPath, SecretsPath) } - lanBridgeAddrs = func(bridge string) ([]net.Addr, error) { + CandidateYAML = RunDir + "/candidate.yaml" + CandidateSec = RunDir + "/candidate-secrets.yaml" + JobFile = RunDir + "/job.json" + JobLog = RunDir + "/job.log" + confirmTokenFile = RunDir + "/confirm-token" + loadLANConfig = func() (*Config, error) { return loadConfig(ConfigPath, SecretsPath) } + lanBridgeAddrs = func(bridge string) ([]net.Addr, error) { i, err := net.InterfaceByName(bridge) if err != nil { return nil, err @@ -118,6 +119,52 @@ func normalizedRemoteIP(remote string) net.IP { return net.ParseIP(strings.SplitN(normalizeRemoteAddr(remote), "%", 2)[0]) } +func newConfirmToken() string { + b := make([]byte, 32) + if _, err := rand.Read(b); err != nil { + return "" + } + return base64.RawURLEncoding.EncodeToString(b) +} + +func lanIPv4Host(cidr string) string { + ip, _, err := net.ParseCIDR(cidr) + if err != nil || ip.To4() == nil { + return "" + } + return ip.To4().String() +} + +// confirmWithToken is deliberately separate from the normal session path. The token +// is scoped to the current pending marker, expires with it, is accepted only here, +// and is consumed by confirm (which removes the marker atomically under its lock). +func confirmWithToken(token, remote string) apiResp { + if len(token) < 32 || len(token) > 128 { + return errResp(401, "invalid confirmation token") + } + okLAN, err := fromLAN(remote) + if err != nil { + return errResp(403, "confirmation is only allowed from the LAN") + } + if !okLAN { + return errResp(403, "confirmation is only allowed from the LAN") + } + p, err := readPending() + if err != nil || p.ConfirmHash == "" || p.left() <= 0 { + return errResp(409, "no matching LAN confirmation is pending") + } + h := sha256.Sum256([]byte(token)) + want, err := hex.DecodeString(p.ConfirmHash) + if err != nil || subtle.ConstantTimeCompare(want, h[:]) != 1 { + return errResp(401, "invalid confirmation token") + } + ok, err := confirm() + if err != nil { + return errResp(409, "%v", err) + } + return apiResp{body: map[string]any{"ok": true, "confirmed": ok}, authed: true} +} + func runAPI() error { r := apiReq{ method: os.Getenv("REQUEST_METHOD"), @@ -176,6 +223,17 @@ func handleAPI(r apiReq) apiResp { case "setup": return apiSetup(r, secrets) } + // A LAN renumber changes the browser's origin, so the old session cookie is not + // available at the new address. The apply response hands the browser a short-lived, + // single-use token that is accepted only by this POST action and only from the LAN. + if r.action == "confirm" && r.method == "POST" { + var in struct { + Token string `json:"token"` + } + if json.Unmarshal(r.body, &in) == nil && in.Token != "" { + return confirmWithToken(in.Token, r.remote) + } + } if !validSession(r.cookie) { return errResp(401, "not logged in") } @@ -666,6 +724,19 @@ func apiApply(r apiReq) apiResp { if via == "" { via = "web UI" } + // Keep the raw handoff token only in a root-readable tmpfs file while the apply + // worker starts. The persistent pending marker stores its SHA-256 digest only. + confirmToken, confirmIP := "", "" + if via == "web UI" { + os.Remove(confirmTokenFile) + if live, e := loadConfig(ConfigPath, SecretsPath); e == nil && live.LAN.IPv4 != c.LAN.IPv4 { + confirmToken = newConfirmToken() + if confirmToken == "" || writeAtomic(confirmTokenFile, []byte(confirmToken), 0600) != nil { + return errResp(500, "cannot create LAN confirmation token") + } + confirmIP = lanIPv4Host(c.LAN.IPv4) + } + } if err := writeAtomic(CandidateYAML, y, 0600); err != nil { return errResp(500, "%v", err) } @@ -675,7 +746,12 @@ func apiApply(r apiReq) apiResp { writeJob(jobState{State: "running", Started: time.Now().Unix(), Confirm: confirmSecs, Via: via, From: r.remote, Comment: in.Comment, BaseRev: base}) self, _ := os.Executable() startDetached(self, "apply-job", strconv.Itoa(confirmSecs)) - return apiResp{body: map[string]any{"ok": true, "confirm": confirmSecs}} + body := map[string]any{"ok": true, "confirm": confirmSecs} + if confirmToken != "" { + body["confirm_token"] = confirmToken + body["confirm_ip"] = confirmIP + } + return apiResp{body: body} } // runApplyJob executes a web-UI apply in the background and records the outcome for polling. @@ -685,7 +761,9 @@ func runApplyJob(confirmSecs int) error { j0 := readJob() j0.Pid = os.Getpid() writeJob(j0) - o := applyOpts{Via: j0.Via, From: j0.From, Comment: j0.Comment, BaseRev: j0.BaseRev} + tokenBytes, _ := os.ReadFile(confirmTokenFile) + os.Remove(confirmTokenFile) + o := applyOpts{Via: j0.Via, From: j0.From, Comment: j0.Comment, BaseRev: j0.BaseRev, ConfirmToken: strings.TrimSpace(string(tokenBytes))} if o.Via == "" { o.Via = "web UI" } diff --git a/mr/api_test.go b/mr/api_test.go index 6dfce97..a1b4574 100644 --- a/mr/api_test.go +++ b/mr/api_test.go @@ -1,14 +1,46 @@ package main import ( + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "net" + "os" "strconv" "strings" "testing" + "time" ) +func TestLANConfirmTokenIsScopedAndHashed(t *testing.T) { + oldConfirm, oldLoad := ConfirmFile, loadLANConfig + t.Cleanup(func() { ConfirmFile, loadLANConfig = oldConfirm, oldLoad }) + ConfirmFile = t.TempDir() + "/confirm-pending" + loadLANConfig = func() (*Config, error) { return &Config{LAN: LAN{IPv4: "192.168.2.1/24"}}, nil } + token := newConfirmToken() + h := sha256.Sum256([]byte(token)) + if len(token) < 32 || token == newConfirmToken() { + t.Fatal("confirmation token is missing entropy") + } + if err := setPending(pendingApply{Snapshot: "/tmp/snap", State: statePending, Deadline: time.Now().Unix() + 60, ConfirmHash: hex.EncodeToString(h[:])}); err != nil { + t.Fatal(err) + } + if got := confirmWithToken(token+"x", "192.168.2.44"); got.status != 401 { + t.Fatalf("wrong token status = %d, want 401", got.status) + } + if _, err := os.Stat(ConfirmFile); err != nil { + t.Fatalf("wrong token consumed pending marker: %v", err) + } + // A token cannot confirm while the apply is still running, even when its hash matches. + if err := setPending(pendingApply{Snapshot: "/tmp/snap", State: stateApplying, Pid: os.Getpid(), ConfirmHash: hex.EncodeToString(h[:])}); err != nil { + t.Fatal(err) + } + if got := confirmWithToken(token, "192.168.2.44"); got.status != 409 { + t.Fatalf("applying token status = %d, want 409", got.status) + } +} + func TestNormalizeRemoteAddrBusyboxFormats(t *testing.T) { for _, tc := range []struct { raw, want string diff --git a/mr/apply.go b/mr/apply.go index 441a0fe..acdd5e3 100644 --- a/mr/apply.go +++ b/mr/apply.go @@ -4,6 +4,8 @@ import ( "archive/tar" "bytes" "compress/gzip" + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "flag" @@ -635,7 +637,7 @@ func applyWith(c *Config, dryRun bool, confirmSecs int, install func() error, o appendChangeLog(fmt.Sprintf("mr apply: %s", summary(p))) fmt.Printf("applied (snapshot %s)\n", filepath.Base(snap)) if confirmSecs > 0 { - armConfirm(snap, confirmSecs, o.Via) + armConfirm(snap, confirmSecs, o.Via, o.ConfirmToken) setResult(snap, "pending") fmt.Printf("run `mr confirm` within %ds or this change is rolled back\n", confirmSecs) } else { @@ -852,11 +854,12 @@ func appendChangeLogAt(t time.Time, line string) { // pendingApply is the content of ConfirmFile. type pendingApply struct { - Snapshot string `json:"snapshot"` // history snapshot taken before the change - State string `json:"state"` // stateApplying | statePending | stateReverting - Deadline int64 `json:"deadline,omitempty"` // unix time the confirm timer rolls back at (statePending) - Via string `json:"via"` // origin: mr apply | web UI | restore - Pid int `json:"pid,omitempty"` // the applying process (stateApplying) + Snapshot string `json:"snapshot"` // history snapshot taken before the change + State string `json:"state"` // stateApplying | statePending | stateReverting + Deadline int64 `json:"deadline,omitempty"` // unix time the confirm timer rolls back at (statePending) + Via string `json:"via"` // origin: mr apply | web UI | restore + Pid int `json:"pid,omitempty"` // the applying process (stateApplying) + ConfirmHash string `json:"confirm_hash,omitempty"` // sha256 of the one-time LAN handoff token } // interrupted: an apply whose process is gone (killed, out of memory). Nothing finishes or undoes it @@ -1023,8 +1026,13 @@ func startRevert(snap string) (*pendingApply, bool) { return p, true } -func armConfirm(snap string, secs int, via string) { - setPending(pendingApply{Snapshot: snap, State: statePending, Deadline: time.Now().Unix() + int64(secs), Via: via}) +func armConfirm(snap string, secs int, via, token string) { + p := pendingApply{Snapshot: snap, State: statePending, Deadline: time.Now().Unix() + int64(secs), Via: via} + if token != "" { + h := sha256.Sum256([]byte(token)) + p.ConfirmHash = hex.EncodeToString(h[:]) + } + setPending(p) self, _ := os.Executable() startDetached(self, "rollback-if-unconfirmed", snap, fmt.Sprint(secs)) } diff --git a/mr/history.go b/mr/history.go index a50f01c..319533f 100644 --- a/mr/history.go +++ b/mr/history.go @@ -47,6 +47,9 @@ type applyOpts struct { // BaseRev: the router.yaml rev the candidate was built from (web UI / API). The apply refuses when // the live file differs by the time it installs (Cd1s/mini-router#68). BaseRev string + // ConfirmToken is a one-time web handoff for a LAN renumber. It is never written + // to the job log or history; applyWith stores only its hash in the pending marker. + ConfirmToken string } // bookkeeping reports files that record state for mr itself (not shown in plans). diff --git a/mr/mod_net_render.go b/mr/mod_net_render.go index f10b92b..a1a4b0c 100644 --- a/mr/mod_net_render.go +++ b/mr/mod_net_render.go @@ -288,7 +288,24 @@ func netSh(c *Config, phase string, b *strings.Builder) { for _, p := range d.ports { fmt.Fprintf(b, "ip link set %s master %s 2>/dev/null; ip link set %s up\n", p, d.br, p) } - fmt.Fprintf(b, "ip addr replace %s dev %s\nip link set %s up\n", d.ipv4, d.br, d.br) + // `ip addr replace` leaves an address from the previous LAN/network behind. Drop + // every old IPv4 after installing the desired one; otherwise the old subnet keeps + // answering ARP and dnsmasq advertises two gateways after a renumber. + fmt.Fprintf(b, "mr_old_%s=0\n", strings.ReplaceAll(d.br, "-", "_")) + fmt.Fprintf(b, "for a in $(ip -4 -o addr show dev %s 2>/dev/null | awk '{print $4}'); do [ \"$a\" = %s ] || mr_old_%s=1; done\n", d.br, d.ipv4, strings.ReplaceAll(d.br, "-", "_")) + fmt.Fprintf(b, "ip addr replace %s dev %s\n", d.ipv4, d.br) + fmt.Fprintf(b, "for a in $(ip -4 -o addr show dev %s 2>/dev/null | awk '{print $4}'); do [ \"$a\" = %s ] || ip addr del \"$a\" dev %s 2>/dev/null || true; done\n", d.br, d.ipv4, d.br) + fmt.Fprintf(b, "ip link set %s up\n", d.br) + if d.br == c.LAN.Bridge { + // A short carrier flap on the wired LAN ports makes DHCP clients renew promptly. + // It does not restart WiFi or touch WAN hardware offload. + name := strings.ReplaceAll(d.br, "-", "_") + fmt.Fprintf(b, "if [ \"$mr_old_%s\" = 1 ]; then\n", name) + for _, p := range d.ports { + fmt.Fprintf(b, "ip link set %s down 2>/dev/null || true; ip link set %s up 2>/dev/null || true\n", p, p) + } + b.WriteString("fi\n") + } } // tagged VLANs: . joins the network's bridge; the port itself keeps its untagged role for _, n := range c.Networks { diff --git a/mr/mod_net_test.go b/mr/mod_net_test.go index 957461d..6a90836 100644 --- a/mr/mod_net_test.go +++ b/mr/mod_net_test.go @@ -121,6 +121,23 @@ func TestNetGeneratedLinkCleanupOnce(t *testing.T) { } } +func TestLANNetworkScriptRemovesOldBridgeAddressesAndRenewsClients(t *testing.T) { + c := testConfig(t) + sh := renderMap(t, c)[GenDir+"/network.sh"] + if !strings.Contains(sh, "ip addr del \"$a\" dev br-lan") { + t.Fatalf("network.sh does not remove stale br-lan IPv4 addresses:\n%s", sh) + } + if !strings.Contains(sh, "ip link set lan2 down") || !strings.Contains(sh, "ip link set lan2 up") { + t.Fatalf("network.sh does not flap LAN ports after a renumber:\n%s", sh) + } + if len(c.Networks) > 0 { + bridge := c.Networks[0].BridgeName() + if !strings.Contains(sh, "ip addr del \"$a\" dev "+bridge) { + t.Fatalf("network.sh does not clean extra network bridge addresses:\n%s", sh) + } + } +} + func TestNetWANProtos(t *testing.T) { c := testConfig(t) c.LAN.Ports = []string{"lan2", "lan3"} diff --git a/mr/mod_sys.go b/mr/mod_sys.go index 0b8b1c5..f7fbf7a 100644 --- a/mr/mod_sys.go +++ b/mr/mod_sys.go @@ -158,8 +158,11 @@ func sysRender(c *Config, out *Out) error { if sv.Tailscale.Enabled { out.Add("/etc/conf.d/tailscale", 0644, fmt.Sprintf("# generated by mr\nTS_PORT=%d\n", sv.Tailscale.Port)+tsExitConf(c)+tsAdvertiseConf(c)) } - if ip, _, ok := strings.Cut(c.LAN.IPv4, "/"); ok && sv.Panel.Enabled { - out.Add("/etc/conf.d/mr-panel", 0644, fmt.Sprintf("# generated by mr: the web UI listens on the main LAN address\nPANEL_ADDR=%s\n", ip)) + if _, _, ok := strings.Cut(c.LAN.IPv4, "/"); ok && sv.Panel.Enabled { + // Keep the panel reachable while a LAN renumber is awaiting confirmation. The + // input firewall still limits port 80 to LAN addresses, so binding all local + // addresses does not expose the panel on WAN interfaces. + out.Add("/etc/conf.d/mr-panel", 0644, "# generated by mr: listen on all local addresses during LAN renumber confirmation\nPANEL_ADDR=0.0.0.0\n") } if cronWanted(c) { out.Add("/etc/conf.d/crond", 0644, renderCrondConf(c)) diff --git a/mr/mod_sys_test.go b/mr/mod_sys_test.go index 73e17c2..0435552 100644 --- a/mr/mod_sys_test.go +++ b/mr/mod_sys_test.go @@ -142,7 +142,7 @@ func TestSysRenderHome(t *testing.T) { "net.ipv4.conf.all.send_redirects=0\n", "net.ipv4.conf.default.send_redirects=0\n", "kernel.kptr_restrict=2\n", "kernel.dmesg_restrict=1\n", "net.core.bpf_jit_harden=2\n", "net.core.rmem_max=7500000\n", "net.core.wmem_max=7500000\n", "net.ipv4.tcp_notsent_lowat=131072\n", "net.ipv4.tcp_slow_start_after_idle=0\n") - wantSubs(t, "mr-panel", f["/etc/conf.d/mr-panel"], "PANEL_ADDR=192.168.1.6\n") + wantSubs(t, "mr-panel", f["/etc/conf.d/mr-panel"], "PANEL_ADDR=0.0.0.0\n") wantSubs(t, "rc_after", f["/etc/conf.d/sysctl"], `rc_after="modules"`) loc, err := time.LoadLocationFromTZData("x", []byte(f["/etc/localtime"])) if err != nil { diff --git a/rootfs/www/ui/core.js b/rootfs/www/ui/core.js index afcbcfa..0f0bbf3 100644 --- a/rootfs/www/ui/core.js +++ b/rootfs/www/ui/core.js @@ -571,7 +571,8 @@ async function doApply(payload, risk){ return runJob(()=>api("apply", Object.ass // low / medium risk change is kept by the page itself once it is applied, verified and the page still // reaches the router (the confirm window only has to catch changes that cut the administrator off). async function runJob(start, auto){ - try { await start(); } catch(e){ + let handoff = null; + try { handoff = await start(); } catch(e){ const msg = e.data&&e.data.pending ? "有待确认的更改("+(VIA[e.data.pending.via]||e.data.pending.via)+"):请先在页面顶部点“保留”或“回滚”。" : e.data&&e.data.errors ? e.data.errors.join("\n") : e.message; return modal("应用失败", h("pre",{}, msg), [h("button",{class:"btn p",onclick:ev=>ev.target.closest(".modal").remove()},"关闭")]); @@ -583,7 +584,18 @@ async function runJob(start, auto){ let seenOk = 0, fails = 0; const poll = async ()=>{ let j; - try { j = await api("job"); fails = 0; } catch(e){ fails++; stateEl.textContent = tr("暂时连不上路由器("+fails+")… 如果是改了 LAN 地址,请到新地址访问;超时未确认会自动回滚。"); return setTimeout(poll, 2000); } + try { j = await api("job"); fails = 0; } catch(e){ + fails++; + if (handoff && handoff.confirm_token && handoff.confirm_ip && fails === 1) { + stateEl.textContent = tr("LAN 地址已切换,正在打开新地址并自动确认…"); + const port = location.port ? ":"+location.port : ""; + const target = location.protocol+"//"+handoff.confirm_ip+port+"/#confirm="+encodeURIComponent(handoff.confirm_token); + setTimeout(()=>location.replace(target), 150); + return; + } + stateEl.textContent = tr("暂时连不上路由器("+fails+")… 如果是改了 LAN 地址,请到新地址访问;超时未确认会自动回滚。"); + return setTimeout(poll, 2000); + } const job = j.job||{}; log.textContent = job.output||""; if (job.state==="running") return setTimeout(poll, 1200); if (job.state==="failed"){ @@ -616,6 +628,24 @@ async function runJob(start, auto){ poll(); } +// A LAN renumber changes the origin and therefore the session-cookie scope. The apply +// response supplies a one-time token; the new origin accepts it only for POST /confirm. +async function settleHandoff(token){ + if (!token) return false; + for (let i=0; i<125; i++) { + try { + await api("confirm", {token}); + history.replaceState(null, "", location.pathname+location.search+"#overview"); + return true; + } catch(e) { + if (e.data && e.data.error && /invalid|only allowed|no matching/.test(e.data.error)) break; + await new Promise(resolve=>setTimeout(resolve, 1000)); + } + } + history.replaceState(null, "", location.pathname+location.search+"#overview"); + return false; +} + // ---------- first-run setup wizard ---------- // The wizard edits the same S.cfg object as the regular pages. Applying it therefore // uses the normal validate → plan → apply → confirm path and automatic rollback. @@ -700,6 +730,8 @@ function renderLogin(setup){ async function boot(opts={}){ await LANG_READY; + const handoffMatch = location.hash.match(/^#confirm=([^&]+)/); + if (handoffMatch) await settleHandoff(decodeURIComponent(handoffMatch[1])); let s; try { s = await api("session"); } catch(e){ $("#root").replaceChildren(h("div",{class:"login"},h("div",{class:"err"},"无法连接路由器:"+e.message))); return; } if (!s.authenticated) return renderLogin(!s.password_set); diff --git a/rootfs/www/ui/lang/en.json b/rootfs/www/ui/lang/en.json index f1a06bc..35d69b0 100644 --- a/rootfs/www/ui/lang/en.json +++ b/rootfs/www/ui/lang/en.json @@ -189,6 +189,7 @@ "应用失败": "Apply failed", "正在应用…": "Applying…", "应用配置": "Applying config", +"LAN 地址已切换,正在打开新地址并自动确认…": "LAN address changed; opening the new address and confirming automatically…", "暂时连不上路由器(": "Cannot reach the router (", ")… 如果是改了 LAN 地址,请到新地址访问;超时未确认会自动回滚。": ")… If you changed the LAN address, open the new address; without confirmation the change rolls back when the time is up.", "应用失败,已自动回滚。": "Apply failed; rolled back automatically.", @@ -247,7 +248,16 @@ "建议使用 ": "Suggested: ", "本向导不会自动修改 LAN 地址;如需换段,请在确认网络可达后手动填写并单独应用。": "This wizard will not change the LAN address automatically; edit and apply it separately only after confirming reachability.", "未检测到无线电,稍后可在无线设置中添加。": "No wireless radio detected. You can add one later in Wireless settings.", +"请选择国家/地区": "Choose a country or region", +"中国": "China", +"新加坡": "Singapore", +"日本": "Japan", +"美国": "United States", +"英国": "United Kingdom", +"德国": "Germany", " 启用 WiFi(稍后也可在无线设置中开启)": " Enable WiFi (you can also enable it later in Wireless settings)", +"请选择无线所在国家/地区;不确定时留空,稍后可在无线设置中设置。": "Choose the WiFi country or region; leave blank if unsure and set it later in WiFi settings.", +"国家/地区": "Country/region", "网络名称": "Network name", "WiFi 密码": "WiFi password", " 显示密码": " Show password", @@ -264,6 +274,7 @@ "跳过首次设置?之后仍可在各网络页面单独配置。": "Skip first-run setup? You can configure each section later.", "跳过首次设置": "Skip first-run setup", "首次设置 · ": "First setup · ", +"应用后请在确认窗口内检查网络并点击“保留”;未确认会自动回滚。": "After applying, check the network in the confirmation window and click Keep; unconfirmed changes roll back automatically.", "密码": "Password", "设置管理员密码": "Set admin password", "登录": "Log in", @@ -1018,6 +1029,20 @@ "负载均衡权重": "Load balancing weights", "故障线路的默认路由 metric 加 10000(下一条线路接管),它的策略路由表也暂时不用,按 MAC / 地址指定走它的设备会改走最好的健康线路;恢复后自动切回。": "A failed line's default route metric is raised by 10000 (the next line takes over) and its policy routing table is suspended; devices pinned to it by MAC / address use the best healthy line instead. It switches back automatically on recovery.", "负载均衡按连接分配:只分配新的 IPv4 连接,同一个连接始终走同一条线路;策略路由、端口转发的回包优先于均衡。IPv6 不参与均衡(每条线路的前缀不同)。": "Load balancing is per connection: only new IPv4 connections are distributed, and a connection always stays on one line; replies for policy routes and port forwards take precedence over balancing. IPv6 is not balanced (each line has its own prefix).", +"DHCP 主机 ": "DHCP host ", +"转发来源 ": "Forward source ", +"开放端口来源 ": "Open-port source ", +"防火墙规则来源 ": "Firewall rule source ", +"防火墙规则目标 ": "Firewall rule destination ", +"静态路由目标 ": "Static route destination ", +"静态路由网关 ": "Static route gateway ", +"DNS 记录 ": "DNS record ", +"DHCP 选项 ": "DHCP option ", +"LAN 网段变更:同步地址": "LAN subnet changed: synchronize addresses", +"以下地址落在旧 LAN 网段。勾选后会按主机号平移到新网段;取消某条即可保留原值。": "These addresses are in the old LAN subnet. Selected entries move to the new subnet with the same host number; clear one to keep its old value.", +"稍后手动处理": "Handle manually later", +"已同步选中的 LAN 地址": "Selected LAN addresses synchronized", +"平移选中地址": "Move selected addresses", "LAN 与网络": "LAN & networks", "网络 · ": "Network · ", "小写字母开头,最多 10 个字符;网桥为 br-<名称>": "Starts with a lowercase letter, max. 10 characters; the bridge is br-", @@ -1051,7 +1076,7 @@ "代理网段(fake-ip 和规则里的 IP 段)都指向本机。应用后生成;命令行:mr proxy routes": "Proxied ranges (fake-ip and the IP ranges in rules) all point to this router. Generated on apply; CLI: mr proxy routes", "(保存并应用、开启代理后显示)": "(shown after Save & apply with the proxy on)", "LAN(主网络)": "LAN (main network)", -"修改后如果浏览器失去连接,超时未确认会自动回滚": "If the browser loses the connection after a change, it is rolled back unless confirmed in time", +"修改网段时会列出旧网段引用;应用后客户端会快速续租,确认期间旧地址会自动跳转到新地址": "Changing the subnet lists references to the old subnet; clients renew quickly after applying, and the old page redirects to the new address during confirmation", "LAN 口": "LAN ports", "WAN 口不能同时做 LAN 口": "A WAN port cannot also be a LAN port", "向 LAN 通告 IPv6 前缀": "Announce the IPv6 prefix to the LAN", @@ -2020,15 +2045,5 @@ "你正从 WAN(": "You are connected from the WAN (", ")连接,而这条线路会重拨": "), and this line will redial", "你正在用 SSH,而 SSH 服务会重启": "You are using SSH, and the SSH service will restart", -"无法判断改动了什么": "Cannot tell what changes", -"请选择国家/地区": "Choose a country or region", -"中国": "China", -"新加坡": "Singapore", -"日本": "Japan", -"美国": "United States", -"英国": "United Kingdom", -"德国": "Germany", -"请选择无线所在国家/地区;不确定时留空,稍后可在无线设置中设置。": "Choose the WiFi country or region; leave blank if unsure and set it later in WiFi settings.", -"国家/地区": "Country/region", -"应用后请在确认窗口内检查网络并点击“保留”;未确认会自动回滚。": "After applying, check the network in the confirmation window and click Keep; unconfirmed changes roll back automatically." +"无法判断改动了什么": "Cannot tell what changes" } diff --git a/rootfs/www/ui/net.js b/rootfs/www/ui/net.js index 71f514c..06a11a5 100644 --- a/rootfs/www/ui/net.js +++ b/rootfs/www/ui/net.js @@ -233,6 +233,50 @@ registerPage("network", "multiwan", "多线路", 15, async ()=>{ }); // ---------- LAN 与网络 ---------- +function lanCIDR(s){ + const m=String(s||"").trim().match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)\/(\d{1,2})$/); + if(!m||m.slice(1,5).some(x=>+x>255)||+m[5]>32)return null; + const ip=(+m[1]<<24|+m[2]<<16|+m[3]<<8|+m[4])>>>0, bits=+m[5]; + const mask=bits===0?0:(0xffffffff<<(32-bits))>>>0; + return {ip,bits,mask,net:(ip&mask)>>>0}; +} +function lanIP(s){ + const m=String(s||"").trim().match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)(?:\/(\d{1,2}))?$/); + if(!m||m.slice(1,5).some(x=>+x>255)||(m[5]!==undefined&&+m[5]>32))return null; + return {ip:(+m[1]<<24|+m[2]<<16|+m[3]<<8|+m[4])>>>0,suffix:m[5]===undefined?"":"/"+m[5]}; +} +function lanDotted(ip){return[(ip>>>24)&255,(ip>>>16)&255,(ip>>>8)&255,ip&255].join(".");} +function lanShiftText(text,oldC,newC){return String(text).replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?\b/g,token=>{ + const x=lanIP(token);if(!x||((x.ip&oldC.mask)>>>0)!==oldC.net)return token; + const off=(x.ip-oldC.net)>>>0,max=newC.bits===32?0:2**(32-newC.bits)-1; + return off>max?token:lanDotted((newC.net+off)>>>0)+x.suffix; +});} +function lanRenumberCandidates(c,oldC,newC){ + const out=[],add=(path,obj,key,label)=>{const old=String(obj?.[key]??""),next=lanShiftText(old,oldC,newC);if(next!==old)out.push({path,obj,key,label,old,next});}; + (c.dhcp?.hosts||[]).forEach((x,i)=>add(`dhcp.hosts[${i}].ip`,x,"ip",`DHCP 主机 ${x.name||x.mac||i+1}`)); + (c.devices||[]).forEach((x,i)=>add(`devices[${i}].ip`,x,"ip",`设备 ${x.name||i+1}`)); + (c.firewall?.forwards||[]).forEach((x,i)=>add(`firewall.forwards[${i}].to`,x,"to",`端口转发 ${x.name||i+1}`)); + (c.firewall?.forwards||[]).forEach((x,i)=>(x.src_ip||[]).forEach((_,j)=>add(`firewall.forwards[${i}].src_ip[${j}]`,x.src_ip,j,`转发来源 ${x.name||i+1}`))); + (c.firewall?.open||[]).forEach((x,i)=>(x.src_ip||[]).forEach((_,j)=>add(`firewall.open[${i}].src_ip[${j}]`,x.src_ip,j,`开放端口来源 ${x.name||i+1}`))); + (c.firewall?.rules||[]).forEach((x,i)=>{ + (x.src_ip||[]).forEach((_,j)=>add(`firewall.rules[${i}].src_ip[${j}]`,x.src_ip,j,`防火墙规则来源 ${x.name||i+1}`)); + (x.dest_ip||[]).forEach((_,j)=>add(`firewall.rules[${i}].dest_ip[${j}]`,x.dest_ip,j,`防火墙规则目标 ${x.name||i+1}`)); + }); + (c.policy_routes||[]).forEach((x,i)=>add(`policy_routes[${i}].src`,x,"src",`策略路由 ${x.name||i+1}`)); + (c.static_routes||[]).forEach((x,i)=>{add(`static_routes[${i}].target`,x,"target",`静态路由目标 ${x.name||i+1}`);add(`static_routes[${i}].via`,x,"via",`静态路由网关 ${x.name||i+1}`);}); + (c.dns?.records||[]).forEach((x,i)=>{if(String(x.type||"").toUpperCase()==="A")add(`dns.records[${i}].value`,x,"value",`DNS 记录 ${x.name||i+1}`);}); + (c.dhcp?.dns||[]).forEach((_,i)=>add(`dhcp.dns[${i}]`,c.dhcp.dns,i,"DNS DHCP "+(i+1))); + (c.dhcp?.ntp||[]).forEach((_,i)=>add(`dhcp.ntp[${i}]`,c.dhcp.ntp,i,"NTP DHCP "+(i+1))); + (c.dhcp?.options||[]).forEach((x,i)=>add(`dhcp.options[${i}].value`,x,"value",`DHCP 选项 ${x.code||i+1}`)); + return out; +} +function lanRenumberPrompt(c,oldValue,newValue){ + const oldC=lanCIDR(oldValue),newC=lanCIDR(newValue);if(!oldC||!newC||oldC.net===newC.net)return; + const rows=lanRenumberCandidates(c,oldC,newC);if(!rows.length)return; + const checks=rows.map(x=>{const cb=h("input",{type:"checkbox",checked:true});x.cb=cb;return h("label",{class:"row",style:"display:flex;gap:8px;align-items:flex-start"},cb,h("span",{},h("b",{},x.label),h("span",{class:"mono"}," · "+x.old+" → "+x.next)));}); + const m=modal("LAN 网段变更:同步地址",[h("p",{},"以下地址落在旧 LAN 网段。勾选后会按主机号平移到新网段;取消某条即可保留原值。"),h("div",{class:"form"},checks)], + [h("button",{class:"btn",onclick:()=>m.remove()},"稍后手动处理"),h("button",{class:"btn p",onclick:()=>{rows.forEach(x=>{if(x.cb.checked)x.obj[x.key]=x.next;});touch();m.remove();toast("已同步选中的 LAN 地址");}},"平移选中地址")]); +} registerPage("network", "lan", "LAN 与网络", 20, async ()=>{ const c = S.cfg; const ports = await portNames(); @@ -285,11 +329,15 @@ registerPage("network", "lan", "LAN 与网络", 20, async ()=>{ return card("工作模式", form(...body.filter(Boolean))); }; const onEdit = (el, fn)=>{ el.addEventListener("input", fn); el.addEventListener("change", fn); return el; }; - const draw = ()=>box.replaceChildren( + const draw = ()=>{ + const oldLAN=c.lan.ipv4; + const lanInput=inText(c.lan,"ipv4",{placeholder:"192.168.1.1/24"}); + lanInput.addEventListener("change",()=>lanRenumberPrompt(c,oldLAN,c.lan.ipv4)); + box.replaceChildren( modeCard(), card("LAN(主网络)", form( ...field("网桥", inText(c.lan,"bridge")), - ...field("IPv4 地址 / 掩码", inText(c.lan,"ipv4",{placeholder:"192.168.1.1/24"}), "修改后如果浏览器失去连接,超时未确认会自动回滚"), + ...field("IPv4 地址 / 掩码", lanInput, "修改网段时会列出旧网段引用;应用后客户端会快速续租,确认期间旧地址会自动跳转到新地址"), ...field("LAN 口", checks(ports, p=>c.lan.ports.includes(p), (p,on)=>setUntagged(p,null,on), p=>wanDevs.has(p)), "WAN 口不能同时做 LAN 口"), ...field("IPv6 RA / SLAAC", inBool(c.lan,"ipv6_ra"), "向 LAN 通告 IPv6 前缀"))), ...c.networks.map(netCard), @@ -298,6 +346,7 @@ registerPage("network", "lan", "LAN 与网络", 20, async ()=>{ c.networks.push({name:k?"net"+(k+1):"guest", ipv4:"192.168."+(20+k*10)+".1/24", zone:"guest", ports:[], vlan:0, trunk:[], ipv6_ra:false, dhcp:{enabled:true, start:100, end:199, lease:"12h"}}); touch(); draw(); }},"+ 添加网络(访客 / IoT / VLAN)"), h("span",{class:"mut"},"WiFi 的 SSID 在“无线设置”里选择加入哪个网络。"))); + }; draw(); return box; }); diff --git a/tools/ci.d/net.sh b/tools/ci.d/net.sh index 2cd05eb..9e28b57 100755 --- a/tools/ci.d/net.sh +++ b/tools/ci.d/net.sh @@ -255,6 +255,15 @@ inC sh "$T/net2.sh" 2> "$T/net.sh.err" || { cat "$T/net.sh.err"; fail "network.s a=$(ip -n "$C" -4 -o addr show dev wan2) has "static address changed" "$a" "inet 10.98.0.3/24" hasnt "static address changed" "$a" "10.98.0.2/" + +# LAN renumber: rerunning network.sh must remove the old bridge address and flap the +# wired LAN port so clients promptly renew DHCP on the new subnet. +sed 's#192\.168\.1\.6/24#192.168.2.1/24#g' "$T/net.sh" > "$T/net-lan-renumber.sh" +inC sh "$T/net-lan-renumber.sh" 2> "$T/net.sh.err" || { cat "$T/net.sh.err"; fail "network.sh (LAN renumber)"; } +lanaddrs=$(ip -n "$C" -4 -o addr show dev br-lan) +has "LAN renumber new address" "$lanaddrs" "192.168.2.1/24" +hasnt "LAN renumber old address" "$lanaddrs" "192.168.1.6/24" +grep -q 'ip link set lan2 down' "$T/net-lan-renumber.sh" || fail "LAN renumber did not flap the wired port" echo "net: functional test ok" step "functional: policy route by domain (dnsmasq nftset -> nft set -> WAN mark), three network namespaces" diff --git a/tools/ci.d/sys.sh b/tools/ci.d/sys.sh index ef9e749..24bb231 100644 --- a/tools/ci.d/sys.sh +++ b/tools/ci.d/sys.sh @@ -176,7 +176,7 @@ for t in home lab; do done # shellcheck disable=SC1091 v=$(. "$L/etc/conf.d/mr-panel"; echo "$PANEL_ADDR") -[ "$v" = 192.168.1.6 ] || fail "PANEL_ADDR=$v" +[ "$v" = 0.0.0.0 ] || fail "PANEL_ADDR=$v" # shellcheck disable=SC1091 v=$(. "$L/etc/conf.d/crond"; echo "$CRON_OPTS|$TZ") [ "$v" = "-c /etc/crontabs|CET-1CEST,M3.5.0,M10.5.0/3" ] || fail "crond conf: $v" From 8975c31ba2075da1926044e16cdd07118961f921 Mon Sep 17 00:00:00 2001 From: Cd1s <135119404+Cd1s@users.noreply.github.com> Date: Sun, 18 Oct 2026 01:13:41 +0800 Subject: [PATCH 2/4] fix: harden LAN renumbering safety --- docs/api.md | 2 +- docs/modules/net.md | 1 + docs/modules/sys.md | 4 ++-- mr/api.go | 10 ++++++++-- mr/api_test.go | 28 ++++++++++++++++++++++++++++ mr/guard.go | 9 +++++++++ mr/guard_test.go | 4 ++++ mr/mod_net_render.go | 19 +++++++++++-------- mr/mod_net_test.go | 6 +++--- mr/mod_sys.go | 8 ++++---- rootfs/etc/init.d/mr-panel | 5 +++-- rootfs/www/ui/core.js | 15 +++++++++------ rootfs/www/ui/lang/en.json | 7 ++++++- rootfs/www/ui/net.js | 12 ++++++++---- tools/ci.d/fw.sh | 4 +++- tools/ci.d/net.sh | 22 ++++++++++++++++++++++ tools/ci.d/sys.sh | 1 + 17 files changed, 123 insertions(+), 34 deletions(-) diff --git a/docs/api.md b/docs/api.md index c1e52bd..b255fcb 100644 --- a/docs/api.md +++ b/docs/api.md @@ -103,6 +103,7 @@ expired token, 403 not allowed, 404 unknown, 405 POST required, 409 conflict, 42 | `POST apply` | `{patch \| yaml \| config, base_rev, confirm (s, default 120), comment, secrets?}` (`yaml`: the whole router.yaml text, written as typed — the web UI's 系统 → router.yaml 原文) → `{ok, confirm}`: the apply job starts; 409 when `base_rev` is stale or another change waits for confirmation | | `GET job` | → `{job: {state: running \| ok \| failed, output}, confirm_pending, pending}` | | `POST confirm` / `POST revert` | keep / undo the pending change (a token: only its own) | +| `GET history`, `POST history.diff {rev}`, `POST rollback {rev}` | revisions; the config from before #rev applied as a new change | When a Web UI apply changes `lan.ipv4`, the response additionally contains `confirm_token` and `confirm_ip`. The browser uses `http://confirm_ip/#confirm=confirm_token` after the old origin goes @@ -110,7 +111,6 @@ away. The token is 256 bits of random data, valid only for this pending apply an window, accepted only by `POST confirm` from a LAN source, and consumed by the first successful confirmation. The pending marker stores only a SHA-256 digest; the raw token is held briefly in a 0600 tmpfs file while the apply worker starts and is never written to the job log or history. -| `GET history`, `POST history.diff {rev}`, `POST rollback {rev}` | revisions; the config from before #rev applied as a new change | `secrets` sets secret values by name (`{"proxy_jp2": "…"}`; empty = keep) — for new credentials; values never come back. `changes` is the config-level diff against the last applied config (`~ path: old → new`, diff --git a/docs/modules/net.md b/docs/modules/net.md index 13eeef3..099583c 100644 --- a/docs/modules/net.md +++ b/docs/modules/net.md @@ -14,6 +14,7 @@ net 负责路由器的"线":物理网口和网桥、LAN 与额外网络(访 | PPPoE(已有) | `pppd` + 生成的 `/etc/ppp/peers/`,服务实例 `mr-pppoe.` | pppd | | DHCP WAN | busybox `udhcpc -f`,服务实例 `mr-udhcpc.`(supervise-daemon 守护);事件脚本 `/usr/libexec/mr/net-udhcpc` → `mr wan dhcp ` 校验租约后配地址、路由、规则、DNS | udhcpc(busybox,≈100 KB) | | 静态 WAN | `network.sh` 配地址,`mr routes` 装默认路由 | 无 | +| LAN / 网络地址更新 | `network.sh` 记录并清理上一次由 mr 写入的网桥地址;同网段换地址先启用 `promote_secondaries`,有线 LAN 口短暂 down/up 触发 DHCP 续租 | 不重启 WiFi;外部工具添加的 secondary 地址保留 | | WAN VLAN | `.` 802.1Q 子接口(PPPoE / DHCP / 静态都可以跑在上面);由 mr 创建的子接口带 `alias mini-router`,取消配置时只清理这类接口 | 无 | | 多线路主备 | `mr-wanmon`:busybox sh 循环,每条线路各自 ping 检测目标;故障线路默认路由 metric +10000,策略路由表去掉默认路由 | sh + 每轮几次 ping | | 负载均衡 | nft `numgen random` 按权重给新 IPv4 连接打 WAN 标记,connmark 保持 | 无(nftables 规则) | diff --git a/docs/modules/sys.md b/docs/modules/sys.md index 0596194..d673636 100644 --- a/docs/modules/sys.md +++ b/docs/modules/sys.md @@ -151,7 +151,7 @@ Validation (the security boundary — everything below ends up in a file, a cron | `/etc/conf.d/ntpd` | `NTPD_OPTS="-N -S /usr/libexec/mr/clock-save -p … [-l]"`(`clock-save` 每小时最多一次把已同步的时间记到闪存,开机时 `mr-clock` 从它恢复——板子没有 RTC) | restart `ntpd` | | `/etc/conf.d/dropbear` (ssh on) | `DROPBEAR_OPTS="-p [addr:]port … -K 300 [-s -g]"` | restart `dropbear` | | `/etc/conf.d/tailscale` (on) | `TS_PORT=` (read by `/etc/init.d/tailscale`) | restart `tailscale` | -| `/etc/conf.d/mr-panel` (on) | `PANEL_ADDR=` main LAN address (was a `sed` on router.yaml) | restart `mr-panel` | +| `/etc/conf.d/mr-panel` (on) | `PANEL_ADDR=0.0.0.0` so both old/new LAN origins remain reachable during confirmation; nftables still restricts WAN input | restart `mr-panel` | | `/etc/conf.d/crond` (schedules) | `CRON_OPTS`, `export TZ=…` | restart `crond` | | `/etc/crontabs/root` | managed block between markers (schedules; DDNS on with an interval adds `*/N * * * * /usr/sbin/mr ddns sync --cron`; the reverse proxy adds `M H * * * /usr/sbin/mr edge renew --cron`, M and H fixed per router, H 2–5; dns.adblock adds `M * * * * /usr/sbin/mr dns adblock update --cron`; `wan[].require_public_ip` adds `* * * * * /usr/sbin/mr wan public-check --cron`; wifi.steering / wifi.self_heal add `* * * * * /usr/sbin/mr wifi tick`); Alpine's periodic lines and anything else kept | — (crond rescans the directory) | | `/etc/mini-router/gen/edge.json` (edge on) | port, WAN port, certificate directory, routes (host, target, certificate name, allow) — nothing secret, 0644 | restart `mr-edge` | @@ -683,7 +683,7 @@ warn); issued and failed certificates are events of type `cert`. * New files: `/etc/localtime` (+08), `/etc/modules-load.d/mr-sys.conf`, `/etc/conf.d/sysctl`, `/etc/conf.d/tailscale` (`TS_PORT=41641`, same as the old hard-coded port), `/etc/conf.d/mr-panel` - (`PANEL_ADDR=192.168.1.6`, what the old `sed` found). The first apply after the update therefore + (`PANEL_ADDR=0.0.0.0`; `mr-panel` requires the nftables firewall before it starts). The first apply after the update therefore restarts `syslog`, `tailscale` and `mr-panel` once. * `conf.d/ntpd`, `conf.d/dropbear`, `90-mini-router.conf`, `hostname`, `tz.sh`: byte-identical. * No crontab, no authorized_keys change (no schedules, no managed keys), crond stays off. diff --git a/mr/api.go b/mr/api.go index dd797bb..7b34a2c 100644 --- a/mr/api.go +++ b/mr/api.go @@ -738,9 +738,11 @@ func apiApply(r apiReq) apiResp { } } if err := writeAtomic(CandidateYAML, y, 0600); err != nil { + os.Remove(confirmTokenFile) return errResp(500, "%v", err) } if err := writeSecrets(CandidateSec, sec); err != nil { + os.Remove(confirmTokenFile) return errResp(500, "%v", err) } writeJob(jobState{State: "running", Started: time.Now().Unix(), Confirm: confirmSecs, Via: via, From: r.remote, Comment: in.Comment, BaseRev: base}) @@ -761,9 +763,13 @@ func runApplyJob(confirmSecs int) error { j0 := readJob() j0.Pid = os.Getpid() writeJob(j0) - tokenBytes, _ := os.ReadFile(confirmTokenFile) + token := "" + if j0.Via == "" || j0.Via == "web UI" { + tokenBytes, _ := os.ReadFile(confirmTokenFile) + token = strings.TrimSpace(string(tokenBytes)) + } os.Remove(confirmTokenFile) - o := applyOpts{Via: j0.Via, From: j0.From, Comment: j0.Comment, BaseRev: j0.BaseRev, ConfirmToken: strings.TrimSpace(string(tokenBytes))} + o := applyOpts{Via: j0.Via, From: j0.From, Comment: j0.Comment, BaseRev: j0.BaseRev, ConfirmToken: token} if o.Via == "" { o.Via = "web UI" } diff --git a/mr/api_test.go b/mr/api_test.go index a1b4574..3bd916e 100644 --- a/mr/api_test.go +++ b/mr/api_test.go @@ -1,6 +1,7 @@ package main import ( + "bytes" "crypto/sha256" "encoding/hex" "encoding/json" @@ -26,6 +27,9 @@ func TestLANConfirmTokenIsScopedAndHashed(t *testing.T) { if err := setPending(pendingApply{Snapshot: "/tmp/snap", State: statePending, Deadline: time.Now().Unix() + 60, ConfirmHash: hex.EncodeToString(h[:])}); err != nil { t.Fatal(err) } + if marker, err := os.ReadFile(ConfirmFile); err != nil || bytes.Contains(marker, []byte(token)) { + t.Fatalf("pending marker contains plaintext token: %q", marker) + } if got := confirmWithToken(token+"x", "192.168.2.44"); got.status != 401 { t.Fatalf("wrong token status = %d, want 401", got.status) } @@ -41,6 +45,30 @@ func TestLANConfirmTokenIsScopedAndHashed(t *testing.T) { } } +func TestLANConfirmTokenSuccessIsOneShotAndLANOnly(t *testing.T) { + _, _, _ = confirmEnv(t) + oldLoad := loadLANConfig + t.Cleanup(func() { loadLANConfig = oldLoad }) + loadLANConfig = func() (*Config, error) { return &Config{LAN: LAN{IPv4: "192.168.2.1/24"}}, nil } + token := newConfirmToken() + h := sha256.Sum256([]byte(token)) + if err := setPending(pendingApply{Snapshot: "/tmp/snap", State: statePending, Deadline: time.Now().Unix() + 60, ConfirmHash: hex.EncodeToString(h[:])}); err != nil { + t.Fatal(err) + } + if got := confirmWithToken(token, "192.168.2.44"); got.status != 0 { + t.Fatalf("valid LAN token status = %d, want success", got.status) + } + if got := confirmWithToken(token, "192.168.2.44"); got.status != 409 { + t.Fatalf("reused token status = %d, want 409", got.status) + } + if err := setPending(pendingApply{Snapshot: "/tmp/snap", State: statePending, Deadline: time.Now().Unix() + 60, ConfirmHash: hex.EncodeToString(h[:])}); err != nil { + t.Fatal(err) + } + if got := confirmWithToken(token, "192.168.9.44"); got.status != 403 { + t.Fatalf("non-LAN token status = %d, want 403", got.status) + } +} + func TestNormalizeRemoteAddrBusyboxFormats(t *testing.T) { for _, tc := range []struct { raw, want string diff --git a/mr/guard.go b/mr/guard.go index 57fef54..36d14b9 100644 --- a/mr/guard.go +++ b/mr/guard.go @@ -74,6 +74,15 @@ func guardValidate(c *Config, v *Validator) { } } } + for _, r := range c.Firewall.Rules { + if r.Dest == "router" && r.Action == "accept" { + for _, p := range ports { + if r.DestPort != "" && portIn(r.DestPort, p) { + v.Add("guard.never_expose: firewall.rules[%s] accepts port %d (%s) towards the router", r.Name, p, s) + } + } + } + } // the HTTPS reverse proxy: a WAN-reachable route to one of these ports on the router itself edgeGuard(c, v, s, ports) } diff --git a/mr/guard_test.go b/mr/guard_test.go index 6035022..769c683 100644 --- a/mr/guard_test.go +++ b/mr/guard_test.go @@ -37,6 +37,10 @@ func TestGuard(t *testing.T) { c.Firewall.Open = append(c.Firewall.Open, Open{Name: "w", Proto: []string{"tcp"}, Port: "80,8080"}) }, "firewall.open[w] opens port 80 (panel)"}, + {"panel accepted by a router rule", func(c *Config) { + c.Firewall.Rules = append(c.Firewall.Rules, FwRule{Name: "panel-rule", Action: "accept", Src: "wan", Dest: "router", Proto: []string{"tcp"}, DestPort: "80"}) + }, + "firewall.rules[panel-rule] accepts port 80 (panel)"}, {"dns forwarded to the router", func(c *Config) { c.Firewall.Forwards = append(c.Firewall.Forwards, Forward{Name: "d", Proto: []string{"udp"}, Port: "5353", To: router, ToPort: "53"}) }, "firewall.forwards[d] forwards to the router's port 53 (dns)"}, diff --git a/mr/mod_net_render.go b/mr/mod_net_render.go index a1a4b0c..e8d649a 100644 --- a/mr/mod_net_render.go +++ b/mr/mod_net_render.go @@ -288,19 +288,22 @@ func netSh(c *Config, phase string, b *strings.Builder) { for _, p := range d.ports { fmt.Fprintf(b, "ip link set %s master %s 2>/dev/null; ip link set %s up\n", p, d.br, p) } - // `ip addr replace` leaves an address from the previous LAN/network behind. Drop - // every old IPv4 after installing the desired one; otherwise the old subnet keeps - // answering ARP and dnsmasq advertises two gateways after a renumber. - fmt.Fprintf(b, "mr_old_%s=0\n", strings.ReplaceAll(d.br, "-", "_")) - fmt.Fprintf(b, "for a in $(ip -4 -o addr show dev %s 2>/dev/null | awk '{print $4}'); do [ \"$a\" = %s ] || mr_old_%s=1; done\n", d.br, d.ipv4, strings.ReplaceAll(d.br, "-", "_")) + // Keep the addresses written by mr in tmpfs. This lets a later apply remove + // only mr's previous address and preserve a secondary address added by an + // administrator or another service. promote_secondaries is required when a + // new address is in the old subnet: without it, deleting the old primary also + // deletes the newly-added secondary on kernels whose default is 0. + fmt.Fprintf(b, "mkdir -p /run/mini-router/net-addresses\n") + fmt.Fprintf(b, "mr_old_br=0; mr_prev=; [ -r /run/mini-router/net-addresses/%s ] && mr_prev=$(cat /run/mini-router/net-addresses/%s)\n", d.br, d.br) + fmt.Fprintf(b, "echo 1 2>/dev/null > /proc/sys/net/ipv4/conf/%s/promote_secondaries\n", d.br) + fmt.Fprintf(b, "for a in $mr_prev; do [ \"$a\" = %s ] || { mr_old_br=1; ip addr del \"$a\" dev %s 2>/dev/null || true; }; done\n", d.ipv4, d.br) fmt.Fprintf(b, "ip addr replace %s dev %s\n", d.ipv4, d.br) - fmt.Fprintf(b, "for a in $(ip -4 -o addr show dev %s 2>/dev/null | awk '{print $4}'); do [ \"$a\" = %s ] || ip addr del \"$a\" dev %s 2>/dev/null || true; done\n", d.br, d.ipv4, d.br) + fmt.Fprintf(b, "printf '%%s\\n' %s > /run/mini-router/net-addresses/%s\n", d.ipv4, d.br) fmt.Fprintf(b, "ip link set %s up\n", d.br) if d.br == c.LAN.Bridge { // A short carrier flap on the wired LAN ports makes DHCP clients renew promptly. // It does not restart WiFi or touch WAN hardware offload. - name := strings.ReplaceAll(d.br, "-", "_") - fmt.Fprintf(b, "if [ \"$mr_old_%s\" = 1 ]; then\n", name) + fmt.Fprintf(b, "if [ \"$mr_old_br\" = 1 ]; then\n") for _, p := range d.ports { fmt.Fprintf(b, "ip link set %s down 2>/dev/null || true; ip link set %s up 2>/dev/null || true\n", p, p) } diff --git a/mr/mod_net_test.go b/mr/mod_net_test.go index 1be4d01..ce0552e 100644 --- a/mr/mod_net_test.go +++ b/mr/mod_net_test.go @@ -125,15 +125,15 @@ func TestNetGeneratedLinkCleanupOnce(t *testing.T) { func TestLANNetworkScriptRemovesOldBridgeAddressesAndRenewsClients(t *testing.T) { c := testConfig(t) sh := renderMap(t, c)[GenDir+"/network.sh"] - if !strings.Contains(sh, "ip addr del \"$a\" dev br-lan") { - t.Fatalf("network.sh does not remove stale br-lan IPv4 addresses:\n%s", sh) + if !strings.Contains(sh, "promote_secondaries") || !strings.Contains(sh, "ip addr del \"$a\" dev br-lan") { + t.Fatalf("network.sh does not safely remove stale br-lan IPv4 addresses:\n%s", sh) } if !strings.Contains(sh, "ip link set lan2 down") || !strings.Contains(sh, "ip link set lan2 up") { t.Fatalf("network.sh does not flap LAN ports after a renumber:\n%s", sh) } if len(c.Networks) > 0 { bridge := c.Networks[0].BridgeName() - if !strings.Contains(sh, "ip addr del \"$a\" dev "+bridge) { + if !strings.Contains(sh, "net-addresses/"+bridge) || !strings.Contains(sh, "ip addr del \"$a\" dev "+bridge) { t.Fatalf("network.sh does not clean extra network bridge addresses:\n%s", sh) } } diff --git a/mr/mod_sys.go b/mr/mod_sys.go index f7fbf7a..addbdca 100644 --- a/mr/mod_sys.go +++ b/mr/mod_sys.go @@ -159,10 +159,10 @@ func sysRender(c *Config, out *Out) error { out.Add("/etc/conf.d/tailscale", 0644, fmt.Sprintf("# generated by mr\nTS_PORT=%d\n", sv.Tailscale.Port)+tsExitConf(c)+tsAdvertiseConf(c)) } if _, _, ok := strings.Cut(c.LAN.IPv4, "/"); ok && sv.Panel.Enabled { - // Keep the panel reachable while a LAN renumber is awaiting confirmation. The - // input firewall still limits port 80 to LAN addresses, so binding all local - // addresses does not expose the panel on WAN interfaces. - out.Add("/etc/conf.d/mr-panel", 0644, "# generated by mr: listen on all local addresses during LAN renumber confirmation\nPANEL_ADDR=0.0.0.0\n") + // Bind all local addresses so a LAN renumber keeps both origins reachable. The + // mr-firewall dependency starts first and its input chain still limits port 80 + // to LAN addresses, so this does not expose the panel on WAN interfaces. + out.Add("/etc/conf.d/mr-panel", 0644, "# generated by mr: all-address listener protected by mr-firewall\nPANEL_ADDR=0.0.0.0\n") } if cronWanted(c) { out.Add("/etc/conf.d/crond", 0644, renderCrondConf(c)) diff --git a/rootfs/etc/init.d/mr-panel b/rootfs/etc/init.d/mr-panel index 9341ed6..f5cb0de 100755 --- a/rootfs/etc/init.d/mr-panel +++ b/rootfs/etc/init.d/mr-panel @@ -8,10 +8,11 @@ respawn_max=10 respawn_period=600 depend() { need mr-network + need mr-firewall } start_pre() { - # PANEL_ADDR: the main LAN address, from /etc/conf.d/mr-panel (rendered by mr from lan.ipv4; - # a LAN address change rewrites it and restarts this service) + # PANEL_ADDR is 0.0.0.0 so a LAN renumber keeps both origins reachable. The firewall + # must be running first (depend() above), and its input chain restricts WAN access. if [ -z "${PANEL_ADDR:-}" ]; then PANEL_ADDR=$(ip -4 -o addr show dev br-lan 2>/dev/null | awk '{split($4, a, "/"); print a[1]; exit}') fi diff --git a/rootfs/www/ui/core.js b/rootfs/www/ui/core.js index 0f0bbf3..e3bfcd1 100644 --- a/rootfs/www/ui/core.js +++ b/rootfs/www/ui/core.js @@ -72,13 +72,15 @@ const clone = o => JSON.parse(JSON.stringify(o)); // ---------- API ---------- async function api(action, body){ - const opt = {method: body===undefined?"GET":"POST", headers:{"X-MR":"1"}, credentials:"same-origin"}; + const ctl = new AbortController(), timer = setTimeout(()=>ctl.abort(), body===undefined?5000:10000); + const opt = {method: body===undefined?"GET":"POST", headers:{"X-MR":"1"}, credentials:"same-origin", signal:ctl.signal}; if (body!==undefined){ opt.headers["Content-Type"]="application/json"; opt.body=JSON.stringify(body); } - const r = await fetch("/cgi-bin/api?a="+action, opt); + let r; + try { r = await fetch("/cgi-bin/api?a="+action, opt); } finally { clearTimeout(timer); } pendingFrom(r); let j = {}; try { j = await r.json(); } catch(e) {} - if (r.status===401 && action!=="login"){ S.auth=false; renderLogin(); throw new Error("未登录"); } - if (!r.ok) { const e=new Error(j.error || (j.errors||[]).join("; ") || ("HTTP "+r.status)); e.data=j; throw e; } + if (r.status===401 && action!=="login" && !(action==="confirm" && body&&body.token)){ S.auth=false; renderLogin(); throw new Error("未登录"); } + if (!r.ok) { const e=new Error(j.error || (j.errors||[]).join("; ") || ("HTTP "+r.status)); e.data=j; e.status=r.status; throw e; } return j; } @@ -586,7 +588,7 @@ async function runJob(start, auto){ let j; try { j = await api("job"); fails = 0; } catch(e){ fails++; - if (handoff && handoff.confirm_token && handoff.confirm_ip && fails === 1) { + if (handoff && handoff.confirm_token && handoff.confirm_ip && fails >= 2) { stateEl.textContent = tr("LAN 地址已切换,正在打开新地址并自动确认…"); const port = location.port ? ":"+location.port : ""; const target = location.protocol+"//"+handoff.confirm_ip+port+"/#confirm="+encodeURIComponent(handoff.confirm_token); @@ -632,13 +634,14 @@ async function runJob(start, auto){ // response supplies a one-time token; the new origin accepts it only for POST /confirm. async function settleHandoff(token){ if (!token) return false; + const root=$("#root"); if(root) root.replaceChildren(h("div",{class:"login"},h("div",{class:"mut"},"正在确认 LAN 变更…"))); for (let i=0; i<125; i++) { try { await api("confirm", {token}); history.replaceState(null, "", location.pathname+location.search+"#overview"); return true; } catch(e) { - if (e.data && e.data.error && /invalid|only allowed|no matching/.test(e.data.error)) break; + if (e.status===401 || e.status===403 || e.status===409) break; await new Promise(resolve=>setTimeout(resolve, 1000)); } } diff --git a/rootfs/www/ui/lang/en.json b/rootfs/www/ui/lang/en.json index 0726c6f..6a48746 100644 --- a/rootfs/www/ui/lang/en.json +++ b/rootfs/www/ui/lang/en.json @@ -201,6 +201,7 @@ "已应用。": "Applied.", " 网络正常的话请点“保留”,否则 ": " If the network works, click “Keep” — ", "立即回滚": "Roll back now", +"正在确认 LAN 变更…": "Confirming the LAN change…", "管理密码": "Admin password", "时区": "Time zone", "WAN 上网方式": "WAN connection", @@ -1052,6 +1053,10 @@ "防火墙规则目标 ": "Firewall rule destination ", "静态路由目标 ": "Static route destination ", "静态路由网关 ": "Static route gateway ", +"LAN 主路由网关": "LAN upstream gateway", +"HTTPS 路由目标 ": "HTTPS route target ", +"HTTPS 路由来源 ": "HTTPS route source ", +"API 令牌来源 ": "API token source ", "DNS 记录 ": "DNS record ", "DHCP 选项 ": "DHCP option ", "LAN 网段变更:同步地址": "LAN subnet changed: synchronize addresses", @@ -1092,7 +1097,7 @@ "代理网段(fake-ip 和规则里的 IP 段)都指向本机。应用后生成;命令行:mr proxy routes": "Proxied ranges (fake-ip and the IP ranges in rules) all point to this router. Generated on apply; CLI: mr proxy routes", "(保存并应用、开启代理后显示)": "(shown after Save & apply with the proxy on)", "LAN(主网络)": "LAN (main network)", -"修改网段时会列出旧网段引用;应用后客户端会快速续租,确认期间旧地址会自动跳转到新地址": "Changing the subnet lists references to the old subnet; clients renew quickly after applying, and the old page redirects to the new address during confirmation", +"修改网段时会列出旧网段引用;有线客户端会快速续租,WiFi 设备需要重新连接,确认期间旧地址会自动跳转到新地址": "Changing the subnet lists old-subnet references; wired clients renew quickly, WiFi devices need to reconnect, and the old address redirects during confirmation", "LAN 口": "LAN ports", "WAN 口不能同时做 LAN 口": "A WAN port cannot also be a LAN port", "向 LAN 通告 IPv6 前缀": "Announce the IPv6 prefix to the LAN", diff --git a/rootfs/www/ui/net.js b/rootfs/www/ui/net.js index 06a11a5..31f979c 100644 --- a/rootfs/www/ui/net.js +++ b/rootfs/www/ui/net.js @@ -246,7 +246,8 @@ function lanIP(s){ return {ip:(+m[1]<<24|+m[2]<<16|+m[3]<<8|+m[4])>>>0,suffix:m[5]===undefined?"":"/"+m[5]}; } function lanDotted(ip){return[(ip>>>24)&255,(ip>>>16)&255,(ip>>>8)&255,ip&255].join(".");} -function lanShiftText(text,oldC,newC){return String(text).replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?\b/g,token=>{ +function lanShiftText(text,oldC,newC){return String(text).replace(/\b(?:\d{1,3}\.){3}\d{1,3}(?:\/\d{1,2})?\b/g,(token,offset,whole)=>{ + if(offset>0&&whole[offset-1]===":")return token; // do not rewrite the IPv4 tail of an IPv4-mapped IPv6 literal const x=lanIP(token);if(!x||((x.ip&oldC.mask)>>>0)!==oldC.net)return token; const off=(x.ip-oldC.net)>>>0,max=newC.bits===32?0:2**(32-newC.bits)-1; return off>max?token:lanDotted((newC.net+off)>>>0)+x.suffix; @@ -264,6 +265,9 @@ function lanRenumberCandidates(c,oldC,newC){ }); (c.policy_routes||[]).forEach((x,i)=>add(`policy_routes[${i}].src`,x,"src",`策略路由 ${x.name||i+1}`)); (c.static_routes||[]).forEach((x,i)=>{add(`static_routes[${i}].target`,x,"target",`静态路由目标 ${x.name||i+1}`);add(`static_routes[${i}].via`,x,"via",`静态路由网关 ${x.name||i+1}`);}); + add("lan.gateway",c.lan,"gateway","LAN 主路由网关"); + (c.services?.edge?.routes||[]).forEach((x,i)=>{add(`services.edge.routes[${i}].to`,x,"to",`HTTPS 路由目标 ${x.name||i+1}`);(x.allow||[]).forEach((_,j)=>add(`services.edge.routes[${i}].allow[${j}]`,x.allow,j,`HTTPS 路由来源 ${x.name||i+1}`));}); + (c.api?.tokens||[]).forEach((x,i)=>(x.from||[]).forEach((_,j)=>add(`api.tokens[${i}].from[${j}]`,x.from,j,`API 令牌来源 ${x.name||i+1}`))); (c.dns?.records||[]).forEach((x,i)=>{if(String(x.type||"").toUpperCase()==="A")add(`dns.records[${i}].value`,x,"value",`DNS 记录 ${x.name||i+1}`);}); (c.dhcp?.dns||[]).forEach((_,i)=>add(`dhcp.dns[${i}]`,c.dhcp.dns,i,"DNS DHCP "+(i+1))); (c.dhcp?.ntp||[]).forEach((_,i)=>add(`dhcp.ntp[${i}]`,c.dhcp.ntp,i,"NTP DHCP "+(i+1))); @@ -330,14 +334,14 @@ registerPage("network", "lan", "LAN 与网络", 20, async ()=>{ }; const onEdit = (el, fn)=>{ el.addEventListener("input", fn); el.addEventListener("change", fn); return el; }; const draw = ()=>{ - const oldLAN=c.lan.ipv4; + let oldLAN=c.lan.ipv4; const lanInput=inText(c.lan,"ipv4",{placeholder:"192.168.1.1/24"}); - lanInput.addEventListener("change",()=>lanRenumberPrompt(c,oldLAN,c.lan.ipv4)); + lanInput.addEventListener("change",()=>{lanRenumberPrompt(c,oldLAN,c.lan.ipv4);oldLAN=c.lan.ipv4;}); box.replaceChildren( modeCard(), card("LAN(主网络)", form( ...field("网桥", inText(c.lan,"bridge")), - ...field("IPv4 地址 / 掩码", lanInput, "修改网段时会列出旧网段引用;应用后客户端会快速续租,确认期间旧地址会自动跳转到新地址"), + ...field("IPv4 地址 / 掩码", lanInput, "修改网段时会列出旧网段引用;有线客户端会快速续租,WiFi 设备需要重新连接,确认期间旧地址会自动跳转到新地址"), ...field("LAN 口", checks(ports, p=>c.lan.ports.includes(p), (p,on)=>setUntagged(p,null,on), p=>wanDevs.has(p)), "WAN 口不能同时做 LAN 口"), ...field("IPv6 RA / SLAAC", inBool(c.lan,"ipv6_ra"), "向 LAN 通告 IPv6 前缀"))), ...c.networks.map(netCard), diff --git a/tools/ci.d/fw.sh b/tools/ci.d/fw.sh index 840e277..fb98b0c 100644 --- a/tools/ci.d/fw.sh +++ b/tools/ci.d/fw.sh @@ -255,7 +255,9 @@ ip -n "$L2" -6 route replace default via 2001:db8:1::1 ok "$W" 203.0.113.1 4443 "WAN -> open port 4443 (IPv4)" ok "$W" 2001:db8:ffff::1 4443 "WAN -> open port 4443 (IPv6)" blocked "$W" 203.0.113.1 22 "WAN -> router SSH dropped" "" "TimeoutError" -blocked "$W" 203.0.113.1 80 "WAN -> router web UI dropped" +blocked "$W" 203.0.113.1 80 "PPPoE WAN -> router web UI dropped (IPv4)" +blocked "$W" 2001:db8:ffff::1 80 "PPPoE WAN -> router web UI dropped (IPv6)" +blocked "$W" 198.51.100.1 80 "WAN2 -> router web UI dropped" blocked "$W" 198.51.100.1 53 "WAN2 -> router DNS dropped" # port forwards ok "$W" 203.0.113.1 7443 "forward 7443 -> desktop:9999" "" "ok from 203.0.113.2" diff --git a/tools/ci.d/net.sh b/tools/ci.d/net.sh index 9e28b57..144c1cb 100755 --- a/tools/ci.d/net.sh +++ b/tools/ci.d/net.sh @@ -124,6 +124,28 @@ has "rules" "$rules" "5300:.*fwmark 0x201 lookup 201" has "wan2 static address" "$(ip -n "$C" -4 addr show dev wan2 2> /dev/null)" "inet 10.98.0.2/24" has "br-lan" "$(ip -n "$C" -4 addr show dev br-lan)" "inet 192.168.1.6/24" +# LAN address changes: keep an address supplied by another tool, and exercise the +# kernel's promote_secondaries=0 path for same-subnet, subnet, and prefix changes. +ip -n "$C" addr add 192.168.1.250/32 dev br-lan +inC sh -c 'echo 0 > /proc/sys/net/ipv4/conf/br-lan/promote_secondaries' +sed 's#192\.168\.1\.6/24#192.168\.1\.1/24#g' "$T/net.sh" > "$T/net-lan-same.sh" +inC sh "$T/net-lan-same.sh" 2> "$T/net.sh.err" || { cat "$T/net.sh.err"; fail "network.sh (same-subnet LAN address)"; } +lanaddrs=$(ip -n "$C" -4 -o addr show dev br-lan) +has "LAN same-subnet new address" "$lanaddrs" "192.168.1.1/24" +hasnt "LAN same-subnet old address" "$lanaddrs" "192.168.1.6/24" +has "LAN external address kept" "$lanaddrs" "192.168.1.250/32" +sed 's#192\.168\.1\.6/24#192\.168\.2\.1/24#g' "$T/net.sh" > "$T/net-lan-change.sh" +inC sh "$T/net-lan-change.sh" 2> "$T/net.sh.err" || { cat "$T/net.sh.err"; fail "network.sh (LAN subnet change)"; } +lanaddrs=$(ip -n "$C" -4 -o addr show dev br-lan) +has "LAN subnet new address" "$lanaddrs" "192.168.2.1/24" +hasnt "LAN subnet old address" "$lanaddrs" "192.168.1.1/24" +has "LAN external address kept after subnet change" "$lanaddrs" "192.168.1.250/32" +sed 's#192\.168\.1\.6/24#192.168.0.1/16#g' "$T/net.sh" > "$T/net-lan-prefix.sh" +inC sh "$T/net-lan-prefix.sh" 2> "$T/net.sh.err" || { cat "$T/net.sh.err"; fail "network.sh (LAN prefix change)"; } +lanaddrs=$(ip -n "$C" -4 -o addr show dev br-lan) +has "LAN prefix new address" "$lanaddrs" "192.168.0.1/16" +has "LAN external address kept after prefix change" "$lanaddrs" "192.168.1.250/32" + # DHCP: the real busybox udhcpc with the real event script → `mr wan dhcp bound` inC busybox udhcpc -f -q -n -t 5 -T 1 -i wan -s "$ROOT/rootfs/usr/libexec/mr/net-udhcpc" > "$T/udhcpc.log" 2>&1 || { cat "$T/udhcpc.log" diff --git a/tools/ci.d/sys.sh b/tools/ci.d/sys.sh index 4e7c773..2586433 100644 --- a/tools/ci.d/sys.sh +++ b/tools/ci.d/sys.sh @@ -181,6 +181,7 @@ done # shellcheck disable=SC1091 v=$(. "$L/etc/conf.d/mr-panel"; echo "$PANEL_ADDR") [ "$v" = 0.0.0.0 ] || fail "PANEL_ADDR=$v" +grep -q 'need mr-firewall' "$ROOT/rootfs/etc/init.d/mr-panel" || fail "mr-panel does not require mr-firewall" # shellcheck disable=SC1091 v=$(. "$L/etc/conf.d/crond"; echo "$CRON_OPTS|$TZ") [ "$v" = "-c /etc/crontabs|CET-1CEST,M3.5.0,M10.5.0/3" ] || fail "crond conf: $v" From 79f94a2baf678c3431e3ff69cf741c63242396cc Mon Sep 17 00:00:00 2001 From: Cd1s <135119404+Cd1s@users.noreply.github.com> Date: Sun, 18 Oct 2026 01:20:44 +0800 Subject: [PATCH 3/4] fix: close LAN handoff edge cases --- mr/api.go | 61 ++++++++++++++++++++++++++++++++++++-------------- mr/api_test.go | 9 ++++++++ mr/apply.go | 8 ++++++- 3 files changed, 60 insertions(+), 18 deletions(-) diff --git a/mr/api.go b/mr/api.go index 7b34a2c..91a206d 100644 --- a/mr/api.go +++ b/mr/api.go @@ -135,6 +135,29 @@ func lanIPv4Host(cidr string) string { return ip.To4().String() } +// prepareLANConfirmToken stages the raw token only for browser-originated changes +// that can strand the current origin, including web rollbacks. API-token and CLI +// changes keep their existing confirmation semantics. +func prepareLANConfirmToken(candidate, via string) (string, string, error) { + os.Remove(confirmTokenFile) + if via != "web UI" && via != "rollback" { + return "", "", nil + } + live, err := loadConfig(ConfigPath, SecretsPath) + if err != nil { + return "", "", nil + } + next, err := loadConfig(candidate, CandidateSec) + if err != nil || live.LAN.IPv4 == next.LAN.IPv4 { + return "", "", nil + } + token := newConfirmToken() + if token == "" || writeAtomic(confirmTokenFile, []byte(token), 0600) != nil { + return "", "", errors.New("cannot create LAN confirmation token") + } + return token, lanIPv4Host(next.LAN.IPv4), nil +} + // confirmWithToken is deliberately separate from the normal session path. The token // is scoped to the current pending marker, expires with it, is accepted only here, // and is consumed by confirm (which removes the marker atomically under its lock). @@ -149,6 +172,8 @@ func confirmWithToken(token, remote string) apiResp { if !okLAN { return errResp(403, "confirmation is only allowed from the LAN") } + unlock := lockPending() + defer unlock() p, err := readPending() if err != nil || p.ConfirmHash == "" || p.left() <= 0 { return errResp(409, "no matching LAN confirmation is pending") @@ -158,7 +183,7 @@ func confirmWithToken(token, remote string) apiResp { if err != nil || subtle.ConstantTimeCompare(want, h[:]) != 1 { return errResp(401, "invalid confirmation token") } - ok, err := confirm() + ok, err := confirmLocked() if err != nil { return errResp(409, "%v", err) } @@ -717,6 +742,7 @@ func apiApply(r apiReq) apiResp { return errResp(400, "comment: one line, at most 200 characters") } os.MkdirAll(RunDir, 0700) + os.Remove(confirmTokenFile) if len(in.Patch) == 0 && in.YAML == "" { y = uiConfigYAML(y, c) // a patch's text is already the live file with only its edits; raw text stays as typed } @@ -724,27 +750,19 @@ func apiApply(r apiReq) apiResp { if via == "" { via = "web UI" } - // Keep the raw handoff token only in a root-readable tmpfs file while the apply - // worker starts. The persistent pending marker stores its SHA-256 digest only. - confirmToken, confirmIP := "", "" - if via == "web UI" { - os.Remove(confirmTokenFile) - if live, e := loadConfig(ConfigPath, SecretsPath); e == nil && live.LAN.IPv4 != c.LAN.IPv4 { - confirmToken = newConfirmToken() - if confirmToken == "" || writeAtomic(confirmTokenFile, []byte(confirmToken), 0600) != nil { - return errResp(500, "cannot create LAN confirmation token") - } - confirmIP = lanIPv4Host(c.LAN.IPv4) - } - } if err := writeAtomic(CandidateYAML, y, 0600); err != nil { - os.Remove(confirmTokenFile) return errResp(500, "%v", err) } if err := writeSecrets(CandidateSec, sec); err != nil { os.Remove(confirmTokenFile) return errResp(500, "%v", err) } + // Keep the raw handoff token only in a root-readable tmpfs file while the apply + // worker starts. The persistent pending marker stores its SHA-256 digest only. + confirmToken, confirmIP, tokenErr := prepareLANConfirmToken(CandidateYAML, via) + if tokenErr != nil { + return errResp(500, "%v", tokenErr) + } writeJob(jobState{State: "running", Started: time.Now().Unix(), Confirm: confirmSecs, Via: via, From: r.remote, Comment: in.Comment, BaseRev: base}) self, _ := os.Executable() startDetached(self, "apply-job", strconv.Itoa(confirmSecs)) @@ -764,7 +782,7 @@ func runApplyJob(confirmSecs int) error { j0.Pid = os.Getpid() writeJob(j0) token := "" - if j0.Via == "" || j0.Via == "web UI" { + if j0.Via == "" || j0.Via == "web UI" || j0.Via == "rollback" { tokenBytes, _ := os.ReadFile(confirmTokenFile) token = strings.TrimSpace(string(tokenBytes)) } @@ -930,10 +948,19 @@ func apiRollback(r apiReq) apiResp { if r.via != "" { via = r.via // an API token (the comment says what it is): it may confirm its own rollback } + confirmToken, confirmIP, tokenErr := prepareLANConfirmToken(CandidateYAML, via) + if tokenErr != nil { + return errResp(500, "%v", tokenErr) + } writeJob(jobState{State: "running", Started: time.Now().Unix(), Confirm: 120, Via: via, From: r.remote, Comment: comment}) self, _ := os.Executable() startDetached(self, "apply-job", "120") - return apiResp{body: map[string]any{"ok": true, "confirm": 120}} + body := map[string]any{"ok": true, "confirm": 120} + if confirmToken != "" { + body["confirm_token"] = confirmToken + body["confirm_ip"] = confirmIP + } + return apiResp{body: body} } func apiLogs() apiResp { diff --git a/mr/api_test.go b/mr/api_test.go index 3bd916e..79bd067 100644 --- a/mr/api_test.go +++ b/mr/api_test.go @@ -67,6 +67,15 @@ func TestLANConfirmTokenSuccessIsOneShotAndLANOnly(t *testing.T) { if got := confirmWithToken(token, "192.168.9.44"); got.status != 403 { t.Fatalf("non-LAN token status = %d, want 403", got.status) } + if err := setPending(pendingApply{Snapshot: "/tmp/snap", State: statePending, Deadline: time.Now().Unix() - 1, ConfirmHash: hex.EncodeToString(h[:])}); err != nil { + t.Fatal(err) + } + if got := confirmWithToken(token, "192.168.2.44"); got.status != 409 { + t.Fatalf("expired token status = %d, want 409", got.status) + } + if got := handleAPI(apiReq{method: "GET", action: "confirm", header: "1", remote: "192.168.2.44", body: []byte(`{"token":"` + token + `"}`)}); got.status == 0 { + t.Fatal("GET confirmation unexpectedly succeeded") + } } func TestNormalizeRemoteAddrBusyboxFormats(t *testing.T) { diff --git a/mr/apply.go b/mr/apply.go index acdd5e3..8aca918 100644 --- a/mr/apply.go +++ b/mr/apply.go @@ -1049,6 +1049,13 @@ func rollbackIfUnconfirmed(snap string, secs int) error { func confirm() (bool, error) { unlock := lockPending() defer unlock() + return confirmLocked() +} + +// confirmLocked is confirm's state transition with lockPending already held. Token +// confirmation uses the same lock while checking the digest, so a token cannot race +// a timer or a second pending change between validation and consumption. +func confirmLocked() (bool, error) { p, err := readPending() if errors.Is(err, fs.ErrNotExist) { return false, nil @@ -1070,7 +1077,6 @@ func confirm() (bool, error) { } clearPending("") // an unreadable marker too: `mr confirm` is the way out acceptStaged() - unlock() if commitCfg != nil { if commitErr := netCommit(commitCfg); commitErr != nil { logf("net: post-confirm cleanup: %v", commitErr) From dd173d856edcbe8d4dbcc5df6b6efd6baa1620ad Mon Sep 17 00:00:00 2001 From: Cd1s <135119404+Cd1s@users.noreply.github.com> Date: Sun, 18 Oct 2026 01:40:25 +0800 Subject: [PATCH 4/4] fix: scope LAN handoff timeout and guard panel rules --- docs/modules/sys.md | 6 +++--- mr/api.go | 7 ++++-- mr/apply.go | 41 +++++++++++++++++++++++++----------- mr/guard.go | 15 ++++++++++++- mr/guard_test.go | 15 ++++++++++++- mr/mod_sys.go | 4 ++-- rootfs/etc/init.d/mr-panel | 9 ++++++-- rootfs/www/ui/core.js | 19 ++++++++++------- tools/ci.d/sys.sh | 2 +- tools/ci.sh | 1 + tools/mock/lan-shift.test.js | 26 +++++++++++++++++++++++ 11 files changed, 113 insertions(+), 32 deletions(-) create mode 100644 tools/mock/lan-shift.test.js diff --git a/docs/modules/sys.md b/docs/modules/sys.md index d673636..97de555 100644 --- a/docs/modules/sys.md +++ b/docs/modules/sys.md @@ -50,7 +50,7 @@ services: lan_only: false # true: listen only on the IPv4 address of every LAN-zone network authorized_keys: # managed block in /root/.ssh/authorized_keys (other lines are never touched) - ssh-ed25519 AAAAC3Nza... me@laptop - panel: {enabled: true} # web UI (busybox httpd on the main LAN address, port 80) + panel: {enabled: true} # web UI (busybox httpd on all addresses while nftables is loaded, port 80) ddns: # dynamic DNS, no daemon (see "DDNS" below) enabled: true interval: 10 # minutes between safety checks by crond (5-60); 0 = only on WAN events @@ -151,7 +151,7 @@ Validation (the security boundary — everything below ends up in a file, a cron | `/etc/conf.d/ntpd` | `NTPD_OPTS="-N -S /usr/libexec/mr/clock-save -p … [-l]"`(`clock-save` 每小时最多一次把已同步的时间记到闪存,开机时 `mr-clock` 从它恢复——板子没有 RTC) | restart `ntpd` | | `/etc/conf.d/dropbear` (ssh on) | `DROPBEAR_OPTS="-p [addr:]port … -K 300 [-s -g]"` | restart `dropbear` | | `/etc/conf.d/tailscale` (on) | `TS_PORT=` (read by `/etc/init.d/tailscale`) | restart `tailscale` | -| `/etc/conf.d/mr-panel` (on) | `PANEL_ADDR=0.0.0.0` so both old/new LAN origins remain reachable during confirmation; nftables still restricts WAN input | restart `mr-panel` | +| `/etc/conf.d/mr-panel` (on) | `PANEL_ADDR=0.0.0.0` so both old/new LAN origins remain reachable; when nftables is absent, init falls back to the LAN address for repair | restart `mr-panel` | | `/etc/conf.d/crond` (schedules) | `CRON_OPTS`, `export TZ=…` | restart `crond` | | `/etc/crontabs/root` | managed block between markers (schedules; DDNS on with an interval adds `*/N * * * * /usr/sbin/mr ddns sync --cron`; the reverse proxy adds `M H * * * /usr/sbin/mr edge renew --cron`, M and H fixed per router, H 2–5; dns.adblock adds `M * * * * /usr/sbin/mr dns adblock update --cron`; `wan[].require_public_ip` adds `* * * * * /usr/sbin/mr wan public-check --cron`; wifi.steering / wifi.self_heal add `* * * * * /usr/sbin/mr wifi tick`); Alpine's periodic lines and anything else kept | — (crond rescans the directory) | | `/etc/mini-router/gen/edge.json` (edge on) | port, WAN port, certificate directory, routes (host, target, certificate name, allow) — nothing secret, 0644 | restart `mr-edge` | @@ -683,7 +683,7 @@ warn); issued and failed certificates are events of type `cert`. * New files: `/etc/localtime` (+08), `/etc/modules-load.d/mr-sys.conf`, `/etc/conf.d/sysctl`, `/etc/conf.d/tailscale` (`TS_PORT=41641`, same as the old hard-coded port), `/etc/conf.d/mr-panel` - (`PANEL_ADDR=0.0.0.0`; `mr-panel` requires the nftables firewall before it starts). The first apply after the update therefore + (`PANEL_ADDR=0.0.0.0`; `mr-panel` starts after the nftables firewall and falls back to the LAN address if its table is absent). The first apply after the update therefore restarts `syslog`, `tailscale` and `mr-panel` once. * `conf.d/ntpd`, `conf.d/dropbear`, `90-mini-router.conf`, `hostname`, `tz.sh`: byte-identical. * No crontab, no authorized_keys change (no schedules, no managed keys), crond stays off. diff --git a/mr/api.go b/mr/api.go index 91a206d..f39bd00 100644 --- a/mr/api.go +++ b/mr/api.go @@ -173,17 +173,20 @@ func confirmWithToken(token, remote string) apiResp { return errResp(403, "confirmation is only allowed from the LAN") } unlock := lockPending() - defer unlock() p, err := readPending() if err != nil || p.ConfirmHash == "" || p.left() <= 0 { + unlock() return errResp(409, "no matching LAN confirmation is pending") } h := sha256.Sum256([]byte(token)) want, err := hex.DecodeString(p.ConfirmHash) if err != nil || subtle.ConstantTimeCompare(want, h[:]) != 1 { + unlock() return errResp(401, "invalid confirmation token") } - ok, err := confirmLocked() + r := confirmTransition() + unlock() + ok, err := finishConfirm(r) if err != nil { return errResp(409, "%v", err) } diff --git a/mr/apply.go b/mr/apply.go index 8aca918..4d07849 100644 --- a/mr/apply.go +++ b/mr/apply.go @@ -1048,23 +1048,31 @@ func rollbackIfUnconfirmed(snap string, secs int) error { // confirm keeps the pending change; false: there was none. func confirm() (bool, error) { unlock := lockPending() - defer unlock() - return confirmLocked() + r := confirmTransition() + unlock() + return finishConfirm(r) +} + +type confirmResult struct { + ok bool + err error + commitCfg *Config + snapshot string } -// confirmLocked is confirm's state transition with lockPending already held. Token +// confirmTransition is confirm's state transition with lockPending already held. Token // confirmation uses the same lock while checking the digest, so a token cannot race // a timer or a second pending change between validation and consumption. -func confirmLocked() (bool, error) { +func confirmTransition() confirmResult { p, err := readPending() if errors.Is(err, fs.ErrNotExist) { - return false, nil + return confirmResult{} } if err == nil && p.State == stateApplying { - return false, errors.New("the apply is still running: confirm it when it has finished") + return confirmResult{err: errors.New("the apply is still running: confirm it when it has finished")} } if err == nil && p.State == stateReverting { - return false, errors.New("the change is being rolled back") + return confirmResult{err: errors.New("the change is being rolled back")} } var commitCfg *Config if err == nil { @@ -1077,15 +1085,24 @@ func confirmLocked() (bool, error) { } clearPending("") // an unreadable marker too: `mr confirm` is the way out acceptStaged() - if commitCfg != nil { - if commitErr := netCommit(commitCfg); commitErr != nil { + return confirmResult{ok: true, commitCfg: commitCfg, snapshot: func() string { + if p != nil { + return p.Snapshot + } + return "" + }()} +} + +func finishConfirm(r confirmResult) (bool, error) { + if r.commitCfg != nil { + if commitErr := netCommit(r.commitCfg); commitErr != nil { logf("net: post-confirm cleanup: %v", commitErr) } } - if err == nil { - setResult(p.Snapshot, "confirmed") + if r.err == nil && r.snapshot != "" { + setResult(r.snapshot, "confirmed") } - return true, nil + return r.ok, r.err } // rollbackCommand is `mr rollback [--boot] [SNAPSHOT]`. diff --git a/mr/guard.go b/mr/guard.go index 36d14b9..1ace624 100644 --- a/mr/guard.go +++ b/mr/guard.go @@ -75,9 +75,12 @@ func guardValidate(c *Config, v *Validator) { } } for _, r := range c.Firewall.Rules { + if r.Enabled != nil && !*r.Enabled || r.Dest != "router" || r.Action != "accept" || !panelRuleTCP(r.Proto) { + continue + } if r.Dest == "router" && r.Action == "accept" { for _, p := range ports { - if r.DestPort != "" && portIn(r.DestPort, p) { + if r.DestPort == "" || portIn(r.DestPort, p) { v.Add("guard.never_expose: firewall.rules[%s] accepts port %d (%s) towards the router", r.Name, p, s) } } @@ -123,6 +126,16 @@ func guardValidate(c *Config, v *Validator) { } } +func panelRuleTCP(proto []string) bool { + if len(proto) == 1 { + return proto[0] == "tcp" + } + if len(proto) == 2 { + return (proto[0] == "tcp" && proto[1] == "udp") || (proto[0] == "udp" && proto[1] == "tcp") + } + return false +} + // portIn: whether port p is in a port spec ("443", "8000-8100", "80,443", ""). func portIn(spec string, p int) bool { for _, part := range strings.Split(spec, ",") { diff --git a/mr/guard_test.go b/mr/guard_test.go index 769c683..3b40373 100644 --- a/mr/guard_test.go +++ b/mr/guard_test.go @@ -41,6 +41,17 @@ func TestGuard(t *testing.T) { c.Firewall.Rules = append(c.Firewall.Rules, FwRule{Name: "panel-rule", Action: "accept", Src: "wan", Dest: "router", Proto: []string{"tcp"}, DestPort: "80"}) }, "firewall.rules[panel-rule] accepts port 80 (panel)"}, + {"panel any TCP port", func(c *Config) { + c.Firewall.Rules = append(c.Firewall.Rules, FwRule{Name: "panel-any", Action: "accept", Src: "wan", Dest: "router", Proto: []string{"tcp"}}) + }, + "firewall.rules[panel-any] accepts port 80 (panel)"}, + {"disabled panel rule allowed", func(c *Config) { + off := false + c.Firewall.Rules = append(c.Firewall.Rules, FwRule{Name: "panel-off", Enabled: &off, Action: "accept", Src: "wan", Dest: "router", Proto: []string{"tcp"}}) + }, ""}, + {"UDP-only panel rule ignored", func(c *Config) { + c.Firewall.Rules = append(c.Firewall.Rules, FwRule{Name: "panel-udp", Action: "accept", Src: "wan", Dest: "router", Proto: []string{"udp"}}) + }, ""}, {"dns forwarded to the router", func(c *Config) { c.Firewall.Forwards = append(c.Firewall.Forwards, Forward{Name: "d", Proto: []string{"udp"}, Port: "5353", To: router, ToPort: "53"}) }, "firewall.forwards[d] forwards to the router's port 53 (dns)"}, @@ -55,7 +66,9 @@ func TestGuard(t *testing.T) { } { c := base() tc.mod(c) - if e := guardErrs(c); !strings.Contains(e, tc.want) { + if e := guardErrs(c); tc.want == "" && e != "" { + t.Errorf("%s: unexpected guard error %q", tc.name, e) + } else if tc.want != "" && !strings.Contains(e, tc.want) { t.Errorf("%s: got %q, want %q", tc.name, e, tc.want) } } diff --git a/mr/mod_sys.go b/mr/mod_sys.go index addbdca..5e650e4 100644 --- a/mr/mod_sys.go +++ b/mr/mod_sys.go @@ -160,8 +160,8 @@ func sysRender(c *Config, out *Out) error { } if _, _, ok := strings.Cut(c.LAN.IPv4, "/"); ok && sv.Panel.Enabled { // Bind all local addresses so a LAN renumber keeps both origins reachable. The - // mr-firewall dependency starts first and its input chain still limits port 80 - // to LAN addresses, so this does not expose the panel on WAN interfaces. + // mr-panel normally starts after mr-firewall. Its init script falls back to the + // LAN address if the nft input chain is absent, preserving a repair path. out.Add("/etc/conf.d/mr-panel", 0644, "# generated by mr: all-address listener protected by mr-firewall\nPANEL_ADDR=0.0.0.0\n") } if cronWanted(c) { diff --git a/rootfs/etc/init.d/mr-panel b/rootfs/etc/init.d/mr-panel index f5cb0de..bf06dfc 100755 --- a/rootfs/etc/init.d/mr-panel +++ b/rootfs/etc/init.d/mr-panel @@ -8,11 +8,16 @@ respawn_max=10 respawn_period=600 depend() { need mr-network - need mr-firewall + after mr-firewall } start_pre() { # PANEL_ADDR is 0.0.0.0 so a LAN renumber keeps both origins reachable. The firewall - # must be running first (depend() above), and its input chain restricts WAN access. + # normally starts first (depend() above). If its table is absent, bind only the LAN + # address so an operator can repair the firewall without exposing the panel on WAN. + if [ "${PANEL_ADDR:-}" = 0.0.0.0 ] && ! nft list chain inet mr input >/dev/null 2>&1; then + PANEL_ADDR=$(ip -4 -o addr show dev br-lan 2>/dev/null | awk '{split($4, a, "/"); print a[1]; exit}') + ewarn "firewall not loaded: web UI listens on the LAN address only" + fi if [ -z "${PANEL_ADDR:-}" ]; then PANEL_ADDR=$(ip -4 -o addr show dev br-lan 2>/dev/null | awk '{split($4, a, "/"); print a[1]; exit}') fi diff --git a/rootfs/www/ui/core.js b/rootfs/www/ui/core.js index e3bfcd1..7855423 100644 --- a/rootfs/www/ui/core.js +++ b/rootfs/www/ui/core.js @@ -71,12 +71,15 @@ function fmtDur(s){ s=Math.floor(+s||0); const d=Math.floor(s/86400),hh=Math.flo const clone = o => JSON.parse(JSON.stringify(o)); // ---------- API ---------- -async function api(action, body){ - const ctl = new AbortController(), timer = setTimeout(()=>ctl.abort(), body===undefined?5000:10000); - const opt = {method: body===undefined?"GET":"POST", headers:{"X-MR":"1"}, credentials:"same-origin", signal:ctl.signal}; +async function api(action, body, opts){ + opts ||= {}; + const ctl = opts.timeout ? new AbortController() : null; + const timer = ctl ? setTimeout(()=>ctl.abort(), opts.timeout) : null; + const opt = {method: body===undefined?"GET":"POST", headers:{"X-MR":"1"}, credentials:"same-origin"}; + if (ctl) opt.signal = ctl.signal; if (body!==undefined){ opt.headers["Content-Type"]="application/json"; opt.body=JSON.stringify(body); } let r; - try { r = await fetch("/cgi-bin/api?a="+action, opt); } finally { clearTimeout(timer); } + try { r = await fetch("/cgi-bin/api?a="+action, opt); } finally { if (timer) clearTimeout(timer); } pendingFrom(r); let j = {}; try { j = await r.json(); } catch(e) {} if (r.status===401 && action!=="login" && !(action==="confirm" && body&&body.token)){ S.auth=false; renderLogin(); throw new Error("未登录"); } @@ -109,14 +112,14 @@ function drawPending(){ b.replaceChildren( h("span",{class:"t"}, h("b",{},"有待确认的更改"), "("+via+")", p.state==="pending" ? [":", h("span",{id:"pleft"}, pendLeft()+" 秒"), "后自动回滚。"] : "。", h("span",{class:"mut"}," 确认前不能应用新的更改。")), h("button",{class:"btn sm d",onclick:async()=>{ if(!confirm("回滚这次更改("+via+")?")) return; - try { await api("revert",{}); toast("正在回滚…",4000); setTimeout(()=>api("job").then(reload).catch(()=>{}), 5000); } catch(e){ toast(e.message,4000); } }},"回滚"), + try { await api("revert",{}); toast("正在回滚…",4000); setTimeout(()=>api("job",undefined,{timeout:5000}).then(reload).catch(()=>{}), 5000); } catch(e){ toast(e.message,4000); } }},"回滚"), h("button",{class:"btn sm p",onclick:async()=>{ try { await api("confirm",{}); toast("已保留新配置"); await api("job"); await reload(); } catch(e){ toast(e.message,4000); } }},"保留")); } setInterval(()=>{ if (!S.auth) return; const e = $("#pleft"); if (e && S.pend) e.textContent = tr(pendLeft()+" 秒"); - if (Date.now()-(S.apiAt||0) > 10000) api("job").catch(()=>{}); + if (Date.now()-(S.apiAt||0) > 10000) api("job",undefined,{timeout:5000}).catch(()=>{}); }, 1000); // ---------- state ---------- @@ -586,7 +589,7 @@ async function runJob(start, auto){ let seenOk = 0, fails = 0; const poll = async ()=>{ let j; - try { j = await api("job"); fails = 0; } catch(e){ + try { j = await api("job",undefined,{timeout:5000}); fails = 0; } catch(e){ fails++; if (handoff && handoff.confirm_token && handoff.confirm_ip && fails >= 2) { stateEl.textContent = tr("LAN 地址已切换,正在打开新地址并自动确认…"); @@ -637,7 +640,7 @@ async function settleHandoff(token){ const root=$("#root"); if(root) root.replaceChildren(h("div",{class:"login"},h("div",{class:"mut"},"正在确认 LAN 变更…"))); for (let i=0; i<125; i++) { try { - await api("confirm", {token}); + await api("confirm", {token}, {timeout:10000}); history.replaceState(null, "", location.pathname+location.search+"#overview"); return true; } catch(e) { diff --git a/tools/ci.d/sys.sh b/tools/ci.d/sys.sh index 2586433..7e54b5a 100644 --- a/tools/ci.d/sys.sh +++ b/tools/ci.d/sys.sh @@ -181,7 +181,7 @@ done # shellcheck disable=SC1091 v=$(. "$L/etc/conf.d/mr-panel"; echo "$PANEL_ADDR") [ "$v" = 0.0.0.0 ] || fail "PANEL_ADDR=$v" -grep -q 'need mr-firewall' "$ROOT/rootfs/etc/init.d/mr-panel" || fail "mr-panel does not require mr-firewall" +grep -q 'after mr-firewall' "$ROOT/rootfs/etc/init.d/mr-panel" || fail "mr-panel does not start after mr-firewall" # shellcheck disable=SC1091 v=$(. "$L/etc/conf.d/crond"; echo "$CRON_OPTS|$TZ") [ "$v" = "-c /etc/crontabs|CET-1CEST,M3.5.0,M10.5.0/3" ] || fail "crond conf: $v" diff --git a/tools/ci.sh b/tools/ci.sh index c7b831f..1a37da7 100755 --- a/tools/ci.sh +++ b/tools/ci.sh @@ -76,6 +76,7 @@ shellcheck -s sh -S warning -e SC2034,SC2154,SC3043 $files rootfs/etc/dhcpcd.exi step "web UI script syntax" if command -v node >/dev/null; then for f in rootfs/www/ui/*.js; do node --check "$f"; done + node tools/mock/lan-shift.test.js echo "ok: $(ls rootfs/www/ui/*.js | wc -l) files" else echo "node not found; skipped" diff --git a/tools/mock/lan-shift.test.js b/tools/mock/lan-shift.test.js new file mode 100644 index 0000000..7a8d876 --- /dev/null +++ b/tools/mock/lan-shift.test.js @@ -0,0 +1,26 @@ +// Focused regression tests for the pure LAN address shifter in rootfs/www/ui/net.js. +// The UI file has no build step; extract the helper region so this stays a real test +// of the shipped implementation without needing a browser DOM. +"use strict"; +const assert = require("assert"); +const fs = require("fs"); +const source = fs.readFileSync("rootfs/www/ui/net.js", "utf8"); +const start = source.indexOf("function lanCIDR"); +const end = source.indexOf("function lanRenumberCandidates"); +assert(start >= 0 && end > start, "LAN helper region missing"); +const {lanCIDR, lanShiftText} = new Function(source.slice(start, end) + "\nreturn {lanCIDR, lanShiftText};")(); + +const old24 = lanCIDR("192.168.1.6/24"); +const new24 = lanCIDR("192.168.2.1/24"); +assert.equal(lanShiftText("192.168.1.5", old24, new24), "192.168.2.5"); +assert.equal(lanShiftText("192.168.1.0/24", old24, new24), "192.168.2.0/24"); +assert.equal(lanShiftText("192.168.0.5", old24, new24), "192.168.0.5"); +assert.equal(lanShiftText("192.168.1.300", old24, new24), "192.168.1.300"); +assert.equal(lanShiftText("::ffff:192.168.1.5", old24, new24), "::ffff:192.168.1.5"); +assert.equal(lanShiftText("64:ff9b::192.168.1.5/128", old24, new24), "64:ff9b::192.168.1.5/128"); + +const old16 = lanCIDR("192.168.1.6/24"); +const new16 = lanCIDR("192.168.0.1/16"); +assert.equal(lanShiftText("192.168.1.200", old16, new16), "192.168.0.200"); +assert.equal(lanShiftText("192.168.1.200/24", old16, new16), "192.168.0.200/24"); +console.log("ok: LAN address shifter");